var __create = Object.create;
var __defProp = Object.defineProperty;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
var __commonJS = (callback, module2) => () => {
  if (!module2) {
    module2 = {exports: {}};
    callback(module2.exports, module2);
  }
  return module2.exports;
};
var __export = (target, all2) => {
  for (var name in all2)
    __defProp(target, name, {get: all2[name], enumerable: true});
};
var __exportStar = (target, module2, desc) => {
  if (module2 && typeof module2 === "object" || typeof module2 === "function") {
    for (let key of __getOwnPropNames(module2))
      if (!__hasOwnProp.call(target, key) && key !== "default")
        __defProp(target, key, {get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable});
  }
  return target;
};
var __toModule = (module2) => {
  return __exportStar(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? {get: () => module2.default, enumerable: true} : {value: module2, enumerable: true})), module2);
};

// build/dashboard/Dashboard.js
var require_Dashboard = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => DashboardSection
  });
  var EmptyDashboard = () => {
    const {t: t5} = useTranslation("dashboard");
    const {realm: realm2} = useRealm();
    return /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(EmptyState, {
      variant: "large"
    }, /* @__PURE__ */ react.createElement(Brand, {
      src: environment_default.resourceUrl + "/icon.svg",
      alt: "Keycloak icon",
      className: "keycloak__dashboard_icon"
    }), /* @__PURE__ */ react.createElement(Title, {
      headingLevel: "h4",
      size: "3xl"
    }, t5("welcome")), /* @__PURE__ */ react.createElement(Title, {
      headingLevel: "h4",
      size: "4xl"
    }, realm2), /* @__PURE__ */ react.createElement(EmptyStateBody, null, t5("introduction"))));
  };
  var Dashboard = () => {
    const {t: t5} = useTranslation("dashboard");
    const {realm: realm2} = useRealm();
    const serverInfo2 = useServerInfo();
    const enabledFeatures = xor(serverInfo2.profileInfo?.disabledFeatures, serverInfo2.profileInfo?.experimentalFeatures, serverInfo2.profileInfo?.previewFeatures);
    const isExperimentalFeature = (feature) => {
      return serverInfo2.profileInfo?.experimentalFeatures?.includes(feature);
    };
    const isPreviewFeature = (feature) => {
      return serverInfo2.profileInfo?.previewFeatures?.includes(feature);
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(TextContent, {
      className: "pf-u-mr-sm"
    }, /* @__PURE__ */ react.createElement(Text, {
      component: "h1"
    }, t5("realmName", {name: toUpperCase(realm2)})), /* @__PURE__ */ react.createElement(Text, null, /* @__PURE__ */ react.createElement(Trans, {
      t: t5,
      i18nKey: "adminUiVersion"
    }, /* @__PURE__ */ react.createElement("strong", null, "Admin UI version"), {version: environment_default.commitHash})))), /* @__PURE__ */ react.createElement(PageSection, null, /* @__PURE__ */ react.createElement(Grid, {
      hasGutter: true
    }, /* @__PURE__ */ react.createElement(GridItem, {
      lg: 2,
      sm: 12
    }, /* @__PURE__ */ react.createElement(Card, {
      className: "keycloak__dashboard_card"
    }, /* @__PURE__ */ react.createElement(CardTitle, null, t5("serverInfo")), /* @__PURE__ */ react.createElement(CardBody, null, /* @__PURE__ */ react.createElement(DescriptionList, null, /* @__PURE__ */ react.createElement(DescriptionListGroup, null, /* @__PURE__ */ react.createElement(DescriptionListTerm, null, t5("version")), /* @__PURE__ */ react.createElement(DescriptionListDescription, null, serverInfo2.systemInfo?.version), /* @__PURE__ */ react.createElement(DescriptionListTerm, null, t5("product")), /* @__PURE__ */ react.createElement(DescriptionListDescription, null, toUpperCase(serverInfo2.profileInfo?.name))))))), /* @__PURE__ */ react.createElement(GridItem, {
      lg: 10,
      sm: 12
    }, /* @__PURE__ */ react.createElement(Card, {
      className: "keycloak__dashboard_card"
    }, /* @__PURE__ */ react.createElement(CardTitle, null, t5("profile")), /* @__PURE__ */ react.createElement(CardBody, null, /* @__PURE__ */ react.createElement(DescriptionList, null, /* @__PURE__ */ react.createElement(DescriptionListGroup, null, /* @__PURE__ */ react.createElement(DescriptionListTerm, null, t5("enabledFeatures"), " ", /* @__PURE__ */ react.createElement(HelpItem, {
      fieldLabelId: "dashboard:enabledFeatures",
      helpText: "dashboard:infoEnabledFeatures"
    })), /* @__PURE__ */ react.createElement(DescriptionListDescription, null, /* @__PURE__ */ react.createElement(List, {
      variant: ListVariant.inline
    }, enabledFeatures.map((feature) => /* @__PURE__ */ react.createElement(ListItem, {
      key: feature
    }, feature, " ", isExperimentalFeature(feature) ? /* @__PURE__ */ react.createElement(Label, {
      color: "orange"
    }, t5("experimental")) : null, isPreviewFeature(feature) ? /* @__PURE__ */ react.createElement(Label, {
      color: "blue"
    }, t5("preview")) : null))))), /* @__PURE__ */ react.createElement(DescriptionListGroup, null, /* @__PURE__ */ react.createElement(DescriptionListTerm, null, t5("disabledFeatures"), " ", /* @__PURE__ */ react.createElement(HelpItem, {
      fieldLabelId: "dashboard:disabledFeatures",
      helpText: "dashboard:infoDisabledFeatures"
    })), /* @__PURE__ */ react.createElement(DescriptionListDescription, null, /* @__PURE__ */ react.createElement(List, {
      variant: ListVariant.inline
    }, serverInfo2.profileInfo?.disabledFeatures?.map((feature) => /* @__PURE__ */ react.createElement(ListItem, {
      key: feature
    }, feature))))))))))));
  };
  function DashboardSection() {
    const {realm: realm2} = useRealm();
    const isMasterRealm = realm2 === "master";
    return /* @__PURE__ */ react.createElement(react.Fragment, null, !isMasterRealm && /* @__PURE__ */ react.createElement(EmptyDashboard, null), isMasterRealm && /* @__PURE__ */ react.createElement(Dashboard, null));
  }
});

// build/realm/add/NewRealmForm.js
var require_NewRealmForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => NewRealmForm
  });
  function NewRealmForm() {
    const {t: t5} = useTranslation("realm");
    const history = useHistory();
    const {refresh} = useWhoAmI();
    const {refresh: refreshRealms} = useRealms();
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const {register: register2, handleSubmit, control, errors, setValue} = useForm({mode: "onChange"});
    const handleFileChange = (obj) => {
      const defaultRealm = {id: "", realm: "", enabled: true};
      Object.entries(obj || defaultRealm).map((entry) => setValue(entry[0], entry[1]));
    };
    const save = async (realm2) => {
      try {
        await adminClient.realms.create(realm2);
        addAlert(t5("saveRealmSuccess"), AlertVariant.success);
        refresh();
        await refreshRealms();
        history.push(toDashboard({realm: realm2.realm}));
      } catch (error2) {
        addError("realm:saveRealmError", error2);
      }
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "realm:createRealm",
      subKey: "realm:realmExplain"
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      onSubmit: handleSubmit(save),
      role: "manage-realm"
    }, /* @__PURE__ */ react.createElement(JsonFileUpload, {
      id: "kc-realm-filename",
      allowEditingUploadedText: true,
      onChange: handleFileChange
    }), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("realmName"),
      isRequired: true,
      fieldId: "kc-realm-name",
      validated: errors.realm ? "error" : "default",
      helperTextInvalid: t5("common:required")
    }, /* @__PURE__ */ react.createElement(TextInput, {
      isRequired: true,
      type: "text",
      id: "kc-realm-name",
      name: "realm",
      validated: errors.realm ? "error" : "default",
      ref: register2({required: true})
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("enabled"),
      fieldId: "kc-realm-enabled-switch"
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "enabled",
      defaultValue: true,
      control,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
        id: "kc-realm-enabled-switch",
        name: "enabled",
        label: t5("common:on"),
        labelOff: t5("common:off"),
        isChecked: value,
        onChange
      })
    })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      variant: "primary",
      type: "submit"
    }, t5("common:create")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      onClick: () => history.goBack()
    }, t5("common:cancel"))))));
  }
});

// build/authentication/FlowDetails.js
var require_FlowDetails = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => FlowDetails,
    providerConditionFilter: () => providerConditionFilter3
  });
  var providerConditionFilter3 = (value) => value.displayName?.startsWith("Condition ");
  function FlowDetails() {
    const {t: t5} = useTranslation("authentication");
    const adminClient = useAdminClient();
    const {realm: realm2} = useRealm();
    const {addAlert, addError} = useAlerts();
    const {id: id3, usedBy, builtIn} = useParams();
    const history = useHistory();
    const [key, setKey] = useState(0);
    const refresh = () => setKey(new Date().getTime());
    const [tableView, setTableView] = useState(true);
    const [flow, setFlow] = useState();
    const [executionList, setExecutionList] = useState();
    const [dragged, setDragged] = useState();
    const [liveText, setLiveText] = useState("");
    const [showAddExecutionDialog, setShowAddExecutionDialog] = useState();
    const [showAddSubFlowDialog, setShowSubFlowDialog] = useState();
    const [selectedExecution, setSelectedExecution] = useState();
    const [open2, toggleOpen, setOpen] = useToggle();
    const [edit, setEdit] = useState(false);
    useFetch(async () => {
      const flows = await adminClient.authenticationManagement.getFlows();
      const flow2 = flows.find((f2) => f2.id === id3);
      if (!flow2) {
        throw new Error(t5("common:notFound"));
      }
      const executions = await adminClient.authenticationManagement.getExecutions({
        flow: flow2.alias
      });
      return {flow: flow2, executions};
    }, ({flow: flow2, executions}) => {
      setFlow(flow2);
      setExecutionList(new ExecutionList(executions));
    }, [key]);
    const executeChange = async (ex, change) => {
      try {
        let id22 = ex.id;
        if ("parent" in change) {
          await adminClient.authenticationManagement.delExecution({id: id22});
          const result = await adminClient.authenticationManagement.addExecutionToFlow({
            flow: change.parent?.displayName || flow?.alias,
            provider: ex.providerId
          });
          id22 = result.id;
        }
        const times = change.newIndex - change.oldIndex;
        for (let index3 = 0; index3 < Math.abs(times); index3++) {
          if (times > 0) {
            await adminClient.authenticationManagement.lowerPriorityExecution({
              id: id22
            });
          } else {
            await adminClient.authenticationManagement.raisePriorityExecution({
              id: id22
            });
          }
        }
        refresh();
        addAlert(t5("updateFlowSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("authentication:updateFlowError", error2);
      }
    };
    const update = async (execution) => {
      try {
        await adminClient.authenticationManagement.updateExecution({flow: flow?.alias}, execution);
        refresh();
        addAlert(t5("updateFlowSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("authentication:updateFlowError", error2);
      }
    };
    const addExecution = async (name, type) => {
      try {
        await adminClient.authenticationManagement.addExecutionToFlow({
          flow: name,
          provider: type.id
        });
        refresh();
        addAlert(t5("updateFlowSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("authentication:updateFlowError", error2);
      }
    };
    const addFlow = async (flow2, {name, description = "", type, provider}) => {
      try {
        await adminClient.authenticationManagement.addFlowToFlow({
          flow: flow2,
          alias: name,
          description,
          provider,
          type
        });
        refresh();
        addAlert(t5("updateFlowSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("authentication:updateFlowError", error2);
      }
    };
    const setAsDefault = async () => {
      try {
        const r3 = await adminClient.realms.findOne({realm: realm2});
        await adminClient.realms.update({realm: realm2}, {...r3, browserFlow: flow?.alias});
        addAlert(t5("updateFlowSuccess"), AlertVariant.success);
        history.push(toFlow({id: id3, realm: realm2, usedBy: "default", builtIn}));
      } catch (error2) {
        addError("authentication:updateFlowError", error2);
      }
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "authentication:deleteConfirmExecution",
      children: /* @__PURE__ */ react.createElement(Trans, {
        i18nKey: "authentication:deleteConfirmExecutionMessage"
      }, " ", /* @__PURE__ */ react.createElement("strong", null, {name: selectedExecution?.displayName}), "."),
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.authenticationManagement.delExecution({
            id: selectedExecution?.id
          });
          addAlert(t5("deleteExecutionSuccess"), AlertVariant.success);
          refresh();
        } catch (error2) {
          addError("authentication:deleteExecutionError", error2);
        }
      }
    });
    const [toggleDeleteFlow, DeleteFlowConfirm] = useConfirmDialog({
      titleKey: "authentication:deleteConfirmFlow",
      children: /* @__PURE__ */ react.createElement(Trans, {
        i18nKey: "authentication:deleteConfirmFlowMessage"
      }, " ", /* @__PURE__ */ react.createElement("strong", null, {flow: flow?.alias || ""}), "."),
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.authenticationManagement.deleteFlow({
            flowId: flow.id
          });
          history.push(toAuthentication({realm: realm2}));
          addAlert(t5("deleteFlowSuccess"), AlertVariant.success);
        } catch (error2) {
          addError("authentication:deleteFlowError", error2);
        }
      }
    });
    const hasExecutions = executionList?.expandableList.length !== 0;
    const dropdownItems = [
      ...usedBy !== "default" ? [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          "data-testid": "set-as-default",
          key: "default",
          onClick: () => setAsDefault()
        }, t5("setAsDefault"))
      ] : [],
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "duplicate",
        onClick: () => setOpen(true)
      }, t5("duplicate")),
      ...!builtIn ? [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          "data-testid": "edit-flow",
          key: "edit",
          onClick: () => setEdit(true)
        }, t5("editInfo")),
        /* @__PURE__ */ react.createElement(DropdownItem, {
          "data-testid": "delete-flow",
          key: "delete",
          onClick: () => toggleDeleteFlow()
        }, t5("common:delete"))
      ] : []
    ];
    return /* @__PURE__ */ react.createElement(react.Fragment, null, open2 && /* @__PURE__ */ react.createElement(DuplicateFlowModal, {
      name: flow?.alias,
      description: flow?.description,
      toggleDialog: toggleOpen,
      onComplete: () => {
        refresh();
        setOpen(false);
      }
    }), edit && /* @__PURE__ */ react.createElement(EditFlowModal, {
      flow,
      toggleDialog: () => {
        setEdit(!edit);
        refresh();
      }
    }), /* @__PURE__ */ react.createElement(DeleteFlowConfirm, null), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: toUpperCase(flow?.alias || ""),
      badges: [
        {text: /* @__PURE__ */ react.createElement(Label, null, t5(usedBy))},
        builtIn ? {
          text: /* @__PURE__ */ react.createElement(Label, {
            className: "keycloak_authentication-section__usedby_label",
            icon: /* @__PURE__ */ react.createElement(CheckCircleIcon, null)
          }, t5("buildIn")),
          id: "builtIn"
        } : {}
      ],
      dropdownItems
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, hasExecutions && /* @__PURE__ */ react.createElement(Toolbar, {
      id: "toolbar"
    }, /* @__PURE__ */ react.createElement(ToolbarContent, null, /* @__PURE__ */ react.createElement(ToggleGroup, null, /* @__PURE__ */ react.createElement(ToggleGroupItem, {
      icon: /* @__PURE__ */ react.createElement(TableIcon, null),
      "aria-label": t5("tableView"),
      buttonId: "tableView",
      isSelected: tableView,
      onChange: () => setTableView(true)
    }), /* @__PURE__ */ react.createElement(ToggleGroupItem, {
      icon: /* @__PURE__ */ react.createElement("i", {
        className: "fas fa-project-diagram"
      }),
      "aria-label": t5("diagramView"),
      buttonId: "diagramView",
      isSelected: !tableView,
      onChange: () => setTableView(false)
    })))), tableView && executionList && hasExecutions && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(DataList, {
      "aria-label": "flows",
      onDragFinish: (order3) => {
        const withoutHeaderId = order3.slice(1);
        setLiveText(t5("common:onDragFinish", {list: dragged?.displayName}));
        const change = executionList.getChange(dragged, withoutHeaderId);
        executeChange(dragged, change);
      },
      onDragStart: (id22) => {
        const item = executionList.findExecution(id22);
        setLiveText(t5("common:onDragStart", {item: item.displayName}));
        setDragged(item);
        if (!item.isCollapsed) {
          item.isCollapsed = true;
          setExecutionList(executionList.clone());
        }
      },
      onDragMove: () => setLiveText(t5("common:onDragMove", {item: dragged?.displayName})),
      onDragCancel: () => setLiveText(t5("common:onDragCancel")),
      itemOrder: [
        "header",
        ...executionList.order().map((ex) => ex.id)
      ]
    }, /* @__PURE__ */ react.createElement(FlowHeader, null), /* @__PURE__ */ react.createElement(react.Fragment, null, executionList.expandableList.map((execution) => /* @__PURE__ */ react.createElement(FlowRow, {
      builtIn: !!builtIn,
      key: execution.id,
      execution,
      onRowClick: (execution2) => {
        execution2.isCollapsed = !execution2.isCollapsed;
        setExecutionList(executionList.clone());
      },
      onRowChange: update,
      onAddExecution: (execution2, type) => addExecution(execution2.displayName, type),
      onAddFlow: (flow2) => addFlow(execution.displayName, flow2),
      onDelete: () => {
        setSelectedExecution(execution);
        toggleDeleteDialog();
      }
    })))), flow && /* @__PURE__ */ react.createElement(react.Fragment, null, showAddExecutionDialog && /* @__PURE__ */ react.createElement(AddStepModal, {
      name: flow.alias,
      type: flow.providerId === "client-flow" ? "client" : "basic",
      onSelect: (type) => {
        if (type) {
          addExecution(flow.alias, type);
        }
        setShowAddExecutionDialog(false);
      }
    }), showAddSubFlowDialog && /* @__PURE__ */ react.createElement(AddSubFlowModal, {
      name: flow.alias,
      onCancel: () => setShowSubFlowDialog(false),
      onConfirm: (newFlow) => {
        addFlow(flow.alias, newFlow);
        setShowSubFlowDialog(false);
      }
    }), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "addStep",
      variant: "link",
      onClick: () => setShowAddExecutionDialog(true)
    }, /* @__PURE__ */ react.createElement(PlusIcon, null), " ", t5("addStep")), /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "addSubFlow",
      variant: "link",
      onClick: () => setShowSubFlowDialog(true)
    }, /* @__PURE__ */ react.createElement(PlusIcon, null), " ", t5("addSubFlow")))), /* @__PURE__ */ react.createElement("div", {
      className: "pf-screen-reader",
      "aria-live": "assertive"
    }, liveText)), !tableView && executionList?.expandableList && /* @__PURE__ */ react.createElement(FlowDiagram, {
      executionList
    }), !executionList?.expandableList || flow && !hasExecutions && /* @__PURE__ */ react.createElement(EmptyExecutionState, {
      flow,
      onAddExecution: (type) => addExecution(flow.alias, type),
      onAddFlow: (newFlow) => addFlow(flow.alias, newFlow)
    })));
  }
});

// build/authentication/form/CreateFlow.js
var require_CreateFlow = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => CreateFlow
  });
  function CreateFlow() {
    const {t: t5} = useTranslation("authentication");
    const history = useHistory();
    const {realm: realm2} = useRealm();
    const form2 = useForm({
      defaultValues: {builtIn: false, topLevel: true}
    });
    const {handleSubmit, register: register2} = form2;
    const adminClient = useAdminClient();
    const {addAlert} = useAlerts();
    const save = async (flow) => {
      try {
        const {id: id3} = await adminClient.authenticationManagement.createFlow(flow);
        addAlert(t5("flowCreatedSuccess"), AlertVariant.success);
        history.push(toFlow({
          realm: realm2,
          id: id3,
          usedBy: "notInUse"
        }));
      } catch (error2) {
        addAlert(t5("flowCreateError", {
          error: error2.response?.data?.errorMessage || error2
        }), AlertVariant.danger);
      }
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "authentication:createFlow",
      subKey: "authentication-help:createFlow"
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      role: "manage-authorization",
      onSubmit: handleSubmit(save)
    }, /* @__PURE__ */ react.createElement("input", {
      name: "builtIn",
      type: "hidden",
      ref: register2
    }), /* @__PURE__ */ react.createElement("input", {
      name: "topLevel",
      type: "hidden",
      ref: register2
    }), /* @__PURE__ */ react.createElement(NameDescription, null), /* @__PURE__ */ react.createElement(FlowType, null), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "create",
      type: "submit"
    }, t5("common:create")), /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "cancel",
      variant: "link",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toAuthentication({realm: realm2})
      })
    }, t5("common:cancel")))))));
  }
});

// build/authentication/AuthenticationSection.js
var require_AuthenticationSection = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => AuthenticationSection
  });
  var realmFlows = [
    "browserFlow",
    "registrationFlow",
    "directGrantFlow",
    "resetCredentialsFlow",
    "clientAuthenticationFlow",
    "dockerAuthenticationFlow"
  ];
  function AuthenticationSection() {
    const {t: t5} = useTranslation("authentication");
    const adminClient = useAdminClient();
    const {realm: realm2} = useRealm();
    const [key, setKey] = useState(0);
    const refresh = () => setKey(new Date().getTime());
    const {addAlert, addError} = useAlerts();
    const [selectedFlow, setSelectedFlow] = useState();
    const [open2, toggleOpen, setOpen] = useToggle();
    const loader = async () => {
      const clients2 = await adminClient.clients.find();
      const idps = await adminClient.identityProviders.find();
      const realmRep = await adminClient.realms.findOne({realm: realm2});
      if (!realmRep) {
        throw new Error(t5("common:notFound"));
      }
      const defaultFlows = Object.entries(realmRep).filter((entry) => realmFlows.includes(entry[0])).map((entry) => entry[1]);
      const flows = await adminClient.authenticationManagement.getFlows();
      for (const flow of flows) {
        flow.usedBy = {values: []};
        const client2 = clients2.find((client22) => client22.authenticationFlowBindingOverrides && (client22.authenticationFlowBindingOverrides["direct_grant"] === flow.id || client22.authenticationFlowBindingOverrides["browser"] === flow.id));
        if (client2) {
          flow.usedBy.type = "specificClients";
          flow.usedBy.values.push(client2.clientId);
        }
        const idp = idps.find((idp2) => idp2.firstBrokerLoginFlowAlias === flow.alias || idp2.postBrokerLoginFlowAlias === flow.alias);
        if (idp) {
          flow.usedBy.type = "specificProviders";
          flow.usedBy.values.push(idp.alias);
        }
        const isDefault = defaultFlows.includes(flow.alias);
        if (isDefault) {
          flow.usedBy.type = "default";
        }
      }
      return flows;
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "authentication:deleteConfirmFlow",
      children: /* @__PURE__ */ react.createElement(Trans, {
        i18nKey: "authentication:deleteConfirmFlowMessage"
      }, " ", /* @__PURE__ */ react.createElement("strong", null, {flow: selectedFlow ? selectedFlow.alias : ""}), "."),
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.authenticationManagement.deleteFlow({
            flowId: selectedFlow.id
          });
          refresh();
          addAlert(t5("deleteFlowSuccess"), AlertVariant.success);
        } catch (error2) {
          addError("authentication:deleteFlowError", error2);
        }
      }
    });
    const UsedBy = ({id: id3, usedBy: {type, values: values2}}) => /* @__PURE__ */ react.createElement(react.Fragment, null, (type === "specificProviders" || type === "specificClients") && /* @__PURE__ */ react.createElement(Popover, {
      key: id3,
      "aria-label": t5("usedBy"),
      bodyContent: /* @__PURE__ */ react.createElement("div", {
        key: `usedBy-${id3}-${values2}`
      }, t5("appliedBy" + (type === "specificClients" ? "Clients" : "Providers")), " ", values2.map((used, index3) => /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement("strong", null, used), index3 < values2.length - 1 ? ", " : "")))
    }, /* @__PURE__ */ react.createElement(Button, {
      variant: ButtonVariant.link,
      key: `button-${id3}`
    }, /* @__PURE__ */ react.createElement(CheckCircleIcon, {
      className: "keycloak_authentication-section__usedby",
      key: `icon-${id3}`
    }), " ", t5(type))), type === "default" && /* @__PURE__ */ react.createElement(Button, {
      key: id3,
      variant: ButtonVariant.link,
      isDisabled: true
    }, /* @__PURE__ */ react.createElement(CheckCircleIcon, {
      className: "keycloak_authentication-section__usedby",
      key: `icon-${id3}`
    }), " ", t5("default")), !type && /* @__PURE__ */ react.createElement(Button, {
      key: id3,
      variant: ButtonVariant.link,
      isDisabled: true
    }, t5("notInUse")));
    const AliasRenderer = ({
      id: id3,
      alias,
      usedBy,
      builtIn
    }) => /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Link, {
      to: toFlow({
        realm: realm2,
        id: id3,
        usedBy: usedBy.type || "notInUse",
        builtIn: builtIn ? "builtIn" : void 0
      }),
      key: `link-${id3}`
    }, toUpperCase(alias)), " ", builtIn && /* @__PURE__ */ react.createElement(Label, {
      key: `label-${id3}`
    }, t5("buildIn")));
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), open2 && /* @__PURE__ */ react.createElement(DuplicateFlowModal, {
      name: selectedFlow ? selectedFlow.alias : "",
      description: selectedFlow?.description,
      toggleDialog: toggleOpen,
      onComplete: () => {
        refresh();
        setOpen(false);
      }
    }), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "authentication:title",
      divider: false
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      className: "pf-u-p-0"
    }, /* @__PURE__ */ react.createElement(KeycloakTabs, {
      isBox: true
    }, /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "flows",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("flows"))
    }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
      key,
      loader,
      ariaLabelKey: "authentication:title",
      searchPlaceholderKey: "authentication:searchForFlow",
      toolbarItem: /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
        component: (props) => /* @__PURE__ */ react.createElement(Link, {
          ...props,
          to: toCreateFlow({realm: realm2})
        })
      }, t5("createFlow"))),
      actionResolver: ({data: data2}) => {
        const defaultActions = [
          {
            title: t5("duplicate"),
            onClick: () => {
              setOpen(true);
              setSelectedFlow(data2);
            }
          }
        ];
        if (data2.builtIn || data2.usedBy.values.length > 0) {
          return defaultActions;
        } else {
          return [
            {
              title: t5("common:delete"),
              onClick: () => {
                setSelectedFlow(data2);
                toggleDeleteDialog();
              }
            },
            ...defaultActions
          ];
        }
      },
      columns: [
        {
          name: "alias",
          displayKey: "authentication:flowName",
          cellRenderer: AliasRenderer
        },
        {
          name: "usedBy",
          displayKey: "authentication:usedBy",
          cellRenderer: UsedBy
        },
        {
          name: "description",
          displayKey: "common:description"
        }
      ],
      emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
        message: t5("emptyEvents"),
        instructions: t5("emptyEventsInstructions")
      })
    })), /* @__PURE__ */ react.createElement(Tab, {
      id: "requiredActions",
      eventKey: "requiredActions",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("requiredActions"))
    }, /* @__PURE__ */ react.createElement(RequiredActions, null)), /* @__PURE__ */ react.createElement(Tab, {
      id: "policies",
      eventKey: "policies",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("policies"))
    }, /* @__PURE__ */ react.createElement(Policies, null)))));
  }
});

// build/client-scopes/ClientScopesSection.js
var require_ClientScopesSection = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => ClientScopesSection
  });
  function ClientScopesSection() {
    const {realm: realm2} = useRealm();
    const {whoAmI: whoAmI2} = useWhoAmI();
    const {t: t5} = useTranslation("client-scopes");
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const [key, setKey] = useState(0);
    const refresh = () => setKey(new Date().getTime());
    const [kebabOpen, setKebabOpen] = useState(false);
    const [selectedScopes, setSelectedScopes] = useState([]);
    const [searchType, setSearchType] = useState("name");
    const [searchTypeType, setSearchTypeType] = useState(AllClientScopes.none);
    const [searchProtocol, setSearchProtocol] = useState("all");
    const loader = async (first2, max2, search2) => {
      const defaultScopes = await adminClient.clientScopes.listDefaultClientScopes();
      const optionalScopes = await adminClient.clientScopes.listDefaultOptionalClientScopes();
      const clientScopes2 = await adminClient.clientScopes.find();
      const filter3 = searchType === "name" ? nameFilter(search2) : searchType === "type" ? typeFilter(searchTypeType) : protocolFilter(searchProtocol);
      return clientScopes2.map((scope) => {
        const row = {
          ...scope,
          type: defaultScopes.find((defaultScope) => defaultScope.name === scope.name) ? ClientScope.default : optionalScopes.find((optionalScope) => optionalScope.name === scope.name) ? ClientScope.optional : AllClientScopes.none
        };
        return row;
      }).filter(filter3).sort((a2, b2) => a2.name.localeCompare(b2.name, whoAmI2.getLocale())).slice(first2, Number(first2) + Number(max2));
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: t5("deleteClientScope", {
        count: selectedScopes.length,
        name: selectedScopes[0]?.name
      }),
      messageKey: "client-scopes:deleteConfirm",
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          for (const scope of selectedScopes) {
            try {
              await removeScope(adminClient, scope);
            } catch (error2) {
              console.warn("could not remove scope", error2.response?.data?.errorMessage || error2);
            }
            await adminClient.clientScopes.del({id: scope.id});
          }
          addAlert(t5("deletedSuccess"), AlertVariant.success);
          refresh();
        } catch (error2) {
          addError("client-scopes:deleteError", error2);
        }
      }
    });
    const TypeSelector = (scope) => /* @__PURE__ */ react.createElement(CellDropdown, {
      clientScope: scope,
      type: scope.type,
      all: true,
      onSelect: async (value) => {
        try {
          await changeScope(adminClient, scope, value);
          addAlert(t5("clientScopeSuccess"), AlertVariant.success);
          refresh();
        } catch (error2) {
          addError("client-scopes:clientScopeError", error2);
        }
      }
    });
    const ClientScopeDetailLink = ({
      id: id3,
      type,
      name
    }) => /* @__PURE__ */ react.createElement(Link, {
      key: id3,
      to: toClientScope({realm: realm2, id: id3, type, tab: "settings"})
    }, name);
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "clientScopes",
      subKey: "client-scopes:clientScopeExplain"
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      className: "pf-u-p-0"
    }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
      key,
      loader,
      ariaLabelKey: "client-scopes:clientScopeList",
      searchPlaceholderKey: searchType === "name" ? "client-scopes:searchFor" : void 0,
      isSearching: searchType !== "name",
      searchTypeComponent: /* @__PURE__ */ react.createElement(SearchDropdown, {
        searchType,
        onSelect: (searchType2) => setSearchType(searchType2),
        withProtocol: true
      }),
      isPaginated: true,
      onSelect: (clientScopes2) => setSelectedScopes([...clientScopes2]),
      canSelectAll: true,
      toolbarItem: /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(SearchToolbar, {
        searchType,
        type: searchTypeType,
        onSelect: (searchType2) => setSearchType(searchType2),
        onType: (value) => {
          setSearchTypeType(value);
          refresh();
        },
        protocol: searchProtocol,
        onProtocol: (protocol) => {
          setSearchProtocol(protocol);
          refresh();
        }
      }), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
        component: (props) => /* @__PURE__ */ react.createElement(Link, {
          ...props,
          to: toNewClientScope({realm: realm2})
        })
      }, t5("createClientScope"))), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(ChangeTypeDropdown, {
        selectedRows: selectedScopes,
        refresh
      })), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Dropdown, {
        toggle: /* @__PURE__ */ react.createElement(KebabToggle, {
          onToggle: setKebabOpen
        }),
        isOpen: kebabOpen,
        isPlain: true,
        dropdownItems: [
          /* @__PURE__ */ react.createElement(DropdownItem, {
            key: "action",
            component: "button",
            isDisabled: selectedScopes.length === 0,
            onClick: () => {
              toggleDeleteDialog();
              setKebabOpen(false);
            }
          }, t5("common:delete"))
        ]
      }))),
      actions: [
        {
          title: t5("common:export")
        },
        {
          title: t5("common:delete"),
          onRowClick: (clientScope) => {
            setSelectedScopes([clientScope]);
            toggleDeleteDialog();
          }
        }
      ],
      columns: [
        {
          name: "name",
          cellRenderer: ClientScopeDetailLink
        },
        {
          name: "type",
          displayKey: "client-scopes:assignedType",
          cellRenderer: TypeSelector
        },
        {
          name: "protocol",
          displayKey: "client-scopes:protocol",
          cellRenderer: (client2) => getProtocolName(t5, client2.protocol ?? "openid-connect"),
          transforms: [cellWidth(15)]
        },
        {
          name: "attributes['gui.order']",
          displayKey: "client-scopes:displayOrder",
          cellFormatters: [emptyFormatter()],
          transforms: [cellWidth(15)]
        },
        {name: "description", cellFormatters: [emptyFormatter()]}
      ]
    })));
  }
});

// build/client-scopes/details/MappingDetails.js
var require_MappingDetails = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => MappingDetails
  });
  function MappingDetails() {
    const {t: t5} = useTranslation("client-scopes");
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const {id: id3, mapperId, type} = useParams();
    const form2 = useForm();
    const {register: register2, setValue, errors, handleSubmit} = form2;
    const [mapping, setMapping] = useState();
    const [config2, setConfig] = useState();
    const history = useHistory();
    const {realm: realm2} = useRealm();
    const serverInfo2 = useServerInfo();
    const isGuid = /^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$/;
    const isUpdating = !!mapperId.match(isGuid);
    const isOnClientScope = !!useRouteMatch(MapperRoute.path);
    const toDetails = () => isOnClientScope ? toClientScope({realm: realm2, id: id3, type, tab: "mappers"}) : `/${realm2}/clients/${id3}/mappers`;
    useFetch(async () => {
      let data2;
      if (isUpdating) {
        if (isOnClientScope) {
          data2 = await adminClient.clientScopes.findProtocolMapper({
            id: id3,
            mapperId
          });
        } else {
          data2 = await adminClient.clients.findProtocolMapperById({
            id: id3,
            mapperId
          });
        }
        if (!data2) {
          throw new Error(t5("common:notFound"));
        }
        const mapperTypes = serverInfo2.protocolMapperTypes[data2.protocol];
        const mapping2 = mapperTypes.find((type2) => type2.id === data2.protocolMapper);
        return {
          config: {
            protocol: data2.protocol,
            protocolMapper: data2.protocolMapper
          },
          mapping: mapping2,
          data: data2
        };
      } else {
        const model = type ? await adminClient.clientScopes.findOne({id: id3}) : await adminClient.clients.findOne({id: id3});
        if (!model) {
          throw new Error(t5("common:notFound"));
        }
        const protocolMappers = serverInfo2.protocolMapperTypes[model.protocol];
        const mapping2 = protocolMappers.find((mapper) => mapper.id === mapperId);
        if (!mapping2) {
          throw new Error(t5("common:notFound"));
        }
        return {
          mapping: mapping2,
          config: {
            protocol: model.protocol,
            protocolMapper: mapperId
          }
        };
      }
    }, ({config: config22, mapping: mapping2, data: data2}) => {
      setConfig(config22);
      setMapping(mapping2);
      if (data2) {
        convertToFormValues(data2, setValue);
      }
    }, []);
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "common:deleteMappingTitle",
      messageKey: "common:deleteMappingConfirm",
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          if (isOnClientScope) {
            await adminClient.clientScopes.delProtocolMapper({
              id: id3,
              mapperId
            });
          } else {
            await adminClient.clients.delProtocolMapper({
              id: id3,
              mapperId
            });
          }
          addAlert(t5("common:mappingDeletedSuccess"), AlertVariant.success);
          history.push(toDetails());
        } catch (error2) {
          addError("common:mappingDeletedError", error2);
        }
      }
    });
    const save = async (formMapping) => {
      const key = isUpdating ? "Updated" : "Created";
      try {
        const mapping2 = {...config2, ...convertFormValuesToObject(formMapping)};
        if (isUpdating) {
          isOnClientScope ? await adminClient.clientScopes.updateProtocolMapper({id: id3, mapperId}, {id: mapperId, ...mapping2}) : await adminClient.clients.updateProtocolMapper({id: id3, mapperId}, {id: mapperId, ...mapping2});
        } else {
          isOnClientScope ? await adminClient.clientScopes.addProtocolMapper({id: id3}, mapping2) : await adminClient.clients.addProtocolMapper({id: id3}, mapping2);
        }
        addAlert(t5(`common:mapping${key}Success`), AlertVariant.success);
      } catch (error2) {
        addError(`common:mapping${key}Error`, error2);
      }
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: isUpdating ? mapping?.name : t5("common:addMapper"),
      subKey: isUpdating ? mapperId : "client-scopes:addMapperExplain",
      dropdownItems: isUpdating ? [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "delete",
          value: "delete",
          onClick: toggleDeleteDialog
        }, t5("common:delete"))
      ] : void 0
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      onSubmit: handleSubmit(save),
      role: "manage-clients",
      className: "keycloak__client-scope-mapping-details__form"
    }, /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:mapperType"),
      fieldId: "mapperType"
    }, /* @__PURE__ */ react.createElement(TextInput, {
      type: "text",
      id: "mapperType",
      name: "mapperType",
      isReadOnly: true,
      value: mapping?.name
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:name"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "name"
      }),
      fieldId: "name",
      isRequired: true,
      validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: register2({required: true}),
      type: "text",
      id: "name",
      name: "name",
      isReadOnly: isUpdating,
      validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default
    })), /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, /* @__PURE__ */ react.createElement(DynamicComponents, {
      properties: mapping?.properties || []
    })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      variant: "primary",
      type: "submit"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toDetails()
      })
    }, t5("common:cancel"))))));
  }
});

// build/client-scopes/form/ClientScopeForm.js
var require_ClientScopeForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => ClientScopeForm
  });
  function ClientScopeForm() {
    const {t: t5} = useTranslation("client-scopes");
    const [clientScope, setClientScope] = useState();
    const history = useHistory();
    const {realm: realm2} = useRealm();
    const [hide3, toggleHide] = useToggle();
    const adminClient = useAdminClient();
    const {id: id3, type} = useParams();
    const {addAlert, addError} = useAlerts();
    const [key, setKey] = useState(0);
    const refresh = () => setKey(new Date().getTime());
    useFetch(async () => {
      if (id3) {
        const clientScope2 = await adminClient.clientScopes.findOne({id: id3});
        if (!clientScope2) {
          throw new Error(t5("common:notFound"));
        }
        return {
          ...clientScope2,
          type
        };
      }
    }, (clientScope2) => {
      setClientScope(clientScope2);
    }, [key, id3]);
    const loader = async () => {
      const assignedRoles = (await adminClient.clientScopes.listRealmScopeMappings({id: id3})).map((role) => ({role}));
      const effectiveRoles = (await adminClient.clientScopes.listCompositeRealmScopeMappings({id: id3})).map((role) => ({role}));
      const clients2 = await adminClient.clients.find();
      const clientRoles = (await Promise.all(clients2.map(async (client2) => {
        const clientAssignedRoles = (await adminClient.clientScopes.listClientScopeMappings({
          id: id3,
          client: client2.id
        })).map((role) => ({role, client: client2}));
        const clientEffectiveRoles = (await adminClient.clientScopes.listCompositeClientScopeMappings({
          id: id3,
          client: client2.id
        })).map((role) => ({role, client: client2}));
        return mapRoles(clientAssignedRoles, clientEffectiveRoles, hide3);
      }))).flat();
      return [...mapRoles(assignedRoles, effectiveRoles, hide3), ...clientRoles];
    };
    const save = async (clientScopes2) => {
      try {
        clientScopes2.name = clientScopes2.name?.trim();
        clientScopes2 = convertFormValuesToObject(clientScopes2);
        if (id3) {
          await adminClient.clientScopes.update({id: id3}, clientScopes2);
          changeScope(adminClient, {...clientScopes2, id: id3, type}, clientScopes2.type);
        } else {
          await adminClient.clientScopes.create(clientScopes2);
          const scope = await adminClient.clientScopes.findOneByName({
            name: clientScopes2.name
          });
          if (!scope) {
            throw new Error(t5("common:notFound"));
          }
          changeScope(adminClient, {...clientScopes2, id: scope.id}, clientScopes2.type);
          history.push(toClientScope({
            realm: realm2,
            id: scope.id,
            type: clientScopes2.type || "none",
            tab: "settings"
          }));
        }
        addAlert(t5((id3 ? "update" : "create") + "Success"), AlertVariant.success);
      } catch (error2) {
        addError(`client-scopes:${id3 ? "update" : "create"}Error`, error2);
      }
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: t5("deleteClientScope", {
        count: 1,
        name: clientScope?.name
      }),
      messageKey: "client-scopes:deleteConfirm",
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.clientScopes.del({id: id3});
          addAlert(t5("deletedSuccess"), AlertVariant.success);
        } catch (error2) {
          addError("client-scopes:deleteError", error2);
        }
      }
    });
    const assignRoles = async (rows) => {
      try {
        const realmRoles = rows.filter((row) => row.client === void 0).map((row) => row.role).flat();
        await adminClient.clientScopes.addRealmScopeMappings({
          id: id3
        }, realmRoles);
        await Promise.all(rows.filter((row) => row.client !== void 0).map((row) => adminClient.clientScopes.addClientScopeMappings({
          id: id3,
          client: row.client.id
        }, [row.role])));
        addAlert(t5("roleMappingUpdatedSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("client-scopes:roleMappingUpdatedError", error2);
      }
    };
    const addMappers = async (mappers) => {
      if (!Array.isArray(mappers)) {
        const mapper = mappers;
        history.push(toMapper({
          realm: realm2,
          id: clientScope.id,
          type,
          mapperId: mapper.id
        }));
      } else {
        try {
          await adminClient.clientScopes.addMultipleProtocolMappers({id: clientScope.id}, mappers);
          refresh();
          addAlert(t5("common:mappingCreatedSuccess"), AlertVariant.success);
        } catch (error2) {
          addError("common:mappingCreatedError", error2);
        }
      }
    };
    const onDelete = async (mapper) => {
      try {
        await adminClient.clientScopes.delProtocolMapper({
          id: clientScope.id,
          mapperId: mapper.id
        });
        addAlert(t5("common:mappingDeletedSuccess"), AlertVariant.success);
        refresh();
      } catch (error2) {
        addError("common:mappingDeletedError", error2);
      }
      return true;
    };
    if (id3 && !clientScope) {
      return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
    }
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: clientScope ? clientScope.name : "client-scopes:createClientScope",
      dropdownItems: clientScope ? [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "delete",
          onClick: toggleDeleteDialog
        }, t5("common:delete"))
      ] : void 0,
      badges: [{text: clientScope ? clientScope.protocol : void 0}],
      divider: !id3
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      className: "pf-u-p-0"
    }, !id3 && /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(ScopeForm, {
      save,
      clientScope: {}
    })), id3 && clientScope && /* @__PURE__ */ react.createElement(KeycloakTabs, {
      isBox: true
    }, /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "settings",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:settings"))
    }, /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(ScopeForm, {
      save,
      clientScope
    }))), /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "mappers",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:mappers"))
    }, /* @__PURE__ */ react.createElement(MapperList, {
      model: clientScope,
      onAdd: addMappers,
      onDelete,
      detailLink: (id22) => toMapper({realm: realm2, id: clientScope.id, type, mapperId: id22})
    })), /* @__PURE__ */ react.createElement(Tab, {
      "data-testid": "scopeTab",
      eventKey: "scope",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("scope"))
    }, /* @__PURE__ */ react.createElement(RoleMapping, {
      id: id3,
      name: clientScope.name,
      type: "client-scope",
      loader,
      save: assignRoles,
      onHideRolesToggle: toggleHide
    })))));
  }
});

// build/realm-settings/key-providers/aes-generated/AESGeneratedForm.js
var require_AESGeneratedForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    AESGeneratedForm: () => AESGeneratedForm2,
    default: () => AESGeneratedSettings
  });
  var AESGeneratedForm2 = ({
    editMode,
    providerType,
    handleModalToggle,
    refresh
  }) => {
    const {t: t5} = useTranslation("realm-settings");
    const serverInfo2 = useServerInfo();
    const [isKeySizeDropdownOpen, setIsKeySizeDropdownOpen] = useState(false);
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const {id: id3} = useParams();
    const providerId = useRouteMatch("/:providerType?")?.params.providerType;
    const save = async (component) => {
      try {
        if (id3) {
          await adminClient.components.update({id: id3}, {
            ...component,
            parentId: component.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE
          });
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
        } else {
          await adminClient.components.create({
            ...component,
            parentId: component.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE,
            config: {priority: ["0"]}
          });
          handleModalToggle?.();
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
          refresh?.();
        }
      } catch (error2) {
        addError("realm-settings:saveProviderError", error2);
      }
    };
    const form2 = useForm({mode: "onChange"});
    const setupForm = (component) => {
      form2.reset();
      convertToFormValues(component, form2.setValue);
    };
    useFetch(async () => {
      if (editMode)
        return await adminClient.components.findOne({id: id3});
    }, (result) => {
      if (result) {
        setupForm(result);
      }
    }, []);
    const allComponentTypes = serverInfo2.componentTypes?.[KEY_PROVIDER_TYPE] ?? [];
    const aesSecretSizeOptions = allComponentTypes[0].properties[3].options;
    return /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      id: "add-provider",
      className: "pf-u-mt-lg",
      role: "manage-realm",
      onSubmit: form2.handleSubmit(save)
    }, editMode && /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("providerId"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "name"
      }),
      fieldId: "id",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      id: "id",
      type: "text",
      name: "id",
      isReadOnly: editMode,
      "aria-label": t5("consoleDisplayName"),
      defaultValue: id3,
      "data-testid": "display-name-input"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:name"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "name"
      }),
      fieldId: "name",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, !editMode && /* @__PURE__ */ react.createElement(Controller, {
      name: "name",
      control: form2.control,
      defaultValue: providerType,
      render: ({onChange, value}) => {
        return /* @__PURE__ */ react.createElement(TextInput, {
          id: "name",
          type: "text",
          "aria-label": t5("consoleDisplayName"),
          defaultValue: providerType,
          value,
          onChange: (value2) => onChange(value2),
          "data-testid": "display-name-input"
        });
      }
    }), editMode && /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      type: "text",
      id: "name",
      name: "name",
      defaultValue: providerId,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:enabled"),
      fieldId: "kc-enabled",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: t5("realm-settings-help:enabled"),
        fieldLabelId: "enabled"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.enabled",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
        id: "kc-enabled",
        label: t5("common:on"),
        labelOff: t5("common:off"),
        isChecked: value[0] === "true",
        "data-testid": value[0] === "true" ? "internationalization-enabled" : "internationalization-disabled",
        onChange: (value2) => {
          onChange([value2.toString()]);
        }
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("active"),
      fieldId: "kc-active",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:active",
        fieldLabelId: "realm-settings:active"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.active",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => {
        return /* @__PURE__ */ react.createElement(Switch, {
          id: "kc-active",
          label: t5("common:on"),
          labelOff: t5("common:off"),
          isChecked: value[0] === "true",
          "data-testid": value[0] === "true" ? "internationalization-enabled" : "internationalization-disabled",
          onChange: (value2) => {
            onChange([value2.toString()]);
          }
        });
      }
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("AESKeySize"),
      fieldId: "kc-aes-keysize",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:AESKeySize",
        fieldLabelId: "realm-settings:AESKeySize"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.secretSize",
      control: form2.control,
      defaultValue: ["16"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
        toggleId: "kc-aes-keysize",
        onToggle: () => setIsKeySizeDropdownOpen(!isKeySizeDropdownOpen),
        onSelect: (_23, value2) => {
          onChange([value2.toString()]);
          setIsKeySizeDropdownOpen(false);
        },
        selections: [value.toString()],
        isOpen: isKeySizeDropdownOpen,
        variant: SelectVariant.single,
        "aria-label": t5("aesKeySize"),
        "data-testid": "select-secret-size"
      }, aesSecretSizeOptions?.map((item) => /* @__PURE__ */ react.createElement(SelectOption, {
        selected: item === value,
        key: item,
        value: item
      })))
    })), /* @__PURE__ */ react.createElement(ActionGroup, {
      className: "kc-AESform-buttons"
    }, /* @__PURE__ */ react.createElement(Button, {
      className: "kc-AESform-save-button",
      "data-testid": "add-provider-button",
      variant: "primary",
      type: "submit"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      className: "kc-AESform-cancel-button",
      onClick: !editMode && handleModalToggle || void 0,
      variant: "link"
    }, t5("common:cancel"))));
  };
  function AESGeneratedSettings() {
    const {t: t5} = useTranslation("realm-settings");
    const providerId = useRouteMatch("/:realm/realm-settings/keys/:id?/:providerType?/settings")?.params.providerType;
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: t5("editProvider"),
      subKey: providerId
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(AESGeneratedForm2, {
      providerType: providerId,
      editMode: true
    })));
  }
});

// build/realm-settings/key-providers/java-keystore/JavaKeystoreForm.js
var require_JavaKeystoreForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    JavaKeystoreForm: () => JavaKeystoreForm2,
    default: () => JavaKeystoreSettings
  });
  var JavaKeystoreForm2 = ({
    editMode,
    providerType,
    handleModalToggle,
    refresh
  }) => {
    const {t: t5} = useTranslation("realm-settings");
    const serverInfo2 = useServerInfo();
    const [isAlgorithmDropdownOpen, setIsAlgorithmDropdownOpen] = useState(false);
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const {id: id3} = useParams();
    const providerId = useRouteMatch("/:providerType?")?.params.providerType;
    const save = async (component) => {
      try {
        if (id3) {
          await adminClient.components.update({id: id3}, {
            ...component,
            parentId: component.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE
          });
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
        } else {
          await adminClient.components.create({
            ...component,
            parentId: component.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE,
            config: {priority: ["0"]}
          });
          handleModalToggle?.();
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
          refresh?.();
        }
      } catch (error2) {
        addError("realm-settings:saveProviderError", error2);
      }
    };
    const form2 = useForm({mode: "onChange"});
    const setupForm = (component) => {
      form2.reset();
      convertToFormValues(component, form2.setValue);
    };
    useFetch(async () => {
      if (editMode)
        return await adminClient.components.findOne({id: id3});
    }, (result) => {
      if (result) {
        setupForm(result);
      }
    }, []);
    const allComponentTypes = serverInfo2.componentTypes?.[KEY_PROVIDER_TYPE] ?? [];
    const javaKeystoreAlgorithmOptions = allComponentTypes[3].properties[3].options;
    return /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      id: "add-provider",
      className: "pf-u-mt-lg",
      role: "manage-realm",
      onSubmit: form2.handleSubmit(save)
    }, editMode && /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("providerId"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "realm-settings:providerId"
      }),
      fieldId: "id",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      id: "id",
      type: "text",
      name: "id",
      isReadOnly: editMode,
      "aria-label": t5("consoleDisplayName"),
      defaultValue: id3,
      "data-testid": "display-name-input"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:name"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "name"
      }),
      fieldId: "name",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, !editMode && /* @__PURE__ */ react.createElement(Controller, {
      name: "name",
      control: form2.control,
      defaultValue: providerType,
      render: ({onChange, value}) => {
        return /* @__PURE__ */ react.createElement(TextInput, {
          id: "name",
          type: "text",
          "aria-label": t5("consoleDisplayName"),
          defaultValue: providerType,
          value,
          onChange: (value2) => onChange(value2),
          "data-testid": "display-name-input"
        });
      }
    }), editMode && /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      type: "text",
      id: "name",
      name: "name",
      defaultValue: providerId,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:enabled"),
      fieldId: "kc-enabled",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: t5("realm-settings-help:enabled"),
        fieldLabelId: "realm-settings:enabled"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.enabled",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
        id: "kc-enabled-switch",
        label: t5("common:on"),
        labelOff: t5("common:off"),
        isChecked: value[0] === "true",
        "data-testid": value[0] === "true" ? "enabled" : "disabled",
        onChange: (value2) => {
          onChange([value2.toString()]);
        }
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("active"),
      fieldId: "kc-active",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:active",
        fieldLabelId: "realm-settings:active"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.active",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => {
        return /* @__PURE__ */ react.createElement(Switch, {
          id: "kc-active-switch",
          label: t5("common:on"),
          labelOff: t5("common:off"),
          isChecked: value[0] === "true",
          "data-testid": value[0] === "true" ? "active" : "passive",
          onChange: (value2) => {
            onChange([value2.toString()]);
          }
        });
      }
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("algorithm"),
      fieldId: "kc-algorithm",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:algorithm",
        fieldLabelId: "realm-settings:algorithm"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.algorithm",
      control: form2.control,
      defaultValue: ["RS256"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
        toggleId: "kc-elliptic",
        onToggle: (isExpanded) => setIsAlgorithmDropdownOpen(isExpanded),
        onSelect: (_23, value2) => {
          onChange([value2.toString()]);
          setIsAlgorithmDropdownOpen(false);
        },
        selections: [value.toString()],
        variant: SelectVariant.single,
        "aria-label": t5("algorithm"),
        isOpen: isAlgorithmDropdownOpen,
        placeholderText: "Select one...",
        "data-testid": "select-algorithm"
      }, javaKeystoreAlgorithmOptions.map((p2, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
        selected: p2 === value,
        key: `algorithm-${idx}`,
        value: p2
      })))
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("keystore"),
      fieldId: "kc-keystore",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:keystore",
        fieldLabelId: "realm-settings:keystore"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.keystore",
      control: form2.control,
      defaultValue: [],
      render: ({onChange}) => /* @__PURE__ */ react.createElement(TextInput, {
        "aria-label": t5("keystore"),
        onChange: (value) => {
          onChange([value.toString()]);
        },
        "data-testid": "select-display-name"
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("keystorePassword"),
      fieldId: "kc-keystore-password",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:keystorePassword",
        fieldLabelId: "realm-settings:keystorePassword"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.keystorePassword",
      control: form2.control,
      defaultValue: [],
      render: ({onChange}) => /* @__PURE__ */ react.createElement(TextInput, {
        "aria-label": t5("consoleDisplayName"),
        onChange: (value) => {
          onChange([value.toString()]);
        },
        "data-testid": "select-display-name"
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("keyAlias"),
      fieldId: "kc-key-alias",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:keyAlias",
        fieldLabelId: "realm-settings:keyAlias"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.keyAlias",
      control: form2.control,
      defaultValue: [],
      render: ({onChange}) => /* @__PURE__ */ react.createElement(TextInput, {
        "aria-label": t5("keyAlias"),
        onChange: (value) => {
          onChange([value.toString()]);
        },
        "data-testid": "key-alias"
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("keyPassword"),
      fieldId: "kc-key-password",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:keyPassword",
        fieldLabelId: "realm-settings:keyPassword"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.keyPassword",
      control: form2.control,
      defaultValue: [],
      render: ({onChange}) => /* @__PURE__ */ react.createElement(TextInput, {
        "aria-label": t5("keyPassword"),
        onChange: (value) => {
          onChange([value.toString()]);
        },
        "data-testid": "key-password"
      })
    })), /* @__PURE__ */ react.createElement(ActionGroup, {
      className: "kc-java-keystore-form-buttons"
    }, /* @__PURE__ */ react.createElement(Button, {
      className: "kc-java-keystore-form-save-button",
      "data-testid": "add-provider-button",
      variant: "primary",
      type: "submit"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      className: "kc-java-keystore-form-cancel-button",
      onClick: !editMode && handleModalToggle || void 0,
      variant: "link"
    }, t5("common:cancel"))));
  };
  function JavaKeystoreSettings() {
    const {t: t5} = useTranslation("realm-settings");
    const providerId = useRouteMatch("/:realm/realm-settings/keys/:id?/:providerType?/settings")?.params.providerType;
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: t5("editProvider"),
      subKey: providerId
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(JavaKeystoreForm2, {
      providerType: providerId,
      editMode: true
    })));
  }
});

// build/realm-settings/key-providers/hmac-generated/HMACGeneratedForm.js
var require_HMACGeneratedForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    HMACGeneratedForm: () => HMACGeneratedForm2,
    default: () => HMACGeneratedSettings
  });
  var HMACGeneratedForm2 = ({
    editMode,
    providerType,
    handleModalToggle,
    refresh
  }) => {
    const {t: t5} = useTranslation("realm-settings");
    const serverInfo2 = useServerInfo();
    const [isKeySizeDropdownOpen, setIsKeySizeDropdownOpen] = useState(false);
    const [isEllipticCurveDropdownOpen, setIsEllipticCurveDropdownOpen] = useState(false);
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const {id: id3} = useParams();
    const providerId = useRouteMatch("/:providerType?")?.params.providerType;
    const save = async (component) => {
      try {
        if (id3) {
          await adminClient.components.update({id: id3}, {
            ...component,
            parentId: component.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE
          });
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
        } else {
          await adminClient.components.create({
            ...component,
            parentId: component.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE,
            config: {priority: ["0"]}
          });
          handleModalToggle?.();
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
          refresh?.();
        }
      } catch (error2) {
        addError("realm-settings:saveProviderError", error2);
      }
    };
    const form2 = useForm({mode: "onChange"});
    const setupForm = (component) => {
      form2.reset();
      convertToFormValues(component, form2.setValue);
    };
    useFetch(async () => {
      if (editMode)
        return await adminClient.components.findOne({id: id3});
    }, (result) => {
      if (result) {
        setupForm(result);
      }
    }, []);
    const allComponentTypes = serverInfo2.componentTypes?.[KEY_PROVIDER_TYPE] ?? [];
    const hmacSecretSizeOptions = allComponentTypes[2].properties[3].options;
    const hmacAlgorithmOptions = allComponentTypes[2].properties[4].options;
    return /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      id: "add-provider",
      className: "pf-u-mt-lg",
      role: "manage-realm",
      onSubmit: form2.handleSubmit(save)
    }, editMode && /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("providerId"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "realm-settings:providerId"
      }),
      fieldId: "id",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      id: "id",
      type: "text",
      name: "id",
      isReadOnly: editMode,
      "aria-label": t5("consoleDisplayName"),
      defaultValue: id3,
      "data-testid": "display-name-input"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:name"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "name"
      }),
      fieldId: "name",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, !editMode && /* @__PURE__ */ react.createElement(Controller, {
      name: "name",
      control: form2.control,
      defaultValue: providerType,
      render: ({onChange, value}) => {
        return /* @__PURE__ */ react.createElement(TextInput, {
          id: "name",
          type: "text",
          "aria-label": t5("consoleDisplayName"),
          defaultValue: providerType,
          value,
          onChange: (value2) => onChange(value2),
          "data-testid": "display-name-input"
        });
      }
    }), editMode && /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      type: "text",
      id: "name",
      name: "name",
      defaultValue: providerId,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:enabled"),
      fieldId: "kc-enabled",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: t5("realm-settings-help:enabled"),
        fieldLabelId: "enabled"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.enabled",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
        id: "kc-enabled-switch",
        label: t5("common:on"),
        labelOff: t5("common:off"),
        isChecked: value[0] === "true",
        "data-testid": value[0] === "true" ? "enabled" : "disabled",
        onChange: (value2) => {
          onChange([value2.toString()]);
        }
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("active"),
      fieldId: "kc-active",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:active",
        fieldLabelId: "realm-settings:active"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.active",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => {
        return /* @__PURE__ */ react.createElement(Switch, {
          id: "kc-active-switch",
          label: t5("common:on"),
          labelOff: t5("common:off"),
          isChecked: value[0] === "true",
          "data-testid": value[0] === "true" ? "active" : "passive",
          onChange: (value2) => {
            onChange([value2.toString()]);
          }
        });
      }
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("secretSize"),
      fieldId: "kc-hmac-keysize",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:secretSize",
        fieldLabelId: "realm-settings:secretSize"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.secretSize",
      control: form2.control,
      defaultValue: ["64"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
        toggleId: "kc-hmac-keysize",
        onToggle: (isExpanded) => setIsKeySizeDropdownOpen(isExpanded),
        onSelect: (_23, value2) => {
          onChange([value2.toString()]);
          setIsKeySizeDropdownOpen(false);
        },
        selections: [value.toString()],
        isOpen: isKeySizeDropdownOpen,
        variant: SelectVariant.single,
        "aria-label": t5("hmacKeySize"),
        "data-testid": "select-secret-size"
      }, hmacSecretSizeOptions.map((item) => /* @__PURE__ */ react.createElement(SelectOption, {
        selected: item === value,
        key: item,
        value: item
      })))
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("algorithm"),
      fieldId: "kc-algorithm",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:algorithm",
        fieldLabelId: "realm-settings:algorithm"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.algorithm",
      control: form2.control,
      defaultValue: ["HS-256"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
        toggleId: "kc-elliptic",
        onToggle: (isExpanded) => setIsEllipticCurveDropdownOpen(isExpanded),
        onSelect: (_23, value2) => {
          onChange([value2.toString()]);
          setIsEllipticCurveDropdownOpen(false);
        },
        selections: [value.toString()],
        variant: SelectVariant.single,
        "aria-label": t5("emailTheme"),
        isOpen: isEllipticCurveDropdownOpen,
        placeholderText: "Select one...",
        "data-testid": "select-email-theme"
      }, hmacAlgorithmOptions.map((p2, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
        selected: p2 === value,
        key: `email-theme-${idx}`,
        value: p2
      })))
    })), /* @__PURE__ */ react.createElement(ActionGroup, {
      className: "kc-hmac-form-buttons"
    }, /* @__PURE__ */ react.createElement(Button, {
      className: "kc-hmac-form-save-button",
      "data-testid": "add-provider-button",
      variant: "primary",
      type: "submit"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      className: "kc-hmac-form-cancel-button",
      onClick: !editMode && handleModalToggle || void 0,
      variant: "link"
    }, t5("common:cancel"))));
  };
  function HMACGeneratedSettings() {
    const {t: t5} = useTranslation("realm-settings");
    const providerId = useRouteMatch("/:realm/realm-settings/keys/:id?/:providerType?/settings")?.params.providerType;
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: t5("editProvider"),
      subKey: providerId
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(HMACGeneratedForm2, {
      providerType: providerId,
      editMode: true
    })));
  }
});

// build/realm-settings/key-providers/ecdsa-generated/ECDSAGeneratedForm.js
var require_ECDSAGeneratedForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    ECDSAGeneratedForm: () => ECDSAGeneratedForm2,
    default: () => ECDSAGeneratedSettings
  });
  var ECDSAGeneratedForm2 = ({
    editMode,
    providerType,
    handleModalToggle,
    refresh
  }) => {
    const {t: t5} = useTranslation("realm-settings");
    const serverInfo2 = useServerInfo();
    const [isKeySizeDropdownOpen, setIsKeySizeDropdownOpen] = useState(false);
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const {id: id3} = useParams();
    const providerId = useRouteMatch("/:providerType?")?.params.providerType;
    const save = async (component) => {
      try {
        if (id3) {
          await adminClient.components.update({id: id3}, {
            ...component,
            parentId: component.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE
          });
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
        } else {
          await adminClient.components.create({
            ...component,
            parentId: component.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE,
            config: {priority: ["0"]}
          });
          handleModalToggle?.();
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
          refresh?.();
        }
      } catch (error2) {
        addError("realm-settings:saveProviderError", error2);
      }
    };
    const form2 = useForm({mode: "onChange"});
    const setupForm = (component) => {
      form2.reset();
      convertToFormValues(component, form2.setValue);
    };
    useFetch(async () => {
      if (editMode)
        return await adminClient.components.findOne({id: id3});
    }, (result) => {
      if (result) {
        setupForm(result);
      }
    }, []);
    const allComponentTypes = serverInfo2.componentTypes?.[KEY_PROVIDER_TYPE] ?? [];
    const ecdsaEllipticCurveOptions = allComponentTypes[1].properties[3].options;
    return /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      id: "add-provider",
      className: "pf-u-mt-lg",
      role: "manage-realm",
      onSubmit: form2.handleSubmit(save)
    }, editMode && /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("providerId"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "client-scopes:providerId"
      }),
      fieldId: "id",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      id: "id",
      type: "text",
      name: "id",
      isReadOnly: editMode,
      "aria-label": t5("consoleDisplayName"),
      defaultValue: id3,
      "data-testid": "display-name-input"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:name"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "name"
      }),
      fieldId: "name",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, !editMode && /* @__PURE__ */ react.createElement(Controller, {
      name: "name",
      control: form2.control,
      defaultValue: providerType,
      render: ({onChange, value}) => {
        return /* @__PURE__ */ react.createElement(TextInput, {
          id: "name",
          type: "text",
          "aria-label": t5("consoleDisplayName"),
          value,
          onChange: (value2) => onChange(value2),
          "data-testid": "display-name-input"
        });
      }
    }), editMode && /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      type: "text",
      id: "name",
      name: "name",
      defaultValue: providerId,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:enabled"),
      fieldId: "kc-enabled",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: t5("realm-settings-help:enabled"),
        fieldLabelId: "enabled"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.enabled",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
        id: "kc-enabled-switch",
        label: t5("common:on"),
        labelOff: t5("common:off"),
        isChecked: value[0] === "true",
        "data-testid": value[0] === "true" ? "enabled" : "disabled",
        onChange: (value2) => {
          onChange([value2.toString()]);
        }
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("active"),
      fieldId: "kc-active",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:active",
        fieldLabelId: "realm-settings:active"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.active",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => {
        return /* @__PURE__ */ react.createElement(Switch, {
          id: "kc-active-switch",
          label: t5("common:on"),
          labelOff: t5("common:off"),
          isChecked: value[0] === "true",
          "data-testid": value[0] === "true" ? "active" : "passive",
          onChange: (value2) => {
            onChange([value2.toString()]);
          }
        });
      }
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("ellipticCurve"),
      fieldId: "kc-elliptic-curve",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:ellipticCurve",
        fieldLabelId: "realm-settings:ellipticCurve"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.ecdsaEllipticCurveKey",
      control: form2.control,
      defaultValue: ["P-256"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
        toggleId: "kc-ecdsa-elliptic-curve",
        onToggle: (isExpanded) => setIsKeySizeDropdownOpen(isExpanded),
        onSelect: (_23, value2) => {
          onChange([value2.toString()]);
          setIsKeySizeDropdownOpen(false);
        },
        selections: [value.toString()],
        isOpen: isKeySizeDropdownOpen,
        variant: SelectVariant.single,
        "aria-label": t5("ellipticCurve"),
        "data-testid": "select-elliptic-curve-size"
      }, ecdsaEllipticCurveOptions?.map((item) => /* @__PURE__ */ react.createElement(SelectOption, {
        selected: item === value,
        key: item,
        value: item
      })))
    })), /* @__PURE__ */ react.createElement(ActionGroup, {
      className: "kc-ecdsa-form-buttons"
    }, /* @__PURE__ */ react.createElement(Button, {
      className: "kc-ecdsa-form-save-button",
      "data-testid": "add-provider-button",
      variant: "primary",
      type: "submit"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      className: "kc-ecdsa-form-cancel-button",
      onClick: !editMode && handleModalToggle || void 0,
      variant: "link"
    }, t5("common:cancel"))));
  };
  function ECDSAGeneratedSettings() {
    const {t: t5} = useTranslation("realm-settings");
    const providerId = useRouteMatch("/:realm/realm-settings/keys/:id?/:providerType?/settings")?.params.providerType;
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: t5("editProvider"),
      subKey: providerId
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(ECDSAGeneratedForm2, {
      providerType: providerId,
      editMode: true
    })));
  }
});

// build/realm-settings/key-providers/rsa-generated/RSAGeneratedForm.js
var require_RSAGeneratedForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    RSAGeneratedForm: () => RSAGeneratedForm2,
    default: () => RSAGeneratedSettings
  });
  var RSAGeneratedForm2 = ({
    editMode,
    providerType,
    handleModalToggle,
    refresh
  }) => {
    const {t: t5} = useTranslation("realm-settings");
    const serverInfo2 = useServerInfo();
    const [isKeySizeDropdownOpen, setIsKeySizeDropdownOpen] = useState(false);
    const [isEllipticCurveDropdownOpen, setIsEllipticCurveDropdownOpen] = useState(false);
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const {id: id3} = useParams();
    const providerId = useRouteMatch("/:providerType?")?.params.providerType;
    const save = async (component) => {
      try {
        if (id3) {
          await adminClient.components.update({id: id3}, {
            ...component,
            parentId: component.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE
          });
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
        } else {
          await adminClient.components.create({
            ...component,
            parentId: component.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE,
            config: {priority: ["0"]}
          });
          handleModalToggle?.();
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
          refresh?.();
        }
      } catch (error2) {
        addError("realm-settings:saveProviderError", error2);
      }
    };
    const form2 = useForm({mode: "onChange"});
    const setupForm = (component) => {
      form2.reset();
      convertToFormValues(component, form2.setValue);
    };
    useFetch(async () => {
      if (editMode)
        return await adminClient.components.findOne({id: id3});
    }, (result) => {
      if (result) {
        setupForm(result);
      }
    }, []);
    const allComponentTypes = serverInfo2.componentTypes?.[KEY_PROVIDER_TYPE] ?? [];
    const rsaGeneratedKeySizeOptions = allComponentTypes[5].properties[4].options;
    const rsaGeneratedAlgorithmOptions = allComponentTypes[5].properties[3].options;
    return /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      id: "add-provider",
      className: "pf-u-mt-lg",
      role: "manage-realm",
      onSubmit: form2.handleSubmit(save)
    }, editMode && /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("providerId"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "client-scopes:providerId"
      }),
      fieldId: "id",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      id: "id",
      type: "text",
      name: "id",
      isReadOnly: editMode,
      "aria-label": t5("consoleDisplayName"),
      defaultValue: id3,
      "data-testid": "display-name-input"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:name"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "name"
      }),
      fieldId: "name",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, !editMode && /* @__PURE__ */ react.createElement(Controller, {
      name: "name",
      control: form2.control,
      defaultValue: providerType,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TextInput, {
        id: "name",
        type: "text",
        "aria-label": t5("consoleDisplayName"),
        value,
        onChange: (value2) => onChange(value2),
        "data-testid": "display-name-input"
      })
    }), editMode && /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      type: "text",
      id: "name",
      name: "name",
      defaultValue: providerId,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:enabled"),
      fieldId: "kc-enabled",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:enabled",
        fieldLabelId: "enabled"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.enabled",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
        id: "kc-enabled-switch",
        label: t5("common:on"),
        labelOff: t5("common:off"),
        isChecked: value[0] === "true",
        "data-testid": value[0] === "true" ? "enabled" : "disabled",
        onChange: (value2) => {
          onChange([value2.toString()]);
        }
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("active"),
      fieldId: "kc-active",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:active",
        fieldLabelId: "realm-settings:active"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.active",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => {
        return /* @__PURE__ */ react.createElement(Switch, {
          id: "kc-active-switch",
          label: t5("common:on"),
          labelOff: t5("common:off"),
          isChecked: value[0] === "true",
          "data-testid": value[0] === "true" ? "active" : "passive",
          onChange: (value2) => {
            onChange([value2.toString()]);
          }
        });
      }
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("secretSize"),
      fieldId: "kc-rsa-generated-keysize",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:secretSize",
        fieldLabelId: "realm-settings:secretSize"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.secretSize",
      control: form2.control,
      defaultValue: ["2048"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
        toggleId: "kc-rsa-generated-keysize",
        onToggle: (isExpanded) => setIsKeySizeDropdownOpen(isExpanded),
        onSelect: (_23, value2) => {
          onChange([value2.toString()]);
          setIsKeySizeDropdownOpen(false);
        },
        selections: [value.toString()],
        isOpen: isKeySizeDropdownOpen,
        variant: SelectVariant.single,
        "aria-label": t5("KeySize"),
        "data-testid": "select-secret-size"
      }, rsaGeneratedKeySizeOptions.map((item) => /* @__PURE__ */ react.createElement(SelectOption, {
        selected: item === value,
        key: item,
        value: item
      })))
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("algorithm"),
      fieldId: "kc-algorithm",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:algorithm",
        fieldLabelId: "realm-settings:algorithm"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.algorithm",
      control: form2.control,
      defaultValue: ["RS256"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
        toggleId: "kc-elliptic",
        onToggle: (isExpanded) => setIsEllipticCurveDropdownOpen(isExpanded),
        onSelect: (_23, value2) => {
          onChange([value2.toString()]);
          setIsEllipticCurveDropdownOpen(false);
        },
        selections: [value.toString()],
        variant: SelectVariant.single,
        "aria-label": t5("emailTheme"),
        isOpen: isEllipticCurveDropdownOpen,
        placeholderText: "Select one...",
        "data-testid": "select-email-theme"
      }, rsaGeneratedAlgorithmOptions.map((p2, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
        selected: p2 === value,
        key: `email-theme-${idx}`,
        value: p2
      })))
    })), /* @__PURE__ */ react.createElement(ActionGroup, {
      className: "kc-rsa-generated-form-buttons"
    }, /* @__PURE__ */ react.createElement(Button, {
      className: "kc-rsa-generated-form-save-button",
      "data-testid": "add-provider-button",
      variant: "primary",
      type: "submit"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      className: "kc-rsa-generated-form-cancel-button",
      onClick: !editMode && handleModalToggle || void 0,
      variant: "link"
    }, t5("common:cancel"))));
  };
  function RSAGeneratedSettings() {
    const {t: t5} = useTranslation("realm-settings");
    const providerId = useRouteMatch("/:realm/realm-settings/keys/:id?/:providerType?/settings")?.params.providerType;
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: t5("editProvider"),
      subKey: providerId
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(RSAGeneratedForm2, {
      providerType: providerId,
      editMode: true
    })));
  }
});

// build/realm-settings/ExecutorForm.js
var require_ExecutorForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => ExecutorForm
  });
  var defaultValues2 = {
    config: {},
    executor: ""
  };
  function ExecutorForm() {
    const {t: t5} = useTranslation("realm-settings");
    const history = useHistory();
    const {realm: realm2, profileName} = useParams();
    const {executorName} = useParams();
    const {addAlert, addError} = useAlerts();
    const [selectExecutorTypeOpen, setSelectExecutorTypeOpen] = useState(false);
    const serverInfo2 = useServerInfo();
    const adminClient = useAdminClient();
    const executorTypes = serverInfo2.componentTypes?.["org.keycloak.services.clientpolicy.executor.ClientPolicyExecutorProvider"];
    const [executors, setExecutors] = useState([]);
    const [executorProperties, setExecutorProperties] = useState([]);
    const [globalProfiles, setGlobalProfiles] = useState([]);
    const [profiles, setProfiles] = useState([]);
    const form2 = useForm({defaultValues: defaultValues2});
    const {control, setValue, handleSubmit} = form2;
    const editMode = !!executorName;
    useFetch(() => adminClient.clientPolicies.listProfiles({includeGlobalProfiles: true}), (profiles2) => {
      setGlobalProfiles(profiles2.globalProfiles ?? []);
      setProfiles(profiles2.profiles ?? []);
      const profile = profiles2.profiles.find((profile2) => profile2.name === profileName);
      const profileExecutor = profile?.executors.find((executor) => executor.executor === executorName);
      if (profileExecutor) {
        convertToFormValues(profileExecutor, setValue);
      }
    }, []);
    const save = async () => {
      const formValues = form2.getValues();
      const updatedProfiles = profiles.map((profile) => {
        if (profile.name !== profileName) {
          return profile;
        }
        const profileExecutor = profile.executors.find((executor) => executor.executor === executorName);
        const executors2 = (profile.executors ?? []).concat({
          executor: formValues.executor,
          configuration: formValues.config
        });
        if (editMode) {
          profileExecutor.configuration = {
            ...profileExecutor.configuration,
            ...formValues.config
          };
        }
        if (editMode) {
          return profile;
        }
        return {
          ...profile,
          executors: executors2
        };
      });
      try {
        await adminClient.clientPolicies.createProfiles({
          profiles: updatedProfiles,
          globalProfiles
        });
        addAlert(editMode ? t5("realm-settings:updateExecutorSuccess") : t5("realm-settings:addExecutorSuccess"), AlertVariant.success);
        history.push(toClientProfile({realm: realm2, profileName}));
      } catch (error2) {
        addError(editMode ? "realm-settings:updateExecutorError" : "realm-settings:addExecutorError", error2);
      }
    };
    const globalProfile = globalProfiles.find((globalProfile2) => globalProfile2.name === profileName);
    const profileExecutorType = executorTypes?.find((executor) => executor.id === executorName);
    const editedProfileExecutors = profileExecutorType?.properties.map((property2) => {
      const globalDefaultValues = editMode ? property2.defaultValue : "";
      return {
        ...property2,
        defaultValue: globalDefaultValues
      };
    });
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: editMode ? executorName : t5("addExecutor"),
      divider: true
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      role: "manage-realm",
      className: "pf-u-mt-lg"
    }, /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("executorType"),
      fieldId: "kc-executorType",
      labelIcon: executors.length > 0 && executors[0].helpText !== "" ? /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: executors[0].helpText,
        fieldLabelId: "realm-settings:executorTypeHelpText"
      }) : editMode ? /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: profileExecutorType?.helpText,
        fieldLabelId: "realm-settings:executorTypeHelpText"
      }) : void 0
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "executor",
      defaultValue: "",
      control,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
        toggleId: "kc-executor",
        placeholderText: "Select an executor",
        onToggle: (isOpen) => setSelectExecutorTypeOpen(isOpen),
        onSelect: (_23, value2) => {
          onChange(value2.toString());
          const selectedExecutor = executorTypes?.filter((type) => type.id === value2);
          setExecutors(selectedExecutor ?? []);
          setExecutorProperties(selectedExecutor?.[0].properties ?? []);
          setSelectExecutorTypeOpen(false);
        },
        selections: editMode ? executorName : value,
        variant: SelectVariant.single,
        "data-testid": "executorType-select",
        "aria-label": t5("executorType"),
        isOpen: selectExecutorTypeOpen,
        maxHeight: 580,
        isDisabled: editMode
      }, executorTypes?.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
        selected: option.id === value,
        key: option.id,
        value: option.id,
        description: option.helpText
      })))
    })), /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, /* @__PURE__ */ react.createElement(DynamicComponents, {
      properties: executorProperties
    }), editMode && /* @__PURE__ */ react.createElement(DynamicComponents, {
      properties: editedProfileExecutors
    })), !globalProfile && /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      variant: "primary",
      onClick: () => handleSubmit(save)(),
      "data-testid": "addExecutor-saveBtn"
    }, editMode ? t5("common:save") : t5("common:add")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toClientProfile({realm: realm2, profileName})
      }),
      "data-testid": "addExecutor-cancelBtn"
    }, t5("common:cancel")))), editMode && globalProfile && /* @__PURE__ */ react.createElement("div", {
      className: "kc-backToProfile"
    }, /* @__PURE__ */ react.createElement(Button, {
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toClientProfile({realm: realm2, profileName})
      }),
      variant: "primary"
    }, t5("realm-settings:back")))));
  }
});

// build/realm-settings/ClientProfileForm.js
var require_ClientProfileForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => ClientProfileForm
  });
  var defaultValues2 = {
    name: "",
    description: "",
    executors: []
  };
  function ClientProfileForm() {
    const {t: t5} = useTranslation("realm-settings");
    const history = useHistory();
    const {
      handleSubmit,
      setValue,
      register: register2,
      errors,
      formState: {isDirty}
    } = useForm({
      defaultValues: defaultValues2,
      mode: "onChange"
    });
    const {addAlert, addError} = useAlerts();
    const adminClient = useAdminClient();
    const [globalProfiles, setGlobalProfiles] = useState([]);
    const [profiles, setProfiles] = useState([]);
    const {realm: realm2, profileName} = useParams();
    const serverInfo2 = useServerInfo();
    const executorTypes = useMemo(() => serverInfo2.componentTypes?.["org.keycloak.services.clientpolicy.executor.ClientPolicyExecutorProvider"], []);
    const [executorToDelete, setExecutorToDelete] = useState();
    const editMode = profileName ? true : false;
    const [key, setKey] = useState(0);
    const reload = () => setKey(new Date().getTime());
    useFetch(() => adminClient.clientPolicies.listProfiles({includeGlobalProfiles: true}), (profiles2) => {
      setGlobalProfiles(profiles2.globalProfiles ?? []);
      setProfiles(profiles2.profiles ?? []);
    }, [key]);
    const save = async (form2) => {
      const updatedProfiles = editMode ? patchProfiles(form2) : addProfile(form2);
      try {
        await adminClient.clientPolicies.createProfiles({
          profiles: updatedProfiles,
          globalProfiles
        });
        addAlert(editMode ? t5("realm-settings:updateClientProfileSuccess") : t5("realm-settings:createClientProfileSuccess"), AlertVariant.success);
        history.push(toClientProfile({realm: realm2, profileName: form2.name}));
      } catch (error2) {
        addError(editMode ? "realm-settings:updateClientProfileError" : "realm-settings:createClientProfileError", error2);
      }
    };
    const patchProfiles = (data2) => profiles.map((profile2) => {
      if (profile2.name !== profileName) {
        return profile2;
      }
      return {
        ...profile2,
        name: data2.name,
        description: data2.description
      };
    });
    const addProfile = (data2) => profiles.concat({
      ...data2,
      executors: []
    });
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: executorToDelete?.name ? t5("deleteExecutorProfileConfirmTitle") : t5("deleteClientProfileConfirmTitle"),
      messageKey: executorToDelete?.name ? t5("deleteExecutorProfileConfirm", {
        executorName: executorToDelete.name
      }) : t5("deleteClientProfileConfirm", {
        profileName
      }),
      continueButtonLabel: t5("delete"),
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        if (executorToDelete?.name) {
          profileExecutors.splice(executorToDelete.idx, 1);
          try {
            await adminClient.clientPolicies.createProfiles({
              profiles,
              globalProfiles
            });
            addAlert(t5("deleteExecutorSuccess"), AlertVariant.success);
            history.push(toClientProfile({realm: realm2, profileName}));
          } catch (error2) {
            addError(t5("deleteExecutorError"), error2);
          }
        } else {
          const updatedProfiles = profiles.filter((profile2) => profile2.name !== profileName);
          try {
            await adminClient.clientPolicies.createProfiles({
              profiles: updatedProfiles,
              globalProfiles
            });
            addAlert(t5("deleteClientSuccess"), AlertVariant.success);
            history.push(toClientPolicies({realm: realm2}));
          } catch (error2) {
            addError(t5("deleteClientError"), error2);
          }
        }
      }
    });
    const profile = profiles.find((profile2) => profile2.name === profileName);
    const profileExecutors = profile?.executors || [];
    const globalProfile = globalProfiles.find((globalProfile2) => globalProfile2.name === profileName);
    const globalProfileExecutors = globalProfile?.executors || [];
    useEffect(() => {
      setValue("name", globalProfile?.name ?? profile?.name);
      setValue("description", globalProfile?.description ?? profile?.description);
    }, [profiles]);
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: editMode ? profileName : t5("newClientProfile"),
      badges: [
        {
          id: "global-client-profile-badge",
          text: globalProfile ? t5("global") : ""
        }
      ],
      divider: true,
      dropdownItems: !globalProfile ? [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "delete",
          value: "delete",
          onClick: toggleDeleteDialog,
          "data-testid": "deleteClientProfileDropdown"
        }, t5("deleteClientProfile"))
      ] : void 0
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      role: "view-realm",
      className: "pf-u-mt-lg"
    }, /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("newClientProfileName"),
      fieldId: "kc-name",
      helperText: t5("createClientProfileNameHelperText"),
      isRequired: true,
      helperTextInvalid: t5("common:required"),
      validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: register2({required: true}),
      name: "name",
      type: "text",
      id: "name",
      "aria-label": t5("name"),
      "data-testid": "client-profile-name",
      isReadOnly: !!globalProfile
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:description"),
      fieldId: "kc-description"
    }, /* @__PURE__ */ react.createElement(TextArea, {
      ref: register2(),
      name: "description",
      type: "text",
      id: "description",
      "aria-label": t5("description"),
      "data-testid": "client-profile-description",
      isReadOnly: !!globalProfile
    })), /* @__PURE__ */ react.createElement(ActionGroup, null, !globalProfile && /* @__PURE__ */ react.createElement(Button, {
      variant: "primary",
      onClick: () => handleSubmit(save)(),
      "data-testid": "saveCreateProfile",
      isDisabled: !isDirty
    }, t5("common:save")), editMode && !globalProfile && /* @__PURE__ */ react.createElement(Button, {
      id: "reloadProfile",
      variant: "link",
      "data-testid": "reloadProfile",
      isDisabled: !isDirty,
      onClick: reload
    }, t5("realm-settings:reload")), !editMode && !globalProfile && /* @__PURE__ */ react.createElement(Button, {
      id: "cancelCreateProfile",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: `/${realm2}/realm-settings/clientPolicies`
      }),
      "data-testid": "cancelCreateProfile"
    }, t5("common:cancel"))), editMode && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Flex, null, /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Text, {
      className: "kc-executors",
      component: TextVariants.h1
    }, t5("executors"), /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings:executorsHelpText",
      fieldLabelId: "realm-settings:executors"
    }))), profile && /* @__PURE__ */ react.createElement(FlexItem, {
      align: {default: "alignRight"}
    }, /* @__PURE__ */ react.createElement(Button, {
      id: "addExecutor",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toAddExecutor({
          realm: realm2,
          profileName
        })
      }),
      variant: "link",
      className: "kc-addExecutor",
      "data-testid": "addExecutor",
      icon: /* @__PURE__ */ react.createElement(PlusCircleIcon, null)
    }, t5("realm-settings:addExecutor")))), profileExecutors.length > 0 && /* @__PURE__ */ react.createElement(DataList, {
      "aria-label": t5("executors"),
      isCompact: true
    }, profileExecutors.map((executor, idx) => /* @__PURE__ */ react.createElement(DataListItem, {
      "aria-labelledby": "executors-list-item",
      key: executor.executor,
      id: executor.executor
    }, /* @__PURE__ */ react.createElement(DataListItemRow, {
      "data-testid": "executors-list-row"
    }, /* @__PURE__ */ react.createElement(DataListItemCells, {
      dataListCells: [
        /* @__PURE__ */ react.createElement(DataListCell, {
          key: "executor",
          "data-testid": "executor-type"
        }, executor.configuration ? /* @__PURE__ */ react.createElement(Button, {
          component: (props) => /* @__PURE__ */ react.createElement(Link, {
            ...props,
            to: toExecutor({
              realm: realm2,
              profileName,
              executorName: executor.executor
            })
          }),
          variant: "link",
          "data-testid": "editExecutor"
        }, executor.executor) : /* @__PURE__ */ react.createElement("span", {
          className: "kc-unclickable-executor"
        }, executor.executor), executorTypes?.filter((type) => type.id === executor.executor).map((type) => /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(HelpItem, {
          key: type.id,
          helpText: type.helpText,
          fieldLabelId: "realm-settings:executorTypeTextHelpText"
        }), /* @__PURE__ */ react.createElement(Button, {
          variant: "link",
          isInline: true,
          icon: /* @__PURE__ */ react.createElement(TrashIcon, {
            key: `executorType-trash-icon-${type.id}`,
            className: "kc-executor-trash-icon",
            "data-testid": "deleteExecutor"
          }),
          onClick: () => {
            toggleDeleteDialog();
            setExecutorToDelete({
              idx,
              name: type.id
            });
          }
        }))))
      ]
    }))))), globalProfileExecutors.length > 0 && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DataList, {
      "aria-label": t5("executors"),
      isCompact: true
    }, globalProfileExecutors.map((executor) => /* @__PURE__ */ react.createElement(DataListItem, {
      "aria-labelledby": "global-executors-list-item",
      key: executor.executor,
      id: executor.executor
    }, /* @__PURE__ */ react.createElement(DataListItemRow, {
      "data-testid": "global-executors-list-row"
    }, /* @__PURE__ */ react.createElement(DataListItemCells, {
      dataListCells: [
        /* @__PURE__ */ react.createElement(DataListCell, {
          key: "executor",
          "data-testid": "global-executor-type"
        }, Object.keys(executor.configuration).length !== 0 ? /* @__PURE__ */ react.createElement(Button, {
          component: (props) => /* @__PURE__ */ react.createElement(Link, {
            ...props,
            to: toExecutor({
              realm: realm2,
              profileName,
              executorName: executor.executor
            })
          }),
          variant: "link",
          "data-testid": "editExecutor"
        }, executor.executor) : /* @__PURE__ */ react.createElement("span", {
          className: "kc-unclickable-executor"
        }, executor.executor), executorTypes?.filter((type) => type.id === executor.executor).map((type) => /* @__PURE__ */ react.createElement(HelpItem, {
          key: type.id,
          helpText: type.helpText,
          fieldLabelId: "realm-settings:executorTypeTextHelpText"
        })))
      ]
    }))))), /* @__PURE__ */ react.createElement(Button, {
      id: "backToClientPolicies",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: `/${realm2}/realm-settings/clientPolicies`
      }),
      variant: "primary",
      className: "kc-backToPolicies",
      "data-testid": "backToClientPolicies"
    }, t5("realm-settings:back"))), profileExecutors.length === 0 && globalProfileExecutors.length === 0 && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Divider, null), /* @__PURE__ */ react.createElement(Text, {
      className: "kc-emptyExecutors",
      component: TextVariants.h6
    }, t5("realm-settings:emptyExecutors")))))));
  }
});

// build/realm-settings/ProfilesTab.js
var require_ProfilesTab = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => ProfilesTab2
  });
  function ProfilesTab2() {
    const {t: t5} = useTranslation("realm-settings");
    const adminClient = useAdminClient();
    const {realm: realm2} = useRealm();
    const {addAlert, addError} = useAlerts();
    const [tableProfiles, setTableProfiles] = useState();
    const [globalProfiles, setGlobalProfiles] = useState();
    const [selectedProfile, setSelectedProfile] = useState();
    const [show2, setShow] = useState(false);
    const [code2, setCode] = useState();
    const [key, setKey] = useState(0);
    useFetch(() => adminClient.clientPolicies.listProfiles({
      includeGlobalProfiles: true
    }), (allProfiles) => {
      setGlobalProfiles(allProfiles.globalProfiles);
      const globalProfiles2 = allProfiles.globalProfiles?.map((globalProfiles3) => ({
        ...globalProfiles3,
        global: true
      }));
      const profiles = allProfiles.profiles?.map((profiles2) => ({
        ...profiles2,
        global: false
      }));
      const allClientProfiles = globalProfiles2?.concat(profiles ?? []);
      setTableProfiles(allClientProfiles || []);
      setCode(JSON.stringify(allClientProfiles, null, 2));
    }, [key]);
    const loader = async () => tableProfiles ?? [];
    const normalizeProfile = (profile) => omit(profile, "global");
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: t5("deleteClientProfileConfirmTitle"),
      messageKey: t5("deleteClientProfileConfirm", {
        profileName: selectedProfile?.name
      }),
      continueButtonLabel: t5("delete"),
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        const updatedProfiles = tableProfiles?.filter((profile) => profile.name !== selectedProfile?.name && !profile.global).map((profile) => normalizeProfile(profile));
        try {
          await adminClient.clientPolicies.createProfiles({
            profiles: updatedProfiles,
            globalProfiles
          });
          addAlert(t5("deleteClientSuccess"), AlertVariant.success);
          setKey(key + 1);
        } catch (error2) {
          addError(t5("deleteClientError"), error2);
        }
      }
    });
    const cellFormatter = (row) => /* @__PURE__ */ react.createElement(Link, {
      to: toClientProfile({
        realm: realm2,
        profileName: row.name
      }),
      key: row.name
    }, row.name, " ", row.global && /* @__PURE__ */ react.createElement(Label, {
      color: "blue"
    }, t5("global")));
    if (!tableProfiles) {
      return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
    }
    const save = async () => {
      if (!code2) {
        return;
      }
      try {
        const obj = JSON.parse(code2);
        const changedProfiles = obj.filter((profile) => !profile.global).map((profile) => normalizeProfile(profile));
        const changedGlobalProfiles = obj.filter((profile) => profile.global).map((profile) => normalizeProfile(profile));
        try {
          await adminClient.clientPolicies.createProfiles({
            profiles: changedProfiles,
            globalProfiles: changedGlobalProfiles
          });
          addAlert(t5("realm-settings:updateClientProfilesSuccess"), AlertVariant.success);
          setKey(key + 1);
        } catch (error2) {
          addError("realm-settings:updateClientProfilesError", error2);
        }
      } catch (error2) {
        console.warn("Invalid json, ignoring value using {}");
      }
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(PageSection, null, /* @__PURE__ */ react.createElement(Flex, {
      className: "kc-profiles-config-section"
    }, /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Title, {
      headingLevel: "h1",
      size: "md"
    }, t5("profilesConfigType"))), /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Radio, {
      isChecked: !show2,
      name: "profilesView",
      onChange: () => setShow(false),
      label: t5("profilesConfigTypes.formView"),
      id: "formView-profilesView",
      className: "kc-form-radio-btn pf-u-mr-sm pf-u-ml-sm",
      "data-testid": "formView-profilesView"
    })), /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Radio, {
      isChecked: show2,
      name: "profilesView",
      onChange: () => setShow(true),
      label: t5("profilesConfigTypes.jsonEditor"),
      id: "jsonEditor-profilesView",
      className: "kc-editor-radio-btn",
      "data-testid": "jsonEditor-profilesView"
    })))), /* @__PURE__ */ react.createElement(Divider, null), !show2 ? /* @__PURE__ */ react.createElement(KeycloakDataTable, {
      key: tableProfiles.length,
      ariaLabelKey: "realm-settings:profiles",
      searchPlaceholderKey: "realm-settings:clientProfileSearch",
      loader,
      toolbarItem: /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
        id: "createProfile",
        component: (props) => /* @__PURE__ */ react.createElement(Link, {
          ...props,
          to: toAddClientProfile({realm: realm2})
        }),
        "data-testid": "createProfile"
      }, t5("createClientProfile"))),
      isRowDisabled: (value) => value.global,
      actions: [
        {
          title: t5("common:delete"),
          onRowClick: (profile) => {
            setSelectedProfile(profile);
            toggleDeleteDialog();
          }
        }
      ],
      columns: [
        {
          name: "name",
          displayKey: t5("common:name"),
          cellRenderer: cellFormatter
        },
        {
          name: "description",
          displayKey: t5("clientProfileDescription")
        }
      ],
      emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
        message: t5("emptyClientProfiles"),
        instructions: t5("emptyClientProfilesInstructions")
      })
    }) : /* @__PURE__ */ react.createElement(FormGroup, {
      fieldId: "jsonEditor"
    }, /* @__PURE__ */ react.createElement("div", {
      className: "pf-u-mt-md pf-u-ml-lg"
    }, /* @__PURE__ */ react.createElement(CodeEditor, {
      isLineNumbersVisible: true,
      isLanguageLabelVisible: true,
      isReadOnly: false,
      code: code2,
      language: Language.json,
      height: "30rem",
      onChange: (value) => {
        setCode(value ?? "");
      }
    })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement("div", {
      className: "pf-u-mt-md"
    }, /* @__PURE__ */ react.createElement(Button, {
      variant: ButtonVariant.primary,
      className: "pf-u-mr-md pf-u-ml-lg",
      onClick: save,
      "data-testid": "jsonEditor-saveBtn"
    }, t5("save")), /* @__PURE__ */ react.createElement(Button, {
      variant: ButtonVariant.link,
      onClick: () => {
        setCode(prettyPrintJSON(tableProfiles));
      },
      "data-testid": "jsonEditor-reloadBtn"
    }, t5("reload"))))));
  }
});

// build/realm-settings/NewClientPolicyCondition.js
var require_NewClientPolicyCondition = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => NewClientPolicyCondition2
  });
  function NewClientPolicyCondition2() {
    const {t: t5} = useTranslation("realm-settings");
    const {addAlert, addError} = useAlerts();
    const history = useHistory();
    const {realm: realm2} = useRealm();
    const [openConditionType, setOpenConditionType] = useState(false);
    const [policies, setPolicies] = useState([]);
    const [condition, setCondition] = useState([]);
    const [conditionData, setConditionData] = useState();
    const [conditionType, setConditionType] = useState("");
    const [conditionProperties, setConditionProperties] = useState([]);
    const {policyName} = useParams();
    const {conditionName} = useParams();
    const serverInfo2 = useServerInfo();
    const form2 = useForm({
      shouldUnregister: false
    });
    const conditionTypes = serverInfo2.componentTypes?.["org.keycloak.services.clientpolicy.condition.ClientPolicyConditionProvider"];
    const adminClient = useAdminClient();
    const setupForm = (condition2, properties) => {
      form2.reset();
      Object.entries(condition2.configuration).map(([key, value]) => {
        const formKey = `config.${key}`;
        const property2 = properties.find((p2) => p2.name === key);
        if (property2?.type === "MultivaluedString" && property2.name !== "scopes" && property2.name !== "groups") {
          form2.setValue(formKey, convertToMultiline(value));
        } else if (property2?.name === "client-scopes") {
          form2.setValue("config.scopes", value);
        } else {
          form2.setValue(formKey, value);
        }
      });
    };
    useFetch(() => adminClient.clientPolicies.listPolicies(), (policies2) => {
      setPolicies(policies2.policies ?? []);
      if (conditionName) {
        const currentPolicy = policies2.policies?.find((item) => item.name === policyName);
        const typeAndConfigData = currentPolicy?.conditions?.find((item) => item.condition === conditionName);
        const currentCondition = conditionTypes?.find((condition2) => condition2.id === conditionName);
        setConditionData(typeAndConfigData);
        setConditionProperties(currentCondition?.properties);
        setupForm(typeAndConfigData, currentCondition?.properties);
      }
    }, []);
    const save = async (configPolicy) => {
      const configValues = configPolicy.config;
      const writeConfig = () => {
        return conditionProperties.reduce((r3, p2) => {
          p2.type === "MultivaluedString" && p2.name !== "scopes" && p2.name !== "groups" ? r3[p2.name] = toValue(configValues[p2.name]) : r3[p2.name] = configValues[p2.name];
          return r3;
        }, {});
      };
      const updatedPolicies = policies.map((policy) => {
        if (policy.name !== policyName) {
          return policy;
        }
        let conditions = policy.conditions ?? [];
        if (conditionName) {
          const createdCondition = {
            condition: conditionData?.condition,
            configuration: writeConfig()
          };
          const index3 = conditions.findIndex((condition2) => conditionName === condition2.condition);
          if (index3 === -1) {
            return;
          }
          const newConditions = [
            ...conditions.slice(0, index3),
            createdCondition,
            ...conditions.slice(index3 + 1)
          ];
          return {
            ...policy,
            conditions: newConditions
          };
        }
        conditions = conditions.concat({
          condition: condition[0].condition,
          configuration: writeConfig()
        });
        return {
          ...policy,
          conditions
        };
      });
      try {
        await adminClient.clientPolicies.updatePolicy({
          policies: updatedPolicies
        });
        setPolicies(updatedPolicies);
        history.push(`/${realm2}/realm-settings/clientPolicies/${policyName}/edit-policy`);
        addAlert(conditionName ? t5("realm-settings:updateClientConditionSuccess") : t5("realm-settings:createClientConditionSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("realm-settings:createClientConditionError", error2);
      }
    };
    return /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormPanel, {
      className: "kc-login-screen",
      title: conditionName ? t5("editCondition") : t5("addCondition")
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      role: "manage-realm",
      className: "pf-u-mt-lg",
      onSubmit: form2.handleSubmit(save)
    }, /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("conditionType"),
      fieldId: "conditionType",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: conditionType ? `realm-settings-help:${camelCase2(conditionType.replace(/-/g, " "))}` : "realm-settings:anyClient",
        fieldLabelId: "realm-settings:conditionType"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "conditions",
      defaultValue: "any-client",
      control: form2.control,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
        placeholderText: t5("selectACondition"),
        className: "kc-conditionType-select",
        "data-testid": "conditionType-select",
        toggleId: "provider",
        isDisabled: !!conditionName,
        onToggle: (toggle) => setOpenConditionType(toggle),
        onSelect: (_23, value2) => {
          onChange(value2);
          setConditionProperties(value2.properties);
          setConditionType(value2.id);
          setCondition([
            {
              condition: value2.id
            }
          ]);
          setOpenConditionType(false);
        },
        selections: conditionName ? conditionName : conditionType,
        variant: SelectVariant.single,
        "aria-label": t5("conditionType"),
        isOpen: openConditionType
      }, conditionTypes?.map((condition2) => /* @__PURE__ */ react.createElement(SelectOption, {
        selected: condition2.id === value,
        description: t5(`realm-settings-help:${camelCase2(condition2.id.replace(/-/g, " "))}`),
        key: condition2.id,
        value: condition2
      }, condition2.id)))
    })), /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, conditionProperties.map((property2) => {
      const componentType = property2.type;
      if (property2.name === "roles") {
        return /* @__PURE__ */ react.createElement(MultivaluedRoleComponent, {
          ...property2
        });
      }
      if (property2.name === "scopes" || property2.name === "groups") {
        return /* @__PURE__ */ react.createElement(MultivaluedChipsComponent, {
          defaultValue: property2.name === "scopes" ? "offline_access" : "topgroup",
          ...property2
        });
      }
      if (isValidComponentType(componentType)) {
        const Component = COMPONENTS[componentType];
        return /* @__PURE__ */ react.createElement(Component, {
          key: property2.name,
          ...property2
        });
      } else {
        console.warn(`There is no editor registered for ${componentType}`);
      }
    })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      variant: "primary",
      type: "submit",
      "data-testid": "addCondition-saveBtn",
      isDisabled: conditionType === "" && !conditionName
    }, conditionName ? t5("common:save") : t5("common:add")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      "data-testid": "addCondition-cancelBtn",
      onClick: () => history.push(toEditClientPolicy({realm: realm2, policyName}))
    }, t5("common:cancel"))))));
  }
});

// build/realm-settings/NewClientPolicyForm.js
var require_NewClientPolicyForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => NewClientPolicyForm
  });
  var defaultValues2 = {
    name: "",
    description: "",
    conditions: [],
    enabled: true,
    profiles: []
  };
  function NewClientPolicyForm() {
    const {t: t5} = useTranslation("realm-settings");
    const {errors, reset: resetForm} = useForm({
      defaultValues: defaultValues2
    });
    const {realm: realm2} = useRealm();
    const {addAlert, addError} = useAlerts();
    const adminClient = useAdminClient();
    const [policies, setPolicies] = useState([]);
    const [clientProfiles, setClientProfiles] = useState([]);
    const [currentPolicy, setCurrentPolicy] = useState();
    const [
      showAddConditionsAndProfilesForm,
      setShowAddConditionsAndProfilesForm
    ] = useState(false);
    const [conditionToDelete, setConditionToDelete] = useState();
    const [profilesModalOpen, setProfilesModalOpen] = useState(false);
    const [profileToDelete, setProfileToDelete] = useState();
    const {policyName} = useParams();
    const history = useHistory();
    const form2 = useForm({mode: "onChange"});
    const {handleSubmit} = form2;
    const [key, setKey] = useState(0);
    const refresh = () => setKey(new Date().getTime());
    const formValues = form2.getValues();
    const ClientPoliciesHeader = ({
      save: save2,
      onChange,
      value
    }) => {
      const {t: t22} = useTranslation("realm-settings");
      const [toggleDisableDialog, DisableConfirm] = useConfirmDialog({
        titleKey: "realm-settings:disablePolicyConfirmTitle",
        messageKey: "realm-settings:disablePolicyConfirm",
        continueButtonLabel: "common:disable",
        onConfirm: () => {
          onChange(!value);
          save2();
        }
      });
      return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DisableConfirm, null), /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(ViewHeader, {
        titleKey: showAddConditionsAndProfilesForm || policyName ? formValues.name : t22("createPolicy"),
        divider: true,
        dropdownItems: showAddConditionsAndProfilesForm || policyName ? [
          /* @__PURE__ */ react.createElement(DropdownItem, {
            key: "delete",
            value: "delete",
            onClick: () => {
              toggleDeleteDialog();
            },
            "data-testid": "deleteClientPolicyDropdown"
          }, t22("deleteClientPolicy"))
        ] : void 0,
        isEnabled: value,
        onToggle: (value2) => {
          if (!value2) {
            toggleDisableDialog();
          } else {
            onChange(value2);
            save2();
          }
        }
      }));
    };
    useFetch(async () => {
      const [policies2, profiles] = await Promise.all([
        adminClient.clientPolicies.listPolicies(),
        adminClient.clientPolicies.listProfiles({
          includeGlobalProfiles: true
        })
      ]);
      return {policies: policies2, profiles};
    }, ({policies: policies2, profiles}) => {
      const currentPolicy2 = policies2.policies?.find((item) => item.name === policyName);
      const allClientProfiles = [
        ...profiles.globalProfiles ?? [],
        ...profiles.profiles ?? []
      ];
      setPolicies(policies2.policies ?? []);
      if (currentPolicy2) {
        setupForm(currentPolicy2);
        setClientProfiles(allClientProfiles);
        setCurrentPolicy(currentPolicy2);
        setShowAddConditionsAndProfilesForm(true);
      }
    }, [key]);
    const setupForm = (policy2) => {
      resetForm();
      Object.entries(policy2).map(([key2, value]) => {
        form2.setValue(key2, value);
      });
    };
    const policy = policies.filter((policy2) => policy2.name === policyName);
    const policyConditions = policy[0]?.conditions || [];
    const policyProfiles = policy[0]?.profiles || [];
    const serverInfo2 = useServerInfo();
    const conditionTypes = serverInfo2.componentTypes?.["org.keycloak.services.clientpolicy.condition.ClientPolicyConditionProvider"];
    const save = async () => {
      const createdForm = form2.getValues();
      const createdPolicy = {
        ...createdForm,
        profiles: [],
        conditions: []
      };
      const getAllPolicies = () => {
        const policyNameExists = policies.some((policy2) => policy2.name === createdPolicy.name);
        if (policyNameExists) {
          return policies.map((policy2) => policy2.name === createdPolicy.name ? createdPolicy : policy2);
        } else if (createdForm.name !== policyName) {
          return policies.filter((item) => item.name !== policyName).concat(createdForm);
        }
        return policies.concat(createdForm);
      };
      try {
        await adminClient.clientPolicies.updatePolicy({
          policies: getAllPolicies()
        });
        addAlert(policyName ? t5("realm-settings:updateClientPolicySuccess") : t5("realm-settings:createClientPolicySuccess"), AlertVariant.success);
        history.push(`/${realm2}/realm-settings/clientPolicies/${createdForm.name}/edit-policy`);
        setShowAddConditionsAndProfilesForm(true);
        refresh();
      } catch (error2) {
        addError("realm-settings:createClientPolicyError", error2);
      }
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: t5("deleteClientPolicyConfirmTitle"),
      messageKey: t5("deleteClientPolicyConfirm", {
        policyName
      }),
      continueButtonLabel: t5("delete"),
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        const updatedPolicies = policies.filter((policy2) => policy2.name !== policyName);
        try {
          await adminClient.clientPolicies.updatePolicy({
            policies: updatedPolicies
          });
          addAlert(t5("deleteClientPolicySuccess"), AlertVariant.success);
          history.push(toClientPolicies({realm: realm2}));
        } catch (error2) {
          addError(t5("deleteClientPolicyError"), error2);
        }
      }
    });
    const [toggleDeleteConditionDialog, DeleteConditionConfirm] = useConfirmDialog({
      titleKey: t5("deleteClientPolicyConditionConfirmTitle"),
      messageKey: t5("deleteClientPolicyConditionConfirm", {
        condition: conditionToDelete?.name
      }),
      continueButtonLabel: t5("delete"),
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        if (conditionToDelete?.name) {
          currentPolicy?.conditions?.splice(conditionToDelete.idx, 1);
          try {
            await adminClient.clientPolicies.updatePolicy({
              policies
            });
            addAlert(t5("deleteConditionSuccess"), AlertVariant.success);
            history.push(`/${realm2}/realm-settings/clientPolicies/${formValues.name}/edit-policy`);
            refresh();
          } catch (error2) {
            addError(t5("deleteConditionError"), error2);
          }
        } else {
          const updatedPolicies = policies.filter((policy2) => policy2.name !== policyName);
          try {
            await adminClient.clientPolicies.updatePolicy({
              policies: updatedPolicies
            });
            addAlert(t5("deleteClientSuccess"), AlertVariant.success);
            history.push(toClientPolicies({realm: realm2}));
          } catch (error2) {
            addError(t5("deleteClientError"), error2);
          }
        }
      }
    });
    const [toggleDeleteProfileDialog, DeleteProfileConfirm] = useConfirmDialog({
      titleKey: t5("deleteClientPolicyProfileConfirmTitle"),
      messageKey: t5("deleteClientPolicyProfileConfirm", {
        profileName: profileToDelete?.name,
        policyName
      }),
      continueButtonLabel: t5("delete"),
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        if (profileToDelete?.name) {
          currentPolicy?.profiles?.splice(profileToDelete.idx, 1);
          try {
            await adminClient.clientPolicies.updatePolicy({
              policies
            });
            addAlert(t5("deleteClientPolicyProfileSuccess"), AlertVariant.success);
            history.push(`/${realm2}/realm-settings/clientPolicies/${formValues.name}/edit-policy`);
          } catch (error2) {
            addError(t5("deleteClientPolicyProfileError"), error2);
          }
        } else {
          const updatedPolicies = policies.filter((policy2) => policy2.name !== policyName);
          try {
            await adminClient.clientPolicies.updatePolicy({
              policies: updatedPolicies
            });
            addAlert(t5("deleteClientSuccess"), AlertVariant.success);
            history.push(toClientPolicies({realm: realm2}));
          } catch (error2) {
            addError(t5("deleteClientError"), error2);
          }
        }
      }
    });
    const reset2 = () => {
      form2.setValue("name", currentPolicy?.name);
      form2.setValue("description", currentPolicy?.description);
    };
    const refreshHeader = () => {
      setKey(new Date().getTime());
    };
    const toggleModal = () => {
      setProfilesModalOpen(!profilesModalOpen);
    };
    const addProfiles = async (profiles) => {
      const createdPolicy = {
        ...currentPolicy,
        profiles: (currentPolicy?.profiles ?? []).concat(profiles),
        conditions: currentPolicy?.conditions
      };
      const index3 = policies.findIndex((policy2) => createdPolicy.name === policy2.name);
      if (index3 === -1) {
        return;
      }
      const newPolicies = [
        ...policies.slice(0, index3),
        createdPolicy,
        ...policies.slice(index3 + 1)
      ];
      try {
        await adminClient.clientPolicies.updatePolicy({
          policies: newPolicies
        });
        setPolicies(newPolicies);
        history.push(`/${realm2}/realm-settings/clientPolicies/${formValues.name}/edit-policy`);
        addAlert(t5("realm-settings:addClientProfileSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("realm-settings:addClientProfileError", error2);
      }
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConditionConfirm, null), /* @__PURE__ */ react.createElement(DeleteProfileConfirm, null), /* @__PURE__ */ react.createElement(AddClientProfileModal, {
      onConfirm: (profiles) => {
        addProfiles(profiles.map((item) => item.name));
      },
      allProfiles: policyProfiles,
      open: profilesModalOpen,
      toggleDialog: toggleModal
    }), /* @__PURE__ */ react.createElement(Controller, {
      name: "enabled",
      defaultValue: true,
      control: form2.control,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(ClientPoliciesHeader, {
        value,
        onChange,
        realmName: realm2,
        refresh: refreshHeader,
        save
      })
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      onSubmit: handleSubmit(save),
      isHorizontal: true,
      role: "view-realm",
      className: "pf-u-mt-lg"
    }, /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:name"),
      fieldId: "kc-name",
      isRequired: true,
      helperTextInvalid: t5("common:required"),
      validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register({required: true}),
      type: "text",
      id: "kc-client-profile-name",
      name: "name",
      "data-testid": "client-policy-name"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:description"),
      fieldId: "kc-description"
    }, /* @__PURE__ */ react.createElement(TextArea, {
      name: "description",
      "aria-label": t5("description"),
      ref: form2.register(),
      type: "text",
      id: "kc-client-policy-description",
      "data-testid": "client-policy-description"
    })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      variant: "primary",
      type: "submit",
      "data-testid": "saveCreatePolicy",
      isDisabled: !formValues.name
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      id: "cancelCreatePolicy",
      variant: "secondary",
      onClick: () => showAddConditionsAndProfilesForm || policyName ? reset2() : history.push(toClientPolicies({realm: realm2})),
      "data-testid": "cancelCreatePolicy"
    }, showAddConditionsAndProfilesForm ? t5("common:revert") : t5("common:cancel"))), (showAddConditionsAndProfilesForm || form2.formState.isSubmitted) && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Flex, null, /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Text, {
      className: "kc-conditions",
      component: TextVariants.h1
    }, t5("conditions"), /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings:realm-settings-help:conditions",
      fieldLabelId: "realm-settings:conditions"
    }))), /* @__PURE__ */ react.createElement(FlexItem, {
      align: {default: "alignRight"}
    }, /* @__PURE__ */ react.createElement(Button, {
      id: "addCondition",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toNewClientPolicyCondition({
          realm: realm2,
          policyName: formValues.name
        })
      }),
      variant: "link",
      className: "kc-addCondition",
      "data-testid": "addCondition",
      icon: /* @__PURE__ */ react.createElement(PlusCircleIcon, null)
    }, t5("realm-settings:addCondition")))), policyConditions.length > 0 ? /* @__PURE__ */ react.createElement(DataList, {
      "aria-label": t5("conditions"),
      isCompact: true
    }, policyConditions.map((condition, idx) => /* @__PURE__ */ react.createElement(DataListItem, {
      "aria-labelledby": "conditions-list-item",
      key: `list-item-${idx}`,
      id: condition.condition,
      "data-testid": "conditions-list-item"
    }, /* @__PURE__ */ react.createElement(DataListItemRow, {
      "data-testid": "conditions-list-row"
    }, /* @__PURE__ */ react.createElement(DataListItemCells, {
      dataListCells: [
        /* @__PURE__ */ react.createElement(DataListCell, {
          key: `name-${idx}`,
          "data-testid": "condition-type"
        }, Object.keys(condition.configuration).length !== 0 ? /* @__PURE__ */ react.createElement(Link, {
          key: condition.condition,
          "data-testid": `${condition.condition}-condition-link`,
          to: toEditClientPolicyCondition({
            realm: realm2,
            conditionName: condition.condition,
            policyName
          }),
          className: "kc-condition-link"
        }, condition.condition) : condition.condition, conditionTypes?.map((type) => type.id === condition.condition && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(HelpItem, {
          helpText: type.helpText,
          fieldLabelId: condition.condition
        }), /* @__PURE__ */ react.createElement(Button, {
          variant: "link",
          isInline: true,
          icon: /* @__PURE__ */ react.createElement(TrashIcon, {
            className: "kc-conditionType-trash-icon",
            "data-testid": `delete-${condition.condition}-condition`,
            onClick: () => {
              toggleDeleteConditionDialog();
              setConditionToDelete({
                idx,
                name: type.id
              });
            }
          })
        }))))
      ]
    }))))) : /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Divider, null), /* @__PURE__ */ react.createElement(Text, {
      className: "kc-emptyConditions",
      component: TextVariants.h6
    }, t5("realm-settings:emptyConditions")))), (showAddConditionsAndProfilesForm || form2.formState.isSubmitted) && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Flex, null, /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Text, {
      className: "kc-client-profiles",
      component: TextVariants.h1
    }, t5("clientProfiles"), /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:clientProfiles",
      fieldLabelId: "realm-settings:clientProfiles"
    }))), /* @__PURE__ */ react.createElement(FlexItem, {
      align: {default: "alignRight"}
    }, /* @__PURE__ */ react.createElement(Button, {
      id: "addClientProfile",
      variant: "link",
      className: "kc-addClientProfile",
      "data-testid": "addClientProfile",
      icon: /* @__PURE__ */ react.createElement(PlusCircleIcon, null),
      onClick: toggleModal
    }, t5("realm-settings:addClientProfile")))), policyProfiles.length > 0 ? /* @__PURE__ */ react.createElement(DataList, {
      "aria-label": t5("profiles"),
      isCompact: true
    }, policyProfiles.map((profile, idx) => /* @__PURE__ */ react.createElement(DataListItem, {
      "aria-labelledby": `${profile}-profile-list-item`,
      key: profile,
      id: `${profile}-profile-list-item`,
      "data-testid": "profile-list-item"
    }, /* @__PURE__ */ react.createElement(DataListItemRow, {
      "data-testid": "profile-list-row"
    }, /* @__PURE__ */ react.createElement(DataListItemCells, {
      dataListCells: [
        /* @__PURE__ */ react.createElement(DataListCell, {
          key: "name",
          "data-testid": "profile-name"
        }, profile && /* @__PURE__ */ react.createElement(Link, {
          key: profile,
          "data-testid": "profile-name-link",
          to: "",
          className: "kc-profile-link"
        }, profile), policyProfiles.filter((type) => type === profile).map((type) => /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(HelpItem, {
          helpText: clientProfiles.find((profile2) => type === profile2.name)?.description,
          fieldLabelId: profile
        }), /* @__PURE__ */ react.createElement(Button, {
          variant: "link",
          isInline: true,
          icon: /* @__PURE__ */ react.createElement(TrashIcon, {
            className: "kc-conditionType-trash-icon",
            "data-testid": "deleteClientProfileDropdown",
            onClick: () => {
              toggleDeleteProfileDialog();
              setProfileToDelete({
                idx,
                name: type
              });
            }
          })
        }))))
      ]
    }))))) : /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Divider, null), /* @__PURE__ */ react.createElement(Text, {
      className: "kc-emptyClientProfiles",
      component: TextVariants.h6
    }, t5("realm-settings:emptyProfiles")))))));
  }
});

// build/realm-settings/RealmSettingsSection.js
var require_RealmSettingsSection = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    EditExecutorCrumb: () => EditExecutorCrumb2,
    EditPolicyCrumb: () => EditPolicyCrumb2,
    EditProfileCrumb: () => EditProfileCrumb2,
    EditProviderCrumb: () => EditProviderCrumb7,
    NewPolicyCrumb: () => NewPolicyCrumb2,
    ToClientPolicies: () => ToClientPolicies,
    default: () => RealmSettingsSection
  });
  var EditProviderCrumb7 = () => {
    const {t: t5} = useTranslation("realm-settings");
    const {realm: realm2} = useRealm();
    return /* @__PURE__ */ react.createElement(Breadcrumb, null, /* @__PURE__ */ react.createElement(BreadcrumbItem, {
      render: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toRealmSettings({realm: realm2, tab: "keys"})
      }, t5("keys"))
    }), /* @__PURE__ */ react.createElement(BreadcrumbItem, null, t5("providers")), /* @__PURE__ */ react.createElement(BreadcrumbItem, {
      isActive: true
    }, t5("editProvider")));
  };
  var ToClientPolicies = () => {
    const {t: t5} = useTranslation("realm-settings");
    const {realm: realm2} = useRealm();
    return /* @__PURE__ */ react.createElement(BreadcrumbItem, {
      render: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toClientPolicies({realm: realm2})
      }, t5("clientPolicies"))
    });
  };
  var EditPolicyCrumb2 = () => {
    const {t: t5} = useTranslation("realm-settings");
    return /* @__PURE__ */ react.createElement(Breadcrumb, null, /* @__PURE__ */ react.createElement(ToClientPolicies, null), /* @__PURE__ */ react.createElement(BreadcrumbItem, {
      isActive: true
    }, t5("policyDetails")));
  };
  var EditProfileCrumb2 = () => {
    const {t: t5} = useTranslation("realm-settings");
    const {realm: realm2} = useRealm();
    return /* @__PURE__ */ react.createElement(Breadcrumb, null, /* @__PURE__ */ react.createElement(BreadcrumbItem, {
      render: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toClientPolicies({realm: realm2})
      }, t5("clientPolicies"))
    }), /* @__PURE__ */ react.createElement(BreadcrumbItem, {
      isActive: true
    }, t5("clientProfile")));
  };
  var EditExecutorCrumb2 = () => {
    const {t: t5} = useTranslation("realm-settings");
    const {realm: realm2} = useRealm();
    return /* @__PURE__ */ react.createElement(Breadcrumb, null, /* @__PURE__ */ react.createElement(BreadcrumbItem, {
      render: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toClientPolicies({realm: realm2})
      }, t5("clientPolicies"))
    }), /* @__PURE__ */ react.createElement(BreadcrumbItem, {
      isActive: true
    }, t5("executorDetails")));
  };
  var NewPolicyCrumb2 = () => {
    const {t: t5} = useTranslation("realm-settings");
    const {realm: realm2} = useRealm();
    return /* @__PURE__ */ react.createElement(Breadcrumb, null, /* @__PURE__ */ react.createElement(BreadcrumbItem, {
      render: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toClientPolicies({realm: realm2})
      }, t5("clientPolicies"))
    }), /* @__PURE__ */ react.createElement(BreadcrumbItem, {
      isActive: true
    }, t5("createPolicy")));
  };
  var sortByPriority = (components3) => {
    const sortedComponents = [...components3].sort((a2, b2) => {
      const priorityA = Number(a2.config?.priority);
      const priorityB = Number(b2.config?.priority);
      return (!isNaN(priorityB) ? priorityB : 0) - (!isNaN(priorityA) ? priorityA : 0);
    });
    return sortedComponents;
  };
  function RealmSettingsSection() {
    const adminClient = useAdminClient();
    const {realm: realmName} = useRealm();
    const [realm2, setRealm] = useState();
    const [realmComponents, setRealmComponents] = useState();
    const [key, setKey] = useState(0);
    const refresh = () => {
      setKey(key + 1);
    };
    useFetch(async () => {
      const realm22 = await adminClient.realms.findOne({realm: realmName});
      const realmComponents2 = await adminClient.components.find({
        type: KEY_PROVIDER_TYPE,
        realm: realmName
      });
      return {realm: realm22, realmComponents: realmComponents2};
    }, ({realm: realm22, realmComponents: realmComponents2}) => {
      setRealmComponents(sortByPriority(realmComponents2));
      setRealm(realm22);
    }, [key]);
    if (!realm2 || !realmComponents) {
      return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
    }
    return /* @__PURE__ */ react.createElement(RealmSettingsTabs, {
      realm: realm2,
      refresh,
      realmComponents
    });
  }
});

// build/realm-roles/RealmRoleTabs.js
var require_RealmRoleTabs = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => RealmRoleTabs
  });
  function RealmRoleTabs() {
    const {t: t5} = useTranslation("roles");
    const form2 = useForm({
      mode: "onChange"
    });
    const {setValue, getValues, trigger, reset: reset2} = form2;
    const history = useHistory();
    const adminClient = useAdminClient();
    const [role, setRole] = useState();
    const {id: id3, clientId} = useParams();
    const {url} = useRouteMatch();
    const {realm: realmName} = useRealm();
    const [key, setKey] = useState("");
    const refresh = () => {
      setKey(`${new Date().getTime()}`);
    };
    const {addAlert, addError} = useAlerts();
    const [open2, setOpen] = useState(false);
    const convert = (role2) => {
      const {attributes, ...rest} = role2;
      return {
        attributes: attributesToArray(attributes),
        ...rest
      };
    };
    const [realm2, setRealm] = useState();
    useFetch(async () => {
      const realm22 = await adminClient.realms.findOne({realm: realmName});
      if (!id3) {
        return {realm: realm22};
      }
      const role2 = await adminClient.roles.findOneById({id: id3});
      return {realm: realm22, role: role2};
    }, ({realm: realm22, role: role2}) => {
      if (!realm22 || !role2 && id3) {
        throw new Error(t5("common:notFound"));
      }
      if (role2) {
        const convertedRole = convert(role2);
        setRole(convertedRole);
        Object.entries(convertedRole).map((entry) => {
          setValue(entry[0], entry[1]);
        });
      }
      setRealm(realm22);
    }, [key]);
    const save = async () => {
      try {
        const values2 = getValues();
        if (values2.attributes && values2.attributes[values2.attributes.length - 1]?.key === "") {
          setValue("attributes", values2.attributes.slice(0, values2.attributes.length - 1));
        }
        if (!await trigger()) {
          return;
        }
        const {attributes, ...rest} = values2;
        let roleRepresentation = rest;
        roleRepresentation.name = roleRepresentation.name?.trim();
        if (id3) {
          if (attributes) {
            roleRepresentation.attributes = arrayToAttributes(attributes);
          }
          roleRepresentation = {
            ...omit(role, "attributes"),
            ...roleRepresentation
          };
          if (!clientId) {
            await adminClient.roles.updateById({id: id3}, roleRepresentation);
          } else {
            await adminClient.clients.updateRole({id: clientId, roleName: values2.name}, roleRepresentation);
          }
          setRole(convert(roleRepresentation));
        } else {
          let createdRole;
          if (!clientId) {
            await adminClient.roles.create(roleRepresentation);
            createdRole = await adminClient.roles.findOneByName({
              name: values2.name
            });
          } else {
            await adminClient.clients.createRole({
              id: clientId,
              name: values2.name
            });
            if (values2.description) {
              await adminClient.clients.updateRole({id: clientId, roleName: values2.name}, roleRepresentation);
            }
            createdRole = await adminClient.clients.findRole({
              id: clientId,
              roleName: values2.name
            });
          }
          if (!createdRole) {
            throw new Error(t5("common:notFound"));
          }
          setRole(convert(createdRole));
          history.push(url.substr(0, url.lastIndexOf("/") + 1) + createdRole.id + "/details");
        }
        addAlert(t5(id3 ? "roleSaveSuccess" : "roleCreated"), AlertVariant.success);
      } catch (error2) {
        addError(`roles:${id3 ? "roleSave" : "roleCreate"}Error`, error2);
      }
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "roles:roleDeleteConfirm",
      messageKey: t5("roles:roleDeleteConfirmDialog", {
        name: role?.name || t5("createRole")
      }),
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          if (!clientId) {
            await adminClient.roles.delById({id: id3});
          } else {
            await adminClient.clients.delRole({
              id: clientId,
              roleName: role.name
            });
          }
          addAlert(t5("roleDeletedSuccess"), AlertVariant.success);
          history.push(url.substr(0, url.indexOf("/roles") + "/roles".length));
        } catch (error2) {
          addError("roles:roleDeleteError", error2);
        }
      }
    });
    const dropdownItems = url.includes("associated-roles") ? [
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "delete-all-associated",
        component: "button",
        onClick: () => toggleDeleteAllAssociatedRolesDialog()
      }, t5("roles:removeAllAssociatedRoles")),
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "delete-role",
        component: "button",
        onClick: () => {
          toggleDeleteDialog();
        }
      }, t5("deleteRole"))
    ] : [
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "toggle-modal",
        "data-testid": "add-roles",
        component: "button",
        onClick: () => toggleModal()
      }, t5("addAssociatedRolesText")),
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "delete-role",
        component: "button",
        onClick: () => toggleDeleteDialog()
      }, t5("deleteRole"))
    ];
    const [
      toggleDeleteAllAssociatedRolesDialog,
      DeleteAllAssociatedRolesConfirm
    ] = useConfirmDialog({
      titleKey: t5("roles:removeAllAssociatedRoles") + "?",
      messageKey: t5("roles:removeAllAssociatedRolesConfirmDialog", {
        name: role?.name || t5("createRole")
      }),
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          const additionalRoles = await adminClient.roles.getCompositeRoles({
            id: role.id
          });
          await adminClient.roles.delCompositeRoles({id: id3}, additionalRoles);
          addAlert(t5("compositeRoleOff"), AlertVariant.success, t5("compositesRemovedAlertDescription"));
          const loc = url.replace(/\/AssociatedRoles/g, "/details");
          history.push(loc);
          refresh();
        } catch (error2) {
          addError("roles:roleDeleteError", error2);
        }
      }
    });
    const toggleModal = () => {
      setOpen(!open2);
    };
    const clientRoleRouteMatch = useRouteMatch(ClientRoleRoute.path);
    const toAssociatedRoles = () => {
      const to = clientRoleRouteMatch ? toClientRole({
        ...clientRoleRouteMatch.params,
        tab: "associated-roles"
      }) : toRealmRole({
        realm: realm2?.realm,
        id: id3,
        tab: "associated-roles"
      });
      history.push(to);
    };
    const addComposites = async (composites) => {
      try {
        await adminClient.roles.createComposite({roleId: role?.id, realm: realm2.realm}, composites);
        refresh();
        toAssociatedRoles();
        addAlert(t5("addAssociatedRolesSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("roles:addAssociatedRolesError", error2);
      }
    };
    const isDefaultRole = (name) => realm2?.defaultRole.name === name;
    if (!realm2) {
      return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
    }
    if (!role) {
      return /* @__PURE__ */ react.createElement(RealmRoleForm, {
        reset: () => reset2(role),
        form: form2,
        save,
        editMode: false
      });
    }
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(DeleteAllAssociatedRolesConfirm, null), open2 && /* @__PURE__ */ react.createElement(AssociatedRolesModal, {
      id: id3,
      toggleDialog: toggleModal,
      onConfirm: addComposites
    }), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: role.name || t5("createRole"),
      badges: [
        {
          id: "composite-role-badge",
          text: role.composite ? t5("composite") : "",
          readonly: true
        }
      ],
      subKey: id3 ? "" : "roles:roleCreateExplain",
      actionsDropdownId: "roles-actions-dropdown",
      dropdownItems,
      divider: !id3
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      className: "pf-u-p-0"
    }, id3 && /* @__PURE__ */ react.createElement(KeycloakTabs, {
      isBox: true,
      mountOnEnter: true
    }, /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "details",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:details"))
    }, /* @__PURE__ */ react.createElement(RealmRoleForm, {
      reset: () => reset2(role),
      form: form2,
      save,
      editMode: true
    })), role.composite && /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "associated-roles",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("associatedRolesText"))
    }, /* @__PURE__ */ react.createElement(AssociatedRolesTab, {
      parentRole: role,
      refresh
    })), !isDefaultRole(role.name) && /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "attributes",
      className: "kc-attributes-tab",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:attributes"))
    }, /* @__PURE__ */ react.createElement(AttributesForm, {
      form: form2,
      save,
      reset: () => reset2(role)
    })), !isDefaultRole(role.name) && /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "users-in-role",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("usersInRole"))
    }, /* @__PURE__ */ react.createElement(UsersInRoleTab, {
      "data-cy": "users-in-role-tab"
    })))));
  }
});

// build/_snowpack/pkg/moment.js
var require_moment = __commonJS((exports2, module2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => moment_default
  });
  //! moment.js
  //! version : 2.29.1
  //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  //! license : MIT
  //! momentjs.com
  var hookCallback;
  function hooks() {
    return hookCallback.apply(null, arguments);
  }
  function setHookCallback(callback) {
    hookCallback = callback;
  }
  function isArray3(input) {
    return input instanceof Array || Object.prototype.toString.call(input) === "[object Array]";
  }
  function isObject5(input) {
    return input != null && Object.prototype.toString.call(input) === "[object Object]";
  }
  function hasOwnProp(a2, b2) {
    return Object.prototype.hasOwnProperty.call(a2, b2);
  }
  function isObjectEmpty(obj) {
    if (Object.getOwnPropertyNames) {
      return Object.getOwnPropertyNames(obj).length === 0;
    } else {
      var k2;
      for (k2 in obj) {
        if (hasOwnProp(obj, k2)) {
          return false;
        }
      }
      return true;
    }
  }
  function isUndefined5(input) {
    return input === void 0;
  }
  function isNumber3(input) {
    return typeof input === "number" || Object.prototype.toString.call(input) === "[object Number]";
  }
  function isDate2(input) {
    return input instanceof Date || Object.prototype.toString.call(input) === "[object Date]";
  }
  function map2(arr, fn) {
    var res = [], i3;
    for (i3 = 0; i3 < arr.length; ++i3) {
      res.push(fn(arr[i3], i3));
    }
    return res;
  }
  function extend3(a2, b2) {
    for (var i3 in b2) {
      if (hasOwnProp(b2, i3)) {
        a2[i3] = b2[i3];
      }
    }
    if (hasOwnProp(b2, "toString")) {
      a2.toString = b2.toString;
    }
    if (hasOwnProp(b2, "valueOf")) {
      a2.valueOf = b2.valueOf;
    }
    return a2;
  }
  function createUTC(input, format3, locale2, strict) {
    return createLocalOrUTC(input, format3, locale2, strict, true).utc();
  }
  function defaultParsingFlags() {
    return {
      empty: false,
      unusedTokens: [],
      unusedInput: [],
      overflow: -2,
      charsLeftOver: 0,
      nullInput: false,
      invalidEra: null,
      invalidMonth: null,
      invalidFormat: false,
      userInvalidated: false,
      iso: false,
      parsedDateParts: [],
      era: null,
      meridiem: null,
      rfc2822: false,
      weekdayMismatch: false
    };
  }
  function getParsingFlags(m2) {
    if (m2._pf == null) {
      m2._pf = defaultParsingFlags();
    }
    return m2._pf;
  }
  var some;
  if (Array.prototype.some) {
    some = Array.prototype.some;
  } else {
    some = function(fun) {
      var t5 = Object(this), len2 = t5.length >>> 0, i3;
      for (i3 = 0; i3 < len2; i3++) {
        if (i3 in t5 && fun.call(this, t5[i3], i3, t5)) {
          return true;
        }
      }
      return false;
    };
  }
  function isValid(m2) {
    if (m2._isValid == null) {
      var flags2 = getParsingFlags(m2), parsedParts = some.call(flags2.parsedDateParts, function(i3) {
        return i3 != null;
      }), isNowValid = !isNaN(m2._d.getTime()) && flags2.overflow < 0 && !flags2.empty && !flags2.invalidEra && !flags2.invalidMonth && !flags2.invalidWeekday && !flags2.weekdayMismatch && !flags2.nullInput && !flags2.invalidFormat && !flags2.userInvalidated && (!flags2.meridiem || flags2.meridiem && parsedParts);
      if (m2._strict) {
        isNowValid = isNowValid && flags2.charsLeftOver === 0 && flags2.unusedTokens.length === 0 && flags2.bigHour === void 0;
      }
      if (Object.isFrozen == null || !Object.isFrozen(m2)) {
        m2._isValid = isNowValid;
      } else {
        return isNowValid;
      }
    }
    return m2._isValid;
  }
  function createInvalid(flags2) {
    var m2 = createUTC(NaN);
    if (flags2 != null) {
      extend3(getParsingFlags(m2), flags2);
    } else {
      getParsingFlags(m2).userInvalidated = true;
    }
    return m2;
  }
  var momentProperties = hooks.momentProperties = [];
  var updateInProgress = false;
  function copyConfig(to2, from2) {
    var i3, prop, val;
    if (!isUndefined5(from2._isAMomentObject)) {
      to2._isAMomentObject = from2._isAMomentObject;
    }
    if (!isUndefined5(from2._i)) {
      to2._i = from2._i;
    }
    if (!isUndefined5(from2._f)) {
      to2._f = from2._f;
    }
    if (!isUndefined5(from2._l)) {
      to2._l = from2._l;
    }
    if (!isUndefined5(from2._strict)) {
      to2._strict = from2._strict;
    }
    if (!isUndefined5(from2._tzm)) {
      to2._tzm = from2._tzm;
    }
    if (!isUndefined5(from2._isUTC)) {
      to2._isUTC = from2._isUTC;
    }
    if (!isUndefined5(from2._offset)) {
      to2._offset = from2._offset;
    }
    if (!isUndefined5(from2._pf)) {
      to2._pf = getParsingFlags(from2);
    }
    if (!isUndefined5(from2._locale)) {
      to2._locale = from2._locale;
    }
    if (momentProperties.length > 0) {
      for (i3 = 0; i3 < momentProperties.length; i3++) {
        prop = momentProperties[i3];
        val = from2[prop];
        if (!isUndefined5(val)) {
          to2[prop] = val;
        }
      }
    }
    return to2;
  }
  function Moment(config2) {
    copyConfig(this, config2);
    this._d = new Date(config2._d != null ? config2._d.getTime() : NaN);
    if (!this.isValid()) {
      this._d = new Date(NaN);
    }
    if (updateInProgress === false) {
      updateInProgress = true;
      hooks.updateOffset(this);
      updateInProgress = false;
    }
  }
  function isMoment(obj) {
    return obj instanceof Moment || obj != null && obj._isAMomentObject != null;
  }
  function warn3(msg) {
    if (hooks.suppressDeprecationWarnings === false && typeof console !== "undefined" && console.warn) {
      console.warn("Deprecation warning: " + msg);
    }
  }
  function deprecate(msg, fn) {
    var firstTime = true;
    return extend3(function() {
      if (hooks.deprecationHandler != null) {
        hooks.deprecationHandler(null, msg);
      }
      if (firstTime) {
        var args = [], arg, i3, key;
        for (i3 = 0; i3 < arguments.length; i3++) {
          arg = "";
          if (typeof arguments[i3] === "object") {
            arg += "\n[" + i3 + "] ";
            for (key in arguments[0]) {
              if (hasOwnProp(arguments[0], key)) {
                arg += key + ": " + arguments[0][key] + ", ";
              }
            }
            arg = arg.slice(0, -2);
          } else {
            arg = arguments[i3];
          }
          args.push(arg);
        }
        warn3(msg + "\nArguments: " + Array.prototype.slice.call(args).join("") + "\n" + new Error().stack);
        firstTime = false;
      }
      return fn.apply(this, arguments);
    }, fn);
  }
  var deprecations = {};
  function deprecateSimple(name, msg) {
    if (hooks.deprecationHandler != null) {
      hooks.deprecationHandler(name, msg);
    }
    if (!deprecations[name]) {
      warn3(msg);
      deprecations[name] = true;
    }
  }
  hooks.suppressDeprecationWarnings = false;
  hooks.deprecationHandler = null;
  function isFunction6(input) {
    return typeof Function !== "undefined" && input instanceof Function || Object.prototype.toString.call(input) === "[object Function]";
  }
  function set3(config2) {
    var prop, i3;
    for (i3 in config2) {
      if (hasOwnProp(config2, i3)) {
        prop = config2[i3];
        if (isFunction6(prop)) {
          this[i3] = prop;
        } else {
          this["_" + i3] = prop;
        }
      }
    }
    this._config = config2;
    this._dayOfMonthOrdinalParseLenient = new RegExp((this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + "|" + /\d{1,2}/.source);
  }
  function mergeConfigs(parentConfig, childConfig) {
    var res = extend3({}, parentConfig), prop;
    for (prop in childConfig) {
      if (hasOwnProp(childConfig, prop)) {
        if (isObject5(parentConfig[prop]) && isObject5(childConfig[prop])) {
          res[prop] = {};
          extend3(res[prop], parentConfig[prop]);
          extend3(res[prop], childConfig[prop]);
        } else if (childConfig[prop] != null) {
          res[prop] = childConfig[prop];
        } else {
          delete res[prop];
        }
      }
    }
    for (prop in parentConfig) {
      if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject5(parentConfig[prop])) {
        res[prop] = extend3({}, res[prop]);
      }
    }
    return res;
  }
  function Locale(config2) {
    if (config2 != null) {
      this.set(config2);
    }
  }
  var keys2;
  if (Object.keys) {
    keys2 = Object.keys;
  } else {
    keys2 = function(obj) {
      var i3, res = [];
      for (i3 in obj) {
        if (hasOwnProp(obj, i3)) {
          res.push(i3);
        }
      }
      return res;
    };
  }
  var defaultCalendar = {
    sameDay: "[Today at] LT",
    nextDay: "[Tomorrow at] LT",
    nextWeek: "dddd [at] LT",
    lastDay: "[Yesterday at] LT",
    lastWeek: "[Last] dddd [at] LT",
    sameElse: "L"
  };
  function calendar(key, mom, now4) {
    var output2 = this._calendar[key] || this._calendar["sameElse"];
    return isFunction6(output2) ? output2.call(mom, now4) : output2;
  }
  function zeroFill(number, targetLength, forceSign) {
    var absNumber = "" + Math.abs(number), zerosToFill = targetLength - absNumber.length, sign2 = number >= 0;
    return (sign2 ? forceSign ? "+" : "" : "-") + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
  }
  var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
  var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
  var formatFunctions = {};
  var formatTokenFunctions = {};
  function addFormatToken(token3, padded, ordinal2, callback) {
    var func = callback;
    if (typeof callback === "string") {
      func = function() {
        return this[callback]();
      };
    }
    if (token3) {
      formatTokenFunctions[token3] = func;
    }
    if (padded) {
      formatTokenFunctions[padded[0]] = function() {
        return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
      };
    }
    if (ordinal2) {
      formatTokenFunctions[ordinal2] = function() {
        return this.localeData().ordinal(func.apply(this, arguments), token3);
      };
    }
  }
  function removeFormattingTokens(input) {
    if (input.match(/\[[\s\S]/)) {
      return input.replace(/^\[|\]$/g, "");
    }
    return input.replace(/\\/g, "");
  }
  function makeFormatFunction(format3) {
    var array2 = format3.match(formattingTokens), i3, length;
    for (i3 = 0, length = array2.length; i3 < length; i3++) {
      if (formatTokenFunctions[array2[i3]]) {
        array2[i3] = formatTokenFunctions[array2[i3]];
      } else {
        array2[i3] = removeFormattingTokens(array2[i3]);
      }
    }
    return function(mom) {
      var output2 = "", i4;
      for (i4 = 0; i4 < length; i4++) {
        output2 += isFunction6(array2[i4]) ? array2[i4].call(mom, format3) : array2[i4];
      }
      return output2;
    };
  }
  function formatMoment(m2, format3) {
    if (!m2.isValid()) {
      return m2.localeData().invalidDate();
    }
    format3 = expandFormat(format3, m2.localeData());
    formatFunctions[format3] = formatFunctions[format3] || makeFormatFunction(format3);
    return formatFunctions[format3](m2);
  }
  function expandFormat(format3, locale2) {
    var i3 = 5;
    function replaceLongDateFormatTokens(input) {
      return locale2.longDateFormat(input) || input;
    }
    localFormattingTokens.lastIndex = 0;
    while (i3 >= 0 && localFormattingTokens.test(format3)) {
      format3 = format3.replace(localFormattingTokens, replaceLongDateFormatTokens);
      localFormattingTokens.lastIndex = 0;
      i3 -= 1;
    }
    return format3;
  }
  var defaultLongDateFormat = {
    LTS: "h:mm:ss A",
    LT: "h:mm A",
    L: "MM/DD/YYYY",
    LL: "MMMM D, YYYY",
    LLL: "MMMM D, YYYY h:mm A",
    LLLL: "dddd, MMMM D, YYYY h:mm A"
  };
  function longDateFormat(key) {
    var format3 = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()];
    if (format3 || !formatUpper) {
      return format3;
    }
    this._longDateFormat[key] = formatUpper.match(formattingTokens).map(function(tok) {
      if (tok === "MMMM" || tok === "MM" || tok === "DD" || tok === "dddd") {
        return tok.slice(1);
      }
      return tok;
    }).join("");
    return this._longDateFormat[key];
  }
  var defaultInvalidDate = "Invalid date";
  function invalidDate() {
    return this._invalidDate;
  }
  var defaultOrdinal = "%d";
  var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  function ordinal(number) {
    return this._ordinal.replace("%d", number);
  }
  var defaultRelativeTime = {
    future: "in %s",
    past: "%s ago",
    s: "a few seconds",
    ss: "%d seconds",
    m: "a minute",
    mm: "%d minutes",
    h: "an hour",
    hh: "%d hours",
    d: "a day",
    dd: "%d days",
    w: "a week",
    ww: "%d weeks",
    M: "a month",
    MM: "%d months",
    y: "a year",
    yy: "%d years"
  };
  function relativeTime(number, withoutSuffix, string2, isFuture) {
    var output2 = this._relativeTime[string2];
    return isFunction6(output2) ? output2(number, withoutSuffix, string2, isFuture) : output2.replace(/%d/i, number);
  }
  function pastFuture(diff2, output2) {
    var format3 = this._relativeTime[diff2 > 0 ? "future" : "past"];
    return isFunction6(format3) ? format3(output2) : format3.replace(/%s/i, output2);
  }
  var aliases = {};
  function addUnitAlias(unit, shorthand) {
    var lowerCase = unit.toLowerCase();
    aliases[lowerCase] = aliases[lowerCase + "s"] = aliases[shorthand] = unit;
  }
  function normalizeUnits(units) {
    return typeof units === "string" ? aliases[units] || aliases[units.toLowerCase()] : void 0;
  }
  function normalizeObjectUnits(inputObject) {
    var normalizedInput = {}, normalizedProp, prop;
    for (prop in inputObject) {
      if (hasOwnProp(inputObject, prop)) {
        normalizedProp = normalizeUnits(prop);
        if (normalizedProp) {
          normalizedInput[normalizedProp] = inputObject[prop];
        }
      }
    }
    return normalizedInput;
  }
  var priorities = {};
  function addUnitPriority(unit, priority) {
    priorities[unit] = priority;
  }
  function getPrioritizedUnits(unitsObj) {
    var units = [], u;
    for (u in unitsObj) {
      if (hasOwnProp(unitsObj, u)) {
        units.push({unit: u, priority: priorities[u]});
      }
    }
    units.sort(function(a2, b2) {
      return a2.priority - b2.priority;
    });
    return units;
  }
  function isLeapYear(year) {
    return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
  }
  function absFloor(number) {
    if (number < 0) {
      return Math.ceil(number) || 0;
    } else {
      return Math.floor(number);
    }
  }
  function toInt(argumentForCoercion) {
    var coercedNumber = +argumentForCoercion, value = 0;
    if (coercedNumber !== 0 && isFinite(coercedNumber)) {
      value = absFloor(coercedNumber);
    }
    return value;
  }
  function makeGetSet(unit, keepTime) {
    return function(value) {
      if (value != null) {
        set$12(this, unit, value);
        hooks.updateOffset(this, keepTime);
        return this;
      } else {
        return get7(this, unit);
      }
    };
  }
  function get7(mom, unit) {
    return mom.isValid() ? mom._d["get" + (mom._isUTC ? "UTC" : "") + unit]() : NaN;
  }
  function set$12(mom, unit, value) {
    if (mom.isValid() && !isNaN(value)) {
      if (unit === "FullYear" && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
        value = toInt(value);
        mom._d["set" + (mom._isUTC ? "UTC" : "") + unit](value, mom.month(), daysInMonth(value, mom.month()));
      } else {
        mom._d["set" + (mom._isUTC ? "UTC" : "") + unit](value);
      }
    }
  }
  function stringGet(units) {
    units = normalizeUnits(units);
    if (isFunction6(this[units])) {
      return this[units]();
    }
    return this;
  }
  function stringSet(units, value) {
    if (typeof units === "object") {
      units = normalizeObjectUnits(units);
      var prioritized = getPrioritizedUnits(units), i3;
      for (i3 = 0; i3 < prioritized.length; i3++) {
        this[prioritized[i3].unit](units[prioritized[i3].unit]);
      }
    } else {
      units = normalizeUnits(units);
      if (isFunction6(this[units])) {
        return this[units](value);
      }
    }
    return this;
  }
  var match1 = /\d/;
  var match2 = /\d\d/;
  var match3 = /\d{3}/;
  var match4 = /\d{4}/;
  var match6 = /[+-]?\d{6}/;
  var match1to2 = /\d\d?/;
  var match3to4 = /\d\d\d\d?/;
  var match5to6 = /\d\d\d\d\d\d?/;
  var match1to3 = /\d{1,3}/;
  var match1to4 = /\d{1,4}/;
  var match1to6 = /[+-]?\d{1,6}/;
  var matchUnsigned = /\d+/;
  var matchSigned = /[+-]?\d+/;
  var matchOffset = /Z|[+-]\d\d:?\d\d/gi;
  var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi;
  var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/;
  var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;
  var regexes;
  regexes = {};
  function addRegexToken(token3, regex, strictRegex) {
    regexes[token3] = isFunction6(regex) ? regex : function(isStrict, localeData2) {
      return isStrict && strictRegex ? strictRegex : regex;
    };
  }
  function getParseRegexForToken(token3, config2) {
    if (!hasOwnProp(regexes, token3)) {
      return new RegExp(unescapeFormat(token3));
    }
    return regexes[token3](config2._strict, config2._locale);
  }
  function unescapeFormat(s2) {
    return regexEscape2(s2.replace("\\", "").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function(matched, p1, p2, p3, p4) {
      return p1 || p2 || p3 || p4;
    }));
  }
  function regexEscape2(s2) {
    return s2.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
  }
  var tokens = {};
  function addParseToken(token3, callback) {
    var i3, func = callback;
    if (typeof token3 === "string") {
      token3 = [token3];
    }
    if (isNumber3(callback)) {
      func = function(input, array2) {
        array2[callback] = toInt(input);
      };
    }
    for (i3 = 0; i3 < token3.length; i3++) {
      tokens[token3[i3]] = func;
    }
  }
  function addWeekParseToken(token3, callback) {
    addParseToken(token3, function(input, array2, config2, token4) {
      config2._w = config2._w || {};
      callback(input, config2._w, config2, token4);
    });
  }
  function addTimeToArrayFromToken(token3, input, config2) {
    if (input != null && hasOwnProp(tokens, token3)) {
      tokens[token3](input, config2._a, config2, token3);
    }
  }
  var YEAR = 0;
  var MONTH = 1;
  var DATE = 2;
  var HOUR = 3;
  var MINUTE = 4;
  var SECOND = 5;
  var MILLISECOND = 6;
  var WEEK = 7;
  var WEEKDAY = 8;
  function mod(n3, x2) {
    return (n3 % x2 + x2) % x2;
  }
  var indexOf;
  if (Array.prototype.indexOf) {
    indexOf = Array.prototype.indexOf;
  } else {
    indexOf = function(o) {
      var i3;
      for (i3 = 0; i3 < this.length; ++i3) {
        if (this[i3] === o) {
          return i3;
        }
      }
      return -1;
    };
  }
  function daysInMonth(year, month) {
    if (isNaN(year) || isNaN(month)) {
      return NaN;
    }
    var modMonth = mod(month, 12);
    year += (month - modMonth) / 12;
    return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2;
  }
  addFormatToken("M", ["MM", 2], "Mo", function() {
    return this.month() + 1;
  });
  addFormatToken("MMM", 0, 0, function(format3) {
    return this.localeData().monthsShort(this, format3);
  });
  addFormatToken("MMMM", 0, 0, function(format3) {
    return this.localeData().months(this, format3);
  });
  addUnitAlias("month", "M");
  addUnitPriority("month", 8);
  addRegexToken("M", match1to2);
  addRegexToken("MM", match1to2, match2);
  addRegexToken("MMM", function(isStrict, locale2) {
    return locale2.monthsShortRegex(isStrict);
  });
  addRegexToken("MMMM", function(isStrict, locale2) {
    return locale2.monthsRegex(isStrict);
  });
  addParseToken(["M", "MM"], function(input, array2) {
    array2[MONTH] = toInt(input) - 1;
  });
  addParseToken(["MMM", "MMMM"], function(input, array2, config2, token3) {
    var month = config2._locale.monthsParse(input, token3, config2._strict);
    if (month != null) {
      array2[MONTH] = month;
    } else {
      getParsingFlags(config2).invalidMonth = input;
    }
  });
  var defaultLocaleMonths = "January_February_March_April_May_June_July_August_September_October_November_December".split("_");
  var defaultLocaleMonthsShort = "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_");
  var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
  var defaultMonthsShortRegex = matchWord;
  var defaultMonthsRegex = matchWord;
  function localeMonths(m2, format3) {
    if (!m2) {
      return isArray3(this._months) ? this._months : this._months["standalone"];
    }
    return isArray3(this._months) ? this._months[m2.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format3) ? "format" : "standalone"][m2.month()];
  }
  function localeMonthsShort(m2, format3) {
    if (!m2) {
      return isArray3(this._monthsShort) ? this._monthsShort : this._monthsShort["standalone"];
    }
    return isArray3(this._monthsShort) ? this._monthsShort[m2.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format3) ? "format" : "standalone"][m2.month()];
  }
  function handleStrictParse(monthName, format3, strict) {
    var i3, ii2, mom, llc = monthName.toLocaleLowerCase();
    if (!this._monthsParse) {
      this._monthsParse = [];
      this._longMonthsParse = [];
      this._shortMonthsParse = [];
      for (i3 = 0; i3 < 12; ++i3) {
        mom = createUTC([2e3, i3]);
        this._shortMonthsParse[i3] = this.monthsShort(mom, "").toLocaleLowerCase();
        this._longMonthsParse[i3] = this.months(mom, "").toLocaleLowerCase();
      }
    }
    if (strict) {
      if (format3 === "MMM") {
        ii2 = indexOf.call(this._shortMonthsParse, llc);
        return ii2 !== -1 ? ii2 : null;
      } else {
        ii2 = indexOf.call(this._longMonthsParse, llc);
        return ii2 !== -1 ? ii2 : null;
      }
    } else {
      if (format3 === "MMM") {
        ii2 = indexOf.call(this._shortMonthsParse, llc);
        if (ii2 !== -1) {
          return ii2;
        }
        ii2 = indexOf.call(this._longMonthsParse, llc);
        return ii2 !== -1 ? ii2 : null;
      } else {
        ii2 = indexOf.call(this._longMonthsParse, llc);
        if (ii2 !== -1) {
          return ii2;
        }
        ii2 = indexOf.call(this._shortMonthsParse, llc);
        return ii2 !== -1 ? ii2 : null;
      }
    }
  }
  function localeMonthsParse(monthName, format3, strict) {
    var i3, mom, regex;
    if (this._monthsParseExact) {
      return handleStrictParse.call(this, monthName, format3, strict);
    }
    if (!this._monthsParse) {
      this._monthsParse = [];
      this._longMonthsParse = [];
      this._shortMonthsParse = [];
    }
    for (i3 = 0; i3 < 12; i3++) {
      mom = createUTC([2e3, i3]);
      if (strict && !this._longMonthsParse[i3]) {
        this._longMonthsParse[i3] = new RegExp("^" + this.months(mom, "").replace(".", "") + "$", "i");
        this._shortMonthsParse[i3] = new RegExp("^" + this.monthsShort(mom, "").replace(".", "") + "$", "i");
      }
      if (!strict && !this._monthsParse[i3]) {
        regex = "^" + this.months(mom, "") + "|^" + this.monthsShort(mom, "");
        this._monthsParse[i3] = new RegExp(regex.replace(".", ""), "i");
      }
      if (strict && format3 === "MMMM" && this._longMonthsParse[i3].test(monthName)) {
        return i3;
      } else if (strict && format3 === "MMM" && this._shortMonthsParse[i3].test(monthName)) {
        return i3;
      } else if (!strict && this._monthsParse[i3].test(monthName)) {
        return i3;
      }
    }
  }
  function setMonth(mom, value) {
    var dayOfMonth;
    if (!mom.isValid()) {
      return mom;
    }
    if (typeof value === "string") {
      if (/^\d+$/.test(value)) {
        value = toInt(value);
      } else {
        value = mom.localeData().monthsParse(value);
        if (!isNumber3(value)) {
          return mom;
        }
      }
    }
    dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
    mom._d["set" + (mom._isUTC ? "UTC" : "") + "Month"](value, dayOfMonth);
    return mom;
  }
  function getSetMonth(value) {
    if (value != null) {
      setMonth(this, value);
      hooks.updateOffset(this, true);
      return this;
    } else {
      return get7(this, "Month");
    }
  }
  function getDaysInMonth() {
    return daysInMonth(this.year(), this.month());
  }
  function monthsShortRegex(isStrict) {
    if (this._monthsParseExact) {
      if (!hasOwnProp(this, "_monthsRegex")) {
        computeMonthsParse.call(this);
      }
      if (isStrict) {
        return this._monthsShortStrictRegex;
      } else {
        return this._monthsShortRegex;
      }
    } else {
      if (!hasOwnProp(this, "_monthsShortRegex")) {
        this._monthsShortRegex = defaultMonthsShortRegex;
      }
      return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex;
    }
  }
  function monthsRegex(isStrict) {
    if (this._monthsParseExact) {
      if (!hasOwnProp(this, "_monthsRegex")) {
        computeMonthsParse.call(this);
      }
      if (isStrict) {
        return this._monthsStrictRegex;
      } else {
        return this._monthsRegex;
      }
    } else {
      if (!hasOwnProp(this, "_monthsRegex")) {
        this._monthsRegex = defaultMonthsRegex;
      }
      return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex;
    }
  }
  function computeMonthsParse() {
    function cmpLenRev(a2, b2) {
      return b2.length - a2.length;
    }
    var shortPieces = [], longPieces = [], mixedPieces = [], i3, mom;
    for (i3 = 0; i3 < 12; i3++) {
      mom = createUTC([2e3, i3]);
      shortPieces.push(this.monthsShort(mom, ""));
      longPieces.push(this.months(mom, ""));
      mixedPieces.push(this.months(mom, ""));
      mixedPieces.push(this.monthsShort(mom, ""));
    }
    shortPieces.sort(cmpLenRev);
    longPieces.sort(cmpLenRev);
    mixedPieces.sort(cmpLenRev);
    for (i3 = 0; i3 < 12; i3++) {
      shortPieces[i3] = regexEscape2(shortPieces[i3]);
      longPieces[i3] = regexEscape2(longPieces[i3]);
    }
    for (i3 = 0; i3 < 24; i3++) {
      mixedPieces[i3] = regexEscape2(mixedPieces[i3]);
    }
    this._monthsRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i");
    this._monthsShortRegex = this._monthsRegex;
    this._monthsStrictRegex = new RegExp("^(" + longPieces.join("|") + ")", "i");
    this._monthsShortStrictRegex = new RegExp("^(" + shortPieces.join("|") + ")", "i");
  }
  addFormatToken("Y", 0, 0, function() {
    var y3 = this.year();
    return y3 <= 9999 ? zeroFill(y3, 4) : "+" + y3;
  });
  addFormatToken(0, ["YY", 2], 0, function() {
    return this.year() % 100;
  });
  addFormatToken(0, ["YYYY", 4], 0, "year");
  addFormatToken(0, ["YYYYY", 5], 0, "year");
  addFormatToken(0, ["YYYYYY", 6, true], 0, "year");
  addUnitAlias("year", "y");
  addUnitPriority("year", 1);
  addRegexToken("Y", matchSigned);
  addRegexToken("YY", match1to2, match2);
  addRegexToken("YYYY", match1to4, match4);
  addRegexToken("YYYYY", match1to6, match6);
  addRegexToken("YYYYYY", match1to6, match6);
  addParseToken(["YYYYY", "YYYYYY"], YEAR);
  addParseToken("YYYY", function(input, array2) {
    array2[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  });
  addParseToken("YY", function(input, array2) {
    array2[YEAR] = hooks.parseTwoDigitYear(input);
  });
  addParseToken("Y", function(input, array2) {
    array2[YEAR] = parseInt(input, 10);
  });
  function daysInYear(year) {
    return isLeapYear(year) ? 366 : 365;
  }
  hooks.parseTwoDigitYear = function(input) {
    return toInt(input) + (toInt(input) > 68 ? 1900 : 2e3);
  };
  var getSetYear = makeGetSet("FullYear", true);
  function getIsLeapYear() {
    return isLeapYear(this.year());
  }
  function createDate(y3, m2, d2, h2, M2, s2, ms) {
    var date;
    if (y3 < 100 && y3 >= 0) {
      date = new Date(y3 + 400, m2, d2, h2, M2, s2, ms);
      if (isFinite(date.getFullYear())) {
        date.setFullYear(y3);
      }
    } else {
      date = new Date(y3, m2, d2, h2, M2, s2, ms);
    }
    return date;
  }
  function createUTCDate(y3) {
    var date, args;
    if (y3 < 100 && y3 >= 0) {
      args = Array.prototype.slice.call(arguments);
      args[0] = y3 + 400;
      date = new Date(Date.UTC.apply(null, args));
      if (isFinite(date.getUTCFullYear())) {
        date.setUTCFullYear(y3);
      }
    } else {
      date = new Date(Date.UTC.apply(null, arguments));
    }
    return date;
  }
  function firstWeekOffset(year, dow, doy) {
    var fwd = 7 + dow - doy, fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
    return -fwdlw + fwd - 1;
  }
  function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
    var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear;
    if (dayOfYear <= 0) {
      resYear = year - 1;
      resDayOfYear = daysInYear(resYear) + dayOfYear;
    } else if (dayOfYear > daysInYear(year)) {
      resYear = year + 1;
      resDayOfYear = dayOfYear - daysInYear(year);
    } else {
      resYear = year;
      resDayOfYear = dayOfYear;
    }
    return {
      year: resYear,
      dayOfYear: resDayOfYear
    };
  }
  function weekOfYear(mom, dow, doy) {
    var weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear;
    if (week < 1) {
      resYear = mom.year() - 1;
      resWeek = week + weeksInYear(resYear, dow, doy);
    } else if (week > weeksInYear(mom.year(), dow, doy)) {
      resWeek = week - weeksInYear(mom.year(), dow, doy);
      resYear = mom.year() + 1;
    } else {
      resYear = mom.year();
      resWeek = week;
    }
    return {
      week: resWeek,
      year: resYear
    };
  }
  function weeksInYear(year, dow, doy) {
    var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
    return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  }
  addFormatToken("w", ["ww", 2], "wo", "week");
  addFormatToken("W", ["WW", 2], "Wo", "isoWeek");
  addUnitAlias("week", "w");
  addUnitAlias("isoWeek", "W");
  addUnitPriority("week", 5);
  addUnitPriority("isoWeek", 5);
  addRegexToken("w", match1to2);
  addRegexToken("ww", match1to2, match2);
  addRegexToken("W", match1to2);
  addRegexToken("WW", match1to2, match2);
  addWeekParseToken(["w", "ww", "W", "WW"], function(input, week, config2, token3) {
    week[token3.substr(0, 1)] = toInt(input);
  });
  function localeWeek(mom) {
    return weekOfYear(mom, this._week.dow, this._week.doy).week;
  }
  var defaultLocaleWeek = {
    dow: 0,
    doy: 6
  };
  function localeFirstDayOfWeek() {
    return this._week.dow;
  }
  function localeFirstDayOfYear() {
    return this._week.doy;
  }
  function getSetWeek(input) {
    var week = this.localeData().week(this);
    return input == null ? week : this.add((input - week) * 7, "d");
  }
  function getSetISOWeek(input) {
    var week = weekOfYear(this, 1, 4).week;
    return input == null ? week : this.add((input - week) * 7, "d");
  }
  addFormatToken("d", 0, "do", "day");
  addFormatToken("dd", 0, 0, function(format3) {
    return this.localeData().weekdaysMin(this, format3);
  });
  addFormatToken("ddd", 0, 0, function(format3) {
    return this.localeData().weekdaysShort(this, format3);
  });
  addFormatToken("dddd", 0, 0, function(format3) {
    return this.localeData().weekdays(this, format3);
  });
  addFormatToken("e", 0, 0, "weekday");
  addFormatToken("E", 0, 0, "isoWeekday");
  addUnitAlias("day", "d");
  addUnitAlias("weekday", "e");
  addUnitAlias("isoWeekday", "E");
  addUnitPriority("day", 11);
  addUnitPriority("weekday", 11);
  addUnitPriority("isoWeekday", 11);
  addRegexToken("d", match1to2);
  addRegexToken("e", match1to2);
  addRegexToken("E", match1to2);
  addRegexToken("dd", function(isStrict, locale2) {
    return locale2.weekdaysMinRegex(isStrict);
  });
  addRegexToken("ddd", function(isStrict, locale2) {
    return locale2.weekdaysShortRegex(isStrict);
  });
  addRegexToken("dddd", function(isStrict, locale2) {
    return locale2.weekdaysRegex(isStrict);
  });
  addWeekParseToken(["dd", "ddd", "dddd"], function(input, week, config2, token3) {
    var weekday = config2._locale.weekdaysParse(input, token3, config2._strict);
    if (weekday != null) {
      week.d = weekday;
    } else {
      getParsingFlags(config2).invalidWeekday = input;
    }
  });
  addWeekParseToken(["d", "e", "E"], function(input, week, config2, token3) {
    week[token3] = toInt(input);
  });
  function parseWeekday(input, locale2) {
    if (typeof input !== "string") {
      return input;
    }
    if (!isNaN(input)) {
      return parseInt(input, 10);
    }
    input = locale2.weekdaysParse(input);
    if (typeof input === "number") {
      return input;
    }
    return null;
  }
  function parseIsoWeekday(input, locale2) {
    if (typeof input === "string") {
      return locale2.weekdaysParse(input) % 7 || 7;
    }
    return isNaN(input) ? null : input;
  }
  function shiftWeekdays(ws, n3) {
    return ws.slice(n3, 7).concat(ws.slice(0, n3));
  }
  var defaultLocaleWeekdays = "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_");
  var defaultLocaleWeekdaysShort = "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_");
  var defaultLocaleWeekdaysMin = "Su_Mo_Tu_We_Th_Fr_Sa".split("_");
  var defaultWeekdaysRegex = matchWord;
  var defaultWeekdaysShortRegex = matchWord;
  var defaultWeekdaysMinRegex = matchWord;
  function localeWeekdays(m2, format3) {
    var weekdays = isArray3(this._weekdays) ? this._weekdays : this._weekdays[m2 && m2 !== true && this._weekdays.isFormat.test(format3) ? "format" : "standalone"];
    return m2 === true ? shiftWeekdays(weekdays, this._week.dow) : m2 ? weekdays[m2.day()] : weekdays;
  }
  function localeWeekdaysShort(m2) {
    return m2 === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m2 ? this._weekdaysShort[m2.day()] : this._weekdaysShort;
  }
  function localeWeekdaysMin(m2) {
    return m2 === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m2 ? this._weekdaysMin[m2.day()] : this._weekdaysMin;
  }
  function handleStrictParse$1(weekdayName, format3, strict) {
    var i3, ii2, mom, llc = weekdayName.toLocaleLowerCase();
    if (!this._weekdaysParse) {
      this._weekdaysParse = [];
      this._shortWeekdaysParse = [];
      this._minWeekdaysParse = [];
      for (i3 = 0; i3 < 7; ++i3) {
        mom = createUTC([2e3, 1]).day(i3);
        this._minWeekdaysParse[i3] = this.weekdaysMin(mom, "").toLocaleLowerCase();
        this._shortWeekdaysParse[i3] = this.weekdaysShort(mom, "").toLocaleLowerCase();
        this._weekdaysParse[i3] = this.weekdays(mom, "").toLocaleLowerCase();
      }
    }
    if (strict) {
      if (format3 === "dddd") {
        ii2 = indexOf.call(this._weekdaysParse, llc);
        return ii2 !== -1 ? ii2 : null;
      } else if (format3 === "ddd") {
        ii2 = indexOf.call(this._shortWeekdaysParse, llc);
        return ii2 !== -1 ? ii2 : null;
      } else {
        ii2 = indexOf.call(this._minWeekdaysParse, llc);
        return ii2 !== -1 ? ii2 : null;
      }
    } else {
      if (format3 === "dddd") {
        ii2 = indexOf.call(this._weekdaysParse, llc);
        if (ii2 !== -1) {
          return ii2;
        }
        ii2 = indexOf.call(this._shortWeekdaysParse, llc);
        if (ii2 !== -1) {
          return ii2;
        }
        ii2 = indexOf.call(this._minWeekdaysParse, llc);
        return ii2 !== -1 ? ii2 : null;
      } else if (format3 === "ddd") {
        ii2 = indexOf.call(this._shortWeekdaysParse, llc);
        if (ii2 !== -1) {
          return ii2;
        }
        ii2 = indexOf.call(this._weekdaysParse, llc);
        if (ii2 !== -1) {
          return ii2;
        }
        ii2 = indexOf.call(this._minWeekdaysParse, llc);
        return ii2 !== -1 ? ii2 : null;
      } else {
        ii2 = indexOf.call(this._minWeekdaysParse, llc);
        if (ii2 !== -1) {
          return ii2;
        }
        ii2 = indexOf.call(this._weekdaysParse, llc);
        if (ii2 !== -1) {
          return ii2;
        }
        ii2 = indexOf.call(this._shortWeekdaysParse, llc);
        return ii2 !== -1 ? ii2 : null;
      }
    }
  }
  function localeWeekdaysParse(weekdayName, format3, strict) {
    var i3, mom, regex;
    if (this._weekdaysParseExact) {
      return handleStrictParse$1.call(this, weekdayName, format3, strict);
    }
    if (!this._weekdaysParse) {
      this._weekdaysParse = [];
      this._minWeekdaysParse = [];
      this._shortWeekdaysParse = [];
      this._fullWeekdaysParse = [];
    }
    for (i3 = 0; i3 < 7; i3++) {
      mom = createUTC([2e3, 1]).day(i3);
      if (strict && !this._fullWeekdaysParse[i3]) {
        this._fullWeekdaysParse[i3] = new RegExp("^" + this.weekdays(mom, "").replace(".", "\\.?") + "$", "i");
        this._shortWeekdaysParse[i3] = new RegExp("^" + this.weekdaysShort(mom, "").replace(".", "\\.?") + "$", "i");
        this._minWeekdaysParse[i3] = new RegExp("^" + this.weekdaysMin(mom, "").replace(".", "\\.?") + "$", "i");
      }
      if (!this._weekdaysParse[i3]) {
        regex = "^" + this.weekdays(mom, "") + "|^" + this.weekdaysShort(mom, "") + "|^" + this.weekdaysMin(mom, "");
        this._weekdaysParse[i3] = new RegExp(regex.replace(".", ""), "i");
      }
      if (strict && format3 === "dddd" && this._fullWeekdaysParse[i3].test(weekdayName)) {
        return i3;
      } else if (strict && format3 === "ddd" && this._shortWeekdaysParse[i3].test(weekdayName)) {
        return i3;
      } else if (strict && format3 === "dd" && this._minWeekdaysParse[i3].test(weekdayName)) {
        return i3;
      } else if (!strict && this._weekdaysParse[i3].test(weekdayName)) {
        return i3;
      }
    }
  }
  function getSetDayOfWeek(input) {
    if (!this.isValid()) {
      return input != null ? this : NaN;
    }
    var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
    if (input != null) {
      input = parseWeekday(input, this.localeData());
      return this.add(input - day, "d");
    } else {
      return day;
    }
  }
  function getSetLocaleDayOfWeek(input) {
    if (!this.isValid()) {
      return input != null ? this : NaN;
    }
    var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
    return input == null ? weekday : this.add(input - weekday, "d");
  }
  function getSetISODayOfWeek(input) {
    if (!this.isValid()) {
      return input != null ? this : NaN;
    }
    if (input != null) {
      var weekday = parseIsoWeekday(input, this.localeData());
      return this.day(this.day() % 7 ? weekday : weekday - 7);
    } else {
      return this.day() || 7;
    }
  }
  function weekdaysRegex(isStrict) {
    if (this._weekdaysParseExact) {
      if (!hasOwnProp(this, "_weekdaysRegex")) {
        computeWeekdaysParse.call(this);
      }
      if (isStrict) {
        return this._weekdaysStrictRegex;
      } else {
        return this._weekdaysRegex;
      }
    } else {
      if (!hasOwnProp(this, "_weekdaysRegex")) {
        this._weekdaysRegex = defaultWeekdaysRegex;
      }
      return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex;
    }
  }
  function weekdaysShortRegex(isStrict) {
    if (this._weekdaysParseExact) {
      if (!hasOwnProp(this, "_weekdaysRegex")) {
        computeWeekdaysParse.call(this);
      }
      if (isStrict) {
        return this._weekdaysShortStrictRegex;
      } else {
        return this._weekdaysShortRegex;
      }
    } else {
      if (!hasOwnProp(this, "_weekdaysShortRegex")) {
        this._weekdaysShortRegex = defaultWeekdaysShortRegex;
      }
      return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
    }
  }
  function weekdaysMinRegex(isStrict) {
    if (this._weekdaysParseExact) {
      if (!hasOwnProp(this, "_weekdaysRegex")) {
        computeWeekdaysParse.call(this);
      }
      if (isStrict) {
        return this._weekdaysMinStrictRegex;
      } else {
        return this._weekdaysMinRegex;
      }
    } else {
      if (!hasOwnProp(this, "_weekdaysMinRegex")) {
        this._weekdaysMinRegex = defaultWeekdaysMinRegex;
      }
      return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
    }
  }
  function computeWeekdaysParse() {
    function cmpLenRev(a2, b2) {
      return b2.length - a2.length;
    }
    var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i3, mom, minp, shortp, longp;
    for (i3 = 0; i3 < 7; i3++) {
      mom = createUTC([2e3, 1]).day(i3);
      minp = regexEscape2(this.weekdaysMin(mom, ""));
      shortp = regexEscape2(this.weekdaysShort(mom, ""));
      longp = regexEscape2(this.weekdays(mom, ""));
      minPieces.push(minp);
      shortPieces.push(shortp);
      longPieces.push(longp);
      mixedPieces.push(minp);
      mixedPieces.push(shortp);
      mixedPieces.push(longp);
    }
    minPieces.sort(cmpLenRev);
    shortPieces.sort(cmpLenRev);
    longPieces.sort(cmpLenRev);
    mixedPieces.sort(cmpLenRev);
    this._weekdaysRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i");
    this._weekdaysShortRegex = this._weekdaysRegex;
    this._weekdaysMinRegex = this._weekdaysRegex;
    this._weekdaysStrictRegex = new RegExp("^(" + longPieces.join("|") + ")", "i");
    this._weekdaysShortStrictRegex = new RegExp("^(" + shortPieces.join("|") + ")", "i");
    this._weekdaysMinStrictRegex = new RegExp("^(" + minPieces.join("|") + ")", "i");
  }
  function hFormat() {
    return this.hours() % 12 || 12;
  }
  function kFormat() {
    return this.hours() || 24;
  }
  addFormatToken("H", ["HH", 2], 0, "hour");
  addFormatToken("h", ["hh", 2], 0, hFormat);
  addFormatToken("k", ["kk", 2], 0, kFormat);
  addFormatToken("hmm", 0, 0, function() {
    return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  });
  addFormatToken("hmmss", 0, 0, function() {
    return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
  });
  addFormatToken("Hmm", 0, 0, function() {
    return "" + this.hours() + zeroFill(this.minutes(), 2);
  });
  addFormatToken("Hmmss", 0, 0, function() {
    return "" + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
  });
  function meridiem(token3, lowercase) {
    addFormatToken(token3, 0, 0, function() {
      return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
    });
  }
  meridiem("a", true);
  meridiem("A", false);
  addUnitAlias("hour", "h");
  addUnitPriority("hour", 13);
  function matchMeridiem(isStrict, locale2) {
    return locale2._meridiemParse;
  }
  addRegexToken("a", matchMeridiem);
  addRegexToken("A", matchMeridiem);
  addRegexToken("H", match1to2);
  addRegexToken("h", match1to2);
  addRegexToken("k", match1to2);
  addRegexToken("HH", match1to2, match2);
  addRegexToken("hh", match1to2, match2);
  addRegexToken("kk", match1to2, match2);
  addRegexToken("hmm", match3to4);
  addRegexToken("hmmss", match5to6);
  addRegexToken("Hmm", match3to4);
  addRegexToken("Hmmss", match5to6);
  addParseToken(["H", "HH"], HOUR);
  addParseToken(["k", "kk"], function(input, array2, config2) {
    var kInput = toInt(input);
    array2[HOUR] = kInput === 24 ? 0 : kInput;
  });
  addParseToken(["a", "A"], function(input, array2, config2) {
    config2._isPm = config2._locale.isPM(input);
    config2._meridiem = input;
  });
  addParseToken(["h", "hh"], function(input, array2, config2) {
    array2[HOUR] = toInt(input);
    getParsingFlags(config2).bigHour = true;
  });
  addParseToken("hmm", function(input, array2, config2) {
    var pos = input.length - 2;
    array2[HOUR] = toInt(input.substr(0, pos));
    array2[MINUTE] = toInt(input.substr(pos));
    getParsingFlags(config2).bigHour = true;
  });
  addParseToken("hmmss", function(input, array2, config2) {
    var pos1 = input.length - 4, pos2 = input.length - 2;
    array2[HOUR] = toInt(input.substr(0, pos1));
    array2[MINUTE] = toInt(input.substr(pos1, 2));
    array2[SECOND] = toInt(input.substr(pos2));
    getParsingFlags(config2).bigHour = true;
  });
  addParseToken("Hmm", function(input, array2, config2) {
    var pos = input.length - 2;
    array2[HOUR] = toInt(input.substr(0, pos));
    array2[MINUTE] = toInt(input.substr(pos));
  });
  addParseToken("Hmmss", function(input, array2, config2) {
    var pos1 = input.length - 4, pos2 = input.length - 2;
    array2[HOUR] = toInt(input.substr(0, pos1));
    array2[MINUTE] = toInt(input.substr(pos1, 2));
    array2[SECOND] = toInt(input.substr(pos2));
  });
  function localeIsPM(input) {
    return (input + "").toLowerCase().charAt(0) === "p";
  }
  var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
  var getSetHour = makeGetSet("Hours", true);
  function localeMeridiem(hours2, minutes2, isLower2) {
    if (hours2 > 11) {
      return isLower2 ? "pm" : "PM";
    } else {
      return isLower2 ? "am" : "AM";
    }
  }
  var baseConfig = {
    calendar: defaultCalendar,
    longDateFormat: defaultLongDateFormat,
    invalidDate: defaultInvalidDate,
    ordinal: defaultOrdinal,
    dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
    relativeTime: defaultRelativeTime,
    months: defaultLocaleMonths,
    monthsShort: defaultLocaleMonthsShort,
    week: defaultLocaleWeek,
    weekdays: defaultLocaleWeekdays,
    weekdaysMin: defaultLocaleWeekdaysMin,
    weekdaysShort: defaultLocaleWeekdaysShort,
    meridiemParse: defaultLocaleMeridiemParse
  };
  var locales = {};
  var localeFamilies = {};
  var globalLocale;
  function commonPrefix(arr1, arr2) {
    var i3, minl = Math.min(arr1.length, arr2.length);
    for (i3 = 0; i3 < minl; i3 += 1) {
      if (arr1[i3] !== arr2[i3]) {
        return i3;
      }
    }
    return minl;
  }
  function normalizeLocale(key) {
    return key ? key.toLowerCase().replace("_", "-") : key;
  }
  function chooseLocale(names) {
    var i3 = 0, j, next, locale2, split2;
    while (i3 < names.length) {
      split2 = normalizeLocale(names[i3]).split("-");
      j = split2.length;
      next = normalizeLocale(names[i3 + 1]);
      next = next ? next.split("-") : null;
      while (j > 0) {
        locale2 = loadLocale(split2.slice(0, j).join("-"));
        if (locale2) {
          return locale2;
        }
        if (next && next.length >= j && commonPrefix(split2, next) >= j - 1) {
          break;
        }
        j--;
      }
      i3++;
    }
    return globalLocale;
  }
  function loadLocale(name) {
    var oldLocale = null, aliasedRequire;
    if (locales[name] === void 0 && typeof module2 !== "undefined" && module2 && module2.exports) {
      try {
        oldLocale = globalLocale._abbr;
        aliasedRequire = require;
        aliasedRequire("./locale/" + name);
        getSetGlobalLocale(oldLocale);
      } catch (e2) {
        locales[name] = null;
      }
    }
    return locales[name];
  }
  function getSetGlobalLocale(key, values2) {
    var data2;
    if (key) {
      if (isUndefined5(values2)) {
        data2 = getLocale(key);
      } else {
        data2 = defineLocale(key, values2);
      }
      if (data2) {
        globalLocale = data2;
      } else {
        if (typeof console !== "undefined" && console.warn) {
          console.warn("Locale " + key + " not found. Did you forget to load it?");
        }
      }
    }
    return globalLocale._abbr;
  }
  function defineLocale(name, config2) {
    if (config2 !== null) {
      var locale2, parentConfig = baseConfig;
      config2.abbr = name;
      if (locales[name] != null) {
        deprecateSimple("defineLocaleOverride", "use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info.");
        parentConfig = locales[name]._config;
      } else if (config2.parentLocale != null) {
        if (locales[config2.parentLocale] != null) {
          parentConfig = locales[config2.parentLocale]._config;
        } else {
          locale2 = loadLocale(config2.parentLocale);
          if (locale2 != null) {
            parentConfig = locale2._config;
          } else {
            if (!localeFamilies[config2.parentLocale]) {
              localeFamilies[config2.parentLocale] = [];
            }
            localeFamilies[config2.parentLocale].push({
              name,
              config: config2
            });
            return null;
          }
        }
      }
      locales[name] = new Locale(mergeConfigs(parentConfig, config2));
      if (localeFamilies[name]) {
        localeFamilies[name].forEach(function(x2) {
          defineLocale(x2.name, x2.config);
        });
      }
      getSetGlobalLocale(name);
      return locales[name];
    } else {
      delete locales[name];
      return null;
    }
  }
  function updateLocale(name, config2) {
    if (config2 != null) {
      var locale2, tmpLocale, parentConfig = baseConfig;
      if (locales[name] != null && locales[name].parentLocale != null) {
        locales[name].set(mergeConfigs(locales[name]._config, config2));
      } else {
        tmpLocale = loadLocale(name);
        if (tmpLocale != null) {
          parentConfig = tmpLocale._config;
        }
        config2 = mergeConfigs(parentConfig, config2);
        if (tmpLocale == null) {
          config2.abbr = name;
        }
        locale2 = new Locale(config2);
        locale2.parentLocale = locales[name];
        locales[name] = locale2;
      }
      getSetGlobalLocale(name);
    } else {
      if (locales[name] != null) {
        if (locales[name].parentLocale != null) {
          locales[name] = locales[name].parentLocale;
          if (name === getSetGlobalLocale()) {
            getSetGlobalLocale(name);
          }
        } else if (locales[name] != null) {
          delete locales[name];
        }
      }
    }
    return locales[name];
  }
  function getLocale(key) {
    var locale2;
    if (key && key._locale && key._locale._abbr) {
      key = key._locale._abbr;
    }
    if (!key) {
      return globalLocale;
    }
    if (!isArray3(key)) {
      locale2 = loadLocale(key);
      if (locale2) {
        return locale2;
      }
      key = [key];
    }
    return chooseLocale(key);
  }
  function listLocales() {
    return keys2(locales);
  }
  function checkOverflow(m2) {
    var overflow, a2 = m2._a;
    if (a2 && getParsingFlags(m2).overflow === -2) {
      overflow = a2[MONTH] < 0 || a2[MONTH] > 11 ? MONTH : a2[DATE] < 1 || a2[DATE] > daysInMonth(a2[YEAR], a2[MONTH]) ? DATE : a2[HOUR] < 0 || a2[HOUR] > 24 || a2[HOUR] === 24 && (a2[MINUTE] !== 0 || a2[SECOND] !== 0 || a2[MILLISECOND] !== 0) ? HOUR : a2[MINUTE] < 0 || a2[MINUTE] > 59 ? MINUTE : a2[SECOND] < 0 || a2[SECOND] > 59 ? SECOND : a2[MILLISECOND] < 0 || a2[MILLISECOND] > 999 ? MILLISECOND : -1;
      if (getParsingFlags(m2)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
        overflow = DATE;
      }
      if (getParsingFlags(m2)._overflowWeeks && overflow === -1) {
        overflow = WEEK;
      }
      if (getParsingFlags(m2)._overflowWeekday && overflow === -1) {
        overflow = WEEKDAY;
      }
      getParsingFlags(m2).overflow = overflow;
    }
    return m2;
  }
  var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
  var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
  var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
  var isoDates = [
    ["YYYYYY-MM-DD", /[+-]\d{6}-\d\d-\d\d/],
    ["YYYY-MM-DD", /\d{4}-\d\d-\d\d/],
    ["GGGG-[W]WW-E", /\d{4}-W\d\d-\d/],
    ["GGGG-[W]WW", /\d{4}-W\d\d/, false],
    ["YYYY-DDD", /\d{4}-\d{3}/],
    ["YYYY-MM", /\d{4}-\d\d/, false],
    ["YYYYYYMMDD", /[+-]\d{10}/],
    ["YYYYMMDD", /\d{8}/],
    ["GGGG[W]WWE", /\d{4}W\d{3}/],
    ["GGGG[W]WW", /\d{4}W\d{2}/, false],
    ["YYYYDDD", /\d{7}/],
    ["YYYYMM", /\d{6}/, false],
    ["YYYY", /\d{4}/, false]
  ];
  var isoTimes = [
    ["HH:mm:ss.SSSS", /\d\d:\d\d:\d\d\.\d+/],
    ["HH:mm:ss,SSSS", /\d\d:\d\d:\d\d,\d+/],
    ["HH:mm:ss", /\d\d:\d\d:\d\d/],
    ["HH:mm", /\d\d:\d\d/],
    ["HHmmss.SSSS", /\d\d\d\d\d\d\.\d+/],
    ["HHmmss,SSSS", /\d\d\d\d\d\d,\d+/],
    ["HHmmss", /\d\d\d\d\d\d/],
    ["HHmm", /\d\d\d\d/],
    ["HH", /\d\d/]
  ];
  var aspNetJsonRegex = /^\/?Date\((-?\d+)/i;
  var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
  var obsOffsets = {
    UT: 0,
    GMT: 0,
    EDT: -4 * 60,
    EST: -5 * 60,
    CDT: -5 * 60,
    CST: -6 * 60,
    MDT: -6 * 60,
    MST: -7 * 60,
    PDT: -7 * 60,
    PST: -8 * 60
  };
  function configFromISO(config2) {
    var i3, l2, string2 = config2._i, match5 = extendedIsoRegex.exec(string2) || basicIsoRegex.exec(string2), allowTime, dateFormat, timeFormat, tzFormat;
    if (match5) {
      getParsingFlags(config2).iso = true;
      for (i3 = 0, l2 = isoDates.length; i3 < l2; i3++) {
        if (isoDates[i3][1].exec(match5[1])) {
          dateFormat = isoDates[i3][0];
          allowTime = isoDates[i3][2] !== false;
          break;
        }
      }
      if (dateFormat == null) {
        config2._isValid = false;
        return;
      }
      if (match5[3]) {
        for (i3 = 0, l2 = isoTimes.length; i3 < l2; i3++) {
          if (isoTimes[i3][1].exec(match5[3])) {
            timeFormat = (match5[2] || " ") + isoTimes[i3][0];
            break;
          }
        }
        if (timeFormat == null) {
          config2._isValid = false;
          return;
        }
      }
      if (!allowTime && timeFormat != null) {
        config2._isValid = false;
        return;
      }
      if (match5[4]) {
        if (tzRegex.exec(match5[4])) {
          tzFormat = "Z";
        } else {
          config2._isValid = false;
          return;
        }
      }
      config2._f = dateFormat + (timeFormat || "") + (tzFormat || "");
      configFromStringAndFormat(config2);
    } else {
      config2._isValid = false;
    }
  }
  function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
    var result = [
      untruncateYear(yearStr),
      defaultLocaleMonthsShort.indexOf(monthStr),
      parseInt(dayStr, 10),
      parseInt(hourStr, 10),
      parseInt(minuteStr, 10)
    ];
    if (secondStr) {
      result.push(parseInt(secondStr, 10));
    }
    return result;
  }
  function untruncateYear(yearStr) {
    var year = parseInt(yearStr, 10);
    if (year <= 49) {
      return 2e3 + year;
    } else if (year <= 999) {
      return 1900 + year;
    }
    return year;
  }
  function preprocessRFC2822(s2) {
    return s2.replace(/\([^)]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").replace(/^\s\s*/, "").replace(/\s\s*$/, "");
  }
  function checkWeekday(weekdayStr, parsedInput, config2) {
    if (weekdayStr) {
      var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
      if (weekdayProvided !== weekdayActual) {
        getParsingFlags(config2).weekdayMismatch = true;
        config2._isValid = false;
        return false;
      }
    }
    return true;
  }
  function calculateOffset(obsOffset, militaryOffset, numOffset) {
    if (obsOffset) {
      return obsOffsets[obsOffset];
    } else if (militaryOffset) {
      return 0;
    } else {
      var hm = parseInt(numOffset, 10), m2 = hm % 100, h2 = (hm - m2) / 100;
      return h2 * 60 + m2;
    }
  }
  function configFromRFC2822(config2) {
    var match5 = rfc2822.exec(preprocessRFC2822(config2._i)), parsedArray;
    if (match5) {
      parsedArray = extractFromRFC2822Strings(match5[4], match5[3], match5[2], match5[5], match5[6], match5[7]);
      if (!checkWeekday(match5[1], parsedArray, config2)) {
        return;
      }
      config2._a = parsedArray;
      config2._tzm = calculateOffset(match5[8], match5[9], match5[10]);
      config2._d = createUTCDate.apply(null, config2._a);
      config2._d.setUTCMinutes(config2._d.getUTCMinutes() - config2._tzm);
      getParsingFlags(config2).rfc2822 = true;
    } else {
      config2._isValid = false;
    }
  }
  function configFromString(config2) {
    var matched = aspNetJsonRegex.exec(config2._i);
    if (matched !== null) {
      config2._d = new Date(+matched[1]);
      return;
    }
    configFromISO(config2);
    if (config2._isValid === false) {
      delete config2._isValid;
    } else {
      return;
    }
    configFromRFC2822(config2);
    if (config2._isValid === false) {
      delete config2._isValid;
    } else {
      return;
    }
    if (config2._strict) {
      config2._isValid = false;
    } else {
      hooks.createFromInputFallback(config2);
    }
  }
  hooks.createFromInputFallback = deprecate("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.", function(config2) {
    config2._d = new Date(config2._i + (config2._useUTC ? " UTC" : ""));
  });
  function defaults3(a2, b2, c3) {
    if (a2 != null) {
      return a2;
    }
    if (b2 != null) {
      return b2;
    }
    return c3;
  }
  function currentDateArray(config2) {
    var nowValue = new Date(hooks.now());
    if (config2._useUTC) {
      return [
        nowValue.getUTCFullYear(),
        nowValue.getUTCMonth(),
        nowValue.getUTCDate()
      ];
    }
    return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  }
  function configFromArray(config2) {
    var i3, date, input = [], currentDate, expectedWeekday, yearToUse;
    if (config2._d) {
      return;
    }
    currentDate = currentDateArray(config2);
    if (config2._w && config2._a[DATE] == null && config2._a[MONTH] == null) {
      dayOfYearFromWeekInfo(config2);
    }
    if (config2._dayOfYear != null) {
      yearToUse = defaults3(config2._a[YEAR], currentDate[YEAR]);
      if (config2._dayOfYear > daysInYear(yearToUse) || config2._dayOfYear === 0) {
        getParsingFlags(config2)._overflowDayOfYear = true;
      }
      date = createUTCDate(yearToUse, 0, config2._dayOfYear);
      config2._a[MONTH] = date.getUTCMonth();
      config2._a[DATE] = date.getUTCDate();
    }
    for (i3 = 0; i3 < 3 && config2._a[i3] == null; ++i3) {
      config2._a[i3] = input[i3] = currentDate[i3];
    }
    for (; i3 < 7; i3++) {
      config2._a[i3] = input[i3] = config2._a[i3] == null ? i3 === 2 ? 1 : 0 : config2._a[i3];
    }
    if (config2._a[HOUR] === 24 && config2._a[MINUTE] === 0 && config2._a[SECOND] === 0 && config2._a[MILLISECOND] === 0) {
      config2._nextDay = true;
      config2._a[HOUR] = 0;
    }
    config2._d = (config2._useUTC ? createUTCDate : createDate).apply(null, input);
    expectedWeekday = config2._useUTC ? config2._d.getUTCDay() : config2._d.getDay();
    if (config2._tzm != null) {
      config2._d.setUTCMinutes(config2._d.getUTCMinutes() - config2._tzm);
    }
    if (config2._nextDay) {
      config2._a[HOUR] = 24;
    }
    if (config2._w && typeof config2._w.d !== "undefined" && config2._w.d !== expectedWeekday) {
      getParsingFlags(config2).weekdayMismatch = true;
    }
  }
  function dayOfYearFromWeekInfo(config2) {
    var w2, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
    w2 = config2._w;
    if (w2.GG != null || w2.W != null || w2.E != null) {
      dow = 1;
      doy = 4;
      weekYear = defaults3(w2.GG, config2._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
      week = defaults3(w2.W, 1);
      weekday = defaults3(w2.E, 1);
      if (weekday < 1 || weekday > 7) {
        weekdayOverflow = true;
      }
    } else {
      dow = config2._locale._week.dow;
      doy = config2._locale._week.doy;
      curWeek = weekOfYear(createLocal(), dow, doy);
      weekYear = defaults3(w2.gg, config2._a[YEAR], curWeek.year);
      week = defaults3(w2.w, curWeek.week);
      if (w2.d != null) {
        weekday = w2.d;
        if (weekday < 0 || weekday > 6) {
          weekdayOverflow = true;
        }
      } else if (w2.e != null) {
        weekday = w2.e + dow;
        if (w2.e < 0 || w2.e > 6) {
          weekdayOverflow = true;
        }
      } else {
        weekday = dow;
      }
    }
    if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
      getParsingFlags(config2)._overflowWeeks = true;
    } else if (weekdayOverflow != null) {
      getParsingFlags(config2)._overflowWeekday = true;
    } else {
      temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
      config2._a[YEAR] = temp.year;
      config2._dayOfYear = temp.dayOfYear;
    }
  }
  hooks.ISO_8601 = function() {
  };
  hooks.RFC_2822 = function() {
  };
  function configFromStringAndFormat(config2) {
    if (config2._f === hooks.ISO_8601) {
      configFromISO(config2);
      return;
    }
    if (config2._f === hooks.RFC_2822) {
      configFromRFC2822(config2);
      return;
    }
    config2._a = [];
    getParsingFlags(config2).empty = true;
    var string2 = "" + config2._i, i3, parsedInput, tokens2, token3, skipped, stringLength = string2.length, totalParsedInputLength = 0, era;
    tokens2 = expandFormat(config2._f, config2._locale).match(formattingTokens) || [];
    for (i3 = 0; i3 < tokens2.length; i3++) {
      token3 = tokens2[i3];
      parsedInput = (string2.match(getParseRegexForToken(token3, config2)) || [])[0];
      if (parsedInput) {
        skipped = string2.substr(0, string2.indexOf(parsedInput));
        if (skipped.length > 0) {
          getParsingFlags(config2).unusedInput.push(skipped);
        }
        string2 = string2.slice(string2.indexOf(parsedInput) + parsedInput.length);
        totalParsedInputLength += parsedInput.length;
      }
      if (formatTokenFunctions[token3]) {
        if (parsedInput) {
          getParsingFlags(config2).empty = false;
        } else {
          getParsingFlags(config2).unusedTokens.push(token3);
        }
        addTimeToArrayFromToken(token3, parsedInput, config2);
      } else if (config2._strict && !parsedInput) {
        getParsingFlags(config2).unusedTokens.push(token3);
      }
    }
    getParsingFlags(config2).charsLeftOver = stringLength - totalParsedInputLength;
    if (string2.length > 0) {
      getParsingFlags(config2).unusedInput.push(string2);
    }
    if (config2._a[HOUR] <= 12 && getParsingFlags(config2).bigHour === true && config2._a[HOUR] > 0) {
      getParsingFlags(config2).bigHour = void 0;
    }
    getParsingFlags(config2).parsedDateParts = config2._a.slice(0);
    getParsingFlags(config2).meridiem = config2._meridiem;
    config2._a[HOUR] = meridiemFixWrap(config2._locale, config2._a[HOUR], config2._meridiem);
    era = getParsingFlags(config2).era;
    if (era !== null) {
      config2._a[YEAR] = config2._locale.erasConvertYear(era, config2._a[YEAR]);
    }
    configFromArray(config2);
    checkOverflow(config2);
  }
  function meridiemFixWrap(locale2, hour, meridiem2) {
    var isPm;
    if (meridiem2 == null) {
      return hour;
    }
    if (locale2.meridiemHour != null) {
      return locale2.meridiemHour(hour, meridiem2);
    } else if (locale2.isPM != null) {
      isPm = locale2.isPM(meridiem2);
      if (isPm && hour < 12) {
        hour += 12;
      }
      if (!isPm && hour === 12) {
        hour = 0;
      }
      return hour;
    } else {
      return hour;
    }
  }
  function configFromStringAndArray(config2) {
    var tempConfig, bestMoment, scoreToBeat, i3, currentScore, validFormatFound, bestFormatIsValid = false;
    if (config2._f.length === 0) {
      getParsingFlags(config2).invalidFormat = true;
      config2._d = new Date(NaN);
      return;
    }
    for (i3 = 0; i3 < config2._f.length; i3++) {
      currentScore = 0;
      validFormatFound = false;
      tempConfig = copyConfig({}, config2);
      if (config2._useUTC != null) {
        tempConfig._useUTC = config2._useUTC;
      }
      tempConfig._f = config2._f[i3];
      configFromStringAndFormat(tempConfig);
      if (isValid(tempConfig)) {
        validFormatFound = true;
      }
      currentScore += getParsingFlags(tempConfig).charsLeftOver;
      currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
      getParsingFlags(tempConfig).score = currentScore;
      if (!bestFormatIsValid) {
        if (scoreToBeat == null || currentScore < scoreToBeat || validFormatFound) {
          scoreToBeat = currentScore;
          bestMoment = tempConfig;
          if (validFormatFound) {
            bestFormatIsValid = true;
          }
        }
      } else {
        if (currentScore < scoreToBeat) {
          scoreToBeat = currentScore;
          bestMoment = tempConfig;
        }
      }
    }
    extend3(config2, bestMoment || tempConfig);
  }
  function configFromObject(config2) {
    if (config2._d) {
      return;
    }
    var i3 = normalizeObjectUnits(config2._i), dayOrDate = i3.day === void 0 ? i3.date : i3.day;
    config2._a = map2([i3.year, i3.month, dayOrDate, i3.hour, i3.minute, i3.second, i3.millisecond], function(obj) {
      return obj && parseInt(obj, 10);
    });
    configFromArray(config2);
  }
  function createFromConfig(config2) {
    var res = new Moment(checkOverflow(prepareConfig(config2)));
    if (res._nextDay) {
      res.add(1, "d");
      res._nextDay = void 0;
    }
    return res;
  }
  function prepareConfig(config2) {
    var input = config2._i, format3 = config2._f;
    config2._locale = config2._locale || getLocale(config2._l);
    if (input === null || format3 === void 0 && input === "") {
      return createInvalid({nullInput: true});
    }
    if (typeof input === "string") {
      config2._i = input = config2._locale.preparse(input);
    }
    if (isMoment(input)) {
      return new Moment(checkOverflow(input));
    } else if (isDate2(input)) {
      config2._d = input;
    } else if (isArray3(format3)) {
      configFromStringAndArray(config2);
    } else if (format3) {
      configFromStringAndFormat(config2);
    } else {
      configFromInput(config2);
    }
    if (!isValid(config2)) {
      config2._d = null;
    }
    return config2;
  }
  function configFromInput(config2) {
    var input = config2._i;
    if (isUndefined5(input)) {
      config2._d = new Date(hooks.now());
    } else if (isDate2(input)) {
      config2._d = new Date(input.valueOf());
    } else if (typeof input === "string") {
      configFromString(config2);
    } else if (isArray3(input)) {
      config2._a = map2(input.slice(0), function(obj) {
        return parseInt(obj, 10);
      });
      configFromArray(config2);
    } else if (isObject5(input)) {
      configFromObject(config2);
    } else if (isNumber3(input)) {
      config2._d = new Date(input);
    } else {
      hooks.createFromInputFallback(config2);
    }
  }
  function createLocalOrUTC(input, format3, locale2, strict, isUTC) {
    var c3 = {};
    if (format3 === true || format3 === false) {
      strict = format3;
      format3 = void 0;
    }
    if (locale2 === true || locale2 === false) {
      strict = locale2;
      locale2 = void 0;
    }
    if (isObject5(input) && isObjectEmpty(input) || isArray3(input) && input.length === 0) {
      input = void 0;
    }
    c3._isAMomentObject = true;
    c3._useUTC = c3._isUTC = isUTC;
    c3._l = locale2;
    c3._i = input;
    c3._f = format3;
    c3._strict = strict;
    return createFromConfig(c3);
  }
  function createLocal(input, format3, locale2, strict) {
    return createLocalOrUTC(input, format3, locale2, strict, false);
  }
  var prototypeMin = deprecate("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/", function() {
    var other = createLocal.apply(null, arguments);
    if (this.isValid() && other.isValid()) {
      return other < this ? this : other;
    } else {
      return createInvalid();
    }
  });
  var prototypeMax = deprecate("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/", function() {
    var other = createLocal.apply(null, arguments);
    if (this.isValid() && other.isValid()) {
      return other > this ? this : other;
    } else {
      return createInvalid();
    }
  });
  function pickBy2(fn, moments) {
    var res, i3;
    if (moments.length === 1 && isArray3(moments[0])) {
      moments = moments[0];
    }
    if (!moments.length) {
      return createLocal();
    }
    res = moments[0];
    for (i3 = 1; i3 < moments.length; ++i3) {
      if (!moments[i3].isValid() || moments[i3][fn](res)) {
        res = moments[i3];
      }
    }
    return res;
  }
  function min2() {
    var args = [].slice.call(arguments, 0);
    return pickBy2("isBefore", args);
  }
  function max2() {
    var args = [].slice.call(arguments, 0);
    return pickBy2("isAfter", args);
  }
  var now3 = function() {
    return Date.now ? Date.now() : +new Date();
  };
  var ordering = [
    "year",
    "quarter",
    "month",
    "week",
    "day",
    "hour",
    "minute",
    "second",
    "millisecond"
  ];
  function isDurationValid(m2) {
    var key, unitHasDecimal = false, i3;
    for (key in m2) {
      if (hasOwnProp(m2, key) && !(indexOf.call(ordering, key) !== -1 && (m2[key] == null || !isNaN(m2[key])))) {
        return false;
      }
    }
    for (i3 = 0; i3 < ordering.length; ++i3) {
      if (m2[ordering[i3]]) {
        if (unitHasDecimal) {
          return false;
        }
        if (parseFloat(m2[ordering[i3]]) !== toInt(m2[ordering[i3]])) {
          unitHasDecimal = true;
        }
      }
    }
    return true;
  }
  function isValid$1() {
    return this._isValid;
  }
  function createInvalid$1() {
    return createDuration(NaN);
  }
  function Duration(duration) {
    var normalizedInput = normalizeObjectUnits(duration), years2 = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months2 = normalizedInput.month || 0, weeks2 = normalizedInput.week || normalizedInput.isoWeek || 0, days2 = normalizedInput.day || 0, hours2 = normalizedInput.hour || 0, minutes2 = normalizedInput.minute || 0, seconds2 = normalizedInput.second || 0, milliseconds2 = normalizedInput.millisecond || 0;
    this._isValid = isDurationValid(normalizedInput);
    this._milliseconds = +milliseconds2 + seconds2 * 1e3 + minutes2 * 6e4 + hours2 * 1e3 * 60 * 60;
    this._days = +days2 + weeks2 * 7;
    this._months = +months2 + quarters * 3 + years2 * 12;
    this._data = {};
    this._locale = getLocale();
    this._bubble();
  }
  function isDuration(obj) {
    return obj instanceof Duration;
  }
  function absRound(number) {
    if (number < 0) {
      return Math.round(-1 * number) * -1;
    } else {
      return Math.round(number);
    }
  }
  function compareArrays(array1, array2, dontConvert) {
    var len2 = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i3;
    for (i3 = 0; i3 < len2; i3++) {
      if (dontConvert && array1[i3] !== array2[i3] || !dontConvert && toInt(array1[i3]) !== toInt(array2[i3])) {
        diffs++;
      }
    }
    return diffs + lengthDiff;
  }
  function offset2(token3, separator) {
    addFormatToken(token3, 0, 0, function() {
      var offset3 = this.utcOffset(), sign2 = "+";
      if (offset3 < 0) {
        offset3 = -offset3;
        sign2 = "-";
      }
      return sign2 + zeroFill(~~(offset3 / 60), 2) + separator + zeroFill(~~offset3 % 60, 2);
    });
  }
  offset2("Z", ":");
  offset2("ZZ", "");
  addRegexToken("Z", matchShortOffset);
  addRegexToken("ZZ", matchShortOffset);
  addParseToken(["Z", "ZZ"], function(input, array2, config2) {
    config2._useUTC = true;
    config2._tzm = offsetFromString(matchShortOffset, input);
  });
  var chunkOffset = /([\+\-]|\d\d)/gi;
  function offsetFromString(matcher2, string2) {
    var matches2 = (string2 || "").match(matcher2), chunk, parts, minutes2;
    if (matches2 === null) {
      return null;
    }
    chunk = matches2[matches2.length - 1] || [];
    parts = (chunk + "").match(chunkOffset) || ["-", 0, 0];
    minutes2 = +(parts[1] * 60) + toInt(parts[2]);
    return minutes2 === 0 ? 0 : parts[0] === "+" ? minutes2 : -minutes2;
  }
  function cloneWithOffset(input, model) {
    var res, diff2;
    if (model._isUTC) {
      res = model.clone();
      diff2 = (isMoment(input) || isDate2(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
      res._d.setTime(res._d.valueOf() + diff2);
      hooks.updateOffset(res, false);
      return res;
    } else {
      return createLocal(input).local();
    }
  }
  function getDateOffset(m2) {
    return -Math.round(m2._d.getTimezoneOffset());
  }
  hooks.updateOffset = function() {
  };
  function getSetOffset(input, keepLocalTime, keepMinutes) {
    var offset3 = this._offset || 0, localAdjust;
    if (!this.isValid()) {
      return input != null ? this : NaN;
    }
    if (input != null) {
      if (typeof input === "string") {
        input = offsetFromString(matchShortOffset, input);
        if (input === null) {
          return this;
        }
      } else if (Math.abs(input) < 16 && !keepMinutes) {
        input = input * 60;
      }
      if (!this._isUTC && keepLocalTime) {
        localAdjust = getDateOffset(this);
      }
      this._offset = input;
      this._isUTC = true;
      if (localAdjust != null) {
        this.add(localAdjust, "m");
      }
      if (offset3 !== input) {
        if (!keepLocalTime || this._changeInProgress) {
          addSubtract(this, createDuration(input - offset3, "m"), 1, false);
        } else if (!this._changeInProgress) {
          this._changeInProgress = true;
          hooks.updateOffset(this, true);
          this._changeInProgress = null;
        }
      }
      return this;
    } else {
      return this._isUTC ? offset3 : getDateOffset(this);
    }
  }
  function getSetZone(input, keepLocalTime) {
    if (input != null) {
      if (typeof input !== "string") {
        input = -input;
      }
      this.utcOffset(input, keepLocalTime);
      return this;
    } else {
      return -this.utcOffset();
    }
  }
  function setOffsetToUTC(keepLocalTime) {
    return this.utcOffset(0, keepLocalTime);
  }
  function setOffsetToLocal(keepLocalTime) {
    if (this._isUTC) {
      this.utcOffset(0, keepLocalTime);
      this._isUTC = false;
      if (keepLocalTime) {
        this.subtract(getDateOffset(this), "m");
      }
    }
    return this;
  }
  function setOffsetToParsedOffset() {
    if (this._tzm != null) {
      this.utcOffset(this._tzm, false, true);
    } else if (typeof this._i === "string") {
      var tZone = offsetFromString(matchOffset, this._i);
      if (tZone != null) {
        this.utcOffset(tZone);
      } else {
        this.utcOffset(0, true);
      }
    }
    return this;
  }
  function hasAlignedHourOffset(input) {
    if (!this.isValid()) {
      return false;
    }
    input = input ? createLocal(input).utcOffset() : 0;
    return (this.utcOffset() - input) % 60 === 0;
  }
  function isDaylightSavingTime() {
    return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset();
  }
  function isDaylightSavingTimeShifted() {
    if (!isUndefined5(this._isDSTShifted)) {
      return this._isDSTShifted;
    }
    var c3 = {}, other;
    copyConfig(c3, this);
    c3 = prepareConfig(c3);
    if (c3._a) {
      other = c3._isUTC ? createUTC(c3._a) : createLocal(c3._a);
      this._isDSTShifted = this.isValid() && compareArrays(c3._a, other.toArray()) > 0;
    } else {
      this._isDSTShifted = false;
    }
    return this._isDSTShifted;
  }
  function isLocal() {
    return this.isValid() ? !this._isUTC : false;
  }
  function isUtcOffset() {
    return this.isValid() ? this._isUTC : false;
  }
  function isUtc() {
    return this.isValid() ? this._isUTC && this._offset === 0 : false;
  }
  var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/;
  var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  function createDuration(input, key) {
    var duration = input, match5 = null, sign2, ret, diffRes;
    if (isDuration(input)) {
      duration = {
        ms: input._milliseconds,
        d: input._days,
        M: input._months
      };
    } else if (isNumber3(input) || !isNaN(+input)) {
      duration = {};
      if (key) {
        duration[key] = +input;
      } else {
        duration.milliseconds = +input;
      }
    } else if (match5 = aspNetRegex.exec(input)) {
      sign2 = match5[1] === "-" ? -1 : 1;
      duration = {
        y: 0,
        d: toInt(match5[DATE]) * sign2,
        h: toInt(match5[HOUR]) * sign2,
        m: toInt(match5[MINUTE]) * sign2,
        s: toInt(match5[SECOND]) * sign2,
        ms: toInt(absRound(match5[MILLISECOND] * 1e3)) * sign2
      };
    } else if (match5 = isoRegex.exec(input)) {
      sign2 = match5[1] === "-" ? -1 : 1;
      duration = {
        y: parseIso(match5[2], sign2),
        M: parseIso(match5[3], sign2),
        w: parseIso(match5[4], sign2),
        d: parseIso(match5[5], sign2),
        h: parseIso(match5[6], sign2),
        m: parseIso(match5[7], sign2),
        s: parseIso(match5[8], sign2)
      };
    } else if (duration == null) {
      duration = {};
    } else if (typeof duration === "object" && ("from" in duration || "to" in duration)) {
      diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
      duration = {};
      duration.ms = diffRes.milliseconds;
      duration.M = diffRes.months;
    }
    ret = new Duration(duration);
    if (isDuration(input) && hasOwnProp(input, "_locale")) {
      ret._locale = input._locale;
    }
    if (isDuration(input) && hasOwnProp(input, "_isValid")) {
      ret._isValid = input._isValid;
    }
    return ret;
  }
  createDuration.fn = Duration.prototype;
  createDuration.invalid = createInvalid$1;
  function parseIso(inp, sign2) {
    var res = inp && parseFloat(inp.replace(",", "."));
    return (isNaN(res) ? 0 : res) * sign2;
  }
  function positiveMomentsDifference(base, other) {
    var res = {};
    res.months = other.month() - base.month() + (other.year() - base.year()) * 12;
    if (base.clone().add(res.months, "M").isAfter(other)) {
      --res.months;
    }
    res.milliseconds = +other - +base.clone().add(res.months, "M");
    return res;
  }
  function momentsDifference(base, other) {
    var res;
    if (!(base.isValid() && other.isValid())) {
      return {milliseconds: 0, months: 0};
    }
    other = cloneWithOffset(other, base);
    if (base.isBefore(other)) {
      res = positiveMomentsDifference(base, other);
    } else {
      res = positiveMomentsDifference(other, base);
      res.milliseconds = -res.milliseconds;
      res.months = -res.months;
    }
    return res;
  }
  function createAdder(direction, name) {
    return function(val, period) {
      var dur, tmp;
      if (period !== null && !isNaN(+period)) {
        deprecateSimple(name, "moment()." + name + "(period, number) is deprecated. Please use moment()." + name + "(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.");
        tmp = val;
        val = period;
        period = tmp;
      }
      dur = createDuration(val, period);
      addSubtract(this, dur, direction);
      return this;
    };
  }
  function addSubtract(mom, duration, isAdding, updateOffset) {
    var milliseconds2 = duration._milliseconds, days2 = absRound(duration._days), months2 = absRound(duration._months);
    if (!mom.isValid()) {
      return;
    }
    updateOffset = updateOffset == null ? true : updateOffset;
    if (months2) {
      setMonth(mom, get7(mom, "Month") + months2 * isAdding);
    }
    if (days2) {
      set$12(mom, "Date", get7(mom, "Date") + days2 * isAdding);
    }
    if (milliseconds2) {
      mom._d.setTime(mom._d.valueOf() + milliseconds2 * isAdding);
    }
    if (updateOffset) {
      hooks.updateOffset(mom, days2 || months2);
    }
  }
  var add = createAdder(1, "add");
  var subtract = createAdder(-1, "subtract");
  function isString5(input) {
    return typeof input === "string" || input instanceof String;
  }
  function isMomentInput(input) {
    return isMoment(input) || isDate2(input) || isString5(input) || isNumber3(input) || isNumberOrStringArray(input) || isMomentInputObject(input) || input === null || input === void 0;
  }
  function isMomentInputObject(input) {
    var objectTest = isObject5(input) && !isObjectEmpty(input), propertyTest = false, properties = [
      "years",
      "year",
      "y",
      "months",
      "month",
      "M",
      "days",
      "day",
      "d",
      "dates",
      "date",
      "D",
      "hours",
      "hour",
      "h",
      "minutes",
      "minute",
      "m",
      "seconds",
      "second",
      "s",
      "milliseconds",
      "millisecond",
      "ms"
    ], i3, property2;
    for (i3 = 0; i3 < properties.length; i3 += 1) {
      property2 = properties[i3];
      propertyTest = propertyTest || hasOwnProp(input, property2);
    }
    return objectTest && propertyTest;
  }
  function isNumberOrStringArray(input) {
    var arrayTest = isArray3(input), dataTypeTest = false;
    if (arrayTest) {
      dataTypeTest = input.filter(function(item) {
        return !isNumber3(item) && isString5(input);
      }).length === 0;
    }
    return arrayTest && dataTypeTest;
  }
  function isCalendarSpec(input) {
    var objectTest = isObject5(input) && !isObjectEmpty(input), propertyTest = false, properties = [
      "sameDay",
      "nextDay",
      "lastDay",
      "nextWeek",
      "lastWeek",
      "sameElse"
    ], i3, property2;
    for (i3 = 0; i3 < properties.length; i3 += 1) {
      property2 = properties[i3];
      propertyTest = propertyTest || hasOwnProp(input, property2);
    }
    return objectTest && propertyTest;
  }
  function getCalendarFormat(myMoment, now4) {
    var diff2 = myMoment.diff(now4, "days", true);
    return diff2 < -6 ? "sameElse" : diff2 < -1 ? "lastWeek" : diff2 < 0 ? "lastDay" : diff2 < 1 ? "sameDay" : diff2 < 2 ? "nextDay" : diff2 < 7 ? "nextWeek" : "sameElse";
  }
  function calendar$1(time2, formats2) {
    if (arguments.length === 1) {
      if (!arguments[0]) {
        time2 = void 0;
        formats2 = void 0;
      } else if (isMomentInput(arguments[0])) {
        time2 = arguments[0];
        formats2 = void 0;
      } else if (isCalendarSpec(arguments[0])) {
        formats2 = arguments[0];
        time2 = void 0;
      }
    }
    var now4 = time2 || createLocal(), sod = cloneWithOffset(now4, this).startOf("day"), format3 = hooks.calendarFormat(this, sod) || "sameElse", output2 = formats2 && (isFunction6(formats2[format3]) ? formats2[format3].call(this, now4) : formats2[format3]);
    return this.format(output2 || this.localeData().calendar(format3, this, createLocal(now4)));
  }
  function clone2() {
    return new Moment(this);
  }
  function isAfter(input, units) {
    var localInput = isMoment(input) ? input : createLocal(input);
    if (!(this.isValid() && localInput.isValid())) {
      return false;
    }
    units = normalizeUnits(units) || "millisecond";
    if (units === "millisecond") {
      return this.valueOf() > localInput.valueOf();
    } else {
      return localInput.valueOf() < this.clone().startOf(units).valueOf();
    }
  }
  function isBefore(input, units) {
    var localInput = isMoment(input) ? input : createLocal(input);
    if (!(this.isValid() && localInput.isValid())) {
      return false;
    }
    units = normalizeUnits(units) || "millisecond";
    if (units === "millisecond") {
      return this.valueOf() < localInput.valueOf();
    } else {
      return this.clone().endOf(units).valueOf() < localInput.valueOf();
    }
  }
  function isBetween(from2, to2, units, inclusivity) {
    var localFrom = isMoment(from2) ? from2 : createLocal(from2), localTo = isMoment(to2) ? to2 : createLocal(to2);
    if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
      return false;
    }
    inclusivity = inclusivity || "()";
    return (inclusivity[0] === "(" ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ")" ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
  }
  function isSame(input, units) {
    var localInput = isMoment(input) ? input : createLocal(input), inputMs;
    if (!(this.isValid() && localInput.isValid())) {
      return false;
    }
    units = normalizeUnits(units) || "millisecond";
    if (units === "millisecond") {
      return this.valueOf() === localInput.valueOf();
    } else {
      inputMs = localInput.valueOf();
      return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
    }
  }
  function isSameOrAfter(input, units) {
    return this.isSame(input, units) || this.isAfter(input, units);
  }
  function isSameOrBefore(input, units) {
    return this.isSame(input, units) || this.isBefore(input, units);
  }
  function diff(input, units, asFloat) {
    var that, zoneDelta, output2;
    if (!this.isValid()) {
      return NaN;
    }
    that = cloneWithOffset(input, this);
    if (!that.isValid()) {
      return NaN;
    }
    zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
    units = normalizeUnits(units);
    switch (units) {
      case "year":
        output2 = monthDiff(this, that) / 12;
        break;
      case "month":
        output2 = monthDiff(this, that);
        break;
      case "quarter":
        output2 = monthDiff(this, that) / 3;
        break;
      case "second":
        output2 = (this - that) / 1e3;
        break;
      case "minute":
        output2 = (this - that) / 6e4;
        break;
      case "hour":
        output2 = (this - that) / 36e5;
        break;
      case "day":
        output2 = (this - that - zoneDelta) / 864e5;
        break;
      case "week":
        output2 = (this - that - zoneDelta) / 6048e5;
        break;
      default:
        output2 = this - that;
    }
    return asFloat ? output2 : absFloor(output2);
  }
  function monthDiff(a2, b2) {
    if (a2.date() < b2.date()) {
      return -monthDiff(b2, a2);
    }
    var wholeMonthDiff = (b2.year() - a2.year()) * 12 + (b2.month() - a2.month()), anchor = a2.clone().add(wholeMonthDiff, "months"), anchor2, adjust2;
    if (b2 - anchor < 0) {
      anchor2 = a2.clone().add(wholeMonthDiff - 1, "months");
      adjust2 = (b2 - anchor) / (anchor - anchor2);
    } else {
      anchor2 = a2.clone().add(wholeMonthDiff + 1, "months");
      adjust2 = (b2 - anchor) / (anchor2 - anchor);
    }
    return -(wholeMonthDiff + adjust2) || 0;
  }
  hooks.defaultFormat = "YYYY-MM-DDTHH:mm:ssZ";
  hooks.defaultFormatUtc = "YYYY-MM-DDTHH:mm:ss[Z]";
  function toString5() {
    return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  }
  function toISOString(keepOffset) {
    if (!this.isValid()) {
      return null;
    }
    var utc = keepOffset !== true, m2 = utc ? this.clone().utc() : this;
    if (m2.year() < 0 || m2.year() > 9999) {
      return formatMoment(m2, utc ? "YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYYYY-MM-DD[T]HH:mm:ss.SSSZ");
    }
    if (isFunction6(Date.prototype.toISOString)) {
      if (utc) {
        return this.toDate().toISOString();
      } else {
        return new Date(this.valueOf() + this.utcOffset() * 60 * 1e3).toISOString().replace("Z", formatMoment(m2, "Z"));
      }
    }
    return formatMoment(m2, utc ? "YYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYY-MM-DD[T]HH:mm:ss.SSSZ");
  }
  function inspect() {
    if (!this.isValid()) {
      return "moment.invalid(/* " + this._i + " */)";
    }
    var func = "moment", zone = "", prefix2, year, datetime, suffix;
    if (!this.isLocal()) {
      func = this.utcOffset() === 0 ? "moment.utc" : "moment.parseZone";
      zone = "Z";
    }
    prefix2 = "[" + func + '("]';
    year = 0 <= this.year() && this.year() <= 9999 ? "YYYY" : "YYYYYY";
    datetime = "-MM-DD[T]HH:mm:ss.SSS";
    suffix = zone + '[")]';
    return this.format(prefix2 + year + datetime + suffix);
  }
  function format2(inputString) {
    if (!inputString) {
      inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
    }
    var output2 = formatMoment(this, inputString);
    return this.localeData().postformat(output2);
  }
  function from(time2, withoutSuffix) {
    if (this.isValid() && (isMoment(time2) && time2.isValid() || createLocal(time2).isValid())) {
      return createDuration({to: this, from: time2}).locale(this.locale()).humanize(!withoutSuffix);
    } else {
      return this.localeData().invalidDate();
    }
  }
  function fromNow(withoutSuffix) {
    return this.from(createLocal(), withoutSuffix);
  }
  function to(time2, withoutSuffix) {
    if (this.isValid() && (isMoment(time2) && time2.isValid() || createLocal(time2).isValid())) {
      return createDuration({from: this, to: time2}).locale(this.locale()).humanize(!withoutSuffix);
    } else {
      return this.localeData().invalidDate();
    }
  }
  function toNow(withoutSuffix) {
    return this.to(createLocal(), withoutSuffix);
  }
  function locale(key) {
    var newLocaleData;
    if (key === void 0) {
      return this._locale._abbr;
    } else {
      newLocaleData = getLocale(key);
      if (newLocaleData != null) {
        this._locale = newLocaleData;
      }
      return this;
    }
  }
  var lang = deprecate("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.", function(key) {
    if (key === void 0) {
      return this.localeData();
    } else {
      return this.locale(key);
    }
  });
  function localeData() {
    return this._locale;
  }
  var MS_PER_SECOND = 1e3;
  var MS_PER_MINUTE = 60 * MS_PER_SECOND;
  var MS_PER_HOUR = 60 * MS_PER_MINUTE;
  var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  function mod$1(dividend, divisor) {
    return (dividend % divisor + divisor) % divisor;
  }
  function localStartOfDate(y3, m2, d2) {
    if (y3 < 100 && y3 >= 0) {
      return new Date(y3 + 400, m2, d2) - MS_PER_400_YEARS;
    } else {
      return new Date(y3, m2, d2).valueOf();
    }
  }
  function utcStartOfDate(y3, m2, d2) {
    if (y3 < 100 && y3 >= 0) {
      return Date.UTC(y3 + 400, m2, d2) - MS_PER_400_YEARS;
    } else {
      return Date.UTC(y3, m2, d2);
    }
  }
  function startOf(units) {
    var time2, startOfDate;
    units = normalizeUnits(units);
    if (units === void 0 || units === "millisecond" || !this.isValid()) {
      return this;
    }
    startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
    switch (units) {
      case "year":
        time2 = startOfDate(this.year(), 0, 1);
        break;
      case "quarter":
        time2 = startOfDate(this.year(), this.month() - this.month() % 3, 1);
        break;
      case "month":
        time2 = startOfDate(this.year(), this.month(), 1);
        break;
      case "week":
        time2 = startOfDate(this.year(), this.month(), this.date() - this.weekday());
        break;
      case "isoWeek":
        time2 = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
        break;
      case "day":
      case "date":
        time2 = startOfDate(this.year(), this.month(), this.date());
        break;
      case "hour":
        time2 = this._d.valueOf();
        time2 -= mod$1(time2 + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
        break;
      case "minute":
        time2 = this._d.valueOf();
        time2 -= mod$1(time2, MS_PER_MINUTE);
        break;
      case "second":
        time2 = this._d.valueOf();
        time2 -= mod$1(time2, MS_PER_SECOND);
        break;
    }
    this._d.setTime(time2);
    hooks.updateOffset(this, true);
    return this;
  }
  function endOf(units) {
    var time2, startOfDate;
    units = normalizeUnits(units);
    if (units === void 0 || units === "millisecond" || !this.isValid()) {
      return this;
    }
    startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
    switch (units) {
      case "year":
        time2 = startOfDate(this.year() + 1, 0, 1) - 1;
        break;
      case "quarter":
        time2 = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
        break;
      case "month":
        time2 = startOfDate(this.year(), this.month() + 1, 1) - 1;
        break;
      case "week":
        time2 = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
        break;
      case "isoWeek":
        time2 = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
        break;
      case "day":
      case "date":
        time2 = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
        break;
      case "hour":
        time2 = this._d.valueOf();
        time2 += MS_PER_HOUR - mod$1(time2 + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
        break;
      case "minute":
        time2 = this._d.valueOf();
        time2 += MS_PER_MINUTE - mod$1(time2, MS_PER_MINUTE) - 1;
        break;
      case "second":
        time2 = this._d.valueOf();
        time2 += MS_PER_SECOND - mod$1(time2, MS_PER_SECOND) - 1;
        break;
    }
    this._d.setTime(time2);
    hooks.updateOffset(this, true);
    return this;
  }
  function valueOf() {
    return this._d.valueOf() - (this._offset || 0) * 6e4;
  }
  function unix() {
    return Math.floor(this.valueOf() / 1e3);
  }
  function toDate() {
    return new Date(this.valueOf());
  }
  function toArray() {
    var m2 = this;
    return [
      m2.year(),
      m2.month(),
      m2.date(),
      m2.hour(),
      m2.minute(),
      m2.second(),
      m2.millisecond()
    ];
  }
  function toObject3() {
    var m2 = this;
    return {
      years: m2.year(),
      months: m2.month(),
      date: m2.date(),
      hours: m2.hours(),
      minutes: m2.minutes(),
      seconds: m2.seconds(),
      milliseconds: m2.milliseconds()
    };
  }
  function toJSON() {
    return this.isValid() ? this.toISOString() : null;
  }
  function isValid$2() {
    return isValid(this);
  }
  function parsingFlags() {
    return extend3({}, getParsingFlags(this));
  }
  function invalidAt() {
    return getParsingFlags(this).overflow;
  }
  function creationData() {
    return {
      input: this._i,
      format: this._f,
      locale: this._locale,
      isUTC: this._isUTC,
      strict: this._strict
    };
  }
  addFormatToken("N", 0, 0, "eraAbbr");
  addFormatToken("NN", 0, 0, "eraAbbr");
  addFormatToken("NNN", 0, 0, "eraAbbr");
  addFormatToken("NNNN", 0, 0, "eraName");
  addFormatToken("NNNNN", 0, 0, "eraNarrow");
  addFormatToken("y", ["y", 1], "yo", "eraYear");
  addFormatToken("y", ["yy", 2], 0, "eraYear");
  addFormatToken("y", ["yyy", 3], 0, "eraYear");
  addFormatToken("y", ["yyyy", 4], 0, "eraYear");
  addRegexToken("N", matchEraAbbr);
  addRegexToken("NN", matchEraAbbr);
  addRegexToken("NNN", matchEraAbbr);
  addRegexToken("NNNN", matchEraName);
  addRegexToken("NNNNN", matchEraNarrow);
  addParseToken(["N", "NN", "NNN", "NNNN", "NNNNN"], function(input, array2, config2, token3) {
    var era = config2._locale.erasParse(input, token3, config2._strict);
    if (era) {
      getParsingFlags(config2).era = era;
    } else {
      getParsingFlags(config2).invalidEra = input;
    }
  });
  addRegexToken("y", matchUnsigned);
  addRegexToken("yy", matchUnsigned);
  addRegexToken("yyy", matchUnsigned);
  addRegexToken("yyyy", matchUnsigned);
  addRegexToken("yo", matchEraYearOrdinal);
  addParseToken(["y", "yy", "yyy", "yyyy"], YEAR);
  addParseToken(["yo"], function(input, array2, config2, token3) {
    var match5;
    if (config2._locale._eraYearOrdinalRegex) {
      match5 = input.match(config2._locale._eraYearOrdinalRegex);
    }
    if (config2._locale.eraYearOrdinalParse) {
      array2[YEAR] = config2._locale.eraYearOrdinalParse(input, match5);
    } else {
      array2[YEAR] = parseInt(input, 10);
    }
  });
  function localeEras(m2, format3) {
    var i3, l2, date, eras = this._eras || getLocale("en")._eras;
    for (i3 = 0, l2 = eras.length; i3 < l2; ++i3) {
      switch (typeof eras[i3].since) {
        case "string":
          date = hooks(eras[i3].since).startOf("day");
          eras[i3].since = date.valueOf();
          break;
      }
      switch (typeof eras[i3].until) {
        case "undefined":
          eras[i3].until = Infinity;
          break;
        case "string":
          date = hooks(eras[i3].until).startOf("day").valueOf();
          eras[i3].until = date.valueOf();
          break;
      }
    }
    return eras;
  }
  function localeErasParse(eraName, format3, strict) {
    var i3, l2, eras = this.eras(), name, abbr, narrow;
    eraName = eraName.toUpperCase();
    for (i3 = 0, l2 = eras.length; i3 < l2; ++i3) {
      name = eras[i3].name.toUpperCase();
      abbr = eras[i3].abbr.toUpperCase();
      narrow = eras[i3].narrow.toUpperCase();
      if (strict) {
        switch (format3) {
          case "N":
          case "NN":
          case "NNN":
            if (abbr === eraName) {
              return eras[i3];
            }
            break;
          case "NNNN":
            if (name === eraName) {
              return eras[i3];
            }
            break;
          case "NNNNN":
            if (narrow === eraName) {
              return eras[i3];
            }
            break;
        }
      } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
        return eras[i3];
      }
    }
  }
  function localeErasConvertYear(era, year) {
    var dir = era.since <= era.until ? 1 : -1;
    if (year === void 0) {
      return hooks(era.since).year();
    } else {
      return hooks(era.since).year() + (year - era.offset) * dir;
    }
  }
  function getEraName() {
    var i3, l2, val, eras = this.localeData().eras();
    for (i3 = 0, l2 = eras.length; i3 < l2; ++i3) {
      val = this.clone().startOf("day").valueOf();
      if (eras[i3].since <= val && val <= eras[i3].until) {
        return eras[i3].name;
      }
      if (eras[i3].until <= val && val <= eras[i3].since) {
        return eras[i3].name;
      }
    }
    return "";
  }
  function getEraNarrow() {
    var i3, l2, val, eras = this.localeData().eras();
    for (i3 = 0, l2 = eras.length; i3 < l2; ++i3) {
      val = this.clone().startOf("day").valueOf();
      if (eras[i3].since <= val && val <= eras[i3].until) {
        return eras[i3].narrow;
      }
      if (eras[i3].until <= val && val <= eras[i3].since) {
        return eras[i3].narrow;
      }
    }
    return "";
  }
  function getEraAbbr() {
    var i3, l2, val, eras = this.localeData().eras();
    for (i3 = 0, l2 = eras.length; i3 < l2; ++i3) {
      val = this.clone().startOf("day").valueOf();
      if (eras[i3].since <= val && val <= eras[i3].until) {
        return eras[i3].abbr;
      }
      if (eras[i3].until <= val && val <= eras[i3].since) {
        return eras[i3].abbr;
      }
    }
    return "";
  }
  function getEraYear() {
    var i3, l2, dir, val, eras = this.localeData().eras();
    for (i3 = 0, l2 = eras.length; i3 < l2; ++i3) {
      dir = eras[i3].since <= eras[i3].until ? 1 : -1;
      val = this.clone().startOf("day").valueOf();
      if (eras[i3].since <= val && val <= eras[i3].until || eras[i3].until <= val && val <= eras[i3].since) {
        return (this.year() - hooks(eras[i3].since).year()) * dir + eras[i3].offset;
      }
    }
    return this.year();
  }
  function erasNameRegex(isStrict) {
    if (!hasOwnProp(this, "_erasNameRegex")) {
      computeErasParse.call(this);
    }
    return isStrict ? this._erasNameRegex : this._erasRegex;
  }
  function erasAbbrRegex(isStrict) {
    if (!hasOwnProp(this, "_erasAbbrRegex")) {
      computeErasParse.call(this);
    }
    return isStrict ? this._erasAbbrRegex : this._erasRegex;
  }
  function erasNarrowRegex(isStrict) {
    if (!hasOwnProp(this, "_erasNarrowRegex")) {
      computeErasParse.call(this);
    }
    return isStrict ? this._erasNarrowRegex : this._erasRegex;
  }
  function matchEraAbbr(isStrict, locale2) {
    return locale2.erasAbbrRegex(isStrict);
  }
  function matchEraName(isStrict, locale2) {
    return locale2.erasNameRegex(isStrict);
  }
  function matchEraNarrow(isStrict, locale2) {
    return locale2.erasNarrowRegex(isStrict);
  }
  function matchEraYearOrdinal(isStrict, locale2) {
    return locale2._eraYearOrdinalRegex || matchUnsigned;
  }
  function computeErasParse() {
    var abbrPieces = [], namePieces = [], narrowPieces = [], mixedPieces = [], i3, l2, eras = this.eras();
    for (i3 = 0, l2 = eras.length; i3 < l2; ++i3) {
      namePieces.push(regexEscape2(eras[i3].name));
      abbrPieces.push(regexEscape2(eras[i3].abbr));
      narrowPieces.push(regexEscape2(eras[i3].narrow));
      mixedPieces.push(regexEscape2(eras[i3].name));
      mixedPieces.push(regexEscape2(eras[i3].abbr));
      mixedPieces.push(regexEscape2(eras[i3].narrow));
    }
    this._erasRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i");
    this._erasNameRegex = new RegExp("^(" + namePieces.join("|") + ")", "i");
    this._erasAbbrRegex = new RegExp("^(" + abbrPieces.join("|") + ")", "i");
    this._erasNarrowRegex = new RegExp("^(" + narrowPieces.join("|") + ")", "i");
  }
  addFormatToken(0, ["gg", 2], 0, function() {
    return this.weekYear() % 100;
  });
  addFormatToken(0, ["GG", 2], 0, function() {
    return this.isoWeekYear() % 100;
  });
  function addWeekYearFormatToken(token3, getter) {
    addFormatToken(0, [token3, token3.length], 0, getter);
  }
  addWeekYearFormatToken("gggg", "weekYear");
  addWeekYearFormatToken("ggggg", "weekYear");
  addWeekYearFormatToken("GGGG", "isoWeekYear");
  addWeekYearFormatToken("GGGGG", "isoWeekYear");
  addUnitAlias("weekYear", "gg");
  addUnitAlias("isoWeekYear", "GG");
  addUnitPriority("weekYear", 1);
  addUnitPriority("isoWeekYear", 1);
  addRegexToken("G", matchSigned);
  addRegexToken("g", matchSigned);
  addRegexToken("GG", match1to2, match2);
  addRegexToken("gg", match1to2, match2);
  addRegexToken("GGGG", match1to4, match4);
  addRegexToken("gggg", match1to4, match4);
  addRegexToken("GGGGG", match1to6, match6);
  addRegexToken("ggggg", match1to6, match6);
  addWeekParseToken(["gggg", "ggggg", "GGGG", "GGGGG"], function(input, week, config2, token3) {
    week[token3.substr(0, 2)] = toInt(input);
  });
  addWeekParseToken(["gg", "GG"], function(input, week, config2, token3) {
    week[token3] = hooks.parseTwoDigitYear(input);
  });
  function getSetWeekYear(input) {
    return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy);
  }
  function getSetISOWeekYear(input) {
    return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4);
  }
  function getISOWeeksInYear() {
    return weeksInYear(this.year(), 1, 4);
  }
  function getISOWeeksInISOWeekYear() {
    return weeksInYear(this.isoWeekYear(), 1, 4);
  }
  function getWeeksInYear() {
    var weekInfo = this.localeData()._week;
    return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  }
  function getWeeksInWeekYear() {
    var weekInfo = this.localeData()._week;
    return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
  }
  function getSetWeekYearHelper(input, week, weekday, dow, doy) {
    var weeksTarget;
    if (input == null) {
      return weekOfYear(this, dow, doy).year;
    } else {
      weeksTarget = weeksInYear(input, dow, doy);
      if (week > weeksTarget) {
        week = weeksTarget;
      }
      return setWeekAll.call(this, input, week, weekday, dow, doy);
    }
  }
  function setWeekAll(weekYear, week, weekday, dow, doy) {
    var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
    this.year(date.getUTCFullYear());
    this.month(date.getUTCMonth());
    this.date(date.getUTCDate());
    return this;
  }
  addFormatToken("Q", 0, "Qo", "quarter");
  addUnitAlias("quarter", "Q");
  addUnitPriority("quarter", 7);
  addRegexToken("Q", match1);
  addParseToken("Q", function(input, array2) {
    array2[MONTH] = (toInt(input) - 1) * 3;
  });
  function getSetQuarter(input) {
    return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  }
  addFormatToken("D", ["DD", 2], "Do", "date");
  addUnitAlias("date", "D");
  addUnitPriority("date", 9);
  addRegexToken("D", match1to2);
  addRegexToken("DD", match1to2, match2);
  addRegexToken("Do", function(isStrict, locale2) {
    return isStrict ? locale2._dayOfMonthOrdinalParse || locale2._ordinalParse : locale2._dayOfMonthOrdinalParseLenient;
  });
  addParseToken(["D", "DD"], DATE);
  addParseToken("Do", function(input, array2) {
    array2[DATE] = toInt(input.match(match1to2)[0]);
  });
  var getSetDayOfMonth = makeGetSet("Date", true);
  addFormatToken("DDD", ["DDDD", 3], "DDDo", "dayOfYear");
  addUnitAlias("dayOfYear", "DDD");
  addUnitPriority("dayOfYear", 4);
  addRegexToken("DDD", match1to3);
  addRegexToken("DDDD", match3);
  addParseToken(["DDD", "DDDD"], function(input, array2, config2) {
    config2._dayOfYear = toInt(input);
  });
  function getSetDayOfYear(input) {
    var dayOfYear = Math.round((this.clone().startOf("day") - this.clone().startOf("year")) / 864e5) + 1;
    return input == null ? dayOfYear : this.add(input - dayOfYear, "d");
  }
  addFormatToken("m", ["mm", 2], 0, "minute");
  addUnitAlias("minute", "m");
  addUnitPriority("minute", 14);
  addRegexToken("m", match1to2);
  addRegexToken("mm", match1to2, match2);
  addParseToken(["m", "mm"], MINUTE);
  var getSetMinute = makeGetSet("Minutes", false);
  addFormatToken("s", ["ss", 2], 0, "second");
  addUnitAlias("second", "s");
  addUnitPriority("second", 15);
  addRegexToken("s", match1to2);
  addRegexToken("ss", match1to2, match2);
  addParseToken(["s", "ss"], SECOND);
  var getSetSecond = makeGetSet("Seconds", false);
  addFormatToken("S", 0, 0, function() {
    return ~~(this.millisecond() / 100);
  });
  addFormatToken(0, ["SS", 2], 0, function() {
    return ~~(this.millisecond() / 10);
  });
  addFormatToken(0, ["SSS", 3], 0, "millisecond");
  addFormatToken(0, ["SSSS", 4], 0, function() {
    return this.millisecond() * 10;
  });
  addFormatToken(0, ["SSSSS", 5], 0, function() {
    return this.millisecond() * 100;
  });
  addFormatToken(0, ["SSSSSS", 6], 0, function() {
    return this.millisecond() * 1e3;
  });
  addFormatToken(0, ["SSSSSSS", 7], 0, function() {
    return this.millisecond() * 1e4;
  });
  addFormatToken(0, ["SSSSSSSS", 8], 0, function() {
    return this.millisecond() * 1e5;
  });
  addFormatToken(0, ["SSSSSSSSS", 9], 0, function() {
    return this.millisecond() * 1e6;
  });
  addUnitAlias("millisecond", "ms");
  addUnitPriority("millisecond", 16);
  addRegexToken("S", match1to3, match1);
  addRegexToken("SS", match1to3, match2);
  addRegexToken("SSS", match1to3, match3);
  var token2;
  var getSetMillisecond;
  for (token2 = "SSSS"; token2.length <= 9; token2 += "S") {
    addRegexToken(token2, matchUnsigned);
  }
  function parseMs(input, array2) {
    array2[MILLISECOND] = toInt(("0." + input) * 1e3);
  }
  for (token2 = "S"; token2.length <= 9; token2 += "S") {
    addParseToken(token2, parseMs);
  }
  getSetMillisecond = makeGetSet("Milliseconds", false);
  addFormatToken("z", 0, 0, "zoneAbbr");
  addFormatToken("zz", 0, 0, "zoneName");
  function getZoneAbbr() {
    return this._isUTC ? "UTC" : "";
  }
  function getZoneName() {
    return this._isUTC ? "Coordinated Universal Time" : "";
  }
  var proto = Moment.prototype;
  proto.add = add;
  proto.calendar = calendar$1;
  proto.clone = clone2;
  proto.diff = diff;
  proto.endOf = endOf;
  proto.format = format2;
  proto.from = from;
  proto.fromNow = fromNow;
  proto.to = to;
  proto.toNow = toNow;
  proto.get = stringGet;
  proto.invalidAt = invalidAt;
  proto.isAfter = isAfter;
  proto.isBefore = isBefore;
  proto.isBetween = isBetween;
  proto.isSame = isSame;
  proto.isSameOrAfter = isSameOrAfter;
  proto.isSameOrBefore = isSameOrBefore;
  proto.isValid = isValid$2;
  proto.lang = lang;
  proto.locale = locale;
  proto.localeData = localeData;
  proto.max = prototypeMax;
  proto.min = prototypeMin;
  proto.parsingFlags = parsingFlags;
  proto.set = stringSet;
  proto.startOf = startOf;
  proto.subtract = subtract;
  proto.toArray = toArray;
  proto.toObject = toObject3;
  proto.toDate = toDate;
  proto.toISOString = toISOString;
  proto.inspect = inspect;
  if (typeof Symbol !== "undefined" && Symbol.for != null) {
    proto[Symbol.for("nodejs.util.inspect.custom")] = function() {
      return "Moment<" + this.format() + ">";
    };
  }
  proto.toJSON = toJSON;
  proto.toString = toString5;
  proto.unix = unix;
  proto.valueOf = valueOf;
  proto.creationData = creationData;
  proto.eraName = getEraName;
  proto.eraNarrow = getEraNarrow;
  proto.eraAbbr = getEraAbbr;
  proto.eraYear = getEraYear;
  proto.year = getSetYear;
  proto.isLeapYear = getIsLeapYear;
  proto.weekYear = getSetWeekYear;
  proto.isoWeekYear = getSetISOWeekYear;
  proto.quarter = proto.quarters = getSetQuarter;
  proto.month = getSetMonth;
  proto.daysInMonth = getDaysInMonth;
  proto.week = proto.weeks = getSetWeek;
  proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  proto.weeksInYear = getWeeksInYear;
  proto.weeksInWeekYear = getWeeksInWeekYear;
  proto.isoWeeksInYear = getISOWeeksInYear;
  proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
  proto.date = getSetDayOfMonth;
  proto.day = proto.days = getSetDayOfWeek;
  proto.weekday = getSetLocaleDayOfWeek;
  proto.isoWeekday = getSetISODayOfWeek;
  proto.dayOfYear = getSetDayOfYear;
  proto.hour = proto.hours = getSetHour;
  proto.minute = proto.minutes = getSetMinute;
  proto.second = proto.seconds = getSetSecond;
  proto.millisecond = proto.milliseconds = getSetMillisecond;
  proto.utcOffset = getSetOffset;
  proto.utc = setOffsetToUTC;
  proto.local = setOffsetToLocal;
  proto.parseZone = setOffsetToParsedOffset;
  proto.hasAlignedHourOffset = hasAlignedHourOffset;
  proto.isDST = isDaylightSavingTime;
  proto.isLocal = isLocal;
  proto.isUtcOffset = isUtcOffset;
  proto.isUtc = isUtc;
  proto.isUTC = isUtc;
  proto.zoneAbbr = getZoneAbbr;
  proto.zoneName = getZoneName;
  proto.dates = deprecate("dates accessor is deprecated. Use date instead.", getSetDayOfMonth);
  proto.months = deprecate("months accessor is deprecated. Use month instead", getSetMonth);
  proto.years = deprecate("years accessor is deprecated. Use year instead", getSetYear);
  proto.zone = deprecate("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/", getSetZone);
  proto.isDSTShifted = deprecate("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information", isDaylightSavingTimeShifted);
  function createUnix(input) {
    return createLocal(input * 1e3);
  }
  function createInZone() {
    return createLocal.apply(null, arguments).parseZone();
  }
  function preParsePostFormat(string2) {
    return string2;
  }
  var proto$1 = Locale.prototype;
  proto$1.calendar = calendar;
  proto$1.longDateFormat = longDateFormat;
  proto$1.invalidDate = invalidDate;
  proto$1.ordinal = ordinal;
  proto$1.preparse = preParsePostFormat;
  proto$1.postformat = preParsePostFormat;
  proto$1.relativeTime = relativeTime;
  proto$1.pastFuture = pastFuture;
  proto$1.set = set3;
  proto$1.eras = localeEras;
  proto$1.erasParse = localeErasParse;
  proto$1.erasConvertYear = localeErasConvertYear;
  proto$1.erasAbbrRegex = erasAbbrRegex;
  proto$1.erasNameRegex = erasNameRegex;
  proto$1.erasNarrowRegex = erasNarrowRegex;
  proto$1.months = localeMonths;
  proto$1.monthsShort = localeMonthsShort;
  proto$1.monthsParse = localeMonthsParse;
  proto$1.monthsRegex = monthsRegex;
  proto$1.monthsShortRegex = monthsShortRegex;
  proto$1.week = localeWeek;
  proto$1.firstDayOfYear = localeFirstDayOfYear;
  proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  proto$1.weekdays = localeWeekdays;
  proto$1.weekdaysMin = localeWeekdaysMin;
  proto$1.weekdaysShort = localeWeekdaysShort;
  proto$1.weekdaysParse = localeWeekdaysParse;
  proto$1.weekdaysRegex = weekdaysRegex;
  proto$1.weekdaysShortRegex = weekdaysShortRegex;
  proto$1.weekdaysMinRegex = weekdaysMinRegex;
  proto$1.isPM = localeIsPM;
  proto$1.meridiem = localeMeridiem;
  function get$12(format3, index3, field, setter) {
    var locale2 = getLocale(), utc = createUTC().set(setter, index3);
    return locale2[field](utc, format3);
  }
  function listMonthsImpl(format3, index3, field) {
    if (isNumber3(format3)) {
      index3 = format3;
      format3 = void 0;
    }
    format3 = format3 || "";
    if (index3 != null) {
      return get$12(format3, index3, field, "month");
    }
    var i3, out = [];
    for (i3 = 0; i3 < 12; i3++) {
      out[i3] = get$12(format3, i3, field, "month");
    }
    return out;
  }
  function listWeekdaysImpl(localeSorted, format3, index3, field) {
    if (typeof localeSorted === "boolean") {
      if (isNumber3(format3)) {
        index3 = format3;
        format3 = void 0;
      }
      format3 = format3 || "";
    } else {
      format3 = localeSorted;
      index3 = format3;
      localeSorted = false;
      if (isNumber3(format3)) {
        index3 = format3;
        format3 = void 0;
      }
      format3 = format3 || "";
    }
    var locale2 = getLocale(), shift2 = localeSorted ? locale2._week.dow : 0, i3, out = [];
    if (index3 != null) {
      return get$12(format3, (index3 + shift2) % 7, field, "day");
    }
    for (i3 = 0; i3 < 7; i3++) {
      out[i3] = get$12(format3, (i3 + shift2) % 7, field, "day");
    }
    return out;
  }
  function listMonths(format3, index3) {
    return listMonthsImpl(format3, index3, "months");
  }
  function listMonthsShort(format3, index3) {
    return listMonthsImpl(format3, index3, "monthsShort");
  }
  function listWeekdays(localeSorted, format3, index3) {
    return listWeekdaysImpl(localeSorted, format3, index3, "weekdays");
  }
  function listWeekdaysShort(localeSorted, format3, index3) {
    return listWeekdaysImpl(localeSorted, format3, index3, "weekdaysShort");
  }
  function listWeekdaysMin(localeSorted, format3, index3) {
    return listWeekdaysImpl(localeSorted, format3, index3, "weekdaysMin");
  }
  getSetGlobalLocale("en", {
    eras: [
      {
        since: "0001-01-01",
        until: Infinity,
        offset: 1,
        name: "Anno Domini",
        narrow: "AD",
        abbr: "AD"
      },
      {
        since: "0000-12-31",
        until: -Infinity,
        offset: 1,
        name: "Before Christ",
        narrow: "BC",
        abbr: "BC"
      }
    ],
    dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
    ordinal: function(number) {
      var b2 = number % 10, output2 = toInt(number % 100 / 10) === 1 ? "th" : b2 === 1 ? "st" : b2 === 2 ? "nd" : b2 === 3 ? "rd" : "th";
      return number + output2;
    }
  });
  hooks.lang = deprecate("moment.lang is deprecated. Use moment.locale instead.", getSetGlobalLocale);
  hooks.langData = deprecate("moment.langData is deprecated. Use moment.localeData instead.", getLocale);
  var mathAbs = Math.abs;
  function abs2() {
    var data2 = this._data;
    this._milliseconds = mathAbs(this._milliseconds);
    this._days = mathAbs(this._days);
    this._months = mathAbs(this._months);
    data2.milliseconds = mathAbs(data2.milliseconds);
    data2.seconds = mathAbs(data2.seconds);
    data2.minutes = mathAbs(data2.minutes);
    data2.hours = mathAbs(data2.hours);
    data2.months = mathAbs(data2.months);
    data2.years = mathAbs(data2.years);
    return this;
  }
  function addSubtract$1(duration, input, value, direction) {
    var other = createDuration(input, value);
    duration._milliseconds += direction * other._milliseconds;
    duration._days += direction * other._days;
    duration._months += direction * other._months;
    return duration._bubble();
  }
  function add$1(input, value) {
    return addSubtract$1(this, input, value, 1);
  }
  function subtract$1(input, value) {
    return addSubtract$1(this, input, value, -1);
  }
  function absCeil(number) {
    if (number < 0) {
      return Math.floor(number);
    } else {
      return Math.ceil(number);
    }
  }
  function bubble() {
    var milliseconds2 = this._milliseconds, days2 = this._days, months2 = this._months, data2 = this._data, seconds2, minutes2, hours2, years2, monthsFromDays;
    if (!(milliseconds2 >= 0 && days2 >= 0 && months2 >= 0 || milliseconds2 <= 0 && days2 <= 0 && months2 <= 0)) {
      milliseconds2 += absCeil(monthsToDays(months2) + days2) * 864e5;
      days2 = 0;
      months2 = 0;
    }
    data2.milliseconds = milliseconds2 % 1e3;
    seconds2 = absFloor(milliseconds2 / 1e3);
    data2.seconds = seconds2 % 60;
    minutes2 = absFloor(seconds2 / 60);
    data2.minutes = minutes2 % 60;
    hours2 = absFloor(minutes2 / 60);
    data2.hours = hours2 % 24;
    days2 += absFloor(hours2 / 24);
    monthsFromDays = absFloor(daysToMonths(days2));
    months2 += monthsFromDays;
    days2 -= absCeil(monthsToDays(monthsFromDays));
    years2 = absFloor(months2 / 12);
    months2 %= 12;
    data2.days = days2;
    data2.months = months2;
    data2.years = years2;
    return this;
  }
  function daysToMonths(days2) {
    return days2 * 4800 / 146097;
  }
  function monthsToDays(months2) {
    return months2 * 146097 / 4800;
  }
  function as(units) {
    if (!this.isValid()) {
      return NaN;
    }
    var days2, months2, milliseconds2 = this._milliseconds;
    units = normalizeUnits(units);
    if (units === "month" || units === "quarter" || units === "year") {
      days2 = this._days + milliseconds2 / 864e5;
      months2 = this._months + daysToMonths(days2);
      switch (units) {
        case "month":
          return months2;
        case "quarter":
          return months2 / 3;
        case "year":
          return months2 / 12;
      }
    } else {
      days2 = this._days + Math.round(monthsToDays(this._months));
      switch (units) {
        case "week":
          return days2 / 7 + milliseconds2 / 6048e5;
        case "day":
          return days2 + milliseconds2 / 864e5;
        case "hour":
          return days2 * 24 + milliseconds2 / 36e5;
        case "minute":
          return days2 * 1440 + milliseconds2 / 6e4;
        case "second":
          return days2 * 86400 + milliseconds2 / 1e3;
        case "millisecond":
          return Math.floor(days2 * 864e5) + milliseconds2;
        default:
          throw new Error("Unknown unit " + units);
      }
    }
  }
  function valueOf$1() {
    if (!this.isValid()) {
      return NaN;
    }
    return this._milliseconds + this._days * 864e5 + this._months % 12 * 2592e6 + toInt(this._months / 12) * 31536e6;
  }
  function makeAs(alias) {
    return function() {
      return this.as(alias);
    };
  }
  var asMilliseconds = makeAs("ms");
  var asSeconds = makeAs("s");
  var asMinutes = makeAs("m");
  var asHours = makeAs("h");
  var asDays = makeAs("d");
  var asWeeks = makeAs("w");
  var asMonths = makeAs("M");
  var asQuarters = makeAs("Q");
  var asYears = makeAs("y");
  function clone$1() {
    return createDuration(this);
  }
  function get$2(units) {
    units = normalizeUnits(units);
    return this.isValid() ? this[units + "s"]() : NaN;
  }
  function makeGetter(name) {
    return function() {
      return this.isValid() ? this._data[name] : NaN;
    };
  }
  var milliseconds = makeGetter("milliseconds");
  var seconds = makeGetter("seconds");
  var minutes = makeGetter("minutes");
  var hours = makeGetter("hours");
  var days = makeGetter("days");
  var months = makeGetter("months");
  var years = makeGetter("years");
  function weeks() {
    return absFloor(this.days() / 7);
  }
  var round = Math.round;
  var thresholds = {
    ss: 44,
    s: 45,
    m: 45,
    h: 22,
    d: 26,
    w: null,
    M: 11
  };
  function substituteTimeAgo(string2, number, withoutSuffix, isFuture, locale2) {
    return locale2.relativeTime(number || 1, !!withoutSuffix, string2, isFuture);
  }
  function relativeTime$1(posNegDuration, withoutSuffix, thresholds2, locale2) {
    var duration = createDuration(posNegDuration).abs(), seconds2 = round(duration.as("s")), minutes2 = round(duration.as("m")), hours2 = round(duration.as("h")), days2 = round(duration.as("d")), months2 = round(duration.as("M")), weeks2 = round(duration.as("w")), years2 = round(duration.as("y")), a2 = seconds2 <= thresholds2.ss && ["s", seconds2] || seconds2 < thresholds2.s && ["ss", seconds2] || minutes2 <= 1 && ["m"] || minutes2 < thresholds2.m && ["mm", minutes2] || hours2 <= 1 && ["h"] || hours2 < thresholds2.h && ["hh", hours2] || days2 <= 1 && ["d"] || days2 < thresholds2.d && ["dd", days2];
    if (thresholds2.w != null) {
      a2 = a2 || weeks2 <= 1 && ["w"] || weeks2 < thresholds2.w && ["ww", weeks2];
    }
    a2 = a2 || months2 <= 1 && ["M"] || months2 < thresholds2.M && ["MM", months2] || years2 <= 1 && ["y"] || ["yy", years2];
    a2[2] = withoutSuffix;
    a2[3] = +posNegDuration > 0;
    a2[4] = locale2;
    return substituteTimeAgo.apply(null, a2);
  }
  function getSetRelativeTimeRounding(roundingFunction) {
    if (roundingFunction === void 0) {
      return round;
    }
    if (typeof roundingFunction === "function") {
      round = roundingFunction;
      return true;
    }
    return false;
  }
  function getSetRelativeTimeThreshold(threshold, limit) {
    if (thresholds[threshold] === void 0) {
      return false;
    }
    if (limit === void 0) {
      return thresholds[threshold];
    }
    thresholds[threshold] = limit;
    if (threshold === "s") {
      thresholds.ss = limit - 1;
    }
    return true;
  }
  function humanize3(argWithSuffix, argThresholds) {
    if (!this.isValid()) {
      return this.localeData().invalidDate();
    }
    var withSuffix = false, th2 = thresholds, locale2, output2;
    if (typeof argWithSuffix === "object") {
      argThresholds = argWithSuffix;
      argWithSuffix = false;
    }
    if (typeof argWithSuffix === "boolean") {
      withSuffix = argWithSuffix;
    }
    if (typeof argThresholds === "object") {
      th2 = Object.assign({}, thresholds, argThresholds);
      if (argThresholds.s != null && argThresholds.ss == null) {
        th2.ss = argThresholds.s - 1;
      }
    }
    locale2 = this.localeData();
    output2 = relativeTime$1(this, !withSuffix, th2, locale2);
    if (withSuffix) {
      output2 = locale2.pastFuture(+this, output2);
    }
    return locale2.postformat(output2);
  }
  var abs$1 = Math.abs;
  function sign(x2) {
    return (x2 > 0) - (x2 < 0) || +x2;
  }
  function toISOString$1() {
    if (!this.isValid()) {
      return this.localeData().invalidDate();
    }
    var seconds2 = abs$1(this._milliseconds) / 1e3, days2 = abs$1(this._days), months2 = abs$1(this._months), minutes2, hours2, years2, s2, total = this.asSeconds(), totalSign, ymSign, daysSign, hmsSign;
    if (!total) {
      return "P0D";
    }
    minutes2 = absFloor(seconds2 / 60);
    hours2 = absFloor(minutes2 / 60);
    seconds2 %= 60;
    minutes2 %= 60;
    years2 = absFloor(months2 / 12);
    months2 %= 12;
    s2 = seconds2 ? seconds2.toFixed(3).replace(/\.?0+$/, "") : "";
    totalSign = total < 0 ? "-" : "";
    ymSign = sign(this._months) !== sign(total) ? "-" : "";
    daysSign = sign(this._days) !== sign(total) ? "-" : "";
    hmsSign = sign(this._milliseconds) !== sign(total) ? "-" : "";
    return totalSign + "P" + (years2 ? ymSign + years2 + "Y" : "") + (months2 ? ymSign + months2 + "M" : "") + (days2 ? daysSign + days2 + "D" : "") + (hours2 || minutes2 || seconds2 ? "T" : "") + (hours2 ? hmsSign + hours2 + "H" : "") + (minutes2 ? hmsSign + minutes2 + "M" : "") + (seconds2 ? hmsSign + s2 + "S" : "");
  }
  var proto$2 = Duration.prototype;
  proto$2.isValid = isValid$1;
  proto$2.abs = abs2;
  proto$2.add = add$1;
  proto$2.subtract = subtract$1;
  proto$2.as = as;
  proto$2.asMilliseconds = asMilliseconds;
  proto$2.asSeconds = asSeconds;
  proto$2.asMinutes = asMinutes;
  proto$2.asHours = asHours;
  proto$2.asDays = asDays;
  proto$2.asWeeks = asWeeks;
  proto$2.asMonths = asMonths;
  proto$2.asQuarters = asQuarters;
  proto$2.asYears = asYears;
  proto$2.valueOf = valueOf$1;
  proto$2._bubble = bubble;
  proto$2.clone = clone$1;
  proto$2.get = get$2;
  proto$2.milliseconds = milliseconds;
  proto$2.seconds = seconds;
  proto$2.minutes = minutes;
  proto$2.hours = hours;
  proto$2.days = days;
  proto$2.weeks = weeks;
  proto$2.months = months;
  proto$2.years = years;
  proto$2.humanize = humanize3;
  proto$2.toISOString = toISOString$1;
  proto$2.toString = toISOString$1;
  proto$2.toJSON = toISOString$1;
  proto$2.locale = locale;
  proto$2.localeData = localeData;
  proto$2.toIsoString = deprecate("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)", toISOString$1);
  proto$2.lang = lang;
  addFormatToken("X", 0, 0, "unix");
  addFormatToken("x", 0, 0, "valueOf");
  addRegexToken("x", matchSigned);
  addRegexToken("X", matchTimestamp);
  addParseToken("X", function(input, array2, config2) {
    config2._d = new Date(parseFloat(input) * 1e3);
  });
  addParseToken("x", function(input, array2, config2) {
    config2._d = new Date(toInt(input));
  });
  //! moment.js
  hooks.version = "2.29.1";
  setHookCallback(createLocal);
  hooks.fn = proto;
  hooks.min = min2;
  hooks.max = max2;
  hooks.now = now3;
  hooks.utc = createUTC;
  hooks.unix = createUnix;
  hooks.months = listMonths;
  hooks.isDate = isDate2;
  hooks.locale = getSetGlobalLocale;
  hooks.invalid = createInvalid;
  hooks.duration = createDuration;
  hooks.isMoment = isMoment;
  hooks.weekdays = listWeekdays;
  hooks.parseZone = createInZone;
  hooks.localeData = getLocale;
  hooks.isDuration = isDuration;
  hooks.monthsShort = listMonthsShort;
  hooks.weekdaysMin = listWeekdaysMin;
  hooks.defineLocale = defineLocale;
  hooks.updateLocale = updateLocale;
  hooks.locales = listLocales;
  hooks.weekdaysShort = listWeekdaysShort;
  hooks.normalizeUnits = normalizeUnits;
  hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  hooks.calendarFormat = getCalendarFormat;
  hooks.prototype = proto;
  hooks.HTML5_FMT = {
    DATETIME_LOCAL: "YYYY-MM-DDTHH:mm",
    DATETIME_LOCAL_SECONDS: "YYYY-MM-DDTHH:mm:ss",
    DATETIME_LOCAL_MS: "YYYY-MM-DDTHH:mm:ss.SSS",
    DATE: "YYYY-MM-DD",
    TIME: "HH:mm",
    TIME_SECONDS: "HH:mm:ss",
    TIME_MS: "HH:mm:ss.SSS",
    WEEK: "GGGG-[W]WW",
    MONTH: "YYYY-MM"
  };
  var moment_default = hooks;
});

// build/clients/initial-access/CreateInitialAccessToken.js
var require_CreateInitialAccessToken = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => CreateInitialAccessToken
  });
  function CreateInitialAccessToken() {
    const {t: t5} = useTranslation("clients");
    const {handleSubmit, control} = useForm();
    const adminClient = useAdminClient();
    const {realm: realm2} = useRealm();
    const {addAlert, addError} = useAlerts();
    const history = useHistory();
    const [token2, setToken] = useState("");
    const save = async (clientToken) => {
      try {
        const access = await adminClient.realms.createClientsInitialAccess({realm: realm2}, clientToken);
        setToken(access.token);
      } catch (error2) {
        addError("clients:tokenSaveError", error2);
      }
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, token2 && /* @__PURE__ */ react.createElement(AccessTokenDialog, {
      token: token2,
      toggleDialog: () => {
        setToken("");
        addAlert(t5("tokenSaveSuccess"), AlertVariant.success);
        history.push(toClients({realm: realm2, tab: "initialAccessToken"}));
      }
    }), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "clients:createToken",
      subKey: "clients-help:createToken"
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      role: "create-client",
      onSubmit: handleSubmit(save)
    }, /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("expiration"),
      fieldId: "expiration",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "clients-help:expiration",
        fieldLabelId: "clients:expiration"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "expiration",
      defaultValue: 86400,
      control,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
        "data-testid": "expiration",
        value,
        onChange,
        units: ["days", "hours", "minutes", "seconds"]
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("count"),
      fieldId: "count",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "clients-help:count",
        fieldLabelId: "clients:count"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "count",
      defaultValue: 1,
      control,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(NumberInput, {
        "data-testid": "count",
        inputName: "count",
        inputAriaLabel: t5("count"),
        min: 1,
        value,
        onPlus: () => onChange(value + 1),
        onMinus: () => onChange(value - 1),
        onChange: (event) => onChange(Number(event.target.value))
      })
    })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      variant: "primary",
      type: "submit",
      "data-testid": "save"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "cancel",
      variant: "link",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toClients({realm: realm2, tab: "initialAccessToken"})
      })
    }, t5("common:cancel"))))));
  }
});

// build/clients/import/ImportForm.js
var require_ImportForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => ImportForm
  });
  function ImportForm() {
    const {t: t5} = useTranslation("clients");
    const history = useHistory();
    const adminClient = useAdminClient();
    const {realm: realm2} = useRealm();
    const form2 = useForm();
    const {register: register2, handleSubmit, setValue} = form2;
    const [imported, setImported] = useState({});
    const {addAlert, addError} = useAlerts();
    const handleFileChange = (obj) => {
      const defaultClient = {
        protocol: "",
        clientId: "",
        name: "",
        description: ""
      };
      convertToFormValues(obj || defaultClient, setValue);
      setImported(obj || defaultClient);
    };
    const save = async (client2) => {
      try {
        const newClient = await adminClient.clients.create({
          ...imported,
          ...convertFormValuesToObject(client2)
        });
        addAlert(t5("clientImportSuccess"), AlertVariant.success);
        history.push(toClient({realm: realm2, clientId: newClient.id, tab: "settings"}));
      } catch (error2) {
        addError("clients:clientImportError", error2);
      }
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "clients:importClient",
      subKey: "clients:clientsExplain"
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      onSubmit: handleSubmit(save),
      role: "manage-clients"
    }, /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, /* @__PURE__ */ react.createElement(JsonFileUpload, {
      id: "realm-file",
      onChange: handleFileChange
    }), /* @__PURE__ */ react.createElement(ClientDescription, null), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:type"),
      fieldId: "kc-type"
    }, /* @__PURE__ */ react.createElement(TextInput, {
      type: "text",
      id: "kc-type",
      name: "protocol",
      isReadOnly: true,
      ref: register2()
    })), /* @__PURE__ */ react.createElement(CapabilityConfig, {
      unWrap: true
    }), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      variant: "primary",
      type: "submit"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toClients({realm: realm2})
      })
    }, t5("common:cancel")))))));
  }
});

// build/clients/ClientsSection.js
var require_ClientsSection = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => ClientsSection
  });
  function ClientsSection() {
    const {t: t5} = useTranslation("clients");
    const {addAlert, addError} = useAlerts();
    const adminClient = useAdminClient();
    const {realm: realm2} = useRealm();
    const baseUrl = getBaseUrl(adminClient);
    const [key, setKey] = useState(0);
    const refresh = () => setKey(new Date().getTime());
    const [selectedClient, setSelectedClient] = useState();
    const loader = async (first2, max2, search2) => {
      const params = {
        first: first2,
        max: max2
      };
      if (search2) {
        params.clientId = search2;
        params.search = true;
      }
      return await adminClient.clients.find({...params});
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: t5("clientDelete", {clientId: selectedClient?.clientId}),
      messageKey: "clients:clientDeleteConfirm",
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.clients.del({
            id: selectedClient.id
          });
          addAlert(t5("clientDeletedSuccess"), AlertVariant.success);
          refresh();
        } catch (error2) {
          addError("clients:clientDeleteError", error2);
        }
      }
    });
    const ClientDetailLink = (client2) => /* @__PURE__ */ react.createElement(Link, {
      key: client2.id,
      to: toClient({realm: realm2, clientId: client2.id, tab: "settings"})
    }, client2.clientId, !client2.enabled && /* @__PURE__ */ react.createElement(Badge, {
      key: `${client2.id}-disabled`,
      isRead: true,
      className: "pf-u-ml-sm"
    }, t5("common:disabled")));
    const ClientDescription2 = (client2) => /* @__PURE__ */ react.createElement(TableText, {
      wrapModifier: "truncate"
    }, emptyFormatter()(client2.description));
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "clients:clientList",
      subKey: "clients:clientsExplain",
      divider: false
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      className: "pf-u-p-0"
    }, /* @__PURE__ */ react.createElement(KeycloakTabs, {
      isBox: true
    }, /* @__PURE__ */ react.createElement(Tab, {
      "data-testid": "list",
      eventKey: "list",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("clientsList"))
    }, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
      key,
      loader,
      isPaginated: true,
      ariaLabelKey: "clients:clientList",
      searchPlaceholderKey: "clients:searchForClient",
      toolbarItem: /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
        component: (props) => /* @__PURE__ */ react.createElement(Link, {
          ...props,
          to: toAddClient({realm: realm2})
        })
      }, t5("createClient"))), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
        component: (props) => /* @__PURE__ */ react.createElement(Link, {
          ...props,
          to: toImportClient({realm: realm2})
        }),
        variant: "link"
      }, t5("importClient")))),
      actionResolver: (rowData) => {
        const client2 = rowData.data;
        const actions2 = [
          {
            title: t5("common:export"),
            onClick() {
              exportClient(client2);
            }
          }
        ];
        if (!isRealmClient(client2)) {
          actions2.push({
            title: t5("common:delete"),
            onClick() {
              setSelectedClient(client2);
              toggleDeleteDialog();
            }
          });
        }
        return actions2;
      },
      columns: [
        {
          name: "clientId",
          displayKey: "common:clientId",
          cellRenderer: ClientDetailLink
        },
        {
          name: "protocol",
          displayKey: "common:type",
          cellRenderer: (client2) => getProtocolName(t5, client2.protocol ?? "openid-connect")
        },
        {
          name: "description",
          displayKey: "common:description",
          transforms: [cellWidth(20)],
          cellRenderer: ClientDescription2
        },
        {
          name: "baseUrl",
          displayKey: "clients:homeURL",
          cellFormatters: [formattedLinkTableCell(), emptyFormatter()],
          cellRenderer: (client2) => {
            if (client2.rootUrl) {
              if (!client2.rootUrl.startsWith("http") || client2.rootUrl.includes("$")) {
                client2.rootUrl = client2.rootUrl.replace("${authBaseUrl}", baseUrl).replace("${authAdminUrl}", baseUrl) + (client2.baseUrl ? client2.baseUrl.substr(1) : "");
              }
            }
            return client2.rootUrl;
          }
        }
      ]
    })), /* @__PURE__ */ react.createElement(Tab, {
      "data-testid": "initialAccessToken",
      eventKey: "initialAccessToken",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("initialAccessToken"))
    }, /* @__PURE__ */ react.createElement(InitialAccessTokenList, null)))));
  }
});

// build/clients/authorization/ResourceDetails.js
var require_ResourceDetails = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => ResourceDetails
  });
  function ResourceDetails() {
    const {t: t5} = useTranslation("clients");
    const [client2, setClient] = useState();
    const [resource2, setResource] = useState();
    const [permissions, setPermission] = useState();
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const form2 = useForm({
      shouldUnregister: false,
      mode: "onChange"
    });
    const {register: register2, errors, control, setValue, handleSubmit} = form2;
    const {id: id3, resourceId, realm: realm2} = useParams();
    const history = useHistory();
    const setupForm = (resource22 = {}) => {
      convertToFormValues(resource22, setValue, ["uris"]);
    };
    useFetch(async () => {
      const [client22, resource22, permissions2] = await Promise.all([
        adminClient.clients.findOne({id: id3}),
        resourceId ? adminClient.clients.getResource({id: id3, resourceId}) : Promise.resolve(void 0),
        resourceId ? adminClient.clients.listPermissionsByResource({id: id3, resourceId}) : Promise.resolve(void 0)
      ]);
      return {client: client22, resource: resource22, permissions: permissions2};
    }, ({client: client22, resource: resource22, permissions: permissions2}) => {
      if (!client22) {
        throw new Error(t5("common:notFound"));
      }
      setClient(client22);
      setPermission(permissions2);
      setResource(resource22);
      setupForm(resource22);
    }, []);
    const save = async (submitted) => {
      const resource22 = convertFormValuesToObject(submitted, ["uris"]);
      try {
        if (resourceId) {
          await adminClient.clients.updateResource({id: id3, resourceId}, resource22);
        } else {
          const result = await adminClient.clients.createResource({id: id3}, resource22);
          history.push(toResourceDetails({realm: realm2, id: id3, resourceId: result._id}));
        }
        addAlert(t5((resourceId ? "update" : "create") + "ResourceSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("clients:resourceSaveError", error2);
      }
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "clients:deleteResource",
      children: /* @__PURE__ */ react.createElement(react.Fragment, null, t5("deleteResourceConfirm"), permissions?.length !== 0 && /* @__PURE__ */ react.createElement(Alert, {
        variant: "warning",
        isInline: true,
        isPlain: true,
        title: t5("deleteResourceWarning"),
        className: "pf-u-pt-lg"
      }, /* @__PURE__ */ react.createElement("p", {
        className: "pf-u-pt-xs"
      }, permissions?.map((permission) => /* @__PURE__ */ react.createElement("strong", {
        key: permission.id,
        className: "pf-u-pr-md"
      }, permission.name))))),
      continueButtonLabel: "clients:confirm",
      onConfirm: async () => {
        try {
          await adminClient.clients.delResource({
            id: id3,
            resourceId
          });
          addAlert(t5("resourceDeletedSuccess"), AlertVariant.success);
          history.push(toClient({realm: realm2, clientId: id3, tab: "authorization"}));
        } catch (error2) {
          addError("clients:resourceDeletedError", error2);
        }
      }
    });
    if (!client2) {
      return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
    }
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: resourceId ? resource2?.name : "clients:createResource",
      dropdownItems: resourceId ? [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "delete",
          "data-testid": "delete-resource",
          onClick: () => toggleDeleteDialog()
        }, t5("common:delete"))
      ] : void 0
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      role: "manage-clients",
      className: "keycloak__resource-details__form",
      onSubmit: handleSubmit(save)
    }, /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("owner"),
      fieldId: "owner",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "clients-help:owner",
        fieldLabelId: "clients:owner"
      })
    }, /* @__PURE__ */ react.createElement(TextInput, {
      id: "owner",
      value: client2.clientId,
      isReadOnly: true
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:name"),
      fieldId: "name",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "clients-help:resourceName",
        fieldLabelId: "name"
      }),
      helperTextInvalid: t5("common:required"),
      validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      isRequired: true
    }, /* @__PURE__ */ react.createElement(TextInput, {
      id: "name",
      name: "name",
      ref: register2({required: true}),
      validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("displayName"),
      fieldId: "displayName",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "clients-help:displayName",
        fieldLabelId: "name"
      })
    }, /* @__PURE__ */ react.createElement(TextInput, {
      id: "displayName",
      name: "name",
      ref: register2
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("type"),
      fieldId: "type",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "clients-help:type",
        fieldLabelId: "type"
      })
    }, /* @__PURE__ */ react.createElement(TextInput, {
      id: "type",
      name: "type",
      ref: register2
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("uris"),
      fieldId: "uris",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "clients-help:uris",
        fieldLabelId: "clients:uris"
      })
    }, /* @__PURE__ */ react.createElement(MultiLineInput, {
      name: "uris",
      "aria-label": t5("uri"),
      addButtonLabel: "clients:addUri"
    })), /* @__PURE__ */ react.createElement(ScopePicker, {
      clientId: id3
    }), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("iconUri"),
      fieldId: "iconUri",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "clients-help:iconUri",
        fieldLabelId: "clients:iconUri"
      })
    }, /* @__PURE__ */ react.createElement(TextInput, {
      id: "iconUri",
      name: "icon_uri",
      ref: register2
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      hasNoPaddingTop: true,
      label: t5("ownerManagedAccess"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "clients-help:ownerManagedAccess",
        fieldLabelId: "clients:ownerManagedAccess"
      }),
      fieldId: "ownerManagedAccess"
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "ownerManagedAccess",
      control,
      defaultValue: false,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
        id: "ownerManagedAccess",
        label: t5("common:on"),
        labelOff: t5("common:off"),
        isChecked: value,
        onChange
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      hasNoPaddingTop: true,
      label: t5("resourceAttribute"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "clients-help:resourceAttribute",
        fieldLabelId: "clients:resourceAttribute"
      }),
      fieldId: "resourceAttribute"
    }, /* @__PURE__ */ react.createElement(AttributeInput, {
      name: "attributes"
    })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement("div", {
      className: "pf-u-mt-md"
    }, /* @__PURE__ */ react.createElement(Button, {
      variant: ButtonVariant.primary,
      type: "submit",
      "data-testid": "save"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      "data-testid": "cancel",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toClient({
          realm: realm2,
          clientId: id3,
          tab: "authorization"
        })
      })
    }, t5("common:cancel"))))))));
  }
});

// build/clients/ClientDetails.js
var require_ClientDetails = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => ClientDetails
  });
  var ClientDetailHeader = ({
    onChange,
    value,
    save,
    client: client2,
    toggleDownloadDialog,
    toggleDeleteDialog
  }) => {
    const {t: t5} = useTranslation("clients");
    const [toggleDisableDialog, DisableConfirm] = useConfirmDialog({
      titleKey: "clients:disableConfirmTitle",
      messageKey: "clients:disableConfirm",
      continueButtonLabel: "common:disable",
      onConfirm: () => {
        onChange(!value);
        save();
      }
    });
    const badges = useMemo(() => {
      const protocolName = getProtocolName(t5, client2.protocol ?? "openid-connect");
      const text = client2.bearerOnly ? /* @__PURE__ */ react.createElement(Tooltip, {
        "data-testid": "bearer-only-explainer-tooltip",
        content: t5("explainBearerOnly")
      }, /* @__PURE__ */ react.createElement(Label, {
        "data-testid": "bearer-only-explainer-label",
        icon: /* @__PURE__ */ react.createElement(InfoCircleIcon, null)
      }, protocolName)) : /* @__PURE__ */ react.createElement(Label, null, protocolName);
      return [{text}];
    }, [client2, t5]);
    const dropdownItems = [
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "download",
        onClick: toggleDownloadDialog
      }, t5("downloadAdapterConfig")),
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "export",
        onClick: () => exportClient(client2)
      }, t5("common:export")),
      ...!isRealmClient(client2) ? [
        /* @__PURE__ */ react.createElement(Divider, {
          key: "divider"
        }),
        /* @__PURE__ */ react.createElement(DropdownItem, {
          "data-testid": "delete-client",
          key: "delete",
          onClick: toggleDeleteDialog
        }, t5("common:delete"))
      ] : []
    ];
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DisableConfirm, null), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: client2 ? client2.clientId : "",
      subKey: "clients:clientsExplain",
      badges,
      divider: false,
      helpTextKey: "clients-help:enableDisable",
      dropdownItems,
      isEnabled: value,
      onToggle: (value2) => {
        if (!value2) {
          toggleDisableDialog();
        } else {
          onChange(value2);
          save();
        }
      }
    }));
  };
  function ClientDetails() {
    const {t: t5} = useTranslation("clients");
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const {realm: realm2} = useRealm();
    const history = useHistory();
    const [downloadDialogOpen, toggleDownloadDialogOpen] = useToggle();
    const [changeAuthenticatorOpen, toggleChangeAuthenticatorOpen] = useToggle();
    const [clientScopeSubTab, setClientScopeSubTab] = useState(30);
    const [authorizationSubTab, setAuthorizationSubTab] = useState(40);
    const form2 = useForm({shouldUnregister: false});
    const {clientId} = useParams();
    const clientAuthenticatorType = useWatch({
      control: form2.control,
      name: "clientAuthenticatorType",
      defaultValue: "client-secret"
    });
    const [client2, setClient] = useState();
    const loader = async () => {
      const roles2 = await adminClient.clients.listRoles({id: clientId});
      return lodash.sortBy(roles2, (role) => role.name?.toUpperCase());
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "clients:clientDeleteConfirmTitle",
      messageKey: "clients:clientDeleteConfirm",
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.clients.del({id: clientId});
          addAlert(t5("clientDeletedSuccess"), AlertVariant.success);
          history.push(toClients({realm: realm2}));
        } catch (error2) {
          addError("clients:clientDeleteError", error2);
        }
      }
    });
    const setupForm = (client22) => {
      convertToFormValues(client22, form2.setValue, ["redirectUris", "webOrigins"]);
    };
    useFetch(() => adminClient.clients.findOne({id: clientId}), (fetchedClient) => {
      if (!fetchedClient) {
        throw new Error(t5("common:notFound"));
      }
      setClient(cloneDeep(fetchedClient));
      setupForm(fetchedClient);
    }, [clientId]);
    const save = async ({confirmed = false, messageKey = "clientSaveSuccess"} = {
      confirmed: false,
      messageKey: "clientSaveSuccess"
    }) => {
      if (await form2.trigger()) {
        if (!client2?.publicClient && client2?.clientAuthenticatorType !== clientAuthenticatorType && !confirmed) {
          toggleChangeAuthenticatorOpen();
          return;
        }
        const submittedClient = convertFormValuesToObject(form2.getValues(), [
          "redirectUris",
          "webOrigins"
        ]);
        try {
          const newClient = {
            ...client2,
            ...submittedClient
          };
          newClient.clientId = newClient.clientId?.trim();
          await adminClient.clients.update({id: clientId}, newClient);
          setupForm(newClient);
          setClient(newClient);
          addAlert(t5(messageKey), AlertVariant.success);
        } catch (error2) {
          addError("clients:clientSaveError", error2);
        }
      }
    };
    const addMappers = async (mappers) => {
      if (!Array.isArray(mappers)) {
        const mapper = mappers;
        history.push(toMapper2({
          realm: realm2,
          id: client2.id,
          mapperId: mapper.id
        }));
      } else {
        try {
          await adminClient.clients.addMultipleProtocolMappers({id: client2.id}, mappers);
          setClient(await adminClient.clients.findOne({id: client2.id}));
          addAlert(t5("common:mappingCreatedSuccess"), AlertVariant.success);
        } catch (error2) {
          addError("common:mappingCreatedError", error2);
        }
      }
    };
    const onDeleteMapper = async (mapper) => {
      try {
        await adminClient.clients.delProtocolMapper({
          id: client2.id,
          mapperId: mapper.id
        });
        setClient({
          ...client2,
          protocolMappers: client2?.protocolMappers?.filter((m2) => m2.id !== mapper.id)
        });
        addAlert(t5("common:mappingDeletedSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("common:mappingDeletedError", error2);
      }
      return true;
    };
    if (!client2) {
      return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
    }
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ConfirmDialogModal, {
      continueButtonLabel: "common:yes",
      titleKey: t5("changeAuthenticatorConfirmTitle", {
        clientAuthenticatorType
      }),
      open: changeAuthenticatorOpen,
      toggleDialog: toggleChangeAuthenticatorOpen,
      onConfirm: () => save({confirmed: true})
    }, /* @__PURE__ */ react.createElement(react.Fragment, null, t5("changeAuthenticatorConfirm", {
      clientAuthenticatorType
    }), clientAuthenticatorType === "client-jwt" && /* @__PURE__ */ react.createElement(Alert, {
      variant: "info",
      isInline: true,
      title: t5("signedJWTConfirm")
    }))), /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(DownloadDialog, {
      id: client2.id,
      protocol: client2.protocol,
      open: downloadDialogOpen,
      toggleDialog: toggleDownloadDialogOpen
    }), /* @__PURE__ */ react.createElement(Controller, {
      name: "enabled",
      control: form2.control,
      defaultValue: true,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(ClientDetailHeader, {
        value,
        onChange,
        client: client2,
        save,
        toggleDeleteDialog,
        toggleDownloadDialog: toggleDownloadDialogOpen
      })
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      className: "pf-u-p-0"
    }, /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, /* @__PURE__ */ react.createElement(KeycloakTabs, {
      "data-testid": "client-tabs",
      isBox: true,
      mountOnEnter: true
    }, /* @__PURE__ */ react.createElement(Tab, {
      id: "settings",
      eventKey: "settings",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:settings"))
    }, /* @__PURE__ */ react.createElement(ClientSettings, {
      client: client2,
      save: () => save(),
      reset: () => setupForm(client2)
    })), (!client2.publicClient && !isRealmClient(client2) || client2.protocol === "saml") && /* @__PURE__ */ react.createElement(Tab, {
      id: "keys",
      eventKey: "keys",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("keys"))
    }, client2.protocol === "openid-connect" && /* @__PURE__ */ react.createElement(Keys, {
      clientId,
      save
    }), client2.protocol === "saml" && /* @__PURE__ */ react.createElement(SamlKeys, {
      clientId,
      save
    })), !client2.publicClient && !isRealmClient(client2) && /* @__PURE__ */ react.createElement(Tab, {
      id: "credentials",
      eventKey: "credentials",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("credentials"))
    }, /* @__PURE__ */ react.createElement(Credentials, {
      clientId,
      save: () => save()
    })), !isRealmClient(client2) && /* @__PURE__ */ react.createElement(Tab, {
      id: "mappers",
      eventKey: "mappers",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("mappers"))
    }, /* @__PURE__ */ react.createElement(MapperList, {
      model: client2,
      onAdd: addMappers,
      onDelete: onDeleteMapper,
      detailLink: (mapperId) => toMapper2({realm: realm2, id: client2.id, mapperId})
    })), /* @__PURE__ */ react.createElement(Tab, {
      id: "roles",
      eventKey: "roles",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("roles"))
    }, /* @__PURE__ */ react.createElement(RolesList, {
      loader,
      paginated: false,
      messageBundle: "clients"
    })), !isRealmClient(client2) && /* @__PURE__ */ react.createElement(Tab, {
      id: "clientScopes",
      eventKey: "clientScopes",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("clientScopes"))
    }, /* @__PURE__ */ react.createElement(Tabs, {
      activeKey: clientScopeSubTab,
      onSelect: (_23, key) => setClientScopeSubTab(key)
    }, /* @__PURE__ */ react.createElement(Tab, {
      id: "setup",
      eventKey: 30,
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("setup"))
    }, /* @__PURE__ */ react.createElement(ClientScopes, {
      clientName: client2.clientId,
      clientId,
      protocol: client2.protocol
    })), /* @__PURE__ */ react.createElement(Tab, {
      id: "evaluate",
      eventKey: 31,
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("evaluate"))
    }, /* @__PURE__ */ react.createElement(EvaluateScopes, {
      clientId,
      protocol: client2.protocol
    })))), client2.serviceAccountsEnabled && /* @__PURE__ */ react.createElement(Tab, {
      id: "authorization",
      eventKey: "authorization",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("authorization"))
    }, /* @__PURE__ */ react.createElement(Tabs, {
      activeKey: authorizationSubTab,
      onSelect: (_23, key) => setAuthorizationSubTab(key),
      mountOnEnter: true,
      unmountOnExit: true
    }, /* @__PURE__ */ react.createElement(Tab, {
      id: "settings",
      eventKey: 40,
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("settings"))
    }, /* @__PURE__ */ react.createElement(AuthorizationSettings, {
      clientId
    })), /* @__PURE__ */ react.createElement(Tab, {
      id: "resources",
      eventKey: 41,
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("resources"))
    }, /* @__PURE__ */ react.createElement(AuthorizationResources, {
      clientId
    })))), client2.serviceAccountsEnabled && /* @__PURE__ */ react.createElement(Tab, {
      id: "serviceAccount",
      eventKey: "serviceAccount",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("serviceAccount"))
    }, /* @__PURE__ */ react.createElement(ServiceAccount, {
      client: client2
    })), /* @__PURE__ */ react.createElement(Tab, {
      id: "advanced",
      eventKey: "advanced",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("advanced"))
    }, /* @__PURE__ */ react.createElement(AdvancedTab, {
      save,
      client: client2
    }))))));
  }
});

// build/clients/add/NewClientForm.js
var require_NewClientForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => NewClientForm
  });
  function NewClientForm() {
    const {t: t5} = useTranslation("clients");
    const {realm: realm2} = useRealm();
    const adminClient = useAdminClient();
    const history = useHistory();
    const [showCapabilityConfig, setShowCapabilityConfig] = useState(false);
    const [client2, setClient] = useState({
      protocol: "openid-connect",
      clientId: "",
      name: "",
      description: "",
      publicClient: true,
      authorizationServicesEnabled: false,
      serviceAccountsEnabled: false,
      implicitFlowEnabled: false,
      directAccessGrantsEnabled: true,
      standardFlowEnabled: true
    });
    const {addAlert, addError} = useAlerts();
    const methods = useForm({defaultValues: client2});
    const save = async () => {
      try {
        const newClient = await adminClient.clients.create({
          ...convertFormValuesToObject(client2),
          clientId: client2.clientId?.trim()
        });
        addAlert(t5("createSuccess"), AlertVariant.success);
        history.push(toClient({realm: realm2, clientId: newClient.id, tab: "settings"}));
      } catch (error2) {
        addError("clients:createError", error2);
      }
    };
    const forward = async (onNext) => {
      if (await methods.trigger()) {
        setClient({
          ...client2,
          ...convertFormValuesToObject(methods.getValues())
        });
        setShowCapabilityConfig(true);
        onNext?.();
      }
    };
    const back = () => {
      setClient({...client2, ...convertFormValuesToObject(methods.getValues())});
      methods.reset({
        ...client2,
        ...convertFormValuesToObject(methods.getValues())
      });
    };
    const onGoToStep = (newStep) => {
      if (newStep.id === "generalSettings") {
        back();
      } else {
        forward();
      }
    };
    const Footer = () => /* @__PURE__ */ react.createElement(WizardFooter, null, /* @__PURE__ */ react.createElement(WizardContextConsumer, null, ({activeStep, onNext, onBack, onClose}) => {
      return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Button, {
        variant: "primary",
        type: "submit",
        onClick: () => {
          forward(onNext);
        }
      }, activeStep.name === t5("capabilityConfig") ? t5("common:save") : t5("common:next")), /* @__PURE__ */ react.createElement(Button, {
        variant: "secondary",
        onClick: () => {
          back();
          onBack();
        },
        isDisabled: activeStep.name === t5("generalSettings")
      }, t5("common:back")), /* @__PURE__ */ react.createElement(Button, {
        variant: "link",
        onClick: onClose
      }, t5("common:cancel")));
    }));
    const title3 = t5("createClient");
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "clients:createClient",
      subKey: "clients:clientsExplain"
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormProvider, {
      ...methods
    }, /* @__PURE__ */ react.createElement(Wizard, {
      onClose: () => history.push(toClients({realm: realm2})),
      navAriaLabel: `${title3} steps`,
      mainAriaLabel: `${title3} content`,
      steps: [
        {
          id: "generalSettings",
          name: t5("generalSettings"),
          component: /* @__PURE__ */ react.createElement(GeneralSettings, null)
        },
        ...showCapabilityConfig ? [
          {
            id: "capabilityConfig",
            name: t5("capabilityConfig"),
            component: /* @__PURE__ */ react.createElement(CapabilityConfig, {
              protocol: client2.protocol
            })
          }
        ] : []
      ],
      footer: /* @__PURE__ */ react.createElement(Footer, null),
      onSave: save,
      onGoToStep
    }))));
  }
});

// build/identity-providers/add/AddMapper.js
var require_AddMapper = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => AddMapper
  });
  function AddMapper() {
    const {t: t5} = useTranslation("identity-providers");
    const form2 = useForm({
      shouldUnregister: false
    });
    const {handleSubmit, register: register2, errors} = form2;
    const {addAlert, addError} = useAlerts();
    const history = useHistory();
    const {realm: realm2} = useRealm();
    const adminClient = useAdminClient();
    const {providerId, alias} = useParams();
    const {id: id3} = useParams();
    const [mapperTypes, setMapperTypes] = useState();
    const [mapperType, setMapperType] = useState();
    const [currentMapper, setCurrentMapper] = useState();
    const save = async (idpMapper) => {
      const mapper = convertFormValuesToObject(idpMapper);
      const attributes = JSON.stringify(idpMapper.config.attributes ?? []);
      const claims = JSON.stringify(idpMapper.config.claims ?? []);
      const identityProviderMapper = {
        ...mapper,
        config: {
          ...mapper.config,
          attributes,
          claims
        },
        identityProviderAlias: alias
      };
      if (id3) {
        try {
          await adminClient.identityProviders.updateMapper({
            id: id3,
            alias
          }, {...identityProviderMapper, name: currentMapper?.name});
          addAlert(t5("mapperSaveSuccess"), AlertVariant.success);
        } catch (error2) {
          addError(t5("mapperSaveError"), error2);
        }
      } else {
        try {
          const createdMapper = await adminClient.identityProviders.createMapper({
            identityProviderMapper,
            alias
          });
          addAlert(t5("mapperCreateSuccess"), AlertVariant.success);
          history.push(toIdentityProviderEditMapper({
            realm: realm2,
            alias,
            providerId,
            id: createdMapper.id
          }));
        } catch (error2) {
          addError(t5("mapperCreateError"), error2);
        }
      }
    };
    useFetch(() => Promise.all([
      id3 ? adminClient.identityProviders.findOneMapper({alias, id: id3}) : null,
      adminClient.identityProviders.findMapperTypes({alias})
    ]), ([mapper, mapperTypes2]) => {
      if (mapper) {
        setCurrentMapper(mapper);
        setupForm(mapper);
        setMapperType(mapper.identityProviderMapper);
      } else {
        setMapperType(Object.keys(mapperTypes2)[0]);
      }
      setMapperTypes(mapperTypes2);
    }, []);
    const setupForm = (mapper) => {
      convertToFormValues(mapper, form2.setValue);
      form2.setValue("config.attributes", JSON.parse(mapper.config.attributes));
      form2.setValue("config.claims", JSON.parse(mapper.config.claims));
    };
    if (!mapperTypes) {
      return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
    }
    return /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(ViewHeader, {
      className: "kc-add-mapper-title",
      titleKey: id3 ? t5("editIdPMapper", {
        providerId: providerId[0].toUpperCase() + providerId.substring(1)
      }) : t5("addIdPMapper", {
        providerId: providerId[0].toUpperCase() + providerId.substring(1)
      }),
      divider: true
    }), /* @__PURE__ */ react.createElement(FormAccess, {
      role: "manage-identity-providers",
      isHorizontal: true,
      onSubmit: handleSubmit(save),
      className: "pf-u-mt-lg"
    }, id3 && /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:id"),
      fieldId: "kc-mapper-id",
      validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: register2(),
      type: "text",
      value: currentMapper?.id,
      "datatest-id": "name-input",
      id: "kc-name",
      name: "name",
      isDisabled: !!id3,
      validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default
    })), /* @__PURE__ */ react.createElement(AddMapperForm, {
      form: form2,
      id: id3,
      mapperTypes,
      updateMapperType: setMapperType,
      mapperType
    }), /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, mapperType && mapperTypes[mapperType].properties && /* @__PURE__ */ react.createElement(DynamicComponents, {
      properties: mapperTypes[mapperType].properties
    })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "new-mapper-save-button",
      variant: "primary",
      type: "submit"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toIdentityProvider({
          realm: realm2,
          providerId,
          alias,
          tab: "settings"
        })
      })
    }, t5("common:cancel")))));
  }
});

// build/identity-providers/add/AddIdentityProvider.js
var require_AddIdentityProvider = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => AddIdentityProvider
  });
  function AddIdentityProvider() {
    const {t: t5} = useTranslation("identity-providers");
    const {providerId} = useParams();
    const form2 = useForm();
    const {
      handleSubmit,
      formState: {isDirty}
    } = form2;
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const history = useHistory();
    const {realm: realm2} = useRealm();
    const save = async (provider) => {
      try {
        await adminClient.identityProviders.create({
          ...provider,
          providerId,
          alias: providerId
        });
        addAlert(t5("createSuccess"), AlertVariant.success);
        history.push(toIdentityProvider({
          realm: realm2,
          providerId,
          alias: providerId,
          tab: "settings"
        }));
      } catch (error2) {
        addError("identity-providers:createError", error2);
      }
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: t5("addIdentityProvider", {
        provider: toUpperCase(providerId)
      })
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      role: "manage-identity-providers",
      isHorizontal: true,
      onSubmit: handleSubmit(save)
    }, /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, /* @__PURE__ */ react.createElement(GeneralSettings2, {
      id: providerId
    })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      isDisabled: !isDirty,
      variant: "primary",
      type: "submit",
      "data-testid": "createProvider"
    }, t5("common:add")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      "data-testid": "cancel",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toIdentityProviders({realm: realm2})
      })
    }, t5("common:cancel"))))));
  }
});

// build/identity-providers/IdentityProvidersSection.js
var require_IdentityProvidersSection = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => IdentityProvidersSection
  });
  function IdentityProvidersSection() {
    const {t: t5} = useTranslation("identity-providers");
    const identityProviders2 = lodash.groupBy(useServerInfo().identityProviders, "groupName");
    const {realm: realm2} = useRealm();
    const history = useHistory();
    const [key, setKey] = useState(0);
    const refresh = () => setKey(new Date().getTime());
    const [addProviderOpen, setAddProviderOpen] = useState(false);
    const [manageDisplayDialog, setManageDisplayDialog] = useState(false);
    const [providers, setProviders] = useState();
    const [selectedProvider, setSelectedProvider] = useState();
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    useFetch(async () => {
      const provider = await adminClient.realms.findOne({realm: realm2});
      if (!provider) {
        throw new Error(t5("common:notFound"));
      }
      return provider.identityProviders;
    }, (providers2) => {
      setProviders(providers2);
    }, []);
    const loader = () => Promise.resolve(lodash.sortBy(providers, "alias"));
    const DetailLink = (identityProvider) => /* @__PURE__ */ react.createElement(Link, {
      key: identityProvider.providerId,
      to: toIdentityProvider({
        realm: realm2,
        providerId: identityProvider.providerId,
        alias: identityProvider.alias,
        tab: "settings"
      })
    }, identityProvider.displayName ? identityProvider.displayName : identityProvider.alias, !identityProvider.enabled && /* @__PURE__ */ react.createElement(Badge, {
      key: `${identityProvider.providerId}-disabled`,
      isRead: true,
      className: "pf-u-ml-sm"
    }, t5("common:disabled")));
    const navigateToCreate = (providerId) => history.push(toIdentityProviderCreate({
      realm: realm2,
      providerId
    }));
    const identityProviderOptions = () => Object.keys(identityProviders2).map((group) => /* @__PURE__ */ react.createElement(DropdownGroup, {
      key: group,
      label: group
    }, lodash.sortBy(identityProviders2[group], "name").map((provider) => /* @__PURE__ */ react.createElement(DropdownItem, {
      key: provider.id,
      value: provider.id,
      component: /* @__PURE__ */ react.createElement(Link, {
        to: toIdentityProviderCreate({
          realm: realm2,
          providerId: provider.id
        }),
        "data-testid": provider.id
      }, provider.name)
    }))));
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "identity-providers:deleteProvider",
      messageKey: t5("deleteConfirm", {provider: selectedProvider?.alias}),
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.identityProviders.del({
            alias: selectedProvider.alias
          });
          setProviders([
            ...providers.filter((p2) => p2.alias !== selectedProvider?.alias)
          ]);
          refresh();
          addAlert(t5("deletedSuccess"), AlertVariant.success);
        } catch (error2) {
          addError("identity-providers:deleteError", error2);
        }
      }
    });
    if (!providers) {
      return /* @__PURE__ */ react.createElement(Spinner, null);
    }
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), manageDisplayDialog && /* @__PURE__ */ react.createElement(ManageOderDialog, {
      onClose: () => setManageDisplayDialog(false),
      providers: providers.filter((p2) => p2.enabled)
    }), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "common:identityProviders",
      subKey: "identity-providers:listExplain"
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: providers.length === 0 ? "default" : "light",
      className: providers.length === 0 ? "" : "pf-u-p-0"
    }, providers.length === 0 && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, {
      component: TextVariants.p
    }, t5("getStarted"))), Object.keys(identityProviders2).map((group) => /* @__PURE__ */ react.createElement(Fragment, {
      key: group
    }, /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, {
      className: "pf-u-mt-lg",
      component: TextVariants.h2
    }, group, ":")), /* @__PURE__ */ react.createElement("hr", {
      className: "pf-u-mb-lg"
    }), /* @__PURE__ */ react.createElement(Gallery, {
      hasGutter: true
    }, lodash.sortBy(identityProviders2[group], "name").map((provider) => /* @__PURE__ */ react.createElement(Card, {
      className: "keycloak-empty-state-card",
      key: provider.id,
      isHoverable: true,
      "data-testid": `${provider.id}-card`,
      onClick: () => navigateToCreate(provider.id)
    }, /* @__PURE__ */ react.createElement(CardTitle, null, /* @__PURE__ */ react.createElement(Split, {
      hasGutter: true
    }, /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(ProviderIconMapper, {
      provider
    })), /* @__PURE__ */ react.createElement(SplitItem, {
      isFilled: true
    }, provider.name))))))))), providers.length !== 0 && /* @__PURE__ */ react.createElement(KeycloakDataTable, {
      key,
      loader,
      ariaLabelKey: "common:identityProviders",
      searchPlaceholderKey: "identity-providers:searchForProvider",
      toolbarItem: /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Dropdown, {
        "data-testid": "addProviderDropdown",
        toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
          onToggle: () => setAddProviderOpen(!addProviderOpen),
          isPrimary: true
        }, t5("addProvider")),
        isOpen: addProviderOpen,
        dropdownItems: identityProviderOptions()
      })), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "manageDisplayOrder",
        variant: "link",
        onClick: () => setManageDisplayDialog(true)
      }, t5("manageDisplayOrder")))),
      actions: [
        {
          title: t5("common:delete"),
          onRowClick: (provider) => {
            setSelectedProvider(provider);
            toggleDeleteDialog();
          }
        }
      ],
      columns: [
        {
          name: "alias",
          displayKey: "common:name",
          cellRenderer: DetailLink
        },
        {
          name: "providerId",
          displayKey: "identity-providers:providerDetails",
          cellFormatters: [upperCaseFormatter()]
        }
      ]
    })));
  }
});

// build/identity-providers/add/DetailSettings.js
var require_DetailSettings = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => DetailSettings
  });
  var Header3 = ({onChange, value, save, toggleDeleteDialog}) => {
    const {t: t5} = useTranslation("identity-providers");
    const {alias} = useParams();
    const [toggleDisableDialog, DisableConfirm] = useConfirmDialog({
      titleKey: "identity-providers:disableProvider",
      messageKey: t5("disableConfirm", {provider: alias}),
      continueButtonLabel: "common:disable",
      onConfirm: () => {
        onChange(!value);
        save();
      }
    });
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DisableConfirm, null), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: toUpperCase(alias),
      divider: false,
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "delete",
          onClick: () => toggleDeleteDialog()
        }, t5("common:delete"))
      ],
      isEnabled: value,
      onToggle: (value2) => {
        if (!value2) {
          toggleDisableDialog();
        } else {
          onChange(value2);
          save();
        }
      }
    }));
  };
  function DetailSettings() {
    const {t: t5} = useTranslation("identity-providers");
    const {alias, providerId} = useParams();
    const form2 = useForm();
    const {handleSubmit, getValues, reset: reset2} = form2;
    const [provider, setProvider] = useState();
    const [selectedMapper, setSelectedMapper] = useState();
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const history = useHistory();
    const {realm: realm2} = useRealm();
    const [key, setKey] = useState(0);
    const refresh = () => setKey(key + 1);
    const MapperLink = ({name, mapperId}) => /* @__PURE__ */ react.createElement(Link, {
      to: toIdentityProviderEditMapper({
        realm: realm2,
        alias,
        providerId: provider?.providerId,
        id: mapperId
      })
    }, name);
    useFetch(() => adminClient.identityProviders.findOne({alias}), (fetchedProvider) => {
      if (!fetchedProvider) {
        throw new Error(t5("common:notFound"));
      }
      reset2(fetchedProvider);
      setProvider(fetchedProvider);
    }, []);
    const save = async (provider2) => {
      const p2 = provider2 || getValues();
      try {
        await adminClient.identityProviders.update({alias}, {...p2, alias, providerId});
        addAlert(t5("updateSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("identity-providers:updateError", error2);
      }
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "identity-providers:deleteProvider",
      messageKey: t5("identity-providers:deleteConfirm", {provider: alias}),
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.identityProviders.del({alias});
          addAlert(t5("deletedSuccess"), AlertVariant.success);
          history.push(toIdentityProviders({realm: realm2}));
        } catch (error2) {
          addError("identity-providers:deleteErrorError", error2);
        }
      }
    });
    const [toggleDeleteMapperDialog, DeleteMapperConfirm] = useConfirmDialog({
      titleKey: "identity-providers:deleteProviderMapper",
      messageKey: t5("identity-providers:deleteMapperConfirm", {
        mapper: selectedMapper?.name
      }),
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.identityProviders.delMapper({
            alias,
            id: selectedMapper?.mapperId
          });
          addAlert(t5("deleteMapperSuccess"), AlertVariant.success);
          refresh();
          history.push(toIdentityProvider({providerId, alias, tab: "mappers", realm: realm2}));
        } catch (error2) {
          addError("identity-providers:deleteErrorError", error2);
        }
      }
    });
    if (!provider) {
      return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
    }
    const sections = [t5("generalSettings"), t5("advancedSettings")];
    const isOIDC = provider.providerId.includes("oidc");
    const isSAML = provider.providerId.includes("saml");
    const loader = async () => {
      const [loaderMappers, loaderMapperTypes] = await Promise.all([
        adminClient.identityProviders.findMappers({alias}),
        adminClient.identityProviders.findMapperTypes({alias})
      ]);
      const components3 = loaderMappers.map((loaderMapper) => {
        const mapperType = Object.values(loaderMapperTypes).find((loaderMapperType) => loaderMapper.identityProviderMapper === loaderMapperType.id);
        const result = {
          ...mapperType,
          name: loaderMapper.name,
          type: mapperType?.name,
          mapperId: loaderMapper.id
        };
        return result;
      });
      return components3;
    };
    if (isOIDC) {
      sections.splice(1, 0, t5("oidcSettings"));
    }
    if (isSAML) {
      sections.splice(1, 0, t5("samlSettings"));
      sections.splice(2, 0, t5("reqAuthnConstraints"));
    }
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(DeleteMapperConfirm, null), /* @__PURE__ */ react.createElement(Controller, {
      name: "enabled",
      control: form2.control,
      defaultValue: true,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Header3, {
        value,
        onChange,
        save,
        toggleDeleteDialog
      })
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      className: "pf-u-p-0"
    }, /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, /* @__PURE__ */ react.createElement(KeycloakTabs, {
      isBox: true
    }, /* @__PURE__ */ react.createElement(Tab, {
      id: "settings",
      eventKey: "settings",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:settings"))
    }, /* @__PURE__ */ react.createElement(ScrollForm, {
      className: "pf-u-px-lg",
      sections
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      role: "manage-identity-providers",
      isHorizontal: true,
      onSubmit: handleSubmit(save)
    }, !isOIDC && !isSAML && /* @__PURE__ */ react.createElement(GeneralSettings2, {
      create: false,
      id: alias
    }), isOIDC && /* @__PURE__ */ react.createElement(OIDCGeneralSettings, {
      id: alias
    }), isSAML && /* @__PURE__ */ react.createElement(SamlGeneralSettings, {
      id: alias
    })), isOIDC && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DiscoverySettings, {
      readOnly: false
    }), /* @__PURE__ */ react.createElement(Form, {
      isHorizontal: true,
      className: "pf-u-py-lg"
    }, /* @__PURE__ */ react.createElement(Divider, null), /* @__PURE__ */ react.createElement(OIDCAuthentication, {
      create: false
    })), /* @__PURE__ */ react.createElement(ExtendedNonDiscoverySettings, null)), isSAML && /* @__PURE__ */ react.createElement(DescriptorSettings, {
      readOnly: false
    }), isSAML && /* @__PURE__ */ react.createElement(FormAccess, {
      role: "manage-identity-providers",
      isHorizontal: true,
      onSubmit: handleSubmit(save)
    }, /* @__PURE__ */ react.createElement(ReqAuthnConstraints, null)), /* @__PURE__ */ react.createElement(FormAccess, {
      role: "manage-identity-providers",
      isHorizontal: true,
      onSubmit: handleSubmit(save)
    }, /* @__PURE__ */ react.createElement(AdvancedSettings2, {
      isOIDC,
      isSAML
    }), /* @__PURE__ */ react.createElement(ActionGroup, {
      className: "keycloak__form_actions"
    }, /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "save",
      type: "submit"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "revert",
      variant: "link",
      onClick: () => {
        reset2();
      }
    }, t5("common:revert")))))), /* @__PURE__ */ react.createElement(Tab, {
      id: "mappers",
      "data-testid": "mappers-tab",
      eventKey: "mappers",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:mappers"))
    }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
      emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
        message: t5("identity-providers:noMappers"),
        instructions: t5("identity-providers:noMappersInstructions"),
        primaryActionText: t5("identity-providers:addMapper"),
        onPrimaryAction: () => history.push(toIdentityProviderAddMapper({
          realm: realm2,
          alias,
          providerId: provider.providerId,
          tab: "mappers"
        }))
      }),
      loader,
      key,
      isPaginated: true,
      ariaLabelKey: "identity-providers:mappersList",
      searchPlaceholderKey: "identity-providers:searchForMapper",
      toolbarItem: /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Link, {
        to: toIdentityProviderAddMapper({
          realm: realm2,
          alias,
          providerId: provider.providerId,
          tab: "mappers"
        }),
        id: "add-mapper-button"
      }, t5("addMapper"))),
      columns: [
        {
          name: "name",
          displayKey: "common:name",
          cellRenderer: MapperLink
        },
        {
          name: "category",
          displayKey: "common:category"
        },
        {
          name: "type",
          displayKey: "common:type"
        }
      ],
      actions: [
        {
          title: t5("common:delete"),
          onRowClick: (mapper) => {
            setSelectedMapper(mapper);
            toggleDeleteMapperDialog();
          }
        }
      ]
    }))))));
  }
});

// build/user/UsersSection.js
var require_UsersSection = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => UsersSection
  });
  function UsersSection() {
    const {t: t5} = useTranslation("users");
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const {realm: realmName} = useRealm();
    const history = useHistory();
    const [listUsers, setListUsers] = useState(false);
    const [searchUser, setSearchUser] = useState();
    const [realm2, setRealm] = useState();
    const [kebabOpen, setKebabOpen] = useState(false);
    const [selectedRows, setSelectedRows] = useState([]);
    const [key, setKey] = useState("");
    const refresh = () => setKey(`${new Date().getTime()}`);
    useFetch(() => {
      const testParams = {
        type: "org.keycloak.storage.UserStorageProvider"
      };
      return Promise.all([
        adminClient.components.find(testParams),
        adminClient.realms.findOne({realm: realmName})
      ]).catch(() => [[], void 0]);
    }, ([storageProviders, realm22]) => {
      setListUsers(!(storageProviders.length > 0));
      setRealm(realm22);
      refresh();
    }, []);
    const UserDetailLink = (user) => /* @__PURE__ */ react.createElement(Link, {
      key: user.username,
      to: toUser({realm: realmName, id: user.id, tab: "settings"})
    }, user.username);
    const loader = async (first2, max2, search2) => {
      const params = {
        first: first2,
        max: max2
      };
      const searchParam = search2 || searchUser || "";
      if (searchParam) {
        params.search = searchParam;
      }
      if (!listUsers && !searchParam) {
        return [];
      }
      try {
        const users2 = await adminClient.users.find({...params});
        if (realm2?.bruteForceProtected) {
          const brutes = await Promise.all(users2.map((user) => adminClient.attackDetection.findOne({
            id: user.id
          })));
          for (let index3 = 0; index3 < users2.length; index3++) {
            const user = users2[index3];
            user.brute = brutes[index3];
          }
        }
        return users2;
      } catch (error2) {
        addError("users:noUsersFoundError", error2);
        return [];
      }
    };
    const [toggleUnlockUsersDialog, UnlockUsersConfirm] = useConfirmDialog({
      titleKey: "users:unlockAllUsers",
      messageKey: "users:unlockUsersConfirm",
      continueButtonLabel: "users:unlock",
      onConfirm: async () => {
        try {
          await adminClient.attackDetection.delAll();
          refresh();
          addAlert(t5("unlockUsersSuccess"), AlertVariant.success);
        } catch (error2) {
          addError("users:unlockUsersError", error2);
        }
      }
    });
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "users:deleteConfirm",
      messageKey: t5("deleteConfirmDialog", {count: selectedRows.length}),
      continueButtonLabel: "delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          for (const user of selectedRows) {
            await adminClient.users.del({id: user.id});
          }
          setSelectedRows([]);
          refresh();
          addAlert(t5("userDeletedSuccess"), AlertVariant.success);
        } catch (error2) {
          addError("users:userDeletedError", error2);
        }
      }
    });
    const StatusRow = (user) => {
      return /* @__PURE__ */ react.createElement(react.Fragment, null, !user.enabled && /* @__PURE__ */ react.createElement(Label, {
        key: user.id,
        color: "red",
        icon: /* @__PURE__ */ react.createElement(InfoCircleIcon, null)
      }, t5("disabled")), user.brute?.disabled && /* @__PURE__ */ react.createElement(Label, {
        key: user.id,
        color: "orange",
        icon: /* @__PURE__ */ react.createElement(WarningTriangleIcon, null)
      }, t5("temporaryDisabled")), user.enabled && !user.brute?.disabled && "—");
    };
    const ValidatedEmail = (user) => {
      return /* @__PURE__ */ react.createElement(react.Fragment, null, !user.emailVerified && /* @__PURE__ */ react.createElement(Tooltip, {
        key: `email-verified-${user.id}`,
        content: /* @__PURE__ */ react.createElement(react.Fragment, null, t5("notVerified"))
      }, /* @__PURE__ */ react.createElement(ExclamationCircleIcon, {
        className: "keycloak__user-section__email-verified"
      })), " ", emptyFormatter()(user.email));
    };
    const goToCreate = () => history.push(toAddUser({realm: realmName}));
    const toolbar2 = /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "add-user",
      onClick: goToCreate
    }, t5("addUser"))), !realm2?.bruteForceProtected ? /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      variant: ButtonVariant.plain,
      onClick: toggleDeleteDialog,
      isDisabled: selectedRows.length === 0
    }, t5("deleteUser"))) : /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Dropdown, {
      toggle: /* @__PURE__ */ react.createElement(KebabToggle, {
        onToggle: (open2) => setKebabOpen(open2)
      }),
      isOpen: kebabOpen,
      isPlain: true,
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "deleteUser",
          component: "button",
          isDisabled: selectedRows.length === 0,
          onClick: () => {
            toggleDeleteDialog();
            setKebabOpen(false);
          }
        }, t5("deleteUser")),
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "unlock",
          component: "button",
          onClick: () => {
            toggleUnlockUsersDialog();
            setKebabOpen(false);
          }
        }, t5("unlockAllUsers"))
      ]
    })));
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(UnlockUsersConfirm, null), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "users:title"
    }), /* @__PURE__ */ react.createElement(PageSection, {
      "data-testid": "users-page",
      variant: "light",
      className: "pf-u-p-0"
    }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
      key,
      loader,
      isPaginated: true,
      ariaLabelKey: "users:title",
      searchPlaceholderKey: "users:searchForUser",
      canSelectAll: true,
      onSelect: (rows) => setSelectedRows([...rows]),
      emptyState: !listUsers ? /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Toolbar, null, /* @__PURE__ */ react.createElement(ToolbarContent, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(TextInput, {
        name: "search-input",
        type: "search",
        "aria-label": t5("search"),
        placeholder: t5("users:searchForUser"),
        onChange: (value) => {
          setSearchUser(value);
        },
        onKeyDown: (e2) => {
          if (e2.key === "Enter") {
            refresh();
          }
        }
      }), /* @__PURE__ */ react.createElement(Button, {
        variant: ButtonVariant.control,
        "aria-label": t5("common:search"),
        onClick: refresh
      }, /* @__PURE__ */ react.createElement(SearchIcon, null)))), toolbar2)), /* @__PURE__ */ react.createElement(EmptyState, {
        "data-testid": "empty-state",
        variant: "large"
      }, /* @__PURE__ */ react.createElement(TextContent, {
        className: "kc-search-users-text"
      }, /* @__PURE__ */ react.createElement(Text, null, t5("searchForUserDescription"))))) : /* @__PURE__ */ react.createElement(ListEmptyState, {
        message: t5("noUsersFound"),
        instructions: t5("emptyInstructions"),
        primaryActionText: t5("createNewUser"),
        onPrimaryAction: goToCreate
      }),
      toolbarItem: toolbar2,
      actions: [
        {
          title: t5("common:delete"),
          onRowClick: (user) => {
            setSelectedRows([user]);
            toggleDeleteDialog();
          }
        }
      ],
      columns: [
        {
          name: "username",
          displayKey: "users:username",
          cellRenderer: UserDetailLink
        },
        {
          name: "email",
          displayKey: "users:email",
          cellRenderer: ValidatedEmail
        },
        {
          name: "lastName",
          displayKey: "users:lastName",
          cellFormatters: [emptyFormatter()]
        },
        {
          name: "firstName",
          displayKey: "users:firstName",
          cellFormatters: [emptyFormatter()]
        },
        {
          name: "status",
          displayKey: "users:status",
          cellRenderer: StatusRow
        }
      ]
    })));
  }
});

// build/user/UsersTabs.js
var require_UsersTabs = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => UsersTabs_default
  });
  var UsersTabs = () => {
    const {t: t5} = useTranslation("users");
    const {addAlert, addError} = useAlerts();
    const history = useHistory();
    const {realm: realm2} = useRealm();
    const {hasAccess} = useAccess();
    const adminClient = useAdminClient();
    const userForm = useForm({mode: "onChange"});
    const {id: id3} = useParams();
    const [user, setUser] = useState();
    const [bruteForced, setBruteForced] = useState();
    const [addedGroups, setAddedGroups] = useState([]);
    useFetch(async () => {
      if (id3) {
        const user2 = await adminClient.users.findOne({id: id3});
        if (!user2) {
          throw new Error(t5("common:notFound"));
        }
        const isBruteForceProtected = (await adminClient.realms.findOne({
          realm: realm2
        })).bruteForceProtected;
        const bruteForce = await adminClient.attackDetection.findOne({
          id: user2.id
        });
        const isLocked = isBruteForceProtected && bruteForce && bruteForce.disabled;
        return {user: user2, bruteForced: {isBruteForceProtected, isLocked}};
      }
      return {user: void 0};
    }, ({user: user2, bruteForced: bruteForced2}) => {
      setUser(user2);
      setBruteForced(bruteForced2);
      user2 && setupForm(user2);
    }, []);
    const setupForm = (user2) => {
      userForm.reset(user2);
    };
    const updateGroups = (groups2) => {
      setAddedGroups(groups2);
    };
    const save = async (user2) => {
      user2.username = user2.username?.trim();
      try {
        if (id3) {
          await adminClient.users.update({id: id3}, user2);
          addAlert(t5("userSaved"), AlertVariant.success);
        } else {
          const createdUser = await adminClient.users.create(user2);
          addedGroups.forEach(async (group) => {
            await adminClient.users.addToGroup({
              id: createdUser.id,
              groupId: group.id
            });
          });
          addAlert(t5("userCreated"), AlertVariant.success);
          history.push(toUser({id: createdUser.id, realm: realm2, tab: "settings"}));
        }
      } catch (error2) {
        addError("users:userCreateError", error2);
      }
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "users:deleteConfirm",
      messageKey: "users:deleteConfirmCurrentUser",
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.users.del({id: id3});
          addAlert(t5("userDeletedSuccess"), AlertVariant.success);
          history.push(toUsers({realm: realm2}));
        } catch (error2) {
          addError("users:userDeletedError", error2);
        }
      }
    });
    const [toggleImpersonateDialog, ImpersonateConfirm] = useConfirmDialog({
      titleKey: "users:impersonateConfirm",
      messageKey: "users:impersonateConfirmDialog",
      continueButtonLabel: "users:impersonate",
      onConfirm: async () => {
        try {
          const data2 = await adminClient.users.impersonation({id: id3}, {user: id3, realm: realm2});
          if (data2.sameRealm) {
            window.location = data2.redirect;
          } else {
            window.open(data2.redirect, "_blank");
          }
        } catch (error2) {
          addError("users:impersonateError", error2);
        }
      }
    });
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ImpersonateConfirm, null), /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: user?.username || t5("createUser"),
      divider: !id3,
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "impersonate",
          onClick: () => toggleImpersonateDialog()
        }, t5("impersonate")),
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "delete",
          onClick: () => toggleDeleteDialog()
        }, t5("common:delete"))
      ]
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      className: "pf-u-p-0"
    }, /* @__PURE__ */ react.createElement(FormProvider, {
      ...userForm
    }, id3 && user && /* @__PURE__ */ react.createElement(KeycloakTabs, {
      isBox: true,
      mountOnEnter: true
    }, /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "settings",
      "data-testid": "user-details-tab",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:details"))
    }, /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, bruteForced && /* @__PURE__ */ react.createElement(UserForm, {
      onGroupsUpdate: updateGroups,
      save,
      user,
      bruteForce: bruteForced
    }))), /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "attributes",
      "data-testid": "attributes",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:attributes"))
    }, /* @__PURE__ */ react.createElement(UserAttributes, {
      user
    })), /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "credentials",
      "data-testid": "credentials",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:credentials"))
    }, /* @__PURE__ */ react.createElement(UserCredentials, {
      user
    })), /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "groups",
      "data-testid": "user-groups-tab",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:groups"))
    }, /* @__PURE__ */ react.createElement(UserGroups, {
      user
    })), /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "consents",
      "data-testid": "user-consents-tab",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("consents"))
    }, /* @__PURE__ */ react.createElement(UserConsents, null)), /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "role-mapping",
      "data-testid": "role-mapping-tab",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("roleMapping"))
    }, /* @__PURE__ */ react.createElement(UserRoleMapping, {
      id: id3,
      name: user.username
    })), hasAccess("view-identity-providers") && /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "identity-provider-links",
      "data-testid": "identity-provider-links-tab",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("identityProviderLinks"))
    }, /* @__PURE__ */ react.createElement(UserIdentityProviderLinks, null))), !id3 && /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(UserForm, {
      onGroupsUpdate: updateGroups,
      save
    })))));
  };
  var UsersTabs_default = UsersTabs;
});

// build/events/EventsSection.js
var require_EventsSection = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => EventsSection
  });
  var import_moment6 = __toModule(require_moment());
  var defaultValues2 = {
    client: "",
    dateFrom: "",
    dateTo: "",
    user: "",
    type: []
  };
  var StatusRow = (event) => !event.error ? /* @__PURE__ */ react.createElement("span", null, /* @__PURE__ */ react.createElement(CheckCircleIcon, {
    color: "green"
  }), " ", event.type) : /* @__PURE__ */ react.createElement(Tooltip, {
    content: event.error
  }, /* @__PURE__ */ react.createElement("span", null, /* @__PURE__ */ react.createElement(WarningTriangleIcon, {
    color: "orange"
  }), " ", event.type));
  var DetailCell2 = (event) => /* @__PURE__ */ react.createElement(DescriptionList, {
    isHorizontal: true,
    className: "keycloak_eventsection_details"
  }, Object.entries(event.details).map(([key, value]) => /* @__PURE__ */ react.createElement(DescriptionListGroup, {
    key
  }, /* @__PURE__ */ react.createElement(DescriptionListTerm, null, key), /* @__PURE__ */ react.createElement(DescriptionListDescription, null, value))));
  function EventsSection() {
    const {t: t5} = useTranslation("events");
    const adminClient = useAdminClient();
    const {realm: realm2} = useRealm();
    const [key, setKey] = useState(0);
    const [searchDropdownOpen, setSearchDropdownOpen] = useState(false);
    const [selectOpen, setSelectOpen] = useState(false);
    const [events, setEvents] = useState();
    const [activeFilters, setActiveFilters] = useState({});
    const filterLabels = {
      client: t5("client"),
      dateFrom: t5("dateFrom"),
      dateTo: t5("dateTo"),
      user: t5("userId"),
      type: t5("eventType")
    };
    const {
      getValues,
      register: register2,
      reset: reset2,
      formState: {isDirty},
      control
    } = useForm({
      shouldUnregister: false,
      mode: "onChange",
      defaultValues: defaultValues2
    });
    useFetch(() => adminClient.realms.getConfigEvents({realm: realm2}), (events2) => setEvents(events2), []);
    function loader(first2, max2) {
      return adminClient.realms.findEvents({
        ...activeFilters,
        realm: realm2,
        first: first2,
        max: max2
      });
    }
    function submitSearch() {
      setSearchDropdownOpen(false);
      commitFilters();
    }
    function removeFilter(key2) {
      const formValues = {...getValues()};
      delete formValues[key2];
      reset2({...defaultValues2, ...formValues});
      commitFilters();
    }
    function removeFilterValue(key2, valueToRemove) {
      const formValues = getValues();
      const fieldValue = formValues[key2];
      const newFieldValue = Array.isArray(fieldValue) ? fieldValue.filter((val) => val !== valueToRemove) : fieldValue;
      reset2({...formValues, [key2]: newFieldValue});
      commitFilters();
    }
    function commitFilters() {
      const newFilters = pickBy(getValues(), (value) => value !== "" || Array.isArray(value) && value.length > 0);
      setActiveFilters(newFilters);
      setKey(key + 1);
    }
    function refresh() {
      commitFilters();
    }
    const UserDetailLink = (event) => /* @__PURE__ */ react.createElement(react.Fragment, null, event.userId && /* @__PURE__ */ react.createElement(Link, {
      key: `link-${event.time}-${event.type}`,
      to: toUser({
        realm: realm2,
        id: event.userId,
        tab: "settings"
      })
    }, event.userId), !event.userId && t5("noUserDetails"));
    const userEventSearchFormDisplay = () => {
      return /* @__PURE__ */ react.createElement(Flex, {
        direction: {default: "column"},
        spaceItems: {default: "spaceItemsNone"}
      }, /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Dropdown, {
        id: "user-events-search-select",
        "data-testid": "UserEventsSearchSelector",
        className: "pf-u-ml-md",
        toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
          "data-testid": "userEventsSearchSelectorToggle",
          onToggle: (isOpen) => setSearchDropdownOpen(isOpen),
          className: "keycloak__events_search_selector_dropdown__toggle"
        }, t5("searchForUserEvent")),
        isOpen: searchDropdownOpen
      }, /* @__PURE__ */ react.createElement(Form, {
        isHorizontal: true,
        className: "keycloak__events_search__form",
        "data-testid": "searchForm"
      }, /* @__PURE__ */ react.createElement(FormGroup, {
        label: t5("userId"),
        fieldId: "kc-userId",
        className: "keycloak__events_search__form_label"
      }, /* @__PURE__ */ react.createElement(TextInput, {
        ref: register2(),
        type: "text",
        id: "kc-userId",
        name: "user",
        "data-testid": "userId-searchField"
      })), /* @__PURE__ */ react.createElement(FormGroup, {
        label: t5("eventType"),
        fieldId: "kc-eventType",
        className: "keycloak__events_search__form_label"
      }, /* @__PURE__ */ react.createElement(Controller, {
        name: "type",
        control,
        render: ({
          onChange,
          value
        }) => /* @__PURE__ */ react.createElement(Select, {
          className: "keycloak__events_search__type_select",
          name: "eventType",
          "data-testid": "event-type-searchField",
          chipGroupProps: {
            numChips: 1,
            expandedText: t5("common:hide"),
            collapsedText: t5("common:showRemaining")
          },
          variant: SelectVariant.typeaheadMulti,
          typeAheadAriaLabel: "Select",
          onToggle: (isOpen) => setSelectOpen(isOpen),
          selections: value,
          onSelect: (_23, selectedValue) => {
            const option = selectedValue.toString();
            const changedValue = value.includes(option) ? value.filter((item) => item !== option) : [...value, option];
            onChange(changedValue);
          },
          onClear: (event) => {
            event.stopPropagation();
            onChange([]);
          },
          isOpen: selectOpen,
          "aria-labelledby": "eventType",
          chipGroupComponent: /* @__PURE__ */ react.createElement(ChipGroup, null, value.map((chip2) => /* @__PURE__ */ react.createElement(Chip, {
            key: chip2,
            onClick: (event) => {
              event.stopPropagation();
              onChange(value.filter((val) => val !== chip2));
            }
          }, chip2)))
        }, events?.enabledEventTypes?.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
          key: option,
          value: option
        })))
      })), /* @__PURE__ */ react.createElement(FormGroup, {
        label: t5("client"),
        fieldId: "kc-client",
        className: "keycloak__events_search__form_label"
      }, /* @__PURE__ */ react.createElement(TextInput, {
        ref: register2(),
        type: "text",
        id: "kc-client",
        name: "client",
        "data-testid": "client-searchField"
      })), /* @__PURE__ */ react.createElement(FormGroup, {
        label: t5("dateFrom"),
        fieldId: "kc-dateFrom",
        className: "keycloak__events_search__form_label"
      }, /* @__PURE__ */ react.createElement(TextInput, {
        ref: register2(),
        type: "text",
        id: "kc-dateFrom",
        name: "dateFrom",
        className: "pf-c-form-control pf-m-icon pf-m-calendar",
        placeholder: "yyyy-MM-dd",
        "data-testid": "dateFrom-searchField"
      })), /* @__PURE__ */ react.createElement(FormGroup, {
        label: t5("dateTo"),
        fieldId: "kc-dateTo",
        className: "keycloak__events_search__form_label"
      }, /* @__PURE__ */ react.createElement(TextInput, {
        ref: register2(),
        type: "text",
        id: "kc-dateTo",
        name: "dateTo",
        className: "pf-c-form-control pf-m-icon pf-m-calendar",
        placeholder: "yyyy-MM-dd",
        "data-testid": "dateTo-searchField"
      })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
        className: "keycloak__user_events_search__form_btn",
        variant: "primary",
        onClick: submitSearch,
        "data-testid": "search-events-btn",
        isDisabled: !isDirty
      }, t5("searchUserEventsBtn"))))), /* @__PURE__ */ react.createElement(Button, {
        className: "pf-u-ml-md",
        onClick: refresh,
        "data-testid": "refresh-btn"
      }, t5("refresh"))), /* @__PURE__ */ react.createElement(FlexItem, null, Object.entries(activeFilters).length > 0 && /* @__PURE__ */ react.createElement("div", {
        className: "keycloak__searchChips pf-u-ml-md"
      }, Object.entries(activeFilters).map((filter3) => {
        const [key2, value] = filter3;
        return /* @__PURE__ */ react.createElement(ChipGroup, {
          className: "pf-u-mt-md pf-u-mr-md",
          key: key2,
          categoryName: filterLabels[key2],
          isClosable: true,
          onClick: () => removeFilter(key2)
        }, typeof value === "string" ? /* @__PURE__ */ react.createElement(Chip, {
          isReadOnly: true
        }, value) : value.map((entry) => /* @__PURE__ */ react.createElement(Chip, {
          key: entry,
          onClick: () => removeFilterValue(key2, entry)
        }, entry)));
      }))));
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "events:title",
      subKey: /* @__PURE__ */ react.createElement(Trans, {
        i18nKey: "events:eventExplain"
      }, "If you want to configure user events, Admin events or Event listeners, please enter", /* @__PURE__ */ react.createElement(Link, {
        to: toRealmSettings({realm: realm2, tab: "events"})
      }, t5("eventConfig")), "page realm settings to configure."),
      divider: false
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      className: "pf-u-p-0"
    }, /* @__PURE__ */ react.createElement(KeycloakTabs, {
      isBox: true
    }, /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "userEvents",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("userEvents"))
    }, /* @__PURE__ */ react.createElement("div", {
      className: "keycloak__events_table"
    }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
      key,
      loader,
      detailColumns: [
        {
          name: "details",
          enabled: (event) => event.details !== void 0,
          cellRenderer: DetailCell2
        }
      ],
      isPaginated: true,
      ariaLabelKey: "events:title",
      toolbarItem: userEventSearchFormDisplay(),
      columns: [
        {
          name: "time",
          displayKey: "events:time",
          cellRenderer: (row) => (0, import_moment6.default)(row.time).format("LLL"),
          cellFormatters: [expandable]
        },
        {
          name: "userId",
          displayKey: "events:user",
          cellRenderer: UserDetailLink
        },
        {
          name: "type",
          displayKey: "events:eventType",
          cellRenderer: StatusRow
        },
        {
          name: "ipAddress",
          displayKey: "events:ipAddress",
          transforms: [cellWidth(10)]
        },
        {
          name: "clientId",
          displayKey: "events:client"
        }
      ],
      emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
        message: t5("emptyEvents"),
        instructions: t5("emptyEventsInstructions")
      }),
      isSearching: Object.keys(activeFilters).length > 0
    }))), /* @__PURE__ */ react.createElement(Tab, {
      eventKey: "adminEvents",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("adminEvents")),
      "data-testid": "admin-events-tab"
    }, /* @__PURE__ */ react.createElement(AdminEvents, null)))));
  }
});

// build/groups/SearchGroups.js
var require_SearchGroups = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => SearchGroups
  });
  function SearchGroups() {
    const {t: t5} = useTranslation("groups");
    const adminClient = useAdminClient();
    const {realm: realm2} = useRealm();
    const [searchTerm, setSearchTerm] = useState("");
    const [searchTerms, setSearchTerms] = useState([]);
    const [key, setKey] = useState(0);
    const refresh = () => setKey(new Date().getTime());
    const {setSubGroups} = useSubGroups();
    useEffect(() => setSubGroups([{name: t5("searchGroups"), id: "search"}]), []);
    const deleteTerm = (id3) => {
      const index3 = searchTerms.indexOf(id3);
      searchTerms.splice(index3, 1);
      setSearchTerms([...searchTerms]);
      refresh();
    };
    const addTerm = () => {
      if (searchTerm !== "") {
        setSearchTerms([...searchTerms, searchTerm]);
        setSearchTerm("");
        refresh();
      }
    };
    const GroupNameCell = (group) => /* @__PURE__ */ react.createElement(Link, {
      key: group.id,
      to: `/${realm2}/groups/search/${group.link}`,
      onClick: () => setSubGroups([{name: t5("searchGroups"), id: "search"}, group])
    }, group.name);
    const flatten4 = (groups2, id3) => {
      let result = [];
      for (const group of groups2) {
        const link = `${id3 || ""}${id3 ? "/" : ""}${group.id}`;
        result.push({...group, link});
        if (group.subGroups) {
          result = [...result, ...flatten4(group.subGroups, link)];
        }
      }
      return result;
    };
    const loader = async (first2, max2) => {
      const params = {
        first: first2,
        max: max2
      };
      let result = [];
      if (searchTerms[0]) {
        result = await adminClient.groups.find({
          ...params,
          search: searchTerms[0]
        });
        result = flatten4(result);
        for (const searchTerm2 of searchTerms) {
          result = result.filter((group) => group.name?.includes(searchTerm2));
        }
      }
      return result;
    };
    const Path = (group) => /* @__PURE__ */ react.createElement(GroupPath, {
      group
    });
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "groups:searchGroups"
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: PageSectionVariants.light,
      className: "pf-u-p-0"
    }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
      key,
      isSearching: true,
      toolbarItem: /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Stack, null, /* @__PURE__ */ react.createElement(StackItem, {
        className: "pf-u-mb-sm"
      }, /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(TextInput, {
        name: "search",
        "data-testid": "group-search",
        type: "search",
        "aria-label": t5("search"),
        placeholder: t5("searchGroups"),
        value: searchTerm,
        onChange: (value) => setSearchTerm(value),
        onKeyDown: (event) => {
          if (event.key === "Enter") {
            addTerm();
          }
        }
      }), /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "search-button",
        variant: ButtonVariant.control,
        "aria-label": t5("search"),
        onClick: addTerm
      }, /* @__PURE__ */ react.createElement(SearchIcon, null)))), /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(ChipGroup, null, searchTerms.map((term) => /* @__PURE__ */ react.createElement(Chip, {
        key: term,
        onClick: () => deleteTerm(term)
      }, term)))))),
      ariaLabelKey: "groups:groups",
      isPaginated: true,
      loader,
      columns: [
        {
          name: "name",
          displayKey: "groups:groupName",
          cellRenderer: GroupNameCell
        },
        {
          name: "path",
          displayKey: "groups:path",
          cellRenderer: Path
        }
      ],
      emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
        message: t5("noSearchResults"),
        instructions: t5("noSearchResultsInstructions"),
        hasIcon: false
      })
    })));
  }
});

// build/groups/GroupsSection.js
var require_GroupsSection = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => GroupsSection
  });
  function GroupsSection() {
    const {t: t5} = useTranslation("groups");
    const [activeTab, setActiveTab] = useState(0);
    const adminClient = useAdminClient();
    const {subGroups, setSubGroups, currentGroup} = useSubGroups();
    const {addAlert, addError} = useAlerts();
    const {realm: realm2} = useRealm();
    const [rename, setRename] = useState();
    const history = useHistory();
    const location2 = useLocation();
    const id3 = getLastId(location2.pathname);
    const deleteGroup = async (group) => {
      try {
        await adminClient.groups.del({
          id: group.id
        });
        addAlert(t5("groupDeleted", {count: 1}), AlertVariant.success);
      } catch (error2) {
        addError("groups:groupDeleteError", error2);
      }
      return true;
    };
    useFetch(async () => {
      const ids = getId(location2.pathname);
      const isNavigationStateInValid = ids && ids.length > subGroups.length;
      if (isNavigationStateInValid) {
        const groups2 = [];
        for (const i3 of ids) {
          const group = await adminClient.groups.findOne({id: i3});
          if (group) {
            groups2.push(group);
          } else {
            throw new Error(t5("common:notFound"));
          }
        }
        return groups2;
      }
      return [];
    }, (groups2) => {
      if (groups2.length)
        setSubGroups(groups2);
    }, [id3]);
    const SearchDropdown2 = /* @__PURE__ */ react.createElement(DropdownItem, {
      key: "searchGroup",
      component: /* @__PURE__ */ react.createElement(Link, {
        "data-testid": "searchGroup",
        to: toGroupsSearch({realm: realm2})
      }, t5("searchGroup"))
    });
    return /* @__PURE__ */ react.createElement(react.Fragment, null, rename && /* @__PURE__ */ react.createElement(GroupsModal, {
      id: id3,
      rename,
      refresh: (group) => setSubGroups([...subGroups.slice(0, subGroups.length - 1), group]),
      handleModalToggle: () => setRename(void 0)
    }), /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: !id3 ? "groups:groups" : currentGroup().name,
      subKey: !id3 ? "groups:groupsDescription" : "",
      divider: !id3,
      dropdownItems: id3 ? [
        SearchDropdown2,
        /* @__PURE__ */ react.createElement(DropdownItem, {
          "data-testid": "renameGroupAction",
          key: "renameGroup",
          onClick: () => setRename(currentGroup().name)
        }, t5("renameGroup")),
        /* @__PURE__ */ react.createElement(DropdownItem, {
          "data-testid": "deleteGroup",
          key: "deleteGroup",
          onClick: async () => {
            await deleteGroup({id: id3});
            history.push(toGroups({realm: realm2}));
          }
        }, t5("deleteGroup"))
      ] : [SearchDropdown2]
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: PageSectionVariants.light,
      className: "pf-u-p-0"
    }, subGroups.length > 0 && /* @__PURE__ */ react.createElement(Tabs, {
      inset: {
        default: "insetNone",
        md: "insetSm",
        xl: "inset2xl",
        "2xl": "insetLg"
      },
      activeKey: activeTab,
      onSelect: (_23, key) => setActiveTab(key),
      isBox: true
    }, /* @__PURE__ */ react.createElement(Tab, {
      "data-testid": "groups",
      eventKey: 0,
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("childGroups"))
    }, /* @__PURE__ */ react.createElement(GroupTable, null)), /* @__PURE__ */ react.createElement(Tab, {
      "data-testid": "members",
      eventKey: 1,
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("members"))
    }, /* @__PURE__ */ react.createElement(Members, null)), /* @__PURE__ */ react.createElement(Tab, {
      "data-testid": "attributes",
      eventKey: 2,
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:attributes"))
    }, /* @__PURE__ */ react.createElement(GroupAttributes, null)), /* @__PURE__ */ react.createElement(Tab, {
      eventKey: 3,
      "data-testid": "role-mapping-tab",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("roleMapping"))
    }, /* @__PURE__ */ react.createElement(GroupRoleMapping, {
      id: id3,
      name: currentGroup().name
    }))), subGroups.length === 0 && /* @__PURE__ */ react.createElement(GroupTable, null)));
  }
});

// build/identity-providers/add/AddOpenIdConnect.js
var require_AddOpenIdConnect = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => AddOpenIdConnect
  });
  function AddOpenIdConnect() {
    const {t: t5} = useTranslation("identity-providers");
    const history = useHistory();
    const {url} = useRouteMatch();
    const isKeycloak = url.endsWith("keycloak-oidc");
    const id3 = `${isKeycloak ? "keycloak-" : ""}oidc`;
    const form2 = useForm({
      defaultValues: {alias: id3}
    });
    const {
      handleSubmit,
      formState: {isDirty}
    } = form2;
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const {realm: realm2} = useRealm();
    const save = async (provider) => {
      delete provider.discoveryEndpoint;
      try {
        await adminClient.identityProviders.create({
          ...provider,
          providerId: id3
        });
        addAlert(t5("createSuccess"), AlertVariant.success);
        history.push(toIdentityProvider({
          realm: realm2,
          providerId: id3,
          alias: provider.alias,
          tab: "settings"
        }));
      } catch (error2) {
        addError("identity-providers:createError", error2);
      }
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: t5(isKeycloak ? "addKeycloakOpenIdProvider" : "addOpenIdProvider")
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      role: "manage-identity-providers",
      isHorizontal: true,
      onSubmit: handleSubmit(save)
    }, /* @__PURE__ */ react.createElement(OIDCGeneralSettings, {
      id: id3
    }), /* @__PURE__ */ react.createElement(OpenIdConnectSettings, null), /* @__PURE__ */ react.createElement(OIDCAuthentication, null), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      isDisabled: !isDirty,
      variant: "primary",
      type: "submit",
      "data-testid": "createProvider"
    }, t5("common:add")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      "data-testid": "cancel",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toIdentityProviders({realm: realm2})
      })
    }, t5("common:cancel")))))));
  }
});

// build/identity-providers/add/AddSamlConnect.js
var require_AddSamlConnect = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => AddSamlConnect
  });
  function AddSamlConnect() {
    const {t: t5} = useTranslation("identity-providers");
    const history = useHistory();
    const id3 = "saml";
    const form2 = useForm({
      defaultValues: {alias: id3}
    });
    const {
      handleSubmit,
      formState: {isDirty}
    } = form2;
    const adminClient = useAdminClient();
    const {addAlert} = useAlerts();
    const {realm: realm2} = useRealm();
    const save = async (provider) => {
      delete provider.discoveryEndpoint;
      try {
        await adminClient.identityProviders.create({
          ...provider,
          providerId: id3
        });
        addAlert(t5("createSuccess"), AlertVariant.success);
        history.push(toIdentityProvider({
          realm: realm2,
          providerId: id3,
          alias: provider.alias,
          tab: "settings"
        }));
      } catch (error2) {
        addAlert(t5("createError", {
          error: error2.response?.data?.errorMessage || error2
        }), AlertVariant.danger);
      }
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: t5("addSamlProvider")
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      role: "manage-identity-providers",
      isHorizontal: true,
      onSubmit: handleSubmit(save)
    }, /* @__PURE__ */ react.createElement(SamlGeneralSettings, {
      id: id3
    }), /* @__PURE__ */ react.createElement(SamlConnectSettings, null), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      isDisabled: !isDirty,
      variant: "primary",
      type: "submit",
      "data-testid": "createProvider"
    }, t5("common:add")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      "data-testid": "cancel",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toIdentityProviders({realm: realm2})
      })
    }, t5("common:cancel")))))));
  }
});

// build/realm-roles/RealmRolesSection.js
var require_RealmRolesSection = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => RealmRolesSection
  });
  function RealmRolesSection() {
    const adminClient = useAdminClient();
    const loader = (first2, max2, search2) => {
      const params = {
        first: first2,
        max: max2
      };
      const searchParam = search2 || "";
      if (searchParam) {
        params.search = searchParam;
      }
      return adminClient.roles.find(params);
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "roles:title",
      subKey: "roles:roleExplain"
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      padding: {default: "noPadding"}
    }, /* @__PURE__ */ react.createElement(RolesList, {
      loader
    })));
  }
});

// build/realm-settings/key-providers/rsa/RSAForm.js
var require_RSAForm = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    RSAForm: () => RSAForm,
    default: () => RSASettings
  });
  var RSAForm = ({
    editMode,
    providerType,
    handleModalToggle,
    refresh
  }) => {
    const {t: t5} = useTranslation("realm-settings");
    const serverInfo2 = useServerInfo();
    const [component, setComponent] = useState();
    const [isRSAalgDropdownOpen, setIsRSAalgDropdownOpen] = useState(false);
    const [keyFileName, setKeyFileName] = useState("");
    const [certificateFileName, setCertificateFileName] = useState("");
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const {id: id3} = useParams();
    const providerId = useRouteMatch("/:providerType?")?.params.providerType;
    const save = async (component2) => {
      try {
        if (id3) {
          await adminClient.components.update({id: id3}, {
            ...component2,
            parentId: component2.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE
          });
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
        } else {
          await adminClient.components.create({
            ...component2,
            parentId: component2.parentId,
            providerId: providerType,
            providerType: KEY_PROVIDER_TYPE,
            config: {priority: ["0"]}
          });
          handleModalToggle?.();
          addAlert(t5("saveProviderSuccess"), AlertVariant.success);
          refresh?.();
        }
      } catch (error2) {
        addError("realm-settings:saveProviderError", error2);
      }
    };
    const form2 = useForm({mode: "onChange"});
    const setupForm = (component2) => {
      form2.reset();
      convertToFormValues(component2, form2.setValue);
    };
    useFetch(async () => {
      if (editMode)
        return await adminClient.components.findOne({id: id3});
    }, (result) => {
      if (result) {
        setupForm(result);
        setComponent(result);
      }
    }, []);
    const allComponentTypes = serverInfo2.componentTypes?.[KEY_PROVIDER_TYPE] ?? [];
    const rsaAlgOptions = allComponentTypes[4].properties[3].options;
    return /* @__PURE__ */ react.createElement(FormAccess, {
      isHorizontal: true,
      id: "add-provider",
      className: "pf-u-mt-lg",
      role: "manage-realm",
      onSubmit: form2.handleSubmit(save)
    }, editMode && /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("providerId"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "realm-settings:providerId"
      }),
      fieldId: "id",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      id: "id",
      type: "text",
      name: "id",
      isReadOnly: editMode,
      "aria-label": t5("consoleDisplayName"),
      defaultValue: id3,
      "data-testid": "display-name-input"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:name"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "client-scopes-help:mapperName",
        fieldLabelId: "name"
      }),
      fieldId: "name",
      isRequired: true,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default,
      helperTextInvalid: t5("common:required")
    }, !editMode && /* @__PURE__ */ react.createElement(Controller, {
      name: "name",
      control: form2.control,
      defaultValue: providerType,
      render: ({onChange, value}) => {
        return /* @__PURE__ */ react.createElement(TextInput, {
          id: "name",
          type: "text",
          "aria-label": t5("consoleDisplayName"),
          defaultValue: providerType,
          value,
          onChange: (value2) => onChange(value2),
          "data-testid": "display-name-input"
        });
      }
    }), editMode && /* @__PURE__ */ react.createElement(TextInput, {
      ref: form2.register(),
      type: "text",
      id: "name",
      name: "name",
      defaultValue: providerId,
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:enabled"),
      fieldId: "kc-enabled",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: t5("realm-settings-help:enabled"),
        fieldLabelId: "enabled"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.enabled",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
        id: "kc-enabled-switch",
        label: t5("common:on"),
        labelOff: t5("common:off"),
        isChecked: value[0] === "true",
        "data-testid": value[0] === "true" ? "enabled" : "disabled",
        onChange: (value2) => {
          onChange([value2.toString()]);
        }
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("active"),
      fieldId: "kc-active",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:active",
        fieldLabelId: "active"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.active",
      control: form2.control,
      defaultValue: ["true"],
      render: ({onChange, value}) => {
        return /* @__PURE__ */ react.createElement(Switch, {
          id: "kc-active-switch",
          label: t5("common:on"),
          labelOff: t5("common:off"),
          isChecked: value[0] === "true",
          "data-testid": value[0] === "true" ? "active" : "passive",
          onChange: (value2) => {
            onChange([value2.toString()]);
          }
        });
      }
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("algorithm"),
      fieldId: "kc-algorithm",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:algorithm",
        fieldLabelId: "realm-settings:algorithm"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.algorithm",
      defaultValue: ["RS256"],
      control: form2.control,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
        toggleId: "kc-rsa-algorithm",
        onToggle: () => setIsRSAalgDropdownOpen(!isRSAalgDropdownOpen),
        onSelect: (_23, value2) => {
          onChange([value2.toString()]);
          setIsRSAalgDropdownOpen(false);
        },
        selections: [value.toString()],
        variant: SelectVariant.single,
        "aria-label": t5("algorithm"),
        isOpen: isRSAalgDropdownOpen,
        "data-testid": "select-rsa-algorithm"
      }, rsaAlgOptions.map((p2, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
        selected: p2 === value,
        key: `rsa-algorithm-${idx}`,
        value: p2
      })))
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("privateRSAKey"),
      fieldId: "kc-private-rsa-key",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:privateRSAKey",
        fieldLabelId: "realm-settings:privateRSAKey"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.privateKey",
      control: form2.control,
      defaultValue: [],
      render: ({onChange}) => /* @__PURE__ */ react.createElement(FileUpload, {
        id: "importPrivateKey",
        type: "text",
        value: component?.config?.privateKey[0],
        filenamePlaceholder: "Upload a PEM file or paste key below",
        filename: keyFileName,
        onChange: (value, fileName) => {
          setKeyFileName(fileName);
          onChange([value]);
        }
      })
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("x509Certificate"),
      fieldId: "kc-aes-keysize",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "realm-settings-help:x509Certificate",
        fieldLabelId: "realm-settings:x509Certificate"
      })
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "config.certificate",
      control: form2.control,
      defaultValue: [],
      render: ({onChange}) => /* @__PURE__ */ react.createElement(FileUpload, {
        id: "importCertificate",
        type: "text",
        value: component?.config?.certificate[0],
        filenamePlaceholder: "Upload a PEM file or paste key below",
        filename: certificateFileName,
        onChange: (value, fileName) => {
          setCertificateFileName(fileName);
          onChange([value]);
        }
      })
    })), /* @__PURE__ */ react.createElement(ActionGroup, {
      className: "kc-hmac-form-buttons"
    }, /* @__PURE__ */ react.createElement(Button, {
      className: "kc-hmac-form-save-button",
      "data-testid": "add-provider-button",
      variant: "primary",
      type: "submit"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      className: "kc-hmac-form-cancel-button",
      onClick: !editMode && handleModalToggle || void 0,
      variant: "link"
    }, t5("common:cancel"))));
  };
  function RSASettings() {
    const {t: t5} = useTranslation("realm-settings");
    const providerId = useRouteMatch("/:realm/realm-settings/keys/:id?/:providerType?/settings")?.params.providerType;
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: t5("editProvider"),
      subKey: providerId
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(RSAForm, {
      providerType: providerId,
      editMode: true
    })));
  }
});

// build/sessions/SessionsSection.js
var require_SessionsSection = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => SessionsSection
  });
  var import_moment6 = __toModule(require_moment());
  var Clients = (row) => {
    return /* @__PURE__ */ react.createElement(react.Fragment, null, Object.values(row.clients).map((client2) => /* @__PURE__ */ react.createElement(Link, {
      key: client2,
      to: "",
      className: "pf-u-mx-sm"
    }, client2)));
  };
  function SessionsSection() {
    const {t: t5} = useTranslation("sessions");
    const adminClient = useAdminClient();
    const [filterDropdownOpen, setFilterDropdownOpen] = useState(false);
    const [revocationModalOpen, setRevocationModalOpen] = useState(false);
    const [logoutAllSessionsModalOpen, setLogoutAllSessionsModalOpen] = useState(false);
    const [activeClientDetails, setActiveClientDetails] = useState([]);
    const [filterType, setFilterType] = useState(t5("sessionsType.allSessions").toString());
    const [key, setKey] = useState(0);
    const [noSessions, setNoSessions] = useState(false);
    const refresh = () => {
      setKey(new Date().getTime());
    };
    const handleRevocationModalToggle = () => {
      setRevocationModalOpen(!revocationModalOpen);
    };
    const handleLogoutAllSessionsModalToggle = () => {
      setLogoutAllSessionsModalOpen(!logoutAllSessionsModalOpen);
    };
    const loader = async () => {
      const activeClients = await adminClient.sessions.find();
      const clientSessions = (await Promise.all(activeClients.map((client2) => adminClient.clients.listSessions({id: client2.id})))).flat();
      setNoSessions(clientSessions.length === 0);
      const allClients = await adminClient.clients.find();
      const getActiveClientDetails = allClients.filter((x2) => activeClients.map((y3) => y3.id).includes(x2.id));
      setActiveClientDetails(getActiveClientDetails);
      const userIds = Array.from(new Set(clientSessions.map((session) => session.userId)));
      const userSessions = (await Promise.all(userIds.map((userId) => adminClient.users.listSessions({id: userId})))).flat();
      return userSessions;
    };
    const dropdownItems = [
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "toggle-modal",
        "data-testid": "revocation",
        component: "button",
        onClick: () => handleRevocationModalToggle()
      }, t5("revocation")),
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "delete-role",
        "data-testid": "logout-all",
        component: "button",
        isDisabled: noSessions,
        onClick: () => handleLogoutAllSessionsModalToggle()
      }, t5("signOutAllActiveSessions"))
    ];
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      dropdownItems,
      titleKey: "sessions:title",
      subKey: "sessions:sessionExplain"
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      className: "pf-u-p-0"
    }, revocationModalOpen && /* @__PURE__ */ react.createElement(RevocationModal, {
      handleModalToggle: handleRevocationModalToggle,
      activeClients: activeClientDetails,
      save: () => {
        handleRevocationModalToggle();
      }
    }), logoutAllSessionsModalOpen && /* @__PURE__ */ react.createElement(LogoutAllSessionsModal, {
      handleModalToggle: handleLogoutAllSessionsModalToggle
    }), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
      key,
      loader,
      ariaLabelKey: "session:title",
      searchPlaceholderKey: "sessions:searchForSession",
      searchTypeComponent: /* @__PURE__ */ react.createElement(Select, {
        "data-testid": "filter-session-type-select",
        isOpen: filterDropdownOpen,
        className: "kc-filter-session-type-select",
        variant: SelectVariant.single,
        onToggle: (isExpanded) => setFilterDropdownOpen(isExpanded),
        toggleIcon: /* @__PURE__ */ react.createElement(FilterIcon, null),
        onSelect: (_23, value) => {
          setFilterType(value.toString());
          refresh();
          setFilterDropdownOpen(false);
        },
        selections: filterType
      }, /* @__PURE__ */ react.createElement(SelectOption, {
        "data-testid": "all-sessions-option",
        value: t5("sessionsType.allSessions"),
        isPlaceholder: true
      }), /* @__PURE__ */ react.createElement(SelectOption, {
        "data-testid": "regular-sso-option",
        value: t5("sessionsType.regularSSO")
      }), /* @__PURE__ */ react.createElement(SelectOption, {
        "data-testid": "offline-option",
        value: t5("sessionsType.offline")
      }), /* @__PURE__ */ react.createElement(SelectOption, {
        "data-testid": "direct-grant-option",
        value: t5("sessionsType.directGrant")
      }), /* @__PURE__ */ react.createElement(SelectOption, {
        "data-testid": "service-account-option",
        value: t5("sessionsType.serviceAccount")
      })),
      columns: [
        {
          name: "username",
          displayKey: "sessions:subject"
        },
        {
          name: "lastAccess",
          displayKey: "sessions:lastAccess",
          cellRenderer: (row) => (0, import_moment6.default)(row.lastAccess).fromNow()
        },
        {
          name: "start",
          displayKey: "sessions:startDate",
          cellRenderer: (row) => (0, import_moment6.default)(row.lastAccess).format("LLL")
        },
        {
          name: "clients",
          displayKey: "sessions:accessedClients",
          cellRenderer: Clients
        }
      ],
      emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
        hasIcon: true,
        icon: CubesIcon,
        message: t5("noSessions"),
        instructions: t5("noSessionsDescription")
      })
    })));
  }
});

// build/user-federation/UserFederationKerberosSettings.js
var require_UserFederationKerberosSettings = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => UserFederationKerberosSettings
  });
  var KerberosSettingsHeader = ({
    onChange,
    value,
    save,
    toggleDeleteDialog
  }) => {
    const {t: t5} = useTranslation("user-federation");
    const {id: id3} = useParams();
    const [toggleDisableDialog, DisableConfirm] = useConfirmDialog({
      titleKey: "user-federation:userFedDisableConfirmTitle",
      messageKey: "user-federation:userFedDisableConfirm",
      continueButtonLabel: "common:disable",
      onConfirm: () => {
        onChange("false");
        save();
      }
    });
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DisableConfirm, null), !id3 ? /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "Kerberos"
    }) : /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "Kerberos",
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "delete",
          onClick: () => toggleDeleteDialog(),
          "data-testid": "delete-kerberos-cmd"
        }, t5("deleteProvider"))
      ],
      isEnabled: value === "true",
      onToggle: (value2) => {
        if (!value2) {
          toggleDisableDialog();
        } else {
          onChange(value2.toString());
          save();
        }
      }
    }));
  };
  function UserFederationKerberosSettings() {
    const {t: t5} = useTranslation("user-federation");
    const form2 = useForm({mode: "onChange"});
    const history = useHistory();
    const adminClient = useAdminClient();
    const {realm: realm2} = useRealm();
    const {id: id3} = useParams();
    const {addAlert, addError} = useAlerts();
    useFetch(async () => {
      if (id3) {
        return adminClient.components.findOne({id: id3});
      }
    }, (fetchedComponent) => {
      if (fetchedComponent) {
        setupForm(fetchedComponent);
      } else if (id3) {
        throw new Error(t5("common:notFound"));
      }
    }, []);
    const setupForm = (component) => {
      form2.reset({...component});
    };
    const save = async (component) => {
      try {
        if (!id3) {
          await adminClient.components.create(component);
          history.push(`/${realm2}/user-federation`);
        } else {
          await adminClient.components.update({id: id3}, component);
        }
        setupForm(component);
        addAlert(t5(!id3 ? "createSuccess" : "saveSuccess"), AlertVariant.success);
      } catch (error2) {
        addError(`user-federation:${!id3 ? "createError" : "saveError"}`, error2);
      }
    };
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "user-federation:userFedDeleteConfirmTitle",
      messageKey: "user-federation:userFedDeleteConfirm",
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.components.del({id: id3});
          addAlert(t5("userFedDeletedSuccess"), AlertVariant.success);
          history.replace(`/${realm2}/user-federation`);
        } catch (error2) {
          addAlert("user-federation:userFedDeleteError", error2);
        }
      }
    });
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(Controller, {
      name: "config.enabled[0]",
      defaultValue: ["true"][0],
      control: form2.control,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(KerberosSettingsHeader, {
        value,
        onChange,
        save: () => save(form2.getValues()),
        toggleDeleteDialog
      })
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light"
    }, /* @__PURE__ */ react.createElement(KerberosSettingsRequired, {
      form: form2,
      showSectionHeading: true
    })), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      isFilled: true
    }, /* @__PURE__ */ react.createElement(SettingsCache, {
      form: form2,
      showSectionHeading: true
    }), /* @__PURE__ */ react.createElement(Form, {
      onSubmit: form2.handleSubmit(save)
    }, /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      isDisabled: !form2.formState.isDirty,
      variant: "primary",
      type: "submit",
      "data-testid": "kerberos-save"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      onClick: () => history.push(`/${realm2}/user-federation`),
      "data-testid": "kerberos-cancel"
    }, t5("common:cancel"))))));
  }
});

// build/user-federation/UserFederationLdapSettings.js
var require_UserFederationLdapSettings = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => UserFederationLdapSettings
  });
  var LdapSettingsHeader = ({
    onChange,
    value,
    editMode,
    save,
    toggleDeleteDialog,
    toggleRemoveUsersDialog
  }) => {
    const {t: t5} = useTranslation("user-federation");
    const {id: id3} = useParams();
    const adminClient = useAdminClient();
    const {addAlert, addError} = useAlerts();
    const [toggleDisableDialog, DisableConfirm] = useConfirmDialog({
      titleKey: "user-federation:userFedDisableConfirmTitle",
      messageKey: "user-federation:userFedDisableConfirm",
      continueButtonLabel: "common:disable",
      onConfirm: () => {
        onChange("false");
        save();
      }
    });
    const [toggleUnlinkUsersDialog, UnlinkUsersDialog] = useConfirmDialog({
      titleKey: "user-federation:userFedUnlinkUsersConfirmTitle",
      messageKey: "user-federation:userFedUnlinkUsersConfirm",
      continueButtonLabel: "user-federation:unlinkUsers",
      onConfirm: () => unlinkUsers()
    });
    const syncChangedUsers = async () => {
      try {
        if (id3) {
          const response = await adminClient.userStorageProvider.sync({
            id: id3,
            action: "triggerChangedUsersSync"
          });
          if (response.ignored) {
            addAlert(`${response.status}.`, AlertVariant.warning);
          } else {
            addAlert(t5("syncUsersSuccess") + `${response.added} users added, ${response.updated} users updated, ${response.removed} users removed, ${response.failed} users failed.`, AlertVariant.success);
          }
        }
      } catch (error2) {
        addError("user-federation:syncUsersError", error2);
      }
    };
    const syncAllUsers = async () => {
      try {
        if (id3) {
          const response = await adminClient.userStorageProvider.sync({
            id: id3,
            action: "triggerFullSync"
          });
          if (response.ignored) {
            addAlert(`${response.status}.`, AlertVariant.warning);
          } else {
            addAlert(t5("syncUsersSuccess") + `${response.added} users added, ${response.updated} users updated, ${response.removed} users removed, ${response.failed} users failed.`, AlertVariant.success);
          }
        }
      } catch (error2) {
        addError("user-federation:syncUsersError", error2);
      }
    };
    const unlinkUsers = async () => {
      try {
        if (id3) {
          await adminClient.userStorageProvider.unlinkUsers({id: id3});
        }
        addAlert(t5("unlinkUsersSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("user-federation:unlinkUsersError", error2);
      }
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DisableConfirm, null), /* @__PURE__ */ react.createElement(UnlinkUsersDialog, null), !id3 ? /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: t5("addOneLdap")
    }) : /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "LDAP",
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "sync",
          onClick: syncChangedUsers
        }, t5("syncChangedUsers")),
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "syncall",
          onClick: syncAllUsers
        }, t5("syncAllUsers")),
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "unlink",
          isDisabled: editMode ? !editMode.includes("UNSYNCED") : false,
          onClick: toggleUnlinkUsersDialog
        }, t5("unlinkUsers")),
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "remove",
          onClick: toggleRemoveUsersDialog
        }, t5("removeImported")),
        /* @__PURE__ */ react.createElement(DropdownSeparator, {
          key: "separator"
        }),
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "delete",
          onClick: toggleDeleteDialog,
          "data-testid": "delete-ldap-cmd"
        }, t5("deleteProvider"))
      ],
      isEnabled: value === "true",
      onToggle: (value2) => {
        if (!value2) {
          toggleDisableDialog();
        } else {
          onChange("" + value2);
          save();
        }
      }
    }));
  };
  function UserFederationLdapSettings() {
    const {t: t5} = useTranslation("user-federation");
    const form2 = useForm({mode: "onChange"});
    const history = useHistory();
    const adminClient = useAdminClient();
    const {realm: realm2} = useRealm();
    const {id: id3} = useParams();
    const {addAlert, addError} = useAlerts();
    const [component, setComponent] = useState();
    const [refreshCount, setRefreshCount] = useState(0);
    const editMode = component?.config?.editMode;
    const refresh = () => setRefreshCount((count) => count + 1);
    useFetch(async () => {
      if (id3) {
        return await adminClient.components.findOne({id: id3});
      }
      return void 0;
    }, (fetchedComponent) => {
      if (fetchedComponent) {
        setupForm(fetchedComponent);
        setComponent(fetchedComponent);
      } else if (id3) {
        throw new Error(t5("common:notFound"));
      }
    }, [refreshCount]);
    const setupForm = (component2) => {
      form2.reset({...component2});
      form2.setValue("config.periodicChangedUsersSync", component2.config?.["changedSyncPeriod"][0] !== "-1");
      form2.setValue("config.periodicFullSync", component2.config?.["fullSyncPeriod"][0] !== "-1");
    };
    const removeImportedUsers = async () => {
      try {
        if (id3) {
          await adminClient.userStorageProvider.removeImportedUsers({id: id3});
        }
        addAlert(t5("removeImportedUsersSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("user-federation:removeImportedUsersError", error2);
      }
    };
    const save = async (component2) => {
      if (component2.config?.periodicChangedUsersSync !== null) {
        if (component2.config?.periodicChangedUsersSync === false) {
          component2.config.changedSyncPeriod = ["-1"];
        }
        delete component2.config?.periodicChangedUsersSync;
      }
      if (component2.config?.periodicFullSync !== null) {
        if (component2.config?.periodicFullSync === false) {
          component2.config.fullSyncPeriod = ["-1"];
        }
        delete component2.config?.periodicFullSync;
      }
      try {
        if (!id3) {
          await adminClient.components.create(component2);
          history.push(`/${realm2}/user-federation`);
        } else {
          await adminClient.components.update({id: id3}, component2);
        }
        addAlert(t5(id3 ? "saveSuccess" : "createSuccess"), AlertVariant.success);
        refresh();
      } catch (error2) {
        addError(`user-federation:${id3 ? "saveError" : "createError"}`, error2);
      }
    };
    const [toggleRemoveUsersDialog, RemoveUsersConfirm] = useConfirmDialog({
      titleKey: t5("removeImportedUsers"),
      messageKey: t5("removeImportedUsersMessage"),
      continueButtonLabel: "common:remove",
      onConfirm: async () => {
        try {
          removeImportedUsers();
          addAlert(t5("removeImportedUsersSuccess"), AlertVariant.success);
        } catch (error2) {
          addError("user-federation:removeImportedUsersError", error2);
        }
      }
    });
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: "user-federation:userFedDeleteConfirmTitle",
      messageKey: "user-federation:userFedDeleteConfirm",
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.components.del({id: id3});
          addAlert(t5("userFedDeletedSuccess"), AlertVariant.success);
          history.replace(`/${realm2}/user-federation`);
        } catch (error2) {
          addError("user-federation:userFedDeleteError", error2);
        }
      }
    });
    const addLdapFormContent = () => {
      return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ScrollForm, {
        sections: [
          t5("generalOptions"),
          t5("connectionAndAuthenticationSettings"),
          t5("ldapSearchingAndUpdatingSettings"),
          t5("synchronizationSettings"),
          t5("kerberosIntegration"),
          t5("cacheSettings"),
          t5("advancedSettings")
        ]
      }, /* @__PURE__ */ react.createElement(LdapSettingsGeneral, {
        form: form2,
        vendorEdit: !!id3
      }), /* @__PURE__ */ react.createElement(LdapSettingsConnection, {
        form: form2,
        edit: !!id3
      }), /* @__PURE__ */ react.createElement(LdapSettingsSearching, {
        form: form2
      }), /* @__PURE__ */ react.createElement(LdapSettingsSynchronization, {
        form: form2
      }), /* @__PURE__ */ react.createElement(LdapSettingsKerberosIntegration, {
        form: form2
      }), /* @__PURE__ */ react.createElement(SettingsCache, {
        form: form2
      }), /* @__PURE__ */ react.createElement(LdapSettingsAdvanced, {
        form: form2
      })), /* @__PURE__ */ react.createElement(Form, {
        onSubmit: form2.handleSubmit(save)
      }, /* @__PURE__ */ react.createElement(ActionGroup, {
        className: "keycloak__form_actions"
      }, /* @__PURE__ */ react.createElement(Button, {
        isDisabled: !form2.formState.isDirty,
        variant: "primary",
        type: "submit",
        "data-testid": "ldap-save"
      }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
        variant: "link",
        onClick: () => history.push(`/${realm2}/user-federation`),
        "data-testid": "ldap-cancel"
      }, t5("common:cancel")))));
    };
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(RemoveUsersConfirm, null), /* @__PURE__ */ react.createElement(Controller, {
      name: "config.enabled[0]",
      defaultValue: ["true"][0],
      control: form2.control,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(LdapSettingsHeader, {
        editMode,
        value,
        save: () => save(form2.getValues()),
        onChange,
        toggleDeleteDialog,
        toggleRemoveUsersDialog
      })
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      isFilled: true
    }, id3 ? /* @__PURE__ */ react.createElement(KeycloakTabs, {
      isBox: true
    }, /* @__PURE__ */ react.createElement(Tab, {
      id: "settings",
      eventKey: "settings",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:settings"))
    }, addLdapFormContent()), /* @__PURE__ */ react.createElement(Tab, {
      id: "mappers",
      eventKey: "mappers",
      title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("common:mappers")),
      "data-testid": "ldap-mappers-tab"
    }, /* @__PURE__ */ react.createElement(LdapMapperList, null))) : addLdapFormContent()));
  }
});

// build/user-federation/UserFederationSection.js
var require_UserFederationSection = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => UserFederationSection
  });
  function UserFederationSection() {
    const [userFederations, setUserFederations] = useState();
    const {addAlert, addError} = useAlerts();
    const {t: t5} = useTranslation("user-federation");
    const {realm: realm2} = useRealm();
    const adminClient = useAdminClient();
    const [key, setKey] = useState(0);
    const refresh = () => setKey(new Date().getTime());
    const {url} = useRouteMatch();
    const history = useHistory();
    useFetch(async () => {
      const realmModel = await adminClient.realms.findOne({realm: realm2});
      const testParams = {
        parentId: realmModel.id,
        type: "org.keycloak.storage.UserStorageProvider"
      };
      return adminClient.components.find(testParams);
    }, (userFederations2) => {
      setUserFederations(userFederations2);
    }, [key]);
    const ufAddProviderDropdownItems = [
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "itemLDAP",
        onClick: () => history.push(`${url}/ldap/new`)
      }, "LDAP"),
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "itemKerberos",
        onClick: () => history.push(`${url}/kerberos/new`)
      }, "Kerberos")
    ];
    const learnMoreLinkProps = {
      title: t5("common:learnMore"),
      href: "https://www.keycloak.org/docs/latest/server_admin/index.html#_user-storage-federation"
    };
    let cards;
    const [currentCard, setCurrentCard] = useState("");
    const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
      titleKey: t5("userFedDeleteConfirmTitle"),
      messageKey: t5("userFedDeleteConfirm"),
      continueButtonLabel: "common:delete",
      continueButtonVariant: ButtonVariant.danger,
      onConfirm: async () => {
        try {
          await adminClient.components.del({id: currentCard});
          refresh();
          addAlert(t5("userFedDeletedSuccess"), AlertVariant.success);
        } catch (error2) {
          addError("user-federation:userFedDeleteError", error2);
        }
      }
    });
    const toggleDeleteForCard = (id3) => {
      setCurrentCard(id3);
      toggleDeleteDialog();
    };
    if (userFederations) {
      cards = userFederations.map((userFederation, index3) => {
        const ufCardDropdownItems = [
          /* @__PURE__ */ react.createElement(DropdownItem, {
            key: `${index3}-cardDelete`,
            onClick: () => {
              toggleDeleteForCard(userFederation.id);
            },
            "data-testid": "card-delete"
          }, t5("common:delete"))
        ];
        return /* @__PURE__ */ react.createElement(GalleryItem, {
          key: index3,
          className: "keycloak-admin--user-federation__gallery-item"
        }, /* @__PURE__ */ react.createElement(KeycloakCard, {
          id: userFederation.id,
          dropdownItems: ufCardDropdownItems,
          providerId: userFederation.providerId,
          title: userFederation.name,
          footerText: userFederation.providerId === "ldap" ? "LDAP" : "Kerberos",
          labelText: userFederation.config["enabled"][0] !== "false" ? `${t5("common:enabled")}` : `${t5("common:disabled")}`,
          labelColor: userFederation.config["enabled"][0] !== "false" ? "blue" : "gray"
        }));
      });
    }
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: "userFederation",
      subKey: "user-federation:userFederationExplanation",
      subKeyLinkProps: learnMoreLinkProps,
      ...userFederations && userFederations.length > 0 ? {
        lowerDropdownItems: ufAddProviderDropdownItems,
        lowerDropdownMenuTitle: "user-federation:addNewProvider"
      } : {}
    }), /* @__PURE__ */ react.createElement(PageSection, null, userFederations && userFederations.length > 0 ? /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(Gallery, {
      hasGutter: true
    }, cards)) : /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, {
      component: TextVariants.p
    }, t5("getStarted"))), /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, {
      className: "pf-u-mt-lg",
      component: TextVariants.h2
    }, t5("providers"))), /* @__PURE__ */ react.createElement("hr", {
      className: "pf-u-mb-lg"
    }), /* @__PURE__ */ react.createElement(Gallery, {
      hasGutter: true
    }, /* @__PURE__ */ react.createElement(Card, {
      className: "keycloak-empty-state-card",
      isHoverable: true,
      onClick: () => history.push(`${url}/kerberos/new`),
      "data-testid": "kerberos-card"
    }, /* @__PURE__ */ react.createElement(CardTitle, null, /* @__PURE__ */ react.createElement(Split, {
      hasGutter: true
    }, /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(DatabaseIcon, {
      size: "lg"
    })), /* @__PURE__ */ react.createElement(SplitItem, {
      isFilled: true
    }, t5("addKerberos"))))), /* @__PURE__ */ react.createElement(Card, {
      className: "keycloak-empty-state-card",
      isHoverable: true,
      onClick: () => history.push(`${url}/ldap/new`),
      "data-testid": "ldap-card"
    }, /* @__PURE__ */ react.createElement(CardTitle, null, /* @__PURE__ */ react.createElement(Split, {
      hasGutter: true
    }, /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(DatabaseIcon, {
      size: "lg"
    })), /* @__PURE__ */ react.createElement(SplitItem, {
      isFilled: true
    }, t5("addLdap")))))))));
  }
});

// build/user-federation/ldap/mappers/LdapMapperDetails.js
var require_LdapMapperDetails = __commonJS((exports2) => {
  __markAsModule(exports2);
  __export(exports2, {
    default: () => LdapMapperDetails
  });
  function LdapMapperDetails() {
    const form2 = useForm();
    const [mapping, setMapping] = useState();
    const [components3, setComponents] = useState();
    const adminClient = useAdminClient();
    const {id: id3, mapperId} = useParams();
    const history = useHistory();
    const {realm: realm2} = useRealm();
    const {t: t5} = useTranslation("user-federation");
    const {addAlert, addError} = useAlerts();
    const [isMapperDropdownOpen, setIsMapperDropdownOpen] = useState(false);
    useFetch(async () => {
      const components22 = await adminClient.components.listSubComponents({
        id: id3,
        type: "org.keycloak.storage.ldap.mappers.LDAPStorageMapper"
      });
      if (mapperId && mapperId !== "new") {
        const fetchedMapper = await adminClient.components.findOne({
          id: mapperId
        });
        return {components: components22, fetchedMapper};
      }
      return {components: components22};
    }, ({components: components22, fetchedMapper}) => {
      setMapping(fetchedMapper);
      setComponents(components22);
      if (mapperId !== "new" && !fetchedMapper)
        throw new Error(t5("common:notFound"));
      if (fetchedMapper)
        setupForm(fetchedMapper);
    }, []);
    const setupForm = (mapper) => {
      convertToFormValues(mapper, form2.setValue);
    };
    const save = async (mapper) => {
      const component = convertFormValuesToObject(mapper);
      const map2 = {
        ...component,
        config: Object.entries(component.config || {}).reduce((result, [key, value]) => {
          result[key] = Array.isArray(value) ? value : [value];
          return result;
        }, {})
      };
      try {
        if (mapperId === "new") {
          await adminClient.components.create(map2);
          history.push(toUserFederationLdap({realm: realm2, id: mapper.parentId, tab: "mappers"}));
        } else {
          await adminClient.components.update({id: mapperId}, map2);
        }
        setupForm(map2);
        addAlert(t5(mapperId === "new" ? "common:mappingCreatedSuccess" : "common:mappingUpdatedSuccess"), AlertVariant.success);
      } catch (error2) {
        addError(mapperId === "new" ? "common:mappingCreatedError" : "common:mappingUpdatedError", error2);
      }
    };
    const mapperType = useWatch({
      control: form2.control,
      name: "providerId"
    });
    const isNew = mapperId === "new";
    if (!components3) {
      return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
    }
    return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ViewHeader, {
      titleKey: mapping ? mapping.name : t5("common:createNewMapper")
    }), /* @__PURE__ */ react.createElement(PageSection, {
      variant: "light",
      isFilled: true
    }, /* @__PURE__ */ react.createElement(FormAccess, {
      role: "manage-realm",
      isHorizontal: true
    }, !isNew && /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:id"),
      fieldId: "kc-ldap-mapper-id"
    }, /* @__PURE__ */ react.createElement(TextInput, {
      isDisabled: true,
      type: "text",
      id: "kc-ldap-mapper-id",
      "data-testid": "ldap-mapper-id",
      name: "id",
      ref: form2.register
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:name"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "user-federation-help:nameHelp",
        fieldLabelId: "name"
      }),
      fieldId: "kc-ldap-mapper-name",
      isRequired: true
    }, /* @__PURE__ */ react.createElement(TextInput, {
      isDisabled: !isNew,
      isRequired: true,
      type: "text",
      id: "kc-ldap-mapper-name",
      "data-testid": "ldap-mapper-name",
      name: "name",
      ref: form2.register({required: true}),
      validated: form2.errors.name ? ValidatedOptions.error : ValidatedOptions.default
    }), /* @__PURE__ */ react.createElement(TextInput, {
      hidden: true,
      defaultValue: isNew ? id3 : mapping ? mapping.parentId : "",
      type: "text",
      id: "kc-ldap-parentId",
      "data-testid": "ldap-mapper-parentId",
      name: "parentId",
      ref: form2.register
    }), /* @__PURE__ */ react.createElement(TextInput, {
      hidden: true,
      defaultValue: "org.keycloak.storage.ldap.mappers.LDAPStorageMapper",
      type: "text",
      id: "kc-ldap-provider-type",
      "data-testid": "ldap-mapper-provider-type",
      name: "providerType",
      ref: form2.register
    })), !isNew ? /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:mapperType"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "user-federation-help:mapperTypeHelp",
        fieldLabelId: "mapperType"
      }),
      fieldId: "kc-ldap-mapper-type",
      isRequired: true
    }, /* @__PURE__ */ react.createElement(TextInput, {
      isDisabled: !isNew,
      isRequired: true,
      type: "text",
      id: "kc-ldap-mapper-type",
      "data-testid": "ldap-mapper-type-fld",
      name: "providerId",
      ref: form2.register
    })) : /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("common:mapperType"),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "user-federation-help:mapperTypeHelp",
        fieldLabelId: "mapperType"
      }),
      fieldId: "kc-providerId",
      isRequired: true
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "providerId",
      defaultValue: "",
      control: form2.control,
      "data-testid": "ldap-mapper-type-select",
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
        toggleId: "kc-providerId",
        required: true,
        onToggle: () => setIsMapperDropdownOpen(!isMapperDropdownOpen),
        isOpen: isMapperDropdownOpen,
        onSelect: (_23, value2) => {
          onChange(value2);
          setIsMapperDropdownOpen(false);
        },
        selections: value,
        variant: SelectVariant.typeahead
      }, components3.map((c3) => /* @__PURE__ */ react.createElement(SelectOption, {
        key: c3.id,
        value: c3.id
      })))
    })), /* @__PURE__ */ react.createElement(FormProvider, {
      ...form2
    }, !!mapperType && /* @__PURE__ */ react.createElement(DynamicComponents, {
      properties: components3.find((c3) => c3.id === mapperType)?.properties
    }))), /* @__PURE__ */ react.createElement(Form, {
      onSubmit: form2.handleSubmit(() => save(form2.getValues()))
    }, /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      isDisabled: !form2.formState.isDirty,
      variant: "primary",
      type: "submit",
      "data-testid": "ldap-mapper-save"
    }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      onClick: () => isNew ? history.goBack() : history.push(`/${realm2}/user-federation/ldap/${mapping.parentId}/mappers`),
      "data-testid": "ldap-mapper-cancel"
    }, t5("common:cancel"))))));
  }
});

// build/_snowpack/pkg/@keycloak/keycloak-admin-client.js
var require_keycloak_admin_client = __commonJS((exports) => {
  __markAsModule(exports);
  __export(exports, {
    default: () => keycloak_admin_client_default
  });
  var requiredActionProviderRepresentation = createCommonjsModule(function(module2, exports2) {
    exports2.__esModule = true;
    exports2.RequiredActionAlias = void 0;
    (function(RequiredActionAlias) {
      RequiredActionAlias["VERIFY_EMAIL"] = "VERIFY_EMAIL";
      RequiredActionAlias["UPDATE_PROFILE"] = "UPDATE_PROFILE";
      RequiredActionAlias["CONFIGURE_TOTP"] = "CONFIGURE_TOTP";
      RequiredActionAlias["UPDATE_PASSWORD"] = "UPDATE_PASSWORD";
      RequiredActionAlias["terms_and_conditions"] = "terms_and_conditions";
    })(exports2.RequiredActionAlias || (exports2.RequiredActionAlias = {}));
  });
  var INFINITY = 1 / 0;
  var symbolTag = "[object Symbol]";
  var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  var rsAstralRange = "\\ud800-\\udfff";
  var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23";
  var rsComboSymbolsRange = "\\u20d0-\\u20f0";
  var rsDingbatRange = "\\u2700-\\u27bf";
  var rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff";
  var rsMathOpRange = "\\xac\\xb1\\xd7\\xf7";
  var rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf";
  var rsPunctuationRange = "\\u2000-\\u206f";
  var rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000";
  var rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde";
  var rsVarRange = "\\ufe0e\\ufe0f";
  var rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  var rsApos = "['’]";
  var rsAstral = "[" + rsAstralRange + "]";
  var rsBreak = "[" + rsBreakRange + "]";
  var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]";
  var rsDigits = "\\d+";
  var rsDingbat = "[" + rsDingbatRange + "]";
  var rsLower = "[" + rsLowerRange + "]";
  var rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]";
  var rsFitz = "\\ud83c[\\udffb-\\udfff]";
  var rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")";
  var rsNonAstral = "[^" + rsAstralRange + "]";
  var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}";
  var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]";
  var rsUpper = "[" + rsUpperRange + "]";
  var rsZWJ = "\\u200d";
  var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")";
  var rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")";
  var rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?";
  var rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?";
  var reOptMod = rsModifier + "?";
  var rsOptVar = "[" + rsVarRange + "]?";
  var rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*";
  var rsSeq = rsOptVar + reOptMod + rsOptJoin;
  var rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq;
  var rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")";
  var reApos = RegExp(rsApos, "g");
  var reComboMark = RegExp(rsCombo, "g");
  var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
  var reUnicodeWord = RegExp([
    rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")",
    rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [rsBreak, rsUpper + rsLowerMisc, "$"].join("|") + ")",
    rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr,
    rsUpper + "+" + rsOptUpperContr,
    rsDigits,
    rsEmoji
  ].join("|"), "g");
  var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]");
  var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
  var deburredLetters = {
    À: "A",
    Á: "A",
    Â: "A",
    Ã: "A",
    Ä: "A",
    Å: "A",
    à: "a",
    á: "a",
    â: "a",
    ã: "a",
    ä: "a",
    å: "a",
    Ç: "C",
    ç: "c",
    Ð: "D",
    ð: "d",
    È: "E",
    É: "E",
    Ê: "E",
    Ë: "E",
    è: "e",
    é: "e",
    ê: "e",
    ë: "e",
    Ì: "I",
    Í: "I",
    Î: "I",
    Ï: "I",
    ì: "i",
    í: "i",
    î: "i",
    ï: "i",
    Ñ: "N",
    ñ: "n",
    Ò: "O",
    Ó: "O",
    Ô: "O",
    Õ: "O",
    Ö: "O",
    Ø: "O",
    ò: "o",
    ó: "o",
    ô: "o",
    õ: "o",
    ö: "o",
    ø: "o",
    Ù: "U",
    Ú: "U",
    Û: "U",
    Ü: "U",
    ù: "u",
    ú: "u",
    û: "u",
    ü: "u",
    Ý: "Y",
    ý: "y",
    ÿ: "y",
    Æ: "Ae",
    æ: "ae",
    Þ: "Th",
    þ: "th",
    ß: "ss",
    Ā: "A",
    Ă: "A",
    Ą: "A",
    ā: "a",
    ă: "a",
    ą: "a",
    Ć: "C",
    Ĉ: "C",
    Ċ: "C",
    Č: "C",
    ć: "c",
    ĉ: "c",
    ċ: "c",
    č: "c",
    Ď: "D",
    Đ: "D",
    ď: "d",
    đ: "d",
    Ē: "E",
    Ĕ: "E",
    Ė: "E",
    Ę: "E",
    Ě: "E",
    ē: "e",
    ĕ: "e",
    ė: "e",
    ę: "e",
    ě: "e",
    Ĝ: "G",
    Ğ: "G",
    Ġ: "G",
    Ģ: "G",
    ĝ: "g",
    ğ: "g",
    ġ: "g",
    ģ: "g",
    Ĥ: "H",
    Ħ: "H",
    ĥ: "h",
    ħ: "h",
    Ĩ: "I",
    Ī: "I",
    Ĭ: "I",
    Į: "I",
    İ: "I",
    ĩ: "i",
    ī: "i",
    ĭ: "i",
    į: "i",
    ı: "i",
    Ĵ: "J",
    ĵ: "j",
    Ķ: "K",
    ķ: "k",
    ĸ: "k",
    Ĺ: "L",
    Ļ: "L",
    Ľ: "L",
    Ŀ: "L",
    Ł: "L",
    ĺ: "l",
    ļ: "l",
    ľ: "l",
    ŀ: "l",
    ł: "l",
    Ń: "N",
    Ņ: "N",
    Ň: "N",
    Ŋ: "N",
    ń: "n",
    ņ: "n",
    ň: "n",
    ŋ: "n",
    Ō: "O",
    Ŏ: "O",
    Ő: "O",
    ō: "o",
    ŏ: "o",
    ő: "o",
    Ŕ: "R",
    Ŗ: "R",
    Ř: "R",
    ŕ: "r",
    ŗ: "r",
    ř: "r",
    Ś: "S",
    Ŝ: "S",
    Ş: "S",
    Š: "S",
    ś: "s",
    ŝ: "s",
    ş: "s",
    š: "s",
    Ţ: "T",
    Ť: "T",
    Ŧ: "T",
    ţ: "t",
    ť: "t",
    ŧ: "t",
    Ũ: "U",
    Ū: "U",
    Ŭ: "U",
    Ů: "U",
    Ű: "U",
    Ų: "U",
    ũ: "u",
    ū: "u",
    ŭ: "u",
    ů: "u",
    ű: "u",
    ų: "u",
    Ŵ: "W",
    ŵ: "w",
    Ŷ: "Y",
    ŷ: "y",
    Ÿ: "Y",
    Ź: "Z",
    Ż: "Z",
    Ž: "Z",
    ź: "z",
    ż: "z",
    ž: "z",
    Ĳ: "IJ",
    ĳ: "ij",
    Œ: "Oe",
    œ: "oe",
    ŉ: "'n",
    ſ: "ss"
  };
  var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  var freeSelf = typeof self == "object" && self && self.Object === Object && self;
  var root = freeGlobal || freeSelf || Function("return this")();
  function arrayReduce(array2, iteratee, accumulator, initAccum) {
    var index3 = -1, length = array2 ? array2.length : 0;
    if (initAccum && length) {
      accumulator = array2[++index3];
    }
    while (++index3 < length) {
      accumulator = iteratee(accumulator, array2[index3], index3, array2);
    }
    return accumulator;
  }
  function asciiToArray(string2) {
    return string2.split("");
  }
  function asciiWords(string2) {
    return string2.match(reAsciiWord) || [];
  }
  function basePropertyOf(object) {
    return function(key) {
      return object == null ? void 0 : object[key];
    };
  }
  var deburrLetter = basePropertyOf(deburredLetters);
  function hasUnicode(string2) {
    return reHasUnicode.test(string2);
  }
  function hasUnicodeWord(string2) {
    return reHasUnicodeWord.test(string2);
  }
  function stringToArray(string2) {
    return hasUnicode(string2) ? unicodeToArray(string2) : asciiToArray(string2);
  }
  function unicodeToArray(string2) {
    return string2.match(reUnicode) || [];
  }
  function unicodeWords(string2) {
    return string2.match(reUnicodeWord) || [];
  }
  var objectProto = Object.prototype;
  var objectToString = objectProto.toString;
  var Symbol$1 = root.Symbol;
  var symbolProto = Symbol$1 ? Symbol$1.prototype : void 0;
  var symbolToString = symbolProto ? symbolProto.toString : void 0;
  function baseSlice(array2, start3, end2) {
    var index3 = -1, length = array2.length;
    if (start3 < 0) {
      start3 = -start3 > length ? 0 : length + start3;
    }
    end2 = end2 > length ? length : end2;
    if (end2 < 0) {
      end2 += length;
    }
    length = start3 > end2 ? 0 : end2 - start3 >>> 0;
    start3 >>>= 0;
    var result = Array(length);
    while (++index3 < length) {
      result[index3] = array2[index3 + start3];
    }
    return result;
  }
  function baseToString(value) {
    if (typeof value == "string") {
      return value;
    }
    if (isSymbol(value)) {
      return symbolToString ? symbolToString.call(value) : "";
    }
    var result = value + "";
    return result == "0" && 1 / value == -INFINITY ? "-0" : result;
  }
  function castSlice(array2, start3, end2) {
    var length = array2.length;
    end2 = end2 === void 0 ? length : end2;
    return !start3 && end2 >= length ? array2 : baseSlice(array2, start3, end2);
  }
  function createCaseFirst(methodName) {
    return function(string2) {
      string2 = toString(string2);
      var strSymbols = hasUnicode(string2) ? stringToArray(string2) : void 0;
      var chr = strSymbols ? strSymbols[0] : string2.charAt(0);
      var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string2.slice(1);
      return chr[methodName]() + trailing;
    };
  }
  function createCompounder(callback) {
    return function(string2) {
      return arrayReduce(words(deburr(string2).replace(reApos, "")), callback, "");
    };
  }
  function isObjectLike(value) {
    return !!value && typeof value == "object";
  }
  function isSymbol(value) {
    return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
  }
  function toString(value) {
    return value == null ? "" : baseToString(value);
  }
  var camelCase = createCompounder(function(result, word, index3) {
    word = word.toLowerCase();
    return result + (index3 ? capitalize(word) : word);
  });
  function capitalize(string2) {
    return upperFirst(toString(string2).toLowerCase());
  }
  function deburr(string2) {
    string2 = toString(string2);
    return string2 && string2.replace(reLatin, deburrLetter).replace(reComboMark, "");
  }
  var upperFirst = createCaseFirst("toUpperCase");
  function words(string2, pattern, guard) {
    string2 = toString(string2);
    pattern = guard ? void 0 : pattern;
    if (pattern === void 0) {
      return hasUnicodeWord(string2) ? unicodeWords(string2) : asciiWords(string2);
    }
    return string2.match(pattern) || [];
  }
  var lodash_camelcase = camelCase;
  var lodash_isdate = createCommonjsModule(function(module2, exports2) {
    var dateTag3 = "[object Date]";
    var freeGlobal3 = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
    var freeExports = exports2 && !exports2.nodeType && exports2;
    var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var freeProcess = moduleExports && freeGlobal3.process;
    var nodeUtil = function() {
      try {
        return freeProcess && freeProcess.binding("util");
      } catch (e2) {
      }
    }();
    var nodeIsDate = nodeUtil && nodeUtil.isDate;
    function baseUnary2(func) {
      return function(value) {
        return func(value);
      };
    }
    var objectProto4 = Object.prototype;
    var objectToString3 = objectProto4.toString;
    function baseIsDate(value) {
      return isObjectLike3(value) && objectToString3.call(value) == dateTag3;
    }
    var isDate2 = nodeIsDate ? baseUnary2(nodeIsDate) : baseIsDate;
    function isObjectLike3(value) {
      return !!value && typeof value == "object";
    }
    module2.exports = isDate2;
  });
  var lodash_isregexp = createCommonjsModule(function(module2, exports2) {
    var regexpTag3 = "[object RegExp]";
    var freeGlobal3 = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
    var freeExports = exports2 && !exports2.nodeType && exports2;
    var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var freeProcess = moduleExports && freeGlobal3.process;
    var nodeUtil = function() {
      try {
        return freeProcess && freeProcess.binding("util");
      } catch (e2) {
      }
    }();
    var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp;
    function baseUnary2(func) {
      return function(value) {
        return func(value);
      };
    }
    var objectProto4 = Object.prototype;
    var objectToString3 = objectProto4.toString;
    function baseIsRegExp(value) {
      return isObject5(value) && objectToString3.call(value) == regexpTag3;
    }
    function isObject5(value) {
      var type = typeof value;
      return !!value && (type == "object" || type == "function");
    }
    var isRegExp = nodeIsRegExp ? baseUnary2(nodeIsRegExp) : baseIsRegExp;
    module2.exports = isRegExp;
  });
  var dist = createCommonjsModule(function(module2, exports2) {
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    Object.defineProperty(exports2, "__esModule", {value: true});
    const lodash_camelcase_1 = __importDefault(lodash_camelcase);
    const lodash_isdate_1 = __importDefault(lodash_isdate);
    const lodash_isregexp_1 = __importDefault(lodash_isregexp);
    function walk(obj) {
      if (!obj || typeof obj !== "object")
        return obj;
      if (lodash_isdate_1.default(obj) || lodash_isregexp_1.default(obj))
        return obj;
      if (Array.isArray(obj))
        return obj.map(walk);
      return Object.keys(obj).reduce((res, key) => {
        const camel = lodash_camelcase_1.default(key);
        res[camel] = walk(obj[key]);
        return res;
      }, {});
    }
    function camelize3(obj) {
      return typeof obj === "string" ? lodash_camelcase_1.default(obj) : walk(obj);
    }
    exports2.default = camelize3;
  });
  var strictUriEncode = (str) => encodeURIComponent(str).replace(/[!'()*]/g, (x2) => `%${x2.charCodeAt(0).toString(16).toUpperCase()}`);
  var token = "%[a-f0-9]{2}";
  var singleMatcher = new RegExp(token, "gi");
  var multiMatcher = new RegExp("(" + token + ")+", "gi");
  function decodeComponents(components3, split2) {
    try {
      return decodeURIComponent(components3.join(""));
    } catch (err) {
    }
    if (components3.length === 1) {
      return components3;
    }
    split2 = split2 || 1;
    var left2 = components3.slice(0, split2);
    var right2 = components3.slice(split2);
    return Array.prototype.concat.call([], decodeComponents(left2), decodeComponents(right2));
  }
  function decode(input) {
    try {
      return decodeURIComponent(input);
    } catch (err) {
      var tokens = input.match(singleMatcher);
      for (var i3 = 1; i3 < tokens.length; i3++) {
        input = decodeComponents(tokens, i3).join("");
        tokens = input.match(singleMatcher);
      }
      return input;
    }
  }
  function customDecodeURIComponent(input) {
    var replaceMap = {
      "%FE%FF": "��",
      "%FF%FE": "��"
    };
    var match2 = multiMatcher.exec(input);
    while (match2) {
      try {
        replaceMap[match2[0]] = decodeURIComponent(match2[0]);
      } catch (err) {
        var result = decode(match2[0]);
        if (result !== match2[0]) {
          replaceMap[match2[0]] = result;
        }
      }
      match2 = multiMatcher.exec(input);
    }
    replaceMap["%C2"] = "�";
    var entries = Object.keys(replaceMap);
    for (var i3 = 0; i3 < entries.length; i3++) {
      var key = entries[i3];
      input = input.replace(new RegExp(key, "g"), replaceMap[key]);
    }
    return input;
  }
  var decodeUriComponent = function(encodedURI) {
    if (typeof encodedURI !== "string") {
      throw new TypeError("Expected `encodedURI` to be of type `string`, got `" + typeof encodedURI + "`");
    }
    try {
      encodedURI = encodedURI.replace(/\+/g, " ");
      return decodeURIComponent(encodedURI);
    } catch (err) {
      return customDecodeURIComponent(encodedURI);
    }
  };
  var splitOnFirst = (string2, separator) => {
    if (!(typeof string2 === "string" && typeof separator === "string")) {
      throw new TypeError("Expected the arguments to be of type `string`");
    }
    if (separator === "") {
      return [string2];
    }
    const separatorIndex = string2.indexOf(separator);
    if (separatorIndex === -1) {
      return [string2];
    }
    return [
      string2.slice(0, separatorIndex),
      string2.slice(separatorIndex + separator.length)
    ];
  };
  var filterObj = function(obj, predicate) {
    var ret = {};
    var keys2 = Object.keys(obj);
    var isArr = Array.isArray(predicate);
    for (var i3 = 0; i3 < keys2.length; i3++) {
      var key = keys2[i3];
      var val = obj[key];
      if (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) {
        ret[key] = val;
      }
    }
    return ret;
  };
  var queryString = createCommonjsModule(function(module2, exports2) {
    const isNullOrUndefined2 = (value) => value === null || value === void 0;
    const encodeFragmentIdentifier = Symbol("encodeFragmentIdentifier");
    function encoderForArrayFormat(options) {
      switch (options.arrayFormat) {
        case "index":
          return (key) => (result, value) => {
            const index3 = result.length;
            if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") {
              return result;
            }
            if (value === null) {
              return [...result, [encode2(key, options), "[", index3, "]"].join("")];
            }
            return [
              ...result,
              [encode2(key, options), "[", encode2(index3, options), "]=", encode2(value, options)].join("")
            ];
          };
        case "bracket":
          return (key) => (result, value) => {
            if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") {
              return result;
            }
            if (value === null) {
              return [...result, [encode2(key, options), "[]"].join("")];
            }
            return [...result, [encode2(key, options), "[]=", encode2(value, options)].join("")];
          };
        case "comma":
        case "separator":
        case "bracket-separator": {
          const keyValueSep = options.arrayFormat === "bracket-separator" ? "[]=" : "=";
          return (key) => (result, value) => {
            if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") {
              return result;
            }
            value = value === null ? "" : value;
            if (result.length === 0) {
              return [[encode2(key, options), keyValueSep, encode2(value, options)].join("")];
            }
            return [[result, encode2(value, options)].join(options.arrayFormatSeparator)];
          };
        }
        default:
          return (key) => (result, value) => {
            if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") {
              return result;
            }
            if (value === null) {
              return [...result, encode2(key, options)];
            }
            return [...result, [encode2(key, options), "=", encode2(value, options)].join("")];
          };
      }
    }
    function parserForArrayFormat(options) {
      let result;
      switch (options.arrayFormat) {
        case "index":
          return (key, value, accumulator) => {
            result = /\[(\d*)\]$/.exec(key);
            key = key.replace(/\[\d*\]$/, "");
            if (!result) {
              accumulator[key] = value;
              return;
            }
            if (accumulator[key] === void 0) {
              accumulator[key] = {};
            }
            accumulator[key][result[1]] = value;
          };
        case "bracket":
          return (key, value, accumulator) => {
            result = /(\[\])$/.exec(key);
            key = key.replace(/\[\]$/, "");
            if (!result) {
              accumulator[key] = value;
              return;
            }
            if (accumulator[key] === void 0) {
              accumulator[key] = [value];
              return;
            }
            accumulator[key] = [].concat(accumulator[key], value);
          };
        case "comma":
        case "separator":
          return (key, value, accumulator) => {
            const isArray3 = typeof value === "string" && value.includes(options.arrayFormatSeparator);
            const isEncodedArray = typeof value === "string" && !isArray3 && decode2(value, options).includes(options.arrayFormatSeparator);
            value = isEncodedArray ? decode2(value, options) : value;
            const newValue = isArray3 || isEncodedArray ? value.split(options.arrayFormatSeparator).map((item) => decode2(item, options)) : value === null ? value : decode2(value, options);
            accumulator[key] = newValue;
          };
        case "bracket-separator":
          return (key, value, accumulator) => {
            const isArray3 = /(\[\])$/.test(key);
            key = key.replace(/\[\]$/, "");
            if (!isArray3) {
              accumulator[key] = value ? decode2(value, options) : value;
              return;
            }
            const arrayValue = value === null ? [] : value.split(options.arrayFormatSeparator).map((item) => decode2(item, options));
            if (accumulator[key] === void 0) {
              accumulator[key] = arrayValue;
              return;
            }
            accumulator[key] = [].concat(accumulator[key], arrayValue);
          };
        default:
          return (key, value, accumulator) => {
            if (accumulator[key] === void 0) {
              accumulator[key] = value;
              return;
            }
            accumulator[key] = [].concat(accumulator[key], value);
          };
      }
    }
    function validateArrayFormatSeparator(value) {
      if (typeof value !== "string" || value.length !== 1) {
        throw new TypeError("arrayFormatSeparator must be single character string");
      }
    }
    function encode2(value, options) {
      if (options.encode) {
        return options.strict ? strictUriEncode(value) : encodeURIComponent(value);
      }
      return value;
    }
    function decode2(value, options) {
      if (options.decode) {
        return decodeUriComponent(value);
      }
      return value;
    }
    function keysSorter(input) {
      if (Array.isArray(input)) {
        return input.sort();
      }
      if (typeof input === "object") {
        return keysSorter(Object.keys(input)).sort((a2, b2) => Number(a2) - Number(b2)).map((key) => input[key]);
      }
      return input;
    }
    function removeHash(input) {
      const hashStart = input.indexOf("#");
      if (hashStart !== -1) {
        input = input.slice(0, hashStart);
      }
      return input;
    }
    function getHash(url) {
      let hash2 = "";
      const hashStart = url.indexOf("#");
      if (hashStart !== -1) {
        hash2 = url.slice(hashStart);
      }
      return hash2;
    }
    function extract(input) {
      input = removeHash(input);
      const queryStart = input.indexOf("?");
      if (queryStart === -1) {
        return "";
      }
      return input.slice(queryStart + 1);
    }
    function parseValue(value, options) {
      if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === "string" && value.trim() !== "")) {
        value = Number(value);
      } else if (options.parseBooleans && value !== null && (value.toLowerCase() === "true" || value.toLowerCase() === "false")) {
        value = value.toLowerCase() === "true";
      }
      return value;
    }
    function parse3(query, options) {
      options = Object.assign({
        decode: true,
        sort: true,
        arrayFormat: "none",
        arrayFormatSeparator: ",",
        parseNumbers: false,
        parseBooleans: false
      }, options);
      validateArrayFormatSeparator(options.arrayFormatSeparator);
      const formatter = parserForArrayFormat(options);
      const ret = Object.create(null);
      if (typeof query !== "string") {
        return ret;
      }
      query = query.trim().replace(/^[?#&]/, "");
      if (!query) {
        return ret;
      }
      for (const param of query.split("&")) {
        if (param === "") {
          continue;
        }
        let [key, value] = splitOnFirst(options.decode ? param.replace(/\+/g, " ") : param, "=");
        value = value === void 0 ? null : ["comma", "separator", "bracket-separator"].includes(options.arrayFormat) ? value : decode2(value, options);
        formatter(decode2(key, options), value, ret);
      }
      for (const key of Object.keys(ret)) {
        const value = ret[key];
        if (typeof value === "object" && value !== null) {
          for (const k2 of Object.keys(value)) {
            value[k2] = parseValue(value[k2], options);
          }
        } else {
          ret[key] = parseValue(value, options);
        }
      }
      if (options.sort === false) {
        return ret;
      }
      return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => {
        const value = ret[key];
        if (Boolean(value) && typeof value === "object" && !Array.isArray(value)) {
          result[key] = keysSorter(value);
        } else {
          result[key] = value;
        }
        return result;
      }, Object.create(null));
    }
    exports2.extract = extract;
    exports2.parse = parse3;
    exports2.stringify = (object, options) => {
      if (!object) {
        return "";
      }
      options = Object.assign({
        encode: true,
        strict: true,
        arrayFormat: "none",
        arrayFormatSeparator: ","
      }, options);
      validateArrayFormatSeparator(options.arrayFormatSeparator);
      const shouldFilter = (key) => options.skipNull && isNullOrUndefined2(object[key]) || options.skipEmptyString && object[key] === "";
      const formatter = encoderForArrayFormat(options);
      const objectCopy = {};
      for (const key of Object.keys(object)) {
        if (!shouldFilter(key)) {
          objectCopy[key] = object[key];
        }
      }
      const keys2 = Object.keys(objectCopy);
      if (options.sort !== false) {
        keys2.sort(options.sort);
      }
      return keys2.map((key) => {
        const value = object[key];
        if (value === void 0) {
          return "";
        }
        if (value === null) {
          return encode2(key, options);
        }
        if (Array.isArray(value)) {
          if (value.length === 0 && options.arrayFormat === "bracket-separator") {
            return encode2(key, options) + "[]";
          }
          return value.reduce(formatter(key), []).join("&");
        }
        return encode2(key, options) + "=" + encode2(value, options);
      }).filter((x2) => x2.length > 0).join("&");
    };
    exports2.parseUrl = (url, options) => {
      options = Object.assign({
        decode: true
      }, options);
      const [url_, hash2] = splitOnFirst(url, "#");
      return Object.assign({
        url: url_.split("?")[0] || "",
        query: parse3(extract(url), options)
      }, options && options.parseFragmentIdentifier && hash2 ? {fragmentIdentifier: decode2(hash2, options)} : {});
    };
    exports2.stringifyUrl = (object, options) => {
      options = Object.assign({
        encode: true,
        strict: true,
        [encodeFragmentIdentifier]: true
      }, options);
      const url = removeHash(object.url).split("?")[0] || "";
      const queryFromUrl = exports2.extract(object.url);
      const parsedQueryFromUrl = exports2.parse(queryFromUrl, {sort: false});
      const query = Object.assign(parsedQueryFromUrl, object.query);
      let queryString2 = exports2.stringify(query, options);
      if (queryString2) {
        queryString2 = `?${queryString2}`;
      }
      let hash2 = getHash(object.url);
      if (object.fragmentIdentifier) {
        hash2 = `#${options[encodeFragmentIdentifier] ? encode2(object.fragmentIdentifier, options) : object.fragmentIdentifier}`;
      }
      return `${url}${queryString2}${hash2}`;
    };
    exports2.pick = (input, filter3, options) => {
      options = Object.assign({
        parseFragmentIdentifier: true,
        [encodeFragmentIdentifier]: false
      }, options);
      const {url, query, fragmentIdentifier} = exports2.parseUrl(input, options);
      return exports2.stringifyUrl({
        url,
        query: filterObj(query, filter3),
        fragmentIdentifier
      }, options);
    };
    exports2.exclude = (input, filter3, options) => {
      const exclusionFilter = Array.isArray(filter3) ? (key) => !filter3.includes(key) : (key, value) => !filter3(key, value);
      return exports2.pick(input, exclusionFilter, options);
    };
  });
  var constants = createCommonjsModule(function(module2, exports2) {
    exports2.__esModule = true;
    exports2.defaultRealm = exports2.defaultBaseUrl = void 0;
    exports2.defaultBaseUrl = "http://127.0.0.1:8080/auth";
    exports2.defaultRealm = "master";
  });
  var auth = createCommonjsModule(function(module2, exports2) {
    var __assign2 = commonjsGlobal && commonjsGlobal.__assign || function() {
      __assign2 = Object.assign || function(t5) {
        for (var s2, i3 = 1, n3 = arguments.length; i3 < n3; i3++) {
          s2 = arguments[i3];
          for (var p2 in s2)
            if (Object.prototype.hasOwnProperty.call(s2, p2))
              t5[p2] = s2[p2];
        }
        return t5;
      };
      return __assign2.apply(this, arguments);
    };
    var __awaiter3 = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P2, generator) {
      function adopt(value) {
        return value instanceof P2 ? value : new P2(function(resolve2) {
          resolve2(value);
        });
      }
      return new (P2 || (P2 = Promise))(function(resolve2, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e2) {
            reject(e2);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e2) {
            reject(e2);
          }
        }
        function step(result) {
          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __generator2 = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
      var _23 = {label: 0, sent: function() {
        if (t5[0] & 1)
          throw t5[1];
        return t5[1];
      }, trys: [], ops: []}, f2, y3, t5, g2;
      return g2 = {next: verb(0), throw: verb(1), return: verb(2)}, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
        return this;
      }), g2;
      function verb(n3) {
        return function(v2) {
          return step([n3, v2]);
        };
      }
      function step(op) {
        if (f2)
          throw new TypeError("Generator is already executing.");
        while (_23)
          try {
            if (f2 = 1, y3 && (t5 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t5 = y3["return"]) && t5.call(y3), 0) : y3.next) && !(t5 = t5.call(y3, op[1])).done)
              return t5;
            if (y3 = 0, t5)
              op = [op[0] & 2, t5.value];
            switch (op[0]) {
              case 0:
              case 1:
                t5 = op;
                break;
              case 4:
                _23.label++;
                return {value: op[1], done: false};
              case 5:
                _23.label++;
                y3 = op[1];
                op = [0];
                continue;
              case 7:
                op = _23.ops.pop();
                _23.trys.pop();
                continue;
              default:
                if (!(t5 = _23.trys, t5 = t5.length > 0 && t5[t5.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                  _23 = 0;
                  continue;
                }
                if (op[0] === 3 && (!t5 || op[1] > t5[0] && op[1] < t5[3])) {
                  _23.label = op[1];
                  break;
                }
                if (op[0] === 6 && _23.label < t5[1]) {
                  _23.label = t5[1];
                  t5 = op;
                  break;
                }
                if (t5 && _23.label < t5[2]) {
                  _23.label = t5[2];
                  _23.ops.push(op);
                  break;
                }
                if (t5[2])
                  _23.ops.pop();
                _23.trys.pop();
                continue;
            }
            op = body.call(thisArg, _23);
          } catch (e2) {
            op = [6, e2];
            y3 = 0;
          } finally {
            f2 = t5 = 0;
          }
        if (op[0] & 5)
          throw op[1];
        return {value: op[0] ? op[1] : void 0, done: true};
      }
    };
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.getToken = void 0;
    var axios_12 = __importDefault(axios$1);
    var camelize_ts_1 = __importDefault(dist);
    var query_string_1 = __importDefault(queryString);
    var getToken = function(settings) {
      return __awaiter3(void 0, void 0, void 0, function() {
        var baseUrl, realmName, url, credentials, payload, config2, data2;
        return __generator2(this, function(_a) {
          switch (_a.label) {
            case 0:
              baseUrl = settings.baseUrl || constants.defaultBaseUrl;
              realmName = settings.realmName || constants.defaultRealm;
              url = "".concat(baseUrl, "/realms/").concat(realmName, "/protocol/openid-connect/token");
              credentials = settings.credentials || {};
              payload = query_string_1["default"].stringify(__assign2(__assign2({username: credentials.username, password: credentials.password, grant_type: credentials.grantType, client_id: credentials.clientId, totp: credentials.totp}, credentials.offlineToken ? {scope: "offline_access"} : {}), credentials.refreshToken ? {
                refresh_token: credentials.refreshToken,
                client_secret: credentials.clientSecret
              } : {}));
              config2 = __assign2({}, settings.requestConfig);
              if (credentials.clientSecret) {
                config2.auth = {
                  username: credentials.clientId,
                  password: credentials.clientSecret
                };
              }
              return [4, axios_12["default"].post(url, payload, config2)];
            case 1:
              data2 = _a.sent().data;
              return [2, (0, camelize_ts_1["default"])(data2)];
          }
        });
      });
    };
    exports2.getToken = getToken;
  });
  var urlJoin = createCommonjsModule(function(module2) {
    (function(name, context2, definition) {
      if (module2.exports)
        module2.exports = definition();
      else
        context2[name] = definition();
    })("urljoin", commonjsGlobal, function() {
      function normalize3(strArray) {
        var resultArray = [];
        if (strArray.length === 0) {
          return "";
        }
        if (typeof strArray[0] !== "string") {
          throw new TypeError("Url must be a string. Received " + strArray[0]);
        }
        if (strArray[0].match(/^[^/:]+:\/*$/) && strArray.length > 1) {
          var first2 = strArray.shift();
          strArray[0] = first2 + strArray[0];
        }
        if (strArray[0].match(/^file:\/\/\//)) {
          strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, "$1:///");
        } else {
          strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, "$1://");
        }
        for (var i3 = 0; i3 < strArray.length; i3++) {
          var component = strArray[i3];
          if (typeof component !== "string") {
            throw new TypeError("Url must be a string. Received " + component);
          }
          if (component === "") {
            continue;
          }
          if (i3 > 0) {
            component = component.replace(/^[\/]+/, "");
          }
          if (i3 < strArray.length - 1) {
            component = component.replace(/[\/]+$/, "");
          } else {
            component = component.replace(/[\/]+$/, "/");
          }
          resultArray.push(component);
        }
        var str = resultArray.join("/");
        str = str.replace(/\/(\?|&|#[^!])/g, "$1");
        var parts = str.split("?");
        str = parts.shift() + (parts.length > 0 ? "?" : "") + parts.join("&");
        return str;
      }
      return function() {
        var input;
        if (typeof arguments[0] === "object") {
          input = arguments[0];
        } else {
          input = [].slice.call(arguments);
        }
        return normalize3(input);
      };
    });
  });
  var urlTemplate = createCommonjsModule(function(module2, exports2) {
    (function(root4, factory) {
      {
        module2.exports = factory();
      }
    })(commonjsGlobal, function() {
      function UrlTemplate() {
      }
      UrlTemplate.prototype.encodeReserved = function(str) {
        return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
          if (!/%[0-9A-Fa-f]/.test(part)) {
            part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
          }
          return part;
        }).join("");
      };
      UrlTemplate.prototype.encodeUnreserved = function(str) {
        return encodeURIComponent(str).replace(/[!'()*]/g, function(c3) {
          return "%" + c3.charCodeAt(0).toString(16).toUpperCase();
        });
      };
      UrlTemplate.prototype.encodeValue = function(operator, value, key) {
        value = operator === "+" || operator === "#" ? this.encodeReserved(value) : this.encodeUnreserved(value);
        if (key) {
          return this.encodeUnreserved(key) + "=" + value;
        } else {
          return value;
        }
      };
      UrlTemplate.prototype.isDefined = function(value) {
        return value !== void 0 && value !== null;
      };
      UrlTemplate.prototype.isKeyOperator = function(operator) {
        return operator === ";" || operator === "&" || operator === "?";
      };
      UrlTemplate.prototype.getValues = function(context2, operator, key, modifier) {
        var value = context2[key], result = [];
        if (this.isDefined(value) && value !== "") {
          if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
            value = value.toString();
            if (modifier && modifier !== "*") {
              value = value.substring(0, parseInt(modifier, 10));
            }
            result.push(this.encodeValue(operator, value, this.isKeyOperator(operator) ? key : null));
          } else {
            if (modifier === "*") {
              if (Array.isArray(value)) {
                value.filter(this.isDefined).forEach(function(value2) {
                  result.push(this.encodeValue(operator, value2, this.isKeyOperator(operator) ? key : null));
                }, this);
              } else {
                Object.keys(value).forEach(function(k2) {
                  if (this.isDefined(value[k2])) {
                    result.push(this.encodeValue(operator, value[k2], k2));
                  }
                }, this);
              }
            } else {
              var tmp = [];
              if (Array.isArray(value)) {
                value.filter(this.isDefined).forEach(function(value2) {
                  tmp.push(this.encodeValue(operator, value2));
                }, this);
              } else {
                Object.keys(value).forEach(function(k2) {
                  if (this.isDefined(value[k2])) {
                    tmp.push(this.encodeUnreserved(k2));
                    tmp.push(this.encodeValue(operator, value[k2].toString()));
                  }
                }, this);
              }
              if (this.isKeyOperator(operator)) {
                result.push(this.encodeUnreserved(key) + "=" + tmp.join(","));
              } else if (tmp.length !== 0) {
                result.push(tmp.join(","));
              }
            }
          }
        } else {
          if (operator === ";") {
            if (this.isDefined(value)) {
              result.push(this.encodeUnreserved(key));
            }
          } else if (value === "" && (operator === "&" || operator === "?")) {
            result.push(this.encodeUnreserved(key) + "=");
          } else if (value === "") {
            result.push("");
          }
        }
        return result;
      };
      UrlTemplate.prototype.parse = function(template) {
        var that = this;
        var operators = ["+", "#", ".", "/", ";", "?", "&"];
        return {
          expand: function(context2) {
            return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function(_23, expression, literal) {
              if (expression) {
                var operator = null, values2 = [];
                if (operators.indexOf(expression.charAt(0)) !== -1) {
                  operator = expression.charAt(0);
                  expression = expression.substr(1);
                }
                expression.split(/,/g).forEach(function(variable) {
                  var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
                  values2.push.apply(values2, that.getValues(context2, operator, tmp[1], tmp[2] || tmp[3]));
                });
                if (operator && operator !== "+") {
                  var separator = ",";
                  if (operator === "?") {
                    separator = "&";
                  } else if (operator !== "#") {
                    separator = operator;
                  }
                  return (values2.length !== 0 ? operator : "") + values2.join(separator);
                } else {
                  return values2.join(",");
                }
              } else {
                return that.encodeReserved(literal);
              }
            });
          }
        };
      };
      return new UrlTemplate();
    });
  });
  var agent = createCommonjsModule(function(module2, exports2) {
    var __assign2 = commonjsGlobal && commonjsGlobal.__assign || function() {
      __assign2 = Object.assign || function(t5) {
        for (var s2, i3 = 1, n3 = arguments.length; i3 < n3; i3++) {
          s2 = arguments[i3];
          for (var p2 in s2)
            if (Object.prototype.hasOwnProperty.call(s2, p2))
              t5[p2] = s2[p2];
        }
        return t5;
      };
      return __assign2.apply(this, arguments);
    };
    var __awaiter3 = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P2, generator) {
      function adopt(value) {
        return value instanceof P2 ? value : new P2(function(resolve2) {
          resolve2(value);
        });
      }
      return new (P2 || (P2 = Promise))(function(resolve2, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e2) {
            reject(e2);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e2) {
            reject(e2);
          }
        }
        function step(result) {
          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __generator2 = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
      var _23 = {label: 0, sent: function() {
        if (t5[0] & 1)
          throw t5[1];
        return t5[1];
      }, trys: [], ops: []}, f2, y3, t5, g2;
      return g2 = {next: verb(0), throw: verb(1), return: verb(2)}, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
        return this;
      }), g2;
      function verb(n3) {
        return function(v2) {
          return step([n3, v2]);
        };
      }
      function step(op) {
        if (f2)
          throw new TypeError("Generator is already executing.");
        while (_23)
          try {
            if (f2 = 1, y3 && (t5 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t5 = y3["return"]) && t5.call(y3), 0) : y3.next) && !(t5 = t5.call(y3, op[1])).done)
              return t5;
            if (y3 = 0, t5)
              op = [op[0] & 2, t5.value];
            switch (op[0]) {
              case 0:
              case 1:
                t5 = op;
                break;
              case 4:
                _23.label++;
                return {value: op[1], done: false};
              case 5:
                _23.label++;
                y3 = op[1];
                op = [0];
                continue;
              case 7:
                op = _23.ops.pop();
                _23.trys.pop();
                continue;
              default:
                if (!(t5 = _23.trys, t5 = t5.length > 0 && t5[t5.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                  _23 = 0;
                  continue;
                }
                if (op[0] === 3 && (!t5 || op[1] > t5[0] && op[1] < t5[3])) {
                  _23.label = op[1];
                  break;
                }
                if (op[0] === 6 && _23.label < t5[1]) {
                  _23.label = t5[1];
                  t5 = op;
                  break;
                }
                if (t5 && _23.label < t5[2]) {
                  _23.label = t5[2];
                  _23.ops.push(op);
                  break;
                }
                if (t5[2])
                  _23.ops.pop();
                _23.trys.pop();
                continue;
            }
            op = body.call(thisArg, _23);
          } catch (e2) {
            op = [6, e2];
            y3 = 0;
          } finally {
            f2 = t5 = 0;
          }
        if (op[0] & 5)
          throw op[1];
        return {value: op[0] ? op[1] : void 0, done: true};
      }
    };
    var __spreadArray = commonjsGlobal && commonjsGlobal.__spreadArray || function(to, from, pack) {
      if (pack || arguments.length === 2)
        for (var i3 = 0, l2 = from.length, ar; i3 < l2; i3++) {
          if (ar || !(i3 in from)) {
            if (!ar)
              ar = Array.prototype.slice.call(from, 0, i3);
            ar[i3] = from[i3];
          }
        }
      return to.concat(ar || Array.prototype.slice.call(from));
    };
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.Agent = void 0;
    var url_join_1 = __importDefault(urlJoin);
    var url_template_1 = __importDefault(urlTemplate);
    var axios_12 = __importDefault(axios$1);
    var query_string_1 = __importDefault(queryString);
    var SLASH = "/";
    var Agent = function() {
      function Agent2(_a) {
        var client2 = _a.client, _b = _a.path, path = _b === void 0 ? "/" : _b, _c = _a.getUrlParams, getUrlParams = _c === void 0 ? function() {
          return {};
        } : _c, _d = _a.getBaseUrl, getBaseUrl2 = _d === void 0 ? function() {
          return client2.baseUrl;
        } : _d;
        this.client = client2;
        this.getBaseParams = getUrlParams;
        this.getBaseUrl = getBaseUrl2;
        this.basePath = path;
      }
      Agent2.prototype.request = function(_a) {
        var _this = this;
        var method = _a.method, _b = _a.path, path = _b === void 0 ? "" : _b, _c = _a.urlParamKeys, urlParamKeys = _c === void 0 ? [] : _c, _d = _a.queryParamKeys, queryParamKeys = _d === void 0 ? [] : _d, _e = _a.catchNotFound, catchNotFound = _e === void 0 ? false : _e, keyTransform = _a.keyTransform, payloadKey = _a.payloadKey, returnResourceIdInLocationHeader = _a.returnResourceIdInLocationHeader, ignoredKeys = _a.ignoredKeys, headers = _a.headers;
        return function(payload) {
          if (payload === void 0) {
            payload = {};
          }
          return __awaiter3(_this, void 0, void 0, function() {
            var baseParams, queryParams, allUrlParamKeys, urlParams, omittedKeys;
            var _a2, _b2;
            return __generator2(this, function(_c2) {
              baseParams = (_b2 = (_a2 = this.getBaseParams) === null || _a2 === void 0 ? void 0 : _a2.call(this)) !== null && _b2 !== void 0 ? _b2 : {};
              queryParams = queryParamKeys ? (0, lodash.pick)(payload, queryParamKeys) : null;
              allUrlParamKeys = __spreadArray(__spreadArray([], Object.keys(baseParams), true), urlParamKeys, true);
              urlParams = __assign2(__assign2({}, baseParams), (0, lodash.pick)(payload, allUrlParamKeys));
              omittedKeys = ignoredKeys ? __spreadArray(__spreadArray([], allUrlParamKeys, true), queryParamKeys, true).filter(function(key) {
                return !ignoredKeys.includes(key);
              }) : __spreadArray(__spreadArray([], allUrlParamKeys, true), queryParamKeys, true);
              payload = (0, lodash.omit)(payload, omittedKeys);
              if (keyTransform) {
                this.transformKey(payload, keyTransform);
                this.transformKey(queryParams, keyTransform);
              }
              return [2, this.requestWithParams({
                method,
                path,
                payload,
                urlParams,
                queryParams,
                catchNotFound,
                payloadKey,
                returnResourceIdInLocationHeader,
                headers
              })];
            });
          });
        };
      };
      Agent2.prototype.updateRequest = function(_a) {
        var _this = this;
        var method = _a.method, _b = _a.path, path = _b === void 0 ? "" : _b, _c = _a.urlParamKeys, urlParamKeys = _c === void 0 ? [] : _c, _d = _a.queryParamKeys, queryParamKeys = _d === void 0 ? [] : _d, _e = _a.catchNotFound, catchNotFound = _e === void 0 ? false : _e, keyTransform = _a.keyTransform, payloadKey = _a.payloadKey, returnResourceIdInLocationHeader = _a.returnResourceIdInLocationHeader, headers = _a.headers;
        return function(query, payload) {
          if (query === void 0) {
            query = {};
          }
          if (payload === void 0) {
            payload = {};
          }
          return __awaiter3(_this, void 0, void 0, function() {
            var baseParams, queryParams, allUrlParamKeys, urlParams;
            var _a2, _b2;
            return __generator2(this, function(_c2) {
              baseParams = (_b2 = (_a2 = this.getBaseParams) === null || _a2 === void 0 ? void 0 : _a2.call(this)) !== null && _b2 !== void 0 ? _b2 : {};
              queryParams = queryParamKeys ? (0, lodash.pick)(query, queryParamKeys) : null;
              allUrlParamKeys = __spreadArray(__spreadArray([], Object.keys(baseParams), true), urlParamKeys, true);
              urlParams = __assign2(__assign2({}, baseParams), (0, lodash.pick)(query, allUrlParamKeys));
              if (keyTransform) {
                this.transformKey(queryParams, keyTransform);
              }
              return [2, this.requestWithParams({
                method,
                path,
                payload,
                urlParams,
                queryParams,
                catchNotFound,
                payloadKey,
                returnResourceIdInLocationHeader,
                headers
              })];
            });
          });
        };
      };
      Agent2.prototype.requestWithParams = function(_a) {
        var _b, _c, _d;
        var method = _a.method, path = _a.path, payload = _a.payload, urlParams = _a.urlParams, queryParams = _a.queryParams, catchNotFound = _a.catchNotFound, payloadKey = _a.payloadKey, returnResourceIdInLocationHeader = _a.returnResourceIdInLocationHeader, headers = _a.headers;
        return __awaiter3(this, void 0, void 0, function() {
          var newPath, pathTemplate, parsedPath, url, requestConfig, _e, _f, _g, res, locationHeader, resourceId, field, err_1;
          var _h, _j;
          return __generator2(this, function(_k) {
            switch (_k.label) {
              case 0:
                newPath = (0, url_join_1["default"])(this.basePath, path);
                pathTemplate = url_template_1["default"].parse(newPath);
                parsedPath = pathTemplate.expand(urlParams);
                url = "".concat((_c = (_b = this.getBaseUrl) === null || _b === void 0 ? void 0 : _b.call(this)) !== null && _c !== void 0 ? _c : "").concat(parsedPath);
                requestConfig = __assign2(__assign2({paramsSerializer: function(params) {
                  return query_string_1["default"].stringify(params);
                }}, this.client.getRequestConfig() || {}), {method, url});
                _e = requestConfig;
                _f = [__assign2({}, requestConfig.headers)];
                _h = {};
                _g = "bearer ".concat;
                return [4, this.client.getAccessToken()];
              case 1:
                _e.headers = __assign2.apply(void 0, [__assign2.apply(void 0, _f.concat([(_h.Authorization = _g.apply("bearer ", [_k.sent()]), _h)])), headers]);
                if (method === "GET") {
                  requestConfig.params = payload;
                } else {
                  requestConfig.data = payloadKey ? payload[payloadKey] : payload;
                }
                if (queryParams) {
                  requestConfig.params = requestConfig.params ? __assign2(__assign2({}, requestConfig.params), queryParams) : queryParams;
                }
                _k.label = 2;
              case 2:
                _k.trys.push([2, 4, , 5]);
                return [4, (0, axios_12["default"])(requestConfig)];
              case 3:
                res = _k.sent();
                if (returnResourceIdInLocationHeader) {
                  locationHeader = res.headers.location;
                  if (typeof locationHeader !== "string") {
                    throw new Error("location header is not found in request: ".concat(res.config.url));
                  }
                  resourceId = (0, lodash.last)(locationHeader.split(SLASH));
                  if (!resourceId) {
                    throw new Error("resourceId is not found in Location header from request: ".concat(res.config.url));
                  }
                  field = returnResourceIdInLocationHeader.field;
                  return [2, (_j = {}, _j[field] = resourceId, _j)];
                }
                return [2, res.data];
              case 4:
                err_1 = _k.sent();
                if (axios_12["default"].isAxiosError(err_1) && ((_d = err_1.response) === null || _d === void 0 ? void 0 : _d.status) === 404 && catchNotFound) {
                  return [2, null];
                }
                throw err_1;
              case 5:
                return [2];
            }
          });
        });
      };
      Agent2.prototype.transformKey = function(payload, keyMapping) {
        if (!payload) {
          return;
        }
        Object.keys(keyMapping).some(function(key) {
          if ((0, lodash.isUndefined)(payload[key])) {
            return false;
          }
          var newKey = keyMapping[key];
          payload[newKey] = payload[key];
          delete payload[key];
        });
      };
      return Agent2;
    }();
    exports2.Agent = Agent;
  });
  var resource = createCommonjsModule(function(module2, exports2) {
    var __assign2 = commonjsGlobal && commonjsGlobal.__assign || function() {
      __assign2 = Object.assign || function(t5) {
        for (var s2, i3 = 1, n3 = arguments.length; i3 < n3; i3++) {
          s2 = arguments[i3];
          for (var p2 in s2)
            if (Object.prototype.hasOwnProperty.call(s2, p2))
              t5[p2] = s2[p2];
        }
        return t5;
      };
      return __assign2.apply(this, arguments);
    };
    exports2.__esModule = true;
    var Resource = function() {
      function Resource2(client2, settings) {
        var _this = this;
        if (settings === void 0) {
          settings = {};
        }
        this.makeRequest = function(args) {
          return _this.agent.request(args);
        };
        this.makeUpdateRequest = function(args) {
          return _this.agent.updateRequest(args);
        };
        this.agent = new agent.Agent(__assign2({client: client2}, settings));
      }
      return Resource2;
    }();
    exports2["default"] = Resource;
  });
  var cache = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.Cache = void 0;
    var resource_1 = __importDefault(resource);
    var Cache = function(_super) {
      __extends2(Cache2, _super);
      function Cache2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.clearUserCache = _this.makeRequest({
          method: "POST",
          path: "/clear-user-cache"
        });
        return _this;
      }
      return Cache2;
    }(resource_1["default"]);
    exports2.Cache = Cache;
  });
  var users = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.Users = void 0;
    var resource_1 = __importDefault(resource);
    var Users = function(_super) {
      __extends2(Users2, _super);
      function Users2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}/users",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.find = _this.makeRequest({
          method: "GET"
        });
        _this.create = _this.makeRequest({
          method: "POST",
          returnResourceIdInLocationHeader: {field: "id"}
        });
        _this.findOne = _this.makeRequest({
          method: "GET",
          path: "/{id}",
          urlParamKeys: ["id"],
          catchNotFound: true
        });
        _this.update = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{id}",
          urlParamKeys: ["id"]
        });
        _this.del = _this.makeRequest({
          method: "DELETE",
          path: "/{id}",
          urlParamKeys: ["id"]
        });
        _this.count = _this.makeRequest({
          method: "GET",
          path: "/count"
        });
        _this.listRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings",
          urlParamKeys: ["id"]
        });
        _this.addRealmRoleMappings = _this.makeRequest({
          method: "POST",
          path: "/{id}/role-mappings/realm",
          urlParamKeys: ["id"],
          payloadKey: "roles"
        });
        _this.listRealmRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/realm",
          urlParamKeys: ["id"]
        });
        _this.delRealmRoleMappings = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/role-mappings/realm",
          urlParamKeys: ["id"],
          payloadKey: "roles"
        });
        _this.listAvailableRealmRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/realm/available",
          urlParamKeys: ["id"]
        });
        _this.listCompositeRealmRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/realm/composite",
          urlParamKeys: ["id"]
        });
        _this.listClientRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/clients/{clientUniqueId}",
          urlParamKeys: ["id", "clientUniqueId"]
        });
        _this.addClientRoleMappings = _this.makeRequest({
          method: "POST",
          path: "/{id}/role-mappings/clients/{clientUniqueId}",
          urlParamKeys: ["id", "clientUniqueId"],
          payloadKey: "roles"
        });
        _this.delClientRoleMappings = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/role-mappings/clients/{clientUniqueId}",
          urlParamKeys: ["id", "clientUniqueId"],
          payloadKey: "roles"
        });
        _this.listAvailableClientRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/clients/{clientUniqueId}/available",
          urlParamKeys: ["id", "clientUniqueId"]
        });
        _this.listCompositeClientRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/clients/{clientUniqueId}/composite",
          urlParamKeys: ["id", "clientUniqueId"]
        });
        _this.executeActionsEmail = _this.makeRequest({
          method: "PUT",
          path: "/{id}/execute-actions-email",
          urlParamKeys: ["id"],
          payloadKey: "actions",
          queryParamKeys: ["lifespan", "redirectUri", "clientId"],
          keyTransform: {
            clientId: "client_id",
            redirectUri: "redirect_uri"
          }
        });
        _this.listGroups = _this.makeRequest({
          method: "GET",
          path: "/{id}/groups",
          urlParamKeys: ["id"]
        });
        _this.addToGroup = _this.makeRequest({
          method: "PUT",
          path: "/{id}/groups/{groupId}",
          urlParamKeys: ["id", "groupId"]
        });
        _this.delFromGroup = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/groups/{groupId}",
          urlParamKeys: ["id", "groupId"]
        });
        _this.countGroups = _this.makeRequest({
          method: "GET",
          path: "/{id}/groups/count",
          urlParamKeys: ["id"]
        });
        _this.listFederatedIdentities = _this.makeRequest({
          method: "GET",
          path: "/{id}/federated-identity",
          urlParamKeys: ["id"]
        });
        _this.addToFederatedIdentity = _this.makeRequest({
          method: "POST",
          path: "/{id}/federated-identity/{federatedIdentityId}",
          urlParamKeys: ["id", "federatedIdentityId"],
          payloadKey: "federatedIdentity"
        });
        _this.delFromFederatedIdentity = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/federated-identity/{federatedIdentityId}",
          urlParamKeys: ["id", "federatedIdentityId"]
        });
        _this.removeTotp = _this.makeRequest({
          method: "PUT",
          path: "/{id}/remove-totp",
          urlParamKeys: ["id"]
        });
        _this.resetPassword = _this.makeRequest({
          method: "PUT",
          path: "/{id}/reset-password",
          urlParamKeys: ["id"],
          payloadKey: "credential"
        });
        _this.getCredentials = _this.makeRequest({
          method: "GET",
          path: "/{id}/credentials",
          urlParamKeys: ["id"]
        });
        _this.deleteCredential = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/credentials/{credentialId}",
          urlParamKeys: ["id", "credentialId"]
        });
        _this.updateCredentialLabel = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{id}/credentials/{credentialId}/userLabel",
          urlParamKeys: ["id", "credentialId"],
          headers: {"content-type": "text/plain"}
        });
        _this.sendVerifyEmail = _this.makeRequest({
          method: "PUT",
          path: "/{id}/send-verify-email",
          urlParamKeys: ["id"],
          queryParamKeys: ["clientId", "redirectUri"],
          keyTransform: {
            clientId: "client_id",
            redirectUri: "redirect_uri"
          }
        });
        _this.listSessions = _this.makeRequest({
          method: "GET",
          path: "/{id}/sessions",
          urlParamKeys: ["id"]
        });
        _this.listOfflineSessions = _this.makeRequest({
          method: "GET",
          path: "/{id}/offline-sessions/{clientId}",
          urlParamKeys: ["id", "clientId"]
        });
        _this.logout = _this.makeRequest({
          method: "POST",
          path: "/{id}/logout",
          urlParamKeys: ["id"]
        });
        _this.listConsents = _this.makeRequest({
          method: "GET",
          path: "/{id}/consents",
          urlParamKeys: ["id"]
        });
        _this.impersonation = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/impersonation",
          urlParamKeys: ["id"]
        });
        _this.revokeConsent = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/consents/{clientId}",
          urlParamKeys: ["id", "clientId"]
        });
        return _this;
      }
      return Users2;
    }(resource_1["default"]);
    exports2.Users = Users;
  });
  var groups = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.Groups = void 0;
    var resource_1 = __importDefault(resource);
    var Groups = function(_super) {
      __extends2(Groups2, _super);
      function Groups2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}/groups",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.find = _this.makeRequest({
          method: "GET"
        });
        _this.create = _this.makeRequest({
          method: "POST",
          returnResourceIdInLocationHeader: {field: "id"}
        });
        _this.findOne = _this.makeRequest({
          method: "GET",
          path: "/{id}",
          urlParamKeys: ["id"],
          catchNotFound: true
        });
        _this.update = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{id}",
          urlParamKeys: ["id"]
        });
        _this.del = _this.makeRequest({
          method: "DELETE",
          path: "/{id}",
          urlParamKeys: ["id"]
        });
        _this.count = _this.makeRequest({
          method: "GET",
          path: "/count"
        });
        _this.setOrCreateChild = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/children",
          urlParamKeys: ["id"],
          returnResourceIdInLocationHeader: {field: "id"}
        });
        _this.listMembers = _this.makeRequest({
          method: "GET",
          path: "/{id}/members",
          urlParamKeys: ["id"],
          catchNotFound: true
        });
        _this.listRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings",
          urlParamKeys: ["id"]
        });
        _this.addRealmRoleMappings = _this.makeRequest({
          method: "POST",
          path: "/{id}/role-mappings/realm",
          urlParamKeys: ["id"],
          payloadKey: "roles"
        });
        _this.listRealmRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/realm",
          urlParamKeys: ["id"]
        });
        _this.delRealmRoleMappings = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/role-mappings/realm",
          urlParamKeys: ["id"],
          payloadKey: "roles"
        });
        _this.listAvailableRealmRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/realm/available",
          urlParamKeys: ["id"]
        });
        _this.listCompositeRealmRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/realm/composite",
          urlParamKeys: ["id"]
        });
        _this.listClientRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/clients/{clientUniqueId}",
          urlParamKeys: ["id", "clientUniqueId"]
        });
        _this.addClientRoleMappings = _this.makeRequest({
          method: "POST",
          path: "/{id}/role-mappings/clients/{clientUniqueId}",
          urlParamKeys: ["id", "clientUniqueId"],
          payloadKey: "roles"
        });
        _this.delClientRoleMappings = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/role-mappings/clients/{clientUniqueId}",
          urlParamKeys: ["id", "clientUniqueId"],
          payloadKey: "roles"
        });
        _this.listAvailableClientRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/clients/{clientUniqueId}/available",
          urlParamKeys: ["id", "clientUniqueId"]
        });
        _this.listCompositeClientRoleMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/role-mappings/clients/{clientUniqueId}/composite",
          urlParamKeys: ["id", "clientUniqueId"]
        });
        _this.updatePermission = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{id}/management/permissions",
          urlParamKeys: ["id"]
        });
        _this.listPermissions = _this.makeRequest({
          method: "GET",
          path: "/{id}/management/permissions",
          urlParamKeys: ["id"]
        });
        return _this;
      }
      return Groups2;
    }(resource_1["default"]);
    exports2.Groups = Groups;
  });
  var roles = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.Roles = void 0;
    var resource_1 = __importDefault(resource);
    var Roles = function(_super) {
      __extends2(Roles2, _super);
      function Roles2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.find = _this.makeRequest({
          method: "GET",
          path: "/roles"
        });
        _this.create = _this.makeRequest({
          method: "POST",
          path: "/roles",
          returnResourceIdInLocationHeader: {field: "roleName"}
        });
        _this.findOneByName = _this.makeRequest({
          method: "GET",
          path: "/roles/{name}",
          urlParamKeys: ["name"],
          catchNotFound: true
        });
        _this.updateByName = _this.makeUpdateRequest({
          method: "PUT",
          path: "/roles/{name}",
          urlParamKeys: ["name"]
        });
        _this.delByName = _this.makeRequest({
          method: "DELETE",
          path: "/roles/{name}",
          urlParamKeys: ["name"]
        });
        _this.findUsersWithRole = _this.makeRequest({
          method: "GET",
          path: "/roles/{name}/users",
          urlParamKeys: ["name"],
          catchNotFound: true
        });
        _this.findOneById = _this.makeRequest({
          method: "GET",
          path: "/roles-by-id/{id}",
          urlParamKeys: ["id"],
          catchNotFound: true
        });
        _this.createComposite = _this.makeUpdateRequest({
          method: "POST",
          path: "/roles-by-id/{roleId}/composites",
          urlParamKeys: ["roleId"]
        });
        _this.getCompositeRoles = _this.makeRequest({
          method: "GET",
          path: "/roles-by-id/{id}/composites",
          urlParamKeys: ["id"]
        });
        _this.getCompositeRolesForRealm = _this.makeRequest({
          method: "GET",
          path: "/roles-by-id/{id}/composites/realm",
          urlParamKeys: ["id"]
        });
        _this.getCompositeRolesForClient = _this.makeRequest({
          method: "GET",
          path: "/roles-by-id/{id}/composites/clients/{clientId}",
          urlParamKeys: ["id", "clientId"]
        });
        _this.delCompositeRoles = _this.makeUpdateRequest({
          method: "DELETE",
          path: "/roles-by-id/{id}/composites",
          urlParamKeys: ["id"]
        });
        _this.updateById = _this.makeUpdateRequest({
          method: "PUT",
          path: "/roles-by-id/{id}",
          urlParamKeys: ["id"]
        });
        _this.delById = _this.makeRequest({
          method: "DELETE",
          path: "/roles-by-id/{id}",
          urlParamKeys: ["id"]
        });
        return _this;
      }
      return Roles2;
    }(resource_1["default"]);
    exports2.Roles = Roles;
  });
  var clients = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __assign2 = commonjsGlobal && commonjsGlobal.__assign || function() {
      __assign2 = Object.assign || function(t5) {
        for (var s2, i3 = 1, n3 = arguments.length; i3 < n3; i3++) {
          s2 = arguments[i3];
          for (var p2 in s2)
            if (Object.prototype.hasOwnProperty.call(s2, p2))
              t5[p2] = s2[p2];
        }
        return t5;
      };
      return __assign2.apply(this, arguments);
    };
    var __awaiter3 = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P2, generator) {
      function adopt(value) {
        return value instanceof P2 ? value : new P2(function(resolve2) {
          resolve2(value);
        });
      }
      return new (P2 || (P2 = Promise))(function(resolve2, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e2) {
            reject(e2);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e2) {
            reject(e2);
          }
        }
        function step(result) {
          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __generator2 = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
      var _23 = {label: 0, sent: function() {
        if (t5[0] & 1)
          throw t5[1];
        return t5[1];
      }, trys: [], ops: []}, f2, y3, t5, g2;
      return g2 = {next: verb(0), throw: verb(1), return: verb(2)}, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
        return this;
      }), g2;
      function verb(n3) {
        return function(v2) {
          return step([n3, v2]);
        };
      }
      function step(op) {
        if (f2)
          throw new TypeError("Generator is already executing.");
        while (_23)
          try {
            if (f2 = 1, y3 && (t5 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t5 = y3["return"]) && t5.call(y3), 0) : y3.next) && !(t5 = t5.call(y3, op[1])).done)
              return t5;
            if (y3 = 0, t5)
              op = [op[0] & 2, t5.value];
            switch (op[0]) {
              case 0:
              case 1:
                t5 = op;
                break;
              case 4:
                _23.label++;
                return {value: op[1], done: false};
              case 5:
                _23.label++;
                y3 = op[1];
                op = [0];
                continue;
              case 7:
                op = _23.ops.pop();
                _23.trys.pop();
                continue;
              default:
                if (!(t5 = _23.trys, t5 = t5.length > 0 && t5[t5.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                  _23 = 0;
                  continue;
                }
                if (op[0] === 3 && (!t5 || op[1] > t5[0] && op[1] < t5[3])) {
                  _23.label = op[1];
                  break;
                }
                if (op[0] === 6 && _23.label < t5[1]) {
                  _23.label = t5[1];
                  t5 = op;
                  break;
                }
                if (t5 && _23.label < t5[2]) {
                  _23.label = t5[2];
                  _23.ops.push(op);
                  break;
                }
                if (t5[2])
                  _23.ops.pop();
                _23.trys.pop();
                continue;
            }
            op = body.call(thisArg, _23);
          } catch (e2) {
            op = [6, e2];
            y3 = 0;
          } finally {
            f2 = t5 = 0;
          }
        if (op[0] & 5)
          throw op[1];
        return {value: op[0] ? op[1] : void 0, done: true};
      }
    };
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.Clients = void 0;
    var resource_1 = __importDefault(resource);
    var Clients = function(_super) {
      __extends2(Clients2, _super);
      function Clients2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}/clients",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.find = _this.makeRequest({
          method: "GET"
        });
        _this.create = _this.makeRequest({
          method: "POST",
          returnResourceIdInLocationHeader: {field: "id"}
        });
        _this.findOne = _this.makeRequest({
          method: "GET",
          path: "/{id}",
          urlParamKeys: ["id"],
          catchNotFound: true
        });
        _this.update = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{id}",
          urlParamKeys: ["id"]
        });
        _this.del = _this.makeRequest({
          method: "DELETE",
          path: "/{id}",
          urlParamKeys: ["id"]
        });
        _this.createRole = _this.makeRequest({
          method: "POST",
          path: "/{id}/roles",
          urlParamKeys: ["id"],
          returnResourceIdInLocationHeader: {field: "roleName"}
        });
        _this.listRoles = _this.makeRequest({
          method: "GET",
          path: "/{id}/roles",
          urlParamKeys: ["id"]
        });
        _this.findRole = _this.makeRequest({
          method: "GET",
          path: "/{id}/roles/{roleName}",
          urlParamKeys: ["id", "roleName"],
          catchNotFound: true
        });
        _this.updateRole = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{id}/roles/{roleName}",
          urlParamKeys: ["id", "roleName"]
        });
        _this.delRole = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/roles/{roleName}",
          urlParamKeys: ["id", "roleName"]
        });
        _this.findUsersWithRole = _this.makeRequest({
          method: "GET",
          path: "/{id}/roles/{roleName}/users",
          urlParamKeys: ["id", "roleName"]
        });
        _this.getServiceAccountUser = _this.makeRequest({
          method: "GET",
          path: "/{id}/service-account-user",
          urlParamKeys: ["id"]
        });
        _this.generateNewClientSecret = _this.makeRequest({
          method: "POST",
          path: "/{id}/client-secret",
          urlParamKeys: ["id"]
        });
        _this.generateRegistrationAccessToken = _this.makeRequest({
          method: "POST",
          path: "/{id}/registration-access-token",
          urlParamKeys: ["id"]
        });
        _this.getClientSecret = _this.makeRequest({
          method: "GET",
          path: "/{id}/client-secret",
          urlParamKeys: ["id"]
        });
        _this.listDefaultClientScopes = _this.makeRequest({
          method: "GET",
          path: "/{id}/default-client-scopes",
          urlParamKeys: ["id"]
        });
        _this.addDefaultClientScope = _this.makeRequest({
          method: "PUT",
          path: "/{id}/default-client-scopes/{clientScopeId}",
          urlParamKeys: ["id", "clientScopeId"]
        });
        _this.delDefaultClientScope = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/default-client-scopes/{clientScopeId}",
          urlParamKeys: ["id", "clientScopeId"]
        });
        _this.listOptionalClientScopes = _this.makeRequest({
          method: "GET",
          path: "/{id}/optional-client-scopes",
          urlParamKeys: ["id"]
        });
        _this.addOptionalClientScope = _this.makeRequest({
          method: "PUT",
          path: "/{id}/optional-client-scopes/{clientScopeId}",
          urlParamKeys: ["id", "clientScopeId"]
        });
        _this.delOptionalClientScope = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/optional-client-scopes/{clientScopeId}",
          urlParamKeys: ["id", "clientScopeId"]
        });
        _this.addMultipleProtocolMappers = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/protocol-mappers/add-models",
          urlParamKeys: ["id"]
        });
        _this.addProtocolMapper = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/protocol-mappers/models",
          urlParamKeys: ["id"]
        });
        _this.listProtocolMappers = _this.makeRequest({
          method: "GET",
          path: "/{id}/protocol-mappers/models",
          urlParamKeys: ["id"]
        });
        _this.findProtocolMapperById = _this.makeRequest({
          method: "GET",
          path: "/{id}/protocol-mappers/models/{mapperId}",
          urlParamKeys: ["id", "mapperId"],
          catchNotFound: true
        });
        _this.findProtocolMappersByProtocol = _this.makeRequest({
          method: "GET",
          path: "/{id}/protocol-mappers/protocol/{protocol}",
          urlParamKeys: ["id", "protocol"],
          catchNotFound: true
        });
        _this.updateProtocolMapper = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{id}/protocol-mappers/models/{mapperId}",
          urlParamKeys: ["id", "mapperId"]
        });
        _this.delProtocolMapper = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/protocol-mappers/models/{mapperId}",
          urlParamKeys: ["id", "mapperId"]
        });
        _this.listScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/scope-mappings",
          urlParamKeys: ["id"]
        });
        _this.addClientScopeMappings = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/scope-mappings/clients/{client}",
          urlParamKeys: ["id", "client"]
        });
        _this.listClientScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/scope-mappings/clients/{client}",
          urlParamKeys: ["id", "client"]
        });
        _this.listAvailableClientScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/scope-mappings/clients/{client}/available",
          urlParamKeys: ["id", "client"]
        });
        _this.listCompositeClientScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/scope-mappings/clients/{client}/available",
          urlParamKeys: ["id", "client"]
        });
        _this.delClientScopeMappings = _this.makeUpdateRequest({
          method: "DELETE",
          path: "/{id}/scope-mappings/clients/{client}",
          urlParamKeys: ["id", "client"]
        });
        _this.evaluatePermission = _this.makeRequest({
          method: "GET",
          path: "/{id}/evaluate-scopes/scope-mappings/{roleContainer}/{type}",
          urlParamKeys: ["id", "roleContainer", "type"],
          queryParamKeys: ["scope"]
        });
        _this.evaluateListProtocolMapper = _this.makeRequest({
          method: "GET",
          path: "/{id}/evaluate-scopes/protocol-mappers",
          urlParamKeys: ["id"],
          queryParamKeys: ["scope"]
        });
        _this.evaluateGenerateAccessToken = _this.makeRequest({
          method: "GET",
          path: "/{id}/evaluate-scopes/generate-example-access-token",
          urlParamKeys: ["id"],
          queryParamKeys: ["scope", "userId"]
        });
        _this.addRealmScopeMappings = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/scope-mappings/realm",
          urlParamKeys: ["id", "client"]
        });
        _this.listRealmScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/scope-mappings/realm",
          urlParamKeys: ["id"]
        });
        _this.listAvailableRealmScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/scope-mappings/realm/available",
          urlParamKeys: ["id"]
        });
        _this.listCompositeRealmScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/{id}/scope-mappings/realm/available",
          urlParamKeys: ["id"]
        });
        _this.delRealmScopeMappings = _this.makeUpdateRequest({
          method: "DELETE",
          path: "/{id}/scope-mappings/realm",
          urlParamKeys: ["id"]
        });
        _this.listSessions = _this.makeRequest({
          method: "GET",
          path: "/{id}/user-sessions",
          urlParamKeys: ["id"]
        });
        _this.listOfflineSessions = _this.makeRequest({
          method: "GET",
          path: "/{id}/offline-sessions",
          urlParamKeys: ["id"]
        });
        _this.getSessionCount = _this.makeRequest({
          method: "GET",
          path: "/{id}/session-count",
          urlParamKeys: ["id"]
        });
        _this.getResourceServer = _this.makeRequest({
          method: "GET",
          path: "{id}/authz/resource-server",
          urlParamKeys: ["id"]
        });
        _this.updateResourceServer = _this.makeUpdateRequest({
          method: "PUT",
          path: "{id}/authz/resource-server",
          urlParamKeys: ["id"]
        });
        _this.listResources = _this.makeRequest({
          method: "GET",
          path: "{id}/authz/resource-server/resource",
          urlParamKeys: ["id"]
        });
        _this.createResource = _this.makeUpdateRequest({
          method: "POST",
          path: "{id}/authz/resource-server/resource",
          urlParamKeys: ["id"]
        });
        _this.getResource = _this.makeRequest({
          method: "GET",
          path: "{id}/authz/resource-server/resource/{resourceId}",
          urlParamKeys: ["id", "resourceId"]
        });
        _this.updateResource = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{id}/authz/resource-server/resource/{resourceId}",
          urlParamKeys: ["id", "resourceId"]
        });
        _this.delResource = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/authz/resource-server/resource/{resourceId}",
          urlParamKeys: ["id", "resourceId"]
        });
        _this.importResource = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/authz/resource-server/import",
          urlParamKeys: ["id"]
        });
        _this.exportResource = _this.makeRequest({
          method: "GET",
          path: "/{id}/authz/resource-server/settings",
          urlParamKeys: ["id"]
        });
        _this.evaluateResource = _this.makeUpdateRequest({
          method: "POST",
          path: "{id}/authz/resource-server/policy/evaluate",
          urlParamKeys: ["id"]
        });
        _this.listPolicies = _this.makeRequest({
          method: "GET",
          path: "{id}/authz/resource-server/policy",
          urlParamKeys: ["id"]
        });
        _this.findPolicyByName = _this.makeRequest({
          method: "GET",
          path: "{id}/authz/resource-server/policy/search",
          urlParamKeys: ["id"]
        });
        _this.updatePolicy = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{id}/authz/resource-server/policy/{type}/{policyId}",
          urlParamKeys: ["id", "type", "policyId"]
        });
        _this.createPolicy = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/authz/resource-server/policy/{type}",
          urlParamKeys: ["id", "type"]
        });
        _this.findOnePolicy = _this.makeRequest({
          method: "GET",
          path: "/{id}/authz/resource-server/policy/{type}/{policyId}",
          urlParamKeys: ["id", "type", "policyId"],
          catchNotFound: true
        });
        _this.delPolicy = _this.makeRequest({
          method: "DELETE",
          path: "{id}/authz/resource-server/policy/{policyId}",
          urlParamKeys: ["id", "policyId"]
        });
        _this.listAllScopes = _this.makeRequest({
          method: "GET",
          path: "/{id}/authz/resource-server/scope",
          urlParamKeys: ["id"]
        });
        _this.listPermissionsByResource = _this.makeRequest({
          method: "GET",
          path: "/{id}/authz/resource-server/resource/{resourceId}/permissions",
          urlParamKeys: ["id", "resourceId"]
        });
        _this.listScopesByResource = _this.makeRequest({
          method: "GET",
          path: "/{id}/authz/resource-server/resource/{resourceName}/scopes",
          urlParamKeys: ["id", "resourceName"]
        });
        _this.createAuthorizationScope = _this.makeUpdateRequest({
          method: "POST",
          path: "{id}/authz/resource-server/scope",
          urlParamKeys: ["id"]
        });
        _this.findPermissions = _this.makeRequest({
          method: "GET",
          path: "{id}/authz/resource-server/permission",
          urlParamKeys: ["id"]
        });
        _this.createPermission = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/authz/resource-server/permission/{type}",
          urlParamKeys: ["id", "type"]
        });
        _this.updatePermission = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{id}/authz/resource-server/permission/{type}/{permissionId}",
          urlParamKeys: ["id", "type", "permissionId"]
        });
        _this.delPermission = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/authz/resource-server/permission/{type}/{permissionId}",
          urlParamKeys: ["id", "type", "permissionId"]
        });
        _this.findOnePermission = _this.makeRequest({
          method: "GET",
          path: "/{id}/authz/resource-server/permission/{type}/{permissionId}",
          urlParamKeys: ["id", "type", "permissionId"]
        });
        _this.getAssociatedScopes = _this.makeRequest({
          method: "GET",
          path: "/{id}/authz/resource-server/policy/{permissionId}/scopes",
          urlParamKeys: ["id", "permissionId"]
        });
        _this.getAssociatedResources = _this.makeRequest({
          method: "GET",
          path: "/{id}/authz/resource-server/policy/{permissionId}/resources",
          urlParamKeys: ["id", "permissionId"]
        });
        _this.getOfflineSessionCount = _this.makeRequest({
          method: "GET",
          path: "/{id}/offline-session-count",
          urlParamKeys: ["id"]
        });
        _this.getInstallationProviders = _this.makeRequest({
          method: "GET",
          path: "/{id}/installation/providers/{providerId}",
          urlParamKeys: ["id", "providerId"]
        });
        _this.pushRevocation = _this.makeRequest({
          method: "POST",
          path: "/{id}/push-revocation",
          urlParamKeys: ["id"]
        });
        _this.addClusterNode = _this.makeRequest({
          method: "POST",
          path: "/{id}/nodes",
          urlParamKeys: ["id"]
        });
        _this.deleteClusterNode = _this.makeRequest({
          method: "DELETE",
          path: "/{id}/nodes/{node}",
          urlParamKeys: ["id", "node"]
        });
        _this.testNodesAvailable = _this.makeRequest({
          method: "GET",
          path: "/{id}/test-nodes-available",
          urlParamKeys: ["id"]
        });
        _this.getKeyInfo = _this.makeRequest({
          method: "GET",
          path: "/{id}/certificates/{attr}",
          urlParamKeys: ["id", "attr"]
        });
        _this.generateKey = _this.makeRequest({
          method: "POST",
          path: "/{id}/certificates/{attr}/generate",
          urlParamKeys: ["id", "attr"]
        });
        _this.downloadKey = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/certificates/{attr}/download",
          urlParamKeys: ["id", "attr"]
        });
        _this.generateAndDownloadKey = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/certificates/{attr}/generate-and-download",
          urlParamKeys: ["id", "attr"]
        });
        _this.uploadKey = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/certificates/{attr}/upload",
          urlParamKeys: ["id", "attr"]
        });
        _this.uploadCertificate = _this.makeUpdateRequest({
          method: "POST",
          path: "/{id}/certificates/{attr}/upload-certificate",
          urlParamKeys: ["id", "attr"]
        });
        return _this;
      }
      Clients2.prototype.createOrUpdatePolicy = function(payload) {
        return __awaiter3(this, void 0, void 0, function() {
          var policyFound;
          return __generator2(this, function(_a) {
            switch (_a.label) {
              case 0:
                return [4, this.findPolicyByName({
                  id: payload.id,
                  name: payload.policyName
                })];
              case 1:
                policyFound = _a.sent();
                if (!policyFound)
                  return [3, 3];
                return [4, this.updatePolicy({id: payload.id, policyId: policyFound.id, type: payload.policy.type}, payload.policy)];
              case 2:
                _a.sent();
                return [2, this.findPolicyByName({id: payload.id, name: payload.policyName})];
              case 3:
                return [2, this.createPolicy({id: payload.id, type: payload.policy.type}, payload.policy)];
            }
          });
        });
      };
      Clients2.prototype.findProtocolMapperByName = function(payload) {
        return __awaiter3(this, void 0, void 0, function() {
          var allProtocolMappers;
          return __generator2(this, function(_a) {
            switch (_a.label) {
              case 0:
                return [4, this.listProtocolMappers(__assign2({id: payload.id}, payload.realm ? {realm: payload.realm} : {}))];
              case 1:
                allProtocolMappers = _a.sent();
                return [2, allProtocolMappers.find(function(mapper) {
                  return mapper.name === payload.name;
                })];
            }
          });
        });
      };
      return Clients2;
    }(resource_1["default"]);
    exports2.Clients = Clients;
  });
  var realms = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.Realms = void 0;
    var resource_1 = __importDefault(resource);
    var Realms = function(_super) {
      __extends2(Realms2, _super);
      function Realms2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms",
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.find = _this.makeRequest({
          method: "GET"
        });
        _this.create = _this.makeRequest({
          method: "POST",
          returnResourceIdInLocationHeader: {field: "realmName"}
        });
        _this.findOne = _this.makeRequest({
          method: "GET",
          path: "/{realm}",
          urlParamKeys: ["realm"],
          catchNotFound: true
        });
        _this.update = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{realm}",
          urlParamKeys: ["realm"]
        });
        _this.del = _this.makeRequest({
          method: "DELETE",
          path: "/{realm}",
          urlParamKeys: ["realm"]
        });
        _this.partialImport = _this.makeRequest({
          method: "POST",
          path: "/{realm}/partialImport",
          urlParamKeys: ["realm"],
          payloadKey: "rep"
        });
        _this["export"] = _this.makeRequest({
          method: "POST",
          path: "/{realm}/partial-export",
          urlParamKeys: ["realm"],
          queryParamKeys: ["exportClients", "exportGroupsAndRoles"]
        });
        _this.findEvents = _this.makeRequest({
          method: "GET",
          path: "/{realm}/events",
          urlParamKeys: ["realm"],
          queryParamKeys: [
            "client",
            "dateFrom",
            "dateTo",
            "first",
            "ipAddress",
            "max",
            "type",
            "user"
          ]
        });
        _this.getConfigEvents = _this.makeRequest({
          method: "GET",
          path: "/{realm}/events/config",
          urlParamKeys: ["realm"]
        });
        _this.updateConfigEvents = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{realm}/events/config",
          urlParamKeys: ["realm"]
        });
        _this.clearEvents = _this.makeRequest({
          method: "DELETE",
          path: "/{realm}/events",
          urlParamKeys: ["realm"]
        });
        _this.clearAdminEvents = _this.makeRequest({
          method: "DELETE",
          path: "/{realm}/admin-events",
          urlParamKeys: ["realm"]
        });
        _this.getClientsInitialAccess = _this.makeRequest({
          method: "GET",
          path: "/{realm}/clients-initial-access",
          urlParamKeys: ["realm"]
        });
        _this.createClientsInitialAccess = _this.makeUpdateRequest({
          method: "POST",
          path: "/{realm}/clients-initial-access",
          urlParamKeys: ["realm"]
        });
        _this.delClientsInitialAccess = _this.makeRequest({
          method: "DELETE",
          path: "/{realm}/clients-initial-access/{id}",
          urlParamKeys: ["realm", "id"]
        });
        _this.removeSession = _this.makeRequest({
          method: "DELETE",
          path: "/{realm}/sessions/{session}",
          urlParamKeys: ["realm", "session"],
          catchNotFound: true
        });
        _this.findAdminEvents = _this.makeRequest({
          method: "GET",
          path: "/{realm}/admin-events",
          urlParamKeys: ["realm"],
          queryParamKeys: [
            "authClient",
            "authIpAddress",
            "authRealm",
            "authUser",
            "dateFrom",
            "dateTo",
            "max",
            "first",
            "operationTypes",
            "resourcePath",
            "resourceTypes"
          ]
        });
        _this.getUsersManagementPermissions = _this.makeRequest({
          method: "GET",
          path: "/{realm}/users-management-permissions",
          urlParamKeys: ["realm"]
        });
        _this.updateUsersManagementPermissions = _this.makeRequest({
          method: "PUT",
          path: "/{realm}/users-management-permissions",
          urlParamKeys: ["realm"]
        });
        _this.logoutAll = _this.makeRequest({
          method: "POST",
          path: "/{realm}/logout-all",
          urlParamKeys: ["realm"]
        });
        _this.deleteSession = _this.makeRequest({
          method: "DELETE",
          path: "/{realm}/sessions/{session}",
          urlParamKeys: ["realm", "session"]
        });
        _this.pushRevocation = _this.makeRequest({
          method: "POST",
          path: "/{realm}/push-revocation",
          urlParamKeys: ["realm"],
          ignoredKeys: ["realm"]
        });
        _this.getKeys = _this.makeRequest({
          method: "GET",
          path: "/{realm}/keys",
          urlParamKeys: ["realm"]
        });
        _this.testLDAPConnection = _this.makeUpdateRequest({
          method: "POST",
          path: "/{realm}/testLDAPConnection",
          urlParamKeys: ["realm"]
        });
        _this.testSMTPConnection = _this.makeUpdateRequest({
          method: "POST",
          path: "/{realm}/testSMTPConnection",
          urlParamKeys: ["realm"]
        });
        _this.getRealmSpecificLocales = _this.makeRequest({
          method: "GET",
          path: "/{realm}/localization",
          urlParamKeys: ["realm"]
        });
        _this.getRealmLocalizationTexts = _this.makeRequest({
          method: "GET",
          path: "/{realm}/localization/{selectedLocale}",
          urlParamKeys: ["realm", "selectedLocale"]
        });
        _this.addLocalization = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{realm}/localization/{selectedLocale}/{key}",
          urlParamKeys: ["realm", "selectedLocale", "key"],
          headers: {"content-type": "text/plain"}
        });
        _this.deleteRealmLocalizationTexts = _this.makeRequest({
          method: "DELETE",
          path: "/{realm}/localization/{selectedLocale}/{key}",
          urlParamKeys: ["realm", "selectedLocale", "key"]
        });
        return _this;
      }
      return Realms2;
    }(resource_1["default"]);
    exports2.Realms = Realms;
  });
  var clientScopes = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __assign2 = commonjsGlobal && commonjsGlobal.__assign || function() {
      __assign2 = Object.assign || function(t5) {
        for (var s2, i3 = 1, n3 = arguments.length; i3 < n3; i3++) {
          s2 = arguments[i3];
          for (var p2 in s2)
            if (Object.prototype.hasOwnProperty.call(s2, p2))
              t5[p2] = s2[p2];
        }
        return t5;
      };
      return __assign2.apply(this, arguments);
    };
    var __awaiter3 = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P2, generator) {
      function adopt(value) {
        return value instanceof P2 ? value : new P2(function(resolve2) {
          resolve2(value);
        });
      }
      return new (P2 || (P2 = Promise))(function(resolve2, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e2) {
            reject(e2);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e2) {
            reject(e2);
          }
        }
        function step(result) {
          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __generator2 = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
      var _23 = {label: 0, sent: function() {
        if (t5[0] & 1)
          throw t5[1];
        return t5[1];
      }, trys: [], ops: []}, f2, y3, t5, g2;
      return g2 = {next: verb(0), throw: verb(1), return: verb(2)}, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
        return this;
      }), g2;
      function verb(n3) {
        return function(v2) {
          return step([n3, v2]);
        };
      }
      function step(op) {
        if (f2)
          throw new TypeError("Generator is already executing.");
        while (_23)
          try {
            if (f2 = 1, y3 && (t5 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t5 = y3["return"]) && t5.call(y3), 0) : y3.next) && !(t5 = t5.call(y3, op[1])).done)
              return t5;
            if (y3 = 0, t5)
              op = [op[0] & 2, t5.value];
            switch (op[0]) {
              case 0:
              case 1:
                t5 = op;
                break;
              case 4:
                _23.label++;
                return {value: op[1], done: false};
              case 5:
                _23.label++;
                y3 = op[1];
                op = [0];
                continue;
              case 7:
                op = _23.ops.pop();
                _23.trys.pop();
                continue;
              default:
                if (!(t5 = _23.trys, t5 = t5.length > 0 && t5[t5.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                  _23 = 0;
                  continue;
                }
                if (op[0] === 3 && (!t5 || op[1] > t5[0] && op[1] < t5[3])) {
                  _23.label = op[1];
                  break;
                }
                if (op[0] === 6 && _23.label < t5[1]) {
                  _23.label = t5[1];
                  t5 = op;
                  break;
                }
                if (t5 && _23.label < t5[2]) {
                  _23.label = t5[2];
                  _23.ops.push(op);
                  break;
                }
                if (t5[2])
                  _23.ops.pop();
                _23.trys.pop();
                continue;
            }
            op = body.call(thisArg, _23);
          } catch (e2) {
            op = [6, e2];
            y3 = 0;
          } finally {
            f2 = t5 = 0;
          }
        if (op[0] & 5)
          throw op[1];
        return {value: op[0] ? op[1] : void 0, done: true};
      }
    };
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.ClientScopes = void 0;
    var resource_1 = __importDefault(resource);
    var ClientScopes2 = function(_super) {
      __extends2(ClientScopes3, _super);
      function ClientScopes3(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.find = _this.makeRequest({
          method: "GET",
          path: "/client-scopes"
        });
        _this.create = _this.makeRequest({
          method: "POST",
          path: "/client-scopes"
        });
        _this.findOne = _this.makeRequest({
          method: "GET",
          path: "/client-scopes/{id}",
          urlParamKeys: ["id"],
          catchNotFound: true
        });
        _this.update = _this.makeUpdateRequest({
          method: "PUT",
          path: "/client-scopes/{id}",
          urlParamKeys: ["id"]
        });
        _this.del = _this.makeRequest({
          method: "DELETE",
          path: "/client-scopes/{id}",
          urlParamKeys: ["id"]
        });
        _this.listDefaultClientScopes = _this.makeRequest({
          method: "GET",
          path: "/default-default-client-scopes"
        });
        _this.addDefaultClientScope = _this.makeRequest({
          method: "PUT",
          path: "/default-default-client-scopes/{id}",
          urlParamKeys: ["id"]
        });
        _this.delDefaultClientScope = _this.makeRequest({
          method: "DELETE",
          path: "/default-default-client-scopes/{id}",
          urlParamKeys: ["id"]
        });
        _this.listDefaultOptionalClientScopes = _this.makeRequest({
          method: "GET",
          path: "/default-optional-client-scopes"
        });
        _this.addDefaultOptionalClientScope = _this.makeRequest({
          method: "PUT",
          path: "/default-optional-client-scopes/{id}",
          urlParamKeys: ["id"]
        });
        _this.delDefaultOptionalClientScope = _this.makeRequest({
          method: "DELETE",
          path: "/default-optional-client-scopes/{id}",
          urlParamKeys: ["id"]
        });
        _this.addMultipleProtocolMappers = _this.makeUpdateRequest({
          method: "POST",
          path: "/client-scopes/{id}/protocol-mappers/add-models",
          urlParamKeys: ["id"]
        });
        _this.addProtocolMapper = _this.makeUpdateRequest({
          method: "POST",
          path: "/client-scopes/{id}/protocol-mappers/models",
          urlParamKeys: ["id"]
        });
        _this.listProtocolMappers = _this.makeRequest({
          method: "GET",
          path: "/client-scopes/{id}/protocol-mappers/models",
          urlParamKeys: ["id"]
        });
        _this.findProtocolMapper = _this.makeRequest({
          method: "GET",
          path: "/client-scopes/{id}/protocol-mappers/models/{mapperId}",
          urlParamKeys: ["id", "mapperId"],
          catchNotFound: true
        });
        _this.findProtocolMappersByProtocol = _this.makeRequest({
          method: "GET",
          path: "/client-scopes/{id}/protocol-mappers/protocol/{protocol}",
          urlParamKeys: ["id", "protocol"],
          catchNotFound: true
        });
        _this.updateProtocolMapper = _this.makeUpdateRequest({
          method: "PUT",
          path: "/client-scopes/{id}/protocol-mappers/models/{mapperId}",
          urlParamKeys: ["id", "mapperId"]
        });
        _this.delProtocolMapper = _this.makeRequest({
          method: "DELETE",
          path: "/client-scopes/{id}/protocol-mappers/models/{mapperId}",
          urlParamKeys: ["id", "mapperId"]
        });
        _this.listScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/client-scopes/{id}/scope-mappings",
          urlParamKeys: ["id"]
        });
        _this.addClientScopeMappings = _this.makeUpdateRequest({
          method: "POST",
          path: "/client-scopes/{id}/scope-mappings/clients/{client}",
          urlParamKeys: ["id", "client"]
        });
        _this.listClientScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/client-scopes/{id}/scope-mappings/clients/{client}",
          urlParamKeys: ["id", "client"]
        });
        _this.listAvailableClientScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/client-scopes/{id}/scope-mappings/clients/{client}/available",
          urlParamKeys: ["id", "client"]
        });
        _this.listCompositeClientScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/client-scopes/{id}/scope-mappings/clients/{client}/composite",
          urlParamKeys: ["id", "client"]
        });
        _this.delClientScopeMappings = _this.makeUpdateRequest({
          method: "DELETE",
          path: "/client-scopes/{id}/scope-mappings/clients/{client}",
          urlParamKeys: ["id", "client"]
        });
        _this.addRealmScopeMappings = _this.makeUpdateRequest({
          method: "POST",
          path: "/client-scopes/{id}/scope-mappings/realm",
          urlParamKeys: ["id"]
        });
        _this.listRealmScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/client-scopes/{id}/scope-mappings/realm",
          urlParamKeys: ["id"]
        });
        _this.listAvailableRealmScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/client-scopes/{id}/scope-mappings/realm/available",
          urlParamKeys: ["id"]
        });
        _this.listCompositeRealmScopeMappings = _this.makeRequest({
          method: "GET",
          path: "/client-scopes/{id}/scope-mappings/realm/composite",
          urlParamKeys: ["id"]
        });
        _this.delRealmScopeMappings = _this.makeUpdateRequest({
          method: "DELETE",
          path: "/client-scopes/{id}/scope-mappings/realm",
          urlParamKeys: ["id"]
        });
        return _this;
      }
      ClientScopes3.prototype.findOneByName = function(payload) {
        return __awaiter3(this, void 0, void 0, function() {
          var allScopes;
          return __generator2(this, function(_a) {
            switch (_a.label) {
              case 0:
                return [4, this.find(__assign2({}, payload.realm ? {realm: payload.realm} : {}))];
              case 1:
                allScopes = _a.sent();
                return [2, allScopes.find(function(item) {
                  return item.name === payload.name;
                })];
            }
          });
        });
      };
      ClientScopes3.prototype.delByName = function(payload) {
        return __awaiter3(this, void 0, void 0, function() {
          var scope;
          return __generator2(this, function(_a) {
            switch (_a.label) {
              case 0:
                return [4, this.findOneByName(payload)];
              case 1:
                scope = _a.sent();
                if (!scope) {
                  throw new Error("Scope not found.");
                }
                return [4, this.del(__assign2(__assign2({}, payload.realm ? {realm: payload.realm} : {}), {id: scope.id}))];
              case 2:
                _a.sent();
                return [2];
            }
          });
        });
      };
      ClientScopes3.prototype.findProtocolMapperByName = function(payload) {
        return __awaiter3(this, void 0, void 0, function() {
          var allProtocolMappers;
          return __generator2(this, function(_a) {
            switch (_a.label) {
              case 0:
                return [4, this.listProtocolMappers(__assign2({id: payload.id}, payload.realm ? {realm: payload.realm} : {}))];
              case 1:
                allProtocolMappers = _a.sent();
                return [2, allProtocolMappers.find(function(mapper) {
                  return mapper.name === payload.name;
                })];
            }
          });
        });
      };
      return ClientScopes3;
    }(resource_1["default"]);
    exports2.ClientScopes = ClientScopes2;
  });
  var clientPolicies = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.ClientPolicies = void 0;
    var resource_1 = __importDefault(resource);
    var ClientPolicies = function(_super) {
      __extends2(ClientPolicies2, _super);
      function ClientPolicies2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}/client-policies",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.listProfiles = _this.makeRequest({
          method: "GET",
          path: "/profiles",
          queryParamKeys: ["include-global-profiles"],
          keyTransform: {
            includeGlobalProfiles: "include-global-profiles"
          }
        });
        _this.createProfiles = _this.makeRequest({
          method: "PUT",
          path: "/profiles"
        });
        _this.listPolicies = _this.makeRequest({
          method: "GET",
          path: "/policies"
        });
        _this.updatePolicy = _this.makeRequest({
          method: "PUT",
          path: "/policies"
        });
        return _this;
      }
      return ClientPolicies2;
    }(resource_1["default"]);
    exports2.ClientPolicies = ClientPolicies;
  });
  var identityProviders = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.IdentityProviders = void 0;
    var resource_1 = __importDefault(resource);
    var IdentityProviders = function(_super) {
      __extends2(IdentityProviders2, _super);
      function IdentityProviders2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}/identity-provider",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.find = _this.makeRequest({
          method: "GET",
          path: "/instances"
        });
        _this.create = _this.makeRequest({
          method: "POST",
          path: "/instances",
          returnResourceIdInLocationHeader: {field: "id"}
        });
        _this.findOne = _this.makeRequest({
          method: "GET",
          path: "/instances/{alias}",
          urlParamKeys: ["alias"],
          catchNotFound: true
        });
        _this.update = _this.makeUpdateRequest({
          method: "PUT",
          path: "/instances/{alias}",
          urlParamKeys: ["alias"]
        });
        _this.del = _this.makeRequest({
          method: "DELETE",
          path: "/instances/{alias}",
          urlParamKeys: ["alias"]
        });
        _this.findFactory = _this.makeRequest({
          method: "GET",
          path: "/providers/{providerId}",
          urlParamKeys: ["providerId"]
        });
        _this.findMappers = _this.makeRequest({
          method: "GET",
          path: "/instances/{alias}/mappers",
          urlParamKeys: ["alias"]
        });
        _this.findOneMapper = _this.makeRequest({
          method: "GET",
          path: "/instances/{alias}/mappers/{id}",
          urlParamKeys: ["alias", "id"],
          catchNotFound: true
        });
        _this.createMapper = _this.makeRequest({
          method: "POST",
          path: "/instances/{alias}/mappers",
          urlParamKeys: ["alias"],
          payloadKey: "identityProviderMapper",
          returnResourceIdInLocationHeader: {field: "id"}
        });
        _this.updateMapper = _this.makeUpdateRequest({
          method: "PUT",
          path: "/instances/{alias}/mappers/{id}",
          urlParamKeys: ["alias", "id"]
        });
        _this.delMapper = _this.makeRequest({
          method: "DELETE",
          path: "/instances/{alias}/mappers/{id}",
          urlParamKeys: ["alias", "id"]
        });
        _this.findMapperTypes = _this.makeRequest({
          method: "GET",
          path: "/instances/{alias}/mapper-types",
          urlParamKeys: ["alias"]
        });
        _this.importFromUrl = _this.makeRequest({
          method: "POST",
          path: "/import-config"
        });
        return _this;
      }
      return IdentityProviders2;
    }(resource_1["default"]);
    exports2.IdentityProviders = IdentityProviders;
  });
  var components = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.Components = void 0;
    var resource_1 = __importDefault(resource);
    var Components = function(_super) {
      __extends2(Components2, _super);
      function Components2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}/components",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.find = _this.makeRequest({
          method: "GET"
        });
        _this.create = _this.makeRequest({
          method: "POST",
          returnResourceIdInLocationHeader: {field: "id"}
        });
        _this.findOne = _this.makeRequest({
          method: "GET",
          path: "/{id}",
          urlParamKeys: ["id"],
          catchNotFound: true
        });
        _this.update = _this.makeUpdateRequest({
          method: "PUT",
          path: "/{id}",
          urlParamKeys: ["id"]
        });
        _this.del = _this.makeRequest({
          method: "DELETE",
          path: "/{id}",
          urlParamKeys: ["id"]
        });
        _this.listSubComponents = _this.makeRequest({
          method: "GET",
          path: "/{id}/sub-component-types",
          urlParamKeys: ["id"],
          queryParamKeys: ["type"]
        });
        return _this;
      }
      return Components2;
    }(resource_1["default"]);
    exports2.Components = Components;
  });
  var authenticationManagement = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.AuthenticationManagement = void 0;
    var resource_1 = __importDefault(resource);
    var AuthenticationManagement = function(_super) {
      __extends2(AuthenticationManagement2, _super);
      function AuthenticationManagement2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}/authentication",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.registerRequiredAction = _this.makeRequest({
          method: "POST",
          path: "/register-required-action"
        });
        _this.getRequiredActions = _this.makeRequest({
          method: "GET",
          path: "/required-actions"
        });
        _this.getRequiredActionForAlias = _this.makeRequest({
          method: "GET",
          path: "/required-actions/{alias}",
          urlParamKeys: ["alias"],
          catchNotFound: true
        });
        _this.getClientAuthenticatorProviders = _this.makeRequest({
          method: "GET",
          path: "/client-authenticator-providers"
        });
        _this.getAuthenticatorProviders = _this.makeRequest({
          method: "GET",
          path: "/authenticator-providers"
        });
        _this.getFormActionProviders = _this.makeRequest({
          method: "GET",
          path: "/form-action-providers"
        });
        _this.updateRequiredAction = _this.makeUpdateRequest({
          method: "PUT",
          path: "/required-actions/{alias}",
          urlParamKeys: ["alias"]
        });
        _this.deleteRequiredAction = _this.makeRequest({
          method: "DELETE",
          path: "/required-actions/{alias}",
          urlParamKeys: ["alias"]
        });
        _this.lowerRequiredActionPriority = _this.makeRequest({
          method: "POST",
          path: "/required-actions/{alias}/lower-priority",
          urlParamKeys: ["alias"]
        });
        _this.raiseRequiredActionPriority = _this.makeRequest({
          method: "POST",
          path: "/required-actions/{alias}/raise-priority",
          urlParamKeys: ["alias"]
        });
        _this.getUnregisteredRequiredActions = _this.makeRequest({
          method: "GET",
          path: "/unregistered-required-actions"
        });
        _this.getFlows = _this.makeRequest({
          method: "GET",
          path: "/flows"
        });
        _this.getFlow = _this.makeRequest({
          method: "GET",
          path: "/flows/{flowId}",
          urlParamKeys: ["flowId"]
        });
        _this.getFormProviders = _this.makeRequest({
          method: "GET",
          path: "/form-providers"
        });
        _this.createFlow = _this.makeRequest({
          method: "POST",
          path: "/flows",
          returnResourceIdInLocationHeader: {field: "id"}
        });
        _this.copyFlow = _this.makeRequest({
          method: "POST",
          path: "/flows/{flow}/copy",
          urlParamKeys: ["flow"]
        });
        _this.deleteFlow = _this.makeRequest({
          method: "DELETE",
          path: "/flows/{flowId}",
          urlParamKeys: ["flowId"]
        });
        _this.updateFlow = _this.makeUpdateRequest({
          method: "PUT",
          path: "/flows/{flowId}",
          urlParamKeys: ["flowId"]
        });
        _this.getExecutions = _this.makeRequest({
          method: "GET",
          path: "/flows/{flow}/executions",
          urlParamKeys: ["flow"]
        });
        _this.addExecution = _this.makeUpdateRequest({
          method: "POST",
          path: "/flows/{flow}/executions",
          urlParamKeys: ["flow"]
        });
        _this.addExecutionToFlow = _this.makeRequest({
          method: "POST",
          path: "/flows/{flow}/executions/execution",
          urlParamKeys: ["flow"],
          returnResourceIdInLocationHeader: {field: "id"}
        });
        _this.addFlowToFlow = _this.makeRequest({
          method: "POST",
          path: "/flows/{flow}/executions/flow",
          urlParamKeys: ["flow"],
          returnResourceIdInLocationHeader: {field: "id"}
        });
        _this.updateExecution = _this.makeUpdateRequest({
          method: "PUT",
          path: "/flows/{flow}/executions",
          urlParamKeys: ["flow"]
        });
        _this.delExecution = _this.makeRequest({
          method: "DELETE",
          path: "/executions/{id}",
          urlParamKeys: ["id"]
        });
        _this.lowerPriorityExecution = _this.makeRequest({
          method: "POST",
          path: "/executions/{id}/lower-priority",
          urlParamKeys: ["id"]
        });
        _this.raisePriorityExecution = _this.makeRequest({
          method: "POST",
          path: "/executions/{id}/raise-priority",
          urlParamKeys: ["id"]
        });
        _this.getConfigDescription = _this.makeRequest({
          method: "GET",
          path: "config-description/{providerId}",
          urlParamKeys: ["providerId"]
        });
        _this.createConfig = _this.makeRequest({
          method: "POST",
          path: "/executions/{id}/config",
          urlParamKeys: ["id"],
          returnResourceIdInLocationHeader: {field: "id"}
        });
        _this.updateConfig = _this.makeRequest({
          method: "PUT",
          path: "/config/{id}",
          urlParamKeys: ["id"]
        });
        _this.getConfig = _this.makeRequest({
          method: "GET",
          path: "/config/{id}",
          urlParamKeys: ["id"]
        });
        _this.delConfig = _this.makeRequest({
          method: "DELETE",
          path: "/config/{id}",
          urlParamKeys: ["id"]
        });
        return _this;
      }
      return AuthenticationManagement2;
    }(resource_1["default"]);
    exports2.AuthenticationManagement = AuthenticationManagement;
  });
  var serverInfo = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.ServerInfo = void 0;
    var resource_1 = __importDefault(resource);
    var ServerInfo = function(_super) {
      __extends2(ServerInfo2, _super);
      function ServerInfo2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/serverinfo",
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.find = _this.makeRequest({
          method: "GET",
          path: "/"
        });
        return _this;
      }
      return ServerInfo2;
    }(resource_1["default"]);
    exports2.ServerInfo = ServerInfo;
  });
  var whoAmI = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.WhoAmI = void 0;
    var resource_1 = __importDefault(resource);
    var WhoAmI2 = function(_super) {
      __extends2(WhoAmI3, _super);
      function WhoAmI3(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/{realm}/console",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.find = _this.makeRequest({
          method: "GET",
          path: "/whoami"
        });
        return _this;
      }
      return WhoAmI3;
    }(resource_1["default"]);
    exports2.WhoAmI = WhoAmI2;
  });
  var attackDetection = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.AttackDetection = void 0;
    var resource_1 = __importDefault(resource);
    var AttackDetection = function(_super) {
      __extends2(AttackDetection2, _super);
      function AttackDetection2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}/attack-detection/brute-force",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.findOne = _this.makeRequest({
          method: "GET",
          path: "/users/{id}",
          urlParamKeys: ["id"],
          catchNotFound: true
        });
        _this.del = _this.makeRequest({
          method: "DELETE",
          path: "/users/{id}",
          urlParamKeys: ["id"]
        });
        _this.delAll = _this.makeRequest({
          method: "DELETE",
          path: "/users"
        });
        return _this;
      }
      return AttackDetection2;
    }(resource_1["default"]);
    exports2.AttackDetection = AttackDetection;
  });
  var sessions = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.Sessions = void 0;
    var resource_1 = __importDefault(resource);
    var Sessions = function(_super) {
      __extends2(Sessions2, _super);
      function Sessions2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}/client-session-stats",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.find = _this.makeRequest({
          method: "GET"
        });
        return _this;
      }
      return Sessions2;
    }(resource_1["default"]);
    exports2.Sessions = Sessions;
  });
  var userStorageProvider = createCommonjsModule(function(module2, exports2) {
    var __extends2 = commonjsGlobal && commonjsGlobal.__extends || function() {
      var extendStatics = function(d2, b2) {
        extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p2 in b3)
            if (Object.prototype.hasOwnProperty.call(b3, p2))
              d3[p2] = b3[p2];
        };
        return extendStatics(d2, b2);
      };
      return function(d2, b2) {
        if (typeof b2 !== "function" && b2 !== null)
          throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
        extendStatics(d2, b2);
        function __() {
          this.constructor = d2;
        }
        d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
      };
    }();
    var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : {default: mod};
    };
    exports2.__esModule = true;
    exports2.UserStorageProvider = void 0;
    var resource_1 = __importDefault(resource);
    var UserStorageProvider = function(_super) {
      __extends2(UserStorageProvider2, _super);
      function UserStorageProvider2(client2) {
        var _this = _super.call(this, client2, {
          path: "/admin/realms/{realm}/user-storage",
          getUrlParams: function() {
            return {
              realm: client2.realmName
            };
          },
          getBaseUrl: function() {
            return client2.baseUrl;
          }
        }) || this;
        _this.name = _this.makeRequest({
          method: "GET",
          path: "/{id}/name",
          urlParamKeys: ["id"]
        });
        _this.removeImportedUsers = _this.makeRequest({
          method: "POST",
          path: "/{id}/remove-imported-users",
          urlParamKeys: ["id"]
        });
        _this.sync = _this.makeRequest({
          method: "POST",
          path: "/{id}/sync",
          urlParamKeys: ["id"],
          queryParamKeys: ["action"]
        });
        _this.unlinkUsers = _this.makeRequest({
          method: "POST",
          path: "/{id}/unlink-users",
          urlParamKeys: ["id"]
        });
        _this.mappersSync = _this.makeRequest({
          method: "POST",
          path: "/{parentId}/mappers/{id}/sync",
          urlParamKeys: ["id", "parentId"],
          queryParamKeys: ["direction"]
        });
        return _this;
      }
      return UserStorageProvider2;
    }(resource_1["default"]);
    exports2.UserStorageProvider = UserStorageProvider;
  });
  var sha256 = createCommonjsModule(function(module) {
    /**
     * [js-sha256]{@link https://github.com/emn178/js-sha256}
     *
     * @version 0.9.0
     * @author Chen, Yi-Cyuan [emn178@gmail.com]
     * @copyright Chen, Yi-Cyuan 2014-2017
     * @license MIT
     */
    (function() {
      var ERROR = "input is invalid type";
      var WINDOW = typeof window === "object";
      var root = WINDOW ? window : {};
      if (root.JS_SHA256_NO_WINDOW) {
        WINDOW = false;
      }
      var WEB_WORKER = !WINDOW && typeof self === "object";
      var NODE_JS = !root.JS_SHA256_NO_NODE_JS && typeof process === "object" && process.versions && process.versions.node;
      if (NODE_JS) {
        root = commonjsGlobal;
      } else if (WEB_WORKER) {
        root = self;
      }
      var COMMON_JS = !root.JS_SHA256_NO_COMMON_JS && true && module.exports;
      var ARRAY_BUFFER = !root.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayBuffer !== "undefined";
      var HEX_CHARS = "0123456789abcdef".split("");
      var EXTRA = [-2147483648, 8388608, 32768, 128];
      var SHIFT = [24, 16, 8, 0];
      var K = [
        1116352408,
        1899447441,
        3049323471,
        3921009573,
        961987163,
        1508970993,
        2453635748,
        2870763221,
        3624381080,
        310598401,
        607225278,
        1426881987,
        1925078388,
        2162078206,
        2614888103,
        3248222580,
        3835390401,
        4022224774,
        264347078,
        604807628,
        770255983,
        1249150122,
        1555081692,
        1996064986,
        2554220882,
        2821834349,
        2952996808,
        3210313671,
        3336571891,
        3584528711,
        113926993,
        338241895,
        666307205,
        773529912,
        1294757372,
        1396182291,
        1695183700,
        1986661051,
        2177026350,
        2456956037,
        2730485921,
        2820302411,
        3259730800,
        3345764771,
        3516065817,
        3600352804,
        4094571909,
        275423344,
        430227734,
        506948616,
        659060556,
        883997877,
        958139571,
        1322822218,
        1537002063,
        1747873779,
        1955562222,
        2024104815,
        2227730452,
        2361852424,
        2428436474,
        2756734187,
        3204031479,
        3329325298
      ];
      var OUTPUT_TYPES = ["hex", "array", "digest", "arrayBuffer"];
      var blocks = [];
      if (root.JS_SHA256_NO_NODE_JS || !Array.isArray) {
        Array.isArray = function(obj) {
          return Object.prototype.toString.call(obj) === "[object Array]";
        };
      }
      if (ARRAY_BUFFER && (root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {
        ArrayBuffer.isView = function(obj) {
          return typeof obj === "object" && obj.buffer && obj.buffer.constructor === ArrayBuffer;
        };
      }
      var createOutputMethod = function(outputType, is224) {
        return function(message) {
          return new Sha256(is224, true).update(message)[outputType]();
        };
      };
      var createMethod = function(is224) {
        var method = createOutputMethod("hex", is224);
        if (NODE_JS) {
          method = nodeWrap(method, is224);
        }
        method.create = function() {
          return new Sha256(is224);
        };
        method.update = function(message) {
          return method.create().update(message);
        };
        for (var i3 = 0; i3 < OUTPUT_TYPES.length; ++i3) {
          var type = OUTPUT_TYPES[i3];
          method[type] = createOutputMethod(type, is224);
        }
        return method;
      };
      var nodeWrap = function(method, is224) {
        var crypto = eval("require('crypto')");
        var Buffer = eval("require('buffer').Buffer");
        var algorithm = is224 ? "sha224" : "sha256";
        var nodeMethod = function(message) {
          if (typeof message === "string") {
            return crypto.createHash(algorithm).update(message, "utf8").digest("hex");
          } else {
            if (message === null || message === void 0) {
              throw new Error(ERROR);
            } else if (message.constructor === ArrayBuffer) {
              message = new Uint8Array(message);
            }
          }
          if (Array.isArray(message) || ArrayBuffer.isView(message) || message.constructor === Buffer) {
            return crypto.createHash(algorithm).update(new Buffer(message)).digest("hex");
          } else {
            return method(message);
          }
        };
        return nodeMethod;
      };
      var createHmacOutputMethod = function(outputType, is224) {
        return function(key, message) {
          return new HmacSha256(key, is224, true).update(message)[outputType]();
        };
      };
      var createHmacMethod = function(is224) {
        var method = createHmacOutputMethod("hex", is224);
        method.create = function(key) {
          return new HmacSha256(key, is224);
        };
        method.update = function(key, message) {
          return method.create(key).update(message);
        };
        for (var i3 = 0; i3 < OUTPUT_TYPES.length; ++i3) {
          var type = OUTPUT_TYPES[i3];
          method[type] = createHmacOutputMethod(type, is224);
        }
        return method;
      };
      function Sha256(is224, sharedMemory) {
        if (sharedMemory) {
          blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
          this.blocks = blocks;
        } else {
          this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        }
        if (is224) {
          this.h0 = 3238371032;
          this.h1 = 914150663;
          this.h2 = 812702999;
          this.h3 = 4144912697;
          this.h4 = 4290775857;
          this.h5 = 1750603025;
          this.h6 = 1694076839;
          this.h7 = 3204075428;
        } else {
          this.h0 = 1779033703;
          this.h1 = 3144134277;
          this.h2 = 1013904242;
          this.h3 = 2773480762;
          this.h4 = 1359893119;
          this.h5 = 2600822924;
          this.h6 = 528734635;
          this.h7 = 1541459225;
        }
        this.block = this.start = this.bytes = this.hBytes = 0;
        this.finalized = this.hashed = false;
        this.first = true;
        this.is224 = is224;
      }
      Sha256.prototype.update = function(message) {
        if (this.finalized) {
          return;
        }
        var notString, type = typeof message;
        if (type !== "string") {
          if (type === "object") {
            if (message === null) {
              throw new Error(ERROR);
            } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {
              message = new Uint8Array(message);
            } else if (!Array.isArray(message)) {
              if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {
                throw new Error(ERROR);
              }
            }
          } else {
            throw new Error(ERROR);
          }
          notString = true;
        }
        var code2, index3 = 0, i3, length = message.length, blocks = this.blocks;
        while (index3 < length) {
          if (this.hashed) {
            this.hashed = false;
            blocks[0] = this.block;
            blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
          }
          if (notString) {
            for (i3 = this.start; index3 < length && i3 < 64; ++index3) {
              blocks[i3 >> 2] |= message[index3] << SHIFT[i3++ & 3];
            }
          } else {
            for (i3 = this.start; index3 < length && i3 < 64; ++index3) {
              code2 = message.charCodeAt(index3);
              if (code2 < 128) {
                blocks[i3 >> 2] |= code2 << SHIFT[i3++ & 3];
              } else if (code2 < 2048) {
                blocks[i3 >> 2] |= (192 | code2 >> 6) << SHIFT[i3++ & 3];
                blocks[i3 >> 2] |= (128 | code2 & 63) << SHIFT[i3++ & 3];
              } else if (code2 < 55296 || code2 >= 57344) {
                blocks[i3 >> 2] |= (224 | code2 >> 12) << SHIFT[i3++ & 3];
                blocks[i3 >> 2] |= (128 | code2 >> 6 & 63) << SHIFT[i3++ & 3];
                blocks[i3 >> 2] |= (128 | code2 & 63) << SHIFT[i3++ & 3];
              } else {
                code2 = 65536 + ((code2 & 1023) << 10 | message.charCodeAt(++index3) & 1023);
                blocks[i3 >> 2] |= (240 | code2 >> 18) << SHIFT[i3++ & 3];
                blocks[i3 >> 2] |= (128 | code2 >> 12 & 63) << SHIFT[i3++ & 3];
                blocks[i3 >> 2] |= (128 | code2 >> 6 & 63) << SHIFT[i3++ & 3];
                blocks[i3 >> 2] |= (128 | code2 & 63) << SHIFT[i3++ & 3];
              }
            }
          }
          this.lastByteIndex = i3;
          this.bytes += i3 - this.start;
          if (i3 >= 64) {
            this.block = blocks[16];
            this.start = i3 - 64;
            this.hash();
            this.hashed = true;
          } else {
            this.start = i3;
          }
        }
        if (this.bytes > 4294967295) {
          this.hBytes += this.bytes / 4294967296 << 0;
          this.bytes = this.bytes % 4294967296;
        }
        return this;
      };
      Sha256.prototype.finalize = function() {
        if (this.finalized) {
          return;
        }
        this.finalized = true;
        var blocks = this.blocks, i3 = this.lastByteIndex;
        blocks[16] = this.block;
        blocks[i3 >> 2] |= EXTRA[i3 & 3];
        this.block = blocks[16];
        if (i3 >= 56) {
          if (!this.hashed) {
            this.hash();
          }
          blocks[0] = this.block;
          blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
        }
        blocks[14] = this.hBytes << 3 | this.bytes >>> 29;
        blocks[15] = this.bytes << 3;
        this.hash();
      };
      Sha256.prototype.hash = function() {
        var a2 = this.h0, b2 = this.h1, c3 = this.h2, d2 = this.h3, e2 = this.h4, f2 = this.h5, g2 = this.h6, h2 = this.h7, blocks = this.blocks, j, s0, s1, maj, t1, t22, ch2, ab2, da2, cd2, bc2;
        for (j = 16; j < 64; ++j) {
          t1 = blocks[j - 15];
          s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3;
          t1 = blocks[j - 2];
          s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10;
          blocks[j] = blocks[j - 16] + s0 + blocks[j - 7] + s1 << 0;
        }
        bc2 = b2 & c3;
        for (j = 0; j < 64; j += 4) {
          if (this.first) {
            if (this.is224) {
              ab2 = 300032;
              t1 = blocks[0] - 1413257819;
              h2 = t1 - 150054599 << 0;
              d2 = t1 + 24177077 << 0;
            } else {
              ab2 = 704751109;
              t1 = blocks[0] - 210244248;
              h2 = t1 - 1521486534 << 0;
              d2 = t1 + 143694565 << 0;
            }
            this.first = false;
          } else {
            s0 = (a2 >>> 2 | a2 << 30) ^ (a2 >>> 13 | a2 << 19) ^ (a2 >>> 22 | a2 << 10);
            s1 = (e2 >>> 6 | e2 << 26) ^ (e2 >>> 11 | e2 << 21) ^ (e2 >>> 25 | e2 << 7);
            ab2 = a2 & b2;
            maj = ab2 ^ a2 & c3 ^ bc2;
            ch2 = e2 & f2 ^ ~e2 & g2;
            t1 = h2 + s1 + ch2 + K[j] + blocks[j];
            t22 = s0 + maj;
            h2 = d2 + t1 << 0;
            d2 = t1 + t22 << 0;
          }
          s0 = (d2 >>> 2 | d2 << 30) ^ (d2 >>> 13 | d2 << 19) ^ (d2 >>> 22 | d2 << 10);
          s1 = (h2 >>> 6 | h2 << 26) ^ (h2 >>> 11 | h2 << 21) ^ (h2 >>> 25 | h2 << 7);
          da2 = d2 & a2;
          maj = da2 ^ d2 & b2 ^ ab2;
          ch2 = h2 & e2 ^ ~h2 & f2;
          t1 = g2 + s1 + ch2 + K[j + 1] + blocks[j + 1];
          t22 = s0 + maj;
          g2 = c3 + t1 << 0;
          c3 = t1 + t22 << 0;
          s0 = (c3 >>> 2 | c3 << 30) ^ (c3 >>> 13 | c3 << 19) ^ (c3 >>> 22 | c3 << 10);
          s1 = (g2 >>> 6 | g2 << 26) ^ (g2 >>> 11 | g2 << 21) ^ (g2 >>> 25 | g2 << 7);
          cd2 = c3 & d2;
          maj = cd2 ^ c3 & a2 ^ da2;
          ch2 = g2 & h2 ^ ~g2 & e2;
          t1 = f2 + s1 + ch2 + K[j + 2] + blocks[j + 2];
          t22 = s0 + maj;
          f2 = b2 + t1 << 0;
          b2 = t1 + t22 << 0;
          s0 = (b2 >>> 2 | b2 << 30) ^ (b2 >>> 13 | b2 << 19) ^ (b2 >>> 22 | b2 << 10);
          s1 = (f2 >>> 6 | f2 << 26) ^ (f2 >>> 11 | f2 << 21) ^ (f2 >>> 25 | f2 << 7);
          bc2 = b2 & c3;
          maj = bc2 ^ b2 & d2 ^ cd2;
          ch2 = f2 & g2 ^ ~f2 & h2;
          t1 = e2 + s1 + ch2 + K[j + 3] + blocks[j + 3];
          t22 = s0 + maj;
          e2 = a2 + t1 << 0;
          a2 = t1 + t22 << 0;
        }
        this.h0 = this.h0 + a2 << 0;
        this.h1 = this.h1 + b2 << 0;
        this.h2 = this.h2 + c3 << 0;
        this.h3 = this.h3 + d2 << 0;
        this.h4 = this.h4 + e2 << 0;
        this.h5 = this.h5 + f2 << 0;
        this.h6 = this.h6 + g2 << 0;
        this.h7 = this.h7 + h2 << 0;
      };
      Sha256.prototype.hex = function() {
        this.finalize();
        var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7;
        var hex2 = HEX_CHARS[h0 >> 28 & 15] + HEX_CHARS[h0 >> 24 & 15] + HEX_CHARS[h0 >> 20 & 15] + HEX_CHARS[h0 >> 16 & 15] + HEX_CHARS[h0 >> 12 & 15] + HEX_CHARS[h0 >> 8 & 15] + HEX_CHARS[h0 >> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >> 28 & 15] + HEX_CHARS[h1 >> 24 & 15] + HEX_CHARS[h1 >> 20 & 15] + HEX_CHARS[h1 >> 16 & 15] + HEX_CHARS[h1 >> 12 & 15] + HEX_CHARS[h1 >> 8 & 15] + HEX_CHARS[h1 >> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >> 28 & 15] + HEX_CHARS[h2 >> 24 & 15] + HEX_CHARS[h2 >> 20 & 15] + HEX_CHARS[h2 >> 16 & 15] + HEX_CHARS[h2 >> 12 & 15] + HEX_CHARS[h2 >> 8 & 15] + HEX_CHARS[h2 >> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >> 28 & 15] + HEX_CHARS[h3 >> 24 & 15] + HEX_CHARS[h3 >> 20 & 15] + HEX_CHARS[h3 >> 16 & 15] + HEX_CHARS[h3 >> 12 & 15] + HEX_CHARS[h3 >> 8 & 15] + HEX_CHARS[h3 >> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >> 28 & 15] + HEX_CHARS[h4 >> 24 & 15] + HEX_CHARS[h4 >> 20 & 15] + HEX_CHARS[h4 >> 16 & 15] + HEX_CHARS[h4 >> 12 & 15] + HEX_CHARS[h4 >> 8 & 15] + HEX_CHARS[h4 >> 4 & 15] + HEX_CHARS[h4 & 15] + HEX_CHARS[h5 >> 28 & 15] + HEX_CHARS[h5 >> 24 & 15] + HEX_CHARS[h5 >> 20 & 15] + HEX_CHARS[h5 >> 16 & 15] + HEX_CHARS[h5 >> 12 & 15] + HEX_CHARS[h5 >> 8 & 15] + HEX_CHARS[h5 >> 4 & 15] + HEX_CHARS[h5 & 15] + HEX_CHARS[h6 >> 28 & 15] + HEX_CHARS[h6 >> 24 & 15] + HEX_CHARS[h6 >> 20 & 15] + HEX_CHARS[h6 >> 16 & 15] + HEX_CHARS[h6 >> 12 & 15] + HEX_CHARS[h6 >> 8 & 15] + HEX_CHARS[h6 >> 4 & 15] + HEX_CHARS[h6 & 15];
        if (!this.is224) {
          hex2 += HEX_CHARS[h7 >> 28 & 15] + HEX_CHARS[h7 >> 24 & 15] + HEX_CHARS[h7 >> 20 & 15] + HEX_CHARS[h7 >> 16 & 15] + HEX_CHARS[h7 >> 12 & 15] + HEX_CHARS[h7 >> 8 & 15] + HEX_CHARS[h7 >> 4 & 15] + HEX_CHARS[h7 & 15];
        }
        return hex2;
      };
      Sha256.prototype.toString = Sha256.prototype.hex;
      Sha256.prototype.digest = function() {
        this.finalize();
        var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7;
        var arr = [
          h0 >> 24 & 255,
          h0 >> 16 & 255,
          h0 >> 8 & 255,
          h0 & 255,
          h1 >> 24 & 255,
          h1 >> 16 & 255,
          h1 >> 8 & 255,
          h1 & 255,
          h2 >> 24 & 255,
          h2 >> 16 & 255,
          h2 >> 8 & 255,
          h2 & 255,
          h3 >> 24 & 255,
          h3 >> 16 & 255,
          h3 >> 8 & 255,
          h3 & 255,
          h4 >> 24 & 255,
          h4 >> 16 & 255,
          h4 >> 8 & 255,
          h4 & 255,
          h5 >> 24 & 255,
          h5 >> 16 & 255,
          h5 >> 8 & 255,
          h5 & 255,
          h6 >> 24 & 255,
          h6 >> 16 & 255,
          h6 >> 8 & 255,
          h6 & 255
        ];
        if (!this.is224) {
          arr.push(h7 >> 24 & 255, h7 >> 16 & 255, h7 >> 8 & 255, h7 & 255);
        }
        return arr;
      };
      Sha256.prototype.array = Sha256.prototype.digest;
      Sha256.prototype.arrayBuffer = function() {
        this.finalize();
        var buffer = new ArrayBuffer(this.is224 ? 28 : 32);
        var dataView = new DataView(buffer);
        dataView.setUint32(0, this.h0);
        dataView.setUint32(4, this.h1);
        dataView.setUint32(8, this.h2);
        dataView.setUint32(12, this.h3);
        dataView.setUint32(16, this.h4);
        dataView.setUint32(20, this.h5);
        dataView.setUint32(24, this.h6);
        if (!this.is224) {
          dataView.setUint32(28, this.h7);
        }
        return buffer;
      };
      function HmacSha256(key, is224, sharedMemory) {
        var i3, type = typeof key;
        if (type === "string") {
          var bytes = [], length = key.length, index3 = 0, code2;
          for (i3 = 0; i3 < length; ++i3) {
            code2 = key.charCodeAt(i3);
            if (code2 < 128) {
              bytes[index3++] = code2;
            } else if (code2 < 2048) {
              bytes[index3++] = 192 | code2 >> 6;
              bytes[index3++] = 128 | code2 & 63;
            } else if (code2 < 55296 || code2 >= 57344) {
              bytes[index3++] = 224 | code2 >> 12;
              bytes[index3++] = 128 | code2 >> 6 & 63;
              bytes[index3++] = 128 | code2 & 63;
            } else {
              code2 = 65536 + ((code2 & 1023) << 10 | key.charCodeAt(++i3) & 1023);
              bytes[index3++] = 240 | code2 >> 18;
              bytes[index3++] = 128 | code2 >> 12 & 63;
              bytes[index3++] = 128 | code2 >> 6 & 63;
              bytes[index3++] = 128 | code2 & 63;
            }
          }
          key = bytes;
        } else {
          if (type === "object") {
            if (key === null) {
              throw new Error(ERROR);
            } else if (ARRAY_BUFFER && key.constructor === ArrayBuffer) {
              key = new Uint8Array(key);
            } else if (!Array.isArray(key)) {
              if (!ARRAY_BUFFER || !ArrayBuffer.isView(key)) {
                throw new Error(ERROR);
              }
            }
          } else {
            throw new Error(ERROR);
          }
        }
        if (key.length > 64) {
          key = new Sha256(is224, true).update(key).array();
        }
        var oKeyPad = [], iKeyPad = [];
        for (i3 = 0; i3 < 64; ++i3) {
          var b2 = key[i3] || 0;
          oKeyPad[i3] = 92 ^ b2;
          iKeyPad[i3] = 54 ^ b2;
        }
        Sha256.call(this, is224, sharedMemory);
        this.update(iKeyPad);
        this.oKeyPad = oKeyPad;
        this.inner = true;
        this.sharedMemory = sharedMemory;
      }
      HmacSha256.prototype = new Sha256();
      HmacSha256.prototype.finalize = function() {
        Sha256.prototype.finalize.call(this);
        if (this.inner) {
          this.inner = false;
          var innerHash = this.array();
          Sha256.call(this, this.is224, this.sharedMemory);
          this.update(this.oKeyPad);
          this.update(innerHash);
          Sha256.prototype.finalize.call(this);
        }
      };
      var exports = createMethod();
      exports.sha256 = exports;
      exports.sha224 = createMethod(true);
      exports.sha256.hmac = createHmacMethod();
      exports.sha224.hmac = createHmacMethod(true);
      if (COMMON_JS) {
        module.exports = exports;
      } else {
        root.sha256 = exports.sha256;
        root.sha224 = exports.sha224;
      }
    })();
  });
  var byteLength_1 = byteLength;
  var toByteArray_1 = toByteArray;
  var fromByteArray_1 = fromByteArray;
  var lookup = [];
  var revLookup = [];
  var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
  var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  for (var i = 0, len = code.length; i < len; ++i) {
    lookup[i] = code[i];
    revLookup[code.charCodeAt(i)] = i;
  }
  revLookup["-".charCodeAt(0)] = 62;
  revLookup["_".charCodeAt(0)] = 63;
  function getLens(b64) {
    var len2 = b64.length;
    if (len2 % 4 > 0) {
      throw new Error("Invalid string. Length must be a multiple of 4");
    }
    var validLen = b64.indexOf("=");
    if (validLen === -1)
      validLen = len2;
    var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
    return [validLen, placeHoldersLen];
  }
  function byteLength(b64) {
    var lens = getLens(b64);
    var validLen = lens[0];
    var placeHoldersLen = lens[1];
    return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  }
  function _byteLength(b64, validLen, placeHoldersLen) {
    return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  }
  function toByteArray(b64) {
    var tmp;
    var lens = getLens(b64);
    var validLen = lens[0];
    var placeHoldersLen = lens[1];
    var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
    var curByte = 0;
    var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
    var i3;
    for (i3 = 0; i3 < len2; i3 += 4) {
      tmp = revLookup[b64.charCodeAt(i3)] << 18 | revLookup[b64.charCodeAt(i3 + 1)] << 12 | revLookup[b64.charCodeAt(i3 + 2)] << 6 | revLookup[b64.charCodeAt(i3 + 3)];
      arr[curByte++] = tmp >> 16 & 255;
      arr[curByte++] = tmp >> 8 & 255;
      arr[curByte++] = tmp & 255;
    }
    if (placeHoldersLen === 2) {
      tmp = revLookup[b64.charCodeAt(i3)] << 2 | revLookup[b64.charCodeAt(i3 + 1)] >> 4;
      arr[curByte++] = tmp & 255;
    }
    if (placeHoldersLen === 1) {
      tmp = revLookup[b64.charCodeAt(i3)] << 10 | revLookup[b64.charCodeAt(i3 + 1)] << 4 | revLookup[b64.charCodeAt(i3 + 2)] >> 2;
      arr[curByte++] = tmp >> 8 & 255;
      arr[curByte++] = tmp & 255;
    }
    return arr;
  }
  function tripletToBase64(num) {
    return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
  }
  function encodeChunk(uint8, start3, end2) {
    var tmp;
    var output2 = [];
    for (var i3 = start3; i3 < end2; i3 += 3) {
      tmp = (uint8[i3] << 16 & 16711680) + (uint8[i3 + 1] << 8 & 65280) + (uint8[i3 + 2] & 255);
      output2.push(tripletToBase64(tmp));
    }
    return output2.join("");
  }
  function fromByteArray(uint8) {
    var tmp;
    var len2 = uint8.length;
    var extraBytes = len2 % 3;
    var parts = [];
    var maxChunkLength = 16383;
    for (var i3 = 0, len22 = len2 - extraBytes; i3 < len22; i3 += maxChunkLength) {
      parts.push(encodeChunk(uint8, i3, i3 + maxChunkLength > len22 ? len22 : i3 + maxChunkLength));
    }
    if (extraBytes === 1) {
      tmp = uint8[len2 - 1];
      parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==");
    } else if (extraBytes === 2) {
      tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
      parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=");
    }
    return parts.join("");
  }
  var base64Js = {
    byteLength: byteLength_1,
    toByteArray: toByteArray_1,
    fromByteArray: fromByteArray_1
  };
  var keycloak = createCommonjsModule(function(module2, exports2) {
    (function(root4, factory) {
      {
        {
          module2.exports = factory(sha256, base64Js);
        }
      }
    })(window, function(sha256_imported, base64js_imported) {
      if (typeof Promise === "undefined") {
        throw Error("Keycloak requires an environment that supports Promises. Make sure that you include the appropriate polyfill.");
      }
      var loggedPromiseDeprecation = false;
      function logPromiseDeprecation() {
        if (!loggedPromiseDeprecation) {
          loggedPromiseDeprecation = true;
          console.warn("[KEYCLOAK] Usage of legacy style promise methods such as `.error()` and `.success()` has been deprecated and support will be removed in future versions. Use standard style promise methods such as `.then() and `.catch()` instead.");
        }
      }
      function Keycloak(config2) {
        if (!(this instanceof Keycloak)) {
          return new Keycloak(config2);
        }
        var kc2 = this;
        var adapter;
        var refreshQueue = [];
        var callbackStorage;
        var loginIframe = {
          enable: true,
          callbackList: [],
          interval: 5
        };
        var scripts = document.getElementsByTagName("script");
        for (var i3 = 0; i3 < scripts.length; i3++) {
          if ((scripts[i3].src.indexOf("keycloak.js") !== -1 || scripts[i3].src.indexOf("keycloak.min.js") !== -1) && scripts[i3].src.indexOf("version=") !== -1) {
            kc2.iframeVersion = scripts[i3].src.substring(scripts[i3].src.indexOf("version=") + 8).split("&")[0];
          }
        }
        var useNonce = true;
        var logInfo = createLogger(console.info);
        var logWarn = createLogger(console.warn);
        kc2.init = function(initOptions2) {
          kc2.authenticated = false;
          callbackStorage = createCallbackStorage();
          var adapters = ["default", "cordova", "cordova-native"];
          if (initOptions2 && adapters.indexOf(initOptions2.adapter) > -1) {
            adapter = loadAdapter(initOptions2.adapter);
          } else if (initOptions2 && typeof initOptions2.adapter === "object") {
            adapter = initOptions2.adapter;
          } else {
            if (window.Cordova || window.cordova) {
              adapter = loadAdapter("cordova");
            } else {
              adapter = loadAdapter();
            }
          }
          if (initOptions2) {
            if (typeof initOptions2.useNonce !== "undefined") {
              useNonce = initOptions2.useNonce;
            }
            if (typeof initOptions2.checkLoginIframe !== "undefined") {
              loginIframe.enable = initOptions2.checkLoginIframe;
            }
            if (initOptions2.checkLoginIframeInterval) {
              loginIframe.interval = initOptions2.checkLoginIframeInterval;
            }
            if (initOptions2.onLoad === "login-required") {
              kc2.loginRequired = true;
            }
            if (initOptions2.responseMode) {
              if (initOptions2.responseMode === "query" || initOptions2.responseMode === "fragment") {
                kc2.responseMode = initOptions2.responseMode;
              } else {
                throw "Invalid value for responseMode";
              }
            }
            if (initOptions2.flow) {
              switch (initOptions2.flow) {
                case "standard":
                  kc2.responseType = "code";
                  break;
                case "implicit":
                  kc2.responseType = "id_token token";
                  break;
                case "hybrid":
                  kc2.responseType = "code id_token token";
                  break;
                default:
                  throw "Invalid value for flow";
              }
              kc2.flow = initOptions2.flow;
            }
            if (initOptions2.timeSkew != null) {
              kc2.timeSkew = initOptions2.timeSkew;
            }
            if (initOptions2.redirectUri) {
              kc2.redirectUri = initOptions2.redirectUri;
            }
            if (initOptions2.silentCheckSsoRedirectUri) {
              kc2.silentCheckSsoRedirectUri = initOptions2.silentCheckSsoRedirectUri;
            }
            if (typeof initOptions2.silentCheckSsoFallback === "boolean") {
              kc2.silentCheckSsoFallback = initOptions2.silentCheckSsoFallback;
            } else {
              kc2.silentCheckSsoFallback = true;
            }
            if (initOptions2.pkceMethod) {
              if (initOptions2.pkceMethod !== "S256") {
                throw "Invalid value for pkceMethod";
              }
              kc2.pkceMethod = initOptions2.pkceMethod;
            }
            if (typeof initOptions2.enableLogging === "boolean") {
              kc2.enableLogging = initOptions2.enableLogging;
            } else {
              kc2.enableLogging = false;
            }
            if (typeof initOptions2.scope === "string") {
              kc2.scope = initOptions2.scope;
            }
            if (typeof initOptions2.messageReceiveTimeout === "number" && initOptions2.messageReceiveTimeout > 0) {
              kc2.messageReceiveTimeout = initOptions2.messageReceiveTimeout;
            } else {
              kc2.messageReceiveTimeout = 1e4;
            }
          }
          if (!kc2.responseMode) {
            kc2.responseMode = "fragment";
          }
          if (!kc2.responseType) {
            kc2.responseType = "code";
            kc2.flow = "standard";
          }
          var promise = createPromise();
          var initPromise = createPromise();
          initPromise.promise.then(function() {
            kc2.onReady && kc2.onReady(kc2.authenticated);
            promise.setSuccess(kc2.authenticated);
          }).catch(function(error2) {
            promise.setError(error2);
          });
          var configPromise = loadConfig();
          function onLoad() {
            var doLogin = function(prompt) {
              if (!prompt) {
                options.prompt = "none";
              }
              kc2.login(options).then(function() {
                initPromise.setSuccess();
              }).catch(function(error2) {
                initPromise.setError(error2);
              });
            };
            var checkSsoSilently = function() {
              var ifrm = document.createElement("iframe");
              var src = kc2.createLoginUrl({prompt: "none", redirectUri: kc2.silentCheckSsoRedirectUri});
              ifrm.setAttribute("src", src);
              ifrm.setAttribute("title", "keycloak-silent-check-sso");
              ifrm.style.display = "none";
              document.body.appendChild(ifrm);
              var messageCallback = function(event) {
                if (event.origin !== window.location.origin || ifrm.contentWindow !== event.source) {
                  return;
                }
                var oauth = parseCallback(event.data);
                processCallback(oauth, initPromise);
                document.body.removeChild(ifrm);
                window.removeEventListener("message", messageCallback);
              };
              window.addEventListener("message", messageCallback);
            };
            var options = {};
            switch (initOptions2.onLoad) {
              case "check-sso":
                if (loginIframe.enable) {
                  setupCheckLoginIframe().then(function() {
                    checkLoginIframe().then(function(unchanged) {
                      if (!unchanged) {
                        kc2.silentCheckSsoRedirectUri ? checkSsoSilently() : doLogin(false);
                      } else {
                        initPromise.setSuccess();
                      }
                    }).catch(function(error2) {
                      initPromise.setError(error2);
                    });
                  });
                } else {
                  kc2.silentCheckSsoRedirectUri ? checkSsoSilently() : doLogin(false);
                }
                break;
              case "login-required":
                doLogin(true);
                break;
              default:
                throw "Invalid value for onLoad";
            }
          }
          function processInit() {
            var callback = parseCallback(window.location.href);
            if (callback) {
              window.history.replaceState(window.history.state, null, callback.newUrl);
            }
            if (callback && callback.valid) {
              return setupCheckLoginIframe().then(function() {
                processCallback(callback, initPromise);
              }).catch(function(error2) {
                initPromise.setError(error2);
              });
            } else if (initOptions2) {
              if (initOptions2.token && initOptions2.refreshToken) {
                setToken(initOptions2.token, initOptions2.refreshToken, initOptions2.idToken);
                if (loginIframe.enable) {
                  setupCheckLoginIframe().then(function() {
                    checkLoginIframe().then(function(unchanged) {
                      if (unchanged) {
                        kc2.onAuthSuccess && kc2.onAuthSuccess();
                        initPromise.setSuccess();
                        scheduleCheckIframe();
                      } else {
                        initPromise.setSuccess();
                      }
                    }).catch(function(error2) {
                      initPromise.setError(error2);
                    });
                  });
                } else {
                  kc2.updateToken(-1).then(function() {
                    kc2.onAuthSuccess && kc2.onAuthSuccess();
                    initPromise.setSuccess();
                  }).catch(function(error2) {
                    kc2.onAuthError && kc2.onAuthError();
                    if (initOptions2.onLoad) {
                      onLoad();
                    } else {
                      initPromise.setError(error2);
                    }
                  });
                }
              } else if (initOptions2.onLoad) {
                onLoad();
              } else {
                initPromise.setSuccess();
              }
            } else {
              initPromise.setSuccess();
            }
          }
          function domReady() {
            var promise2 = createPromise();
            var checkReadyState = function() {
              if (document.readyState === "interactive" || document.readyState === "complete") {
                document.removeEventListener("readystatechange", checkReadyState);
                promise2.setSuccess();
              }
            };
            document.addEventListener("readystatechange", checkReadyState);
            checkReadyState();
            return promise2.promise;
          }
          configPromise.then(function() {
            domReady().then(check3pCookiesSupported).then(processInit).catch(function(error2) {
              promise.setError(error2);
            });
          });
          configPromise.catch(function(error2) {
            promise.setError(error2);
          });
          return promise.promise;
        };
        kc2.login = function(options) {
          return adapter.login(options);
        };
        function generateRandomData(len2) {
          var array2 = null;
          var crypto = window.crypto || window.msCrypto;
          if (crypto && crypto.getRandomValues && window.Uint8Array) {
            array2 = new Uint8Array(len2);
            crypto.getRandomValues(array2);
            return array2;
          }
          array2 = new Array(len2);
          for (var j = 0; j < array2.length; j++) {
            array2[j] = Math.floor(256 * Math.random());
          }
          return array2;
        }
        function generateCodeVerifier(len2) {
          return generateRandomString(len2, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
        }
        function generateRandomString(len2, alphabet) {
          var randomData = generateRandomData(len2);
          var chars2 = new Array(len2);
          for (var i4 = 0; i4 < len2; i4++) {
            chars2[i4] = alphabet.charCodeAt(randomData[i4] % alphabet.length);
          }
          return String.fromCharCode.apply(null, chars2);
        }
        function generatePkceChallenge(pkceMethod, codeVerifier) {
          switch (pkceMethod) {
            case "S256":
              var hashBytes = new Uint8Array(sha256_imported.arrayBuffer(codeVerifier));
              var encodedHash = base64js_imported.fromByteArray(hashBytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/\=/g, "");
              return encodedHash;
            default:
              throw "Invalid value for pkceMethod";
          }
        }
        kc2.createLoginUrl = function(options) {
          var state = createUUID();
          var nonce = createUUID();
          var redirectUri = adapter.redirectUri(options);
          var callbackState = {
            state,
            nonce,
            redirectUri: encodeURIComponent(redirectUri)
          };
          if (options && options.prompt) {
            callbackState.prompt = options.prompt;
          }
          var baseUrl;
          if (options && options.action == "register") {
            baseUrl = kc2.endpoints.register();
          } else {
            baseUrl = kc2.endpoints.authorize();
          }
          var scope = options && options.scope || kc2.scope;
          if (!scope) {
            scope = "openid";
          } else if (scope.indexOf("openid") === -1) {
            scope = "openid " + scope;
          }
          var url = baseUrl + "?client_id=" + encodeURIComponent(kc2.clientId) + "&redirect_uri=" + encodeURIComponent(redirectUri) + "&state=" + encodeURIComponent(state) + "&response_mode=" + encodeURIComponent(kc2.responseMode) + "&response_type=" + encodeURIComponent(kc2.responseType) + "&scope=" + encodeURIComponent(scope);
          if (useNonce) {
            url = url + "&nonce=" + encodeURIComponent(nonce);
          }
          if (options && options.prompt) {
            url += "&prompt=" + encodeURIComponent(options.prompt);
          }
          if (options && options.maxAge) {
            url += "&max_age=" + encodeURIComponent(options.maxAge);
          }
          if (options && options.loginHint) {
            url += "&login_hint=" + encodeURIComponent(options.loginHint);
          }
          if (options && options.idpHint) {
            url += "&kc_idp_hint=" + encodeURIComponent(options.idpHint);
          }
          if (options && options.action && options.action != "register") {
            url += "&kc_action=" + encodeURIComponent(options.action);
          }
          if (options && options.locale) {
            url += "&ui_locales=" + encodeURIComponent(options.locale);
          }
          if (kc2.pkceMethod) {
            var codeVerifier = generateCodeVerifier(96);
            callbackState.pkceCodeVerifier = codeVerifier;
            var pkceChallenge = generatePkceChallenge(kc2.pkceMethod, codeVerifier);
            url += "&code_challenge=" + pkceChallenge;
            url += "&code_challenge_method=" + kc2.pkceMethod;
          }
          callbackStorage.add(callbackState);
          return url;
        };
        kc2.logout = function(options) {
          return adapter.logout(options);
        };
        kc2.createLogoutUrl = function(options) {
          var url = kc2.endpoints.logout() + "?redirect_uri=" + encodeURIComponent(adapter.redirectUri(options, false));
          return url;
        };
        kc2.register = function(options) {
          return adapter.register(options);
        };
        kc2.createRegisterUrl = function(options) {
          if (!options) {
            options = {};
          }
          options.action = "register";
          return kc2.createLoginUrl(options);
        };
        kc2.createAccountUrl = function(options) {
          var realm2 = getRealmUrl();
          var url = void 0;
          if (typeof realm2 !== "undefined") {
            url = realm2 + "/account?referrer=" + encodeURIComponent(kc2.clientId) + "&referrer_uri=" + encodeURIComponent(adapter.redirectUri(options));
          }
          return url;
        };
        kc2.accountManagement = function() {
          return adapter.accountManagement();
        };
        kc2.hasRealmRole = function(role) {
          var access = kc2.realmAccess;
          return !!access && access.roles.indexOf(role) >= 0;
        };
        kc2.hasResourceRole = function(role, resource2) {
          if (!kc2.resourceAccess) {
            return false;
          }
          var access = kc2.resourceAccess[resource2 || kc2.clientId];
          return !!access && access.roles.indexOf(role) >= 0;
        };
        kc2.loadUserProfile = function() {
          var url = getRealmUrl() + "/account";
          var req = new XMLHttpRequest();
          req.open("GET", url, true);
          req.setRequestHeader("Accept", "application/json");
          req.setRequestHeader("Authorization", "bearer " + kc2.token);
          var promise = createPromise();
          req.onreadystatechange = function() {
            if (req.readyState == 4) {
              if (req.status == 200) {
                kc2.profile = JSON.parse(req.responseText);
                promise.setSuccess(kc2.profile);
              } else {
                promise.setError();
              }
            }
          };
          req.send();
          return promise.promise;
        };
        kc2.loadUserInfo = function() {
          var url = kc2.endpoints.userinfo();
          var req = new XMLHttpRequest();
          req.open("GET", url, true);
          req.setRequestHeader("Accept", "application/json");
          req.setRequestHeader("Authorization", "bearer " + kc2.token);
          var promise = createPromise();
          req.onreadystatechange = function() {
            if (req.readyState == 4) {
              if (req.status == 200) {
                kc2.userInfo = JSON.parse(req.responseText);
                promise.setSuccess(kc2.userInfo);
              } else {
                promise.setError();
              }
            }
          };
          req.send();
          return promise.promise;
        };
        kc2.isTokenExpired = function(minValidity) {
          if (!kc2.tokenParsed || !kc2.refreshToken && kc2.flow != "implicit") {
            throw "Not authenticated";
          }
          if (kc2.timeSkew == null) {
            logInfo("[KEYCLOAK] Unable to determine if token is expired as timeskew is not set");
            return true;
          }
          var expiresIn = kc2.tokenParsed["exp"] - Math.ceil(new Date().getTime() / 1e3) + kc2.timeSkew;
          if (minValidity) {
            if (isNaN(minValidity)) {
              throw "Invalid minValidity";
            }
            expiresIn -= minValidity;
          }
          return expiresIn < 0;
        };
        kc2.updateToken = function(minValidity) {
          var promise = createPromise();
          if (!kc2.refreshToken) {
            promise.setError();
            return promise.promise;
          }
          minValidity = minValidity || 5;
          var exec = function() {
            var refreshToken = false;
            if (minValidity == -1) {
              refreshToken = true;
              logInfo("[KEYCLOAK] Refreshing token: forced refresh");
            } else if (!kc2.tokenParsed || kc2.isTokenExpired(minValidity)) {
              refreshToken = true;
              logInfo("[KEYCLOAK] Refreshing token: token expired");
            }
            if (!refreshToken) {
              promise.setSuccess(false);
            } else {
              var params = "grant_type=refresh_token&refresh_token=" + kc2.refreshToken;
              var url = kc2.endpoints.token();
              refreshQueue.push(promise);
              if (refreshQueue.length == 1) {
                var req = new XMLHttpRequest();
                req.open("POST", url, true);
                req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                req.withCredentials = true;
                params += "&client_id=" + encodeURIComponent(kc2.clientId);
                var timeLocal = new Date().getTime();
                req.onreadystatechange = function() {
                  if (req.readyState == 4) {
                    if (req.status == 200) {
                      logInfo("[KEYCLOAK] Token refreshed");
                      timeLocal = (timeLocal + new Date().getTime()) / 2;
                      var tokenResponse = JSON.parse(req.responseText);
                      setToken(tokenResponse["access_token"], tokenResponse["refresh_token"], tokenResponse["id_token"], timeLocal);
                      kc2.onAuthRefreshSuccess && kc2.onAuthRefreshSuccess();
                      for (var p2 = refreshQueue.pop(); p2 != null; p2 = refreshQueue.pop()) {
                        p2.setSuccess(true);
                      }
                    } else {
                      logWarn("[KEYCLOAK] Failed to refresh token");
                      if (req.status == 400) {
                        kc2.clearToken();
                      }
                      kc2.onAuthRefreshError && kc2.onAuthRefreshError();
                      for (var p2 = refreshQueue.pop(); p2 != null; p2 = refreshQueue.pop()) {
                        p2.setError(true);
                      }
                    }
                  }
                };
                req.send(params);
              }
            }
          };
          if (loginIframe.enable) {
            var iframePromise = checkLoginIframe();
            iframePromise.then(function() {
              exec();
            }).catch(function(error2) {
              promise.setError(error2);
            });
          } else {
            exec();
          }
          return promise.promise;
        };
        kc2.clearToken = function() {
          if (kc2.token) {
            setToken(null, null, null);
            kc2.onAuthLogout && kc2.onAuthLogout();
            if (kc2.loginRequired) {
              kc2.login();
            }
          }
        };
        function getRealmUrl() {
          if (typeof kc2.authServerUrl !== "undefined") {
            if (kc2.authServerUrl.charAt(kc2.authServerUrl.length - 1) == "/") {
              return kc2.authServerUrl + "realms/" + encodeURIComponent(kc2.realm);
            } else {
              return kc2.authServerUrl + "/realms/" + encodeURIComponent(kc2.realm);
            }
          } else {
            return void 0;
          }
        }
        function getOrigin() {
          if (!window.location.origin) {
            return window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
          } else {
            return window.location.origin;
          }
        }
        function processCallback(oauth, promise) {
          var code2 = oauth.code;
          var error2 = oauth.error;
          var prompt = oauth.prompt;
          var timeLocal = new Date().getTime();
          if (oauth["kc_action_status"]) {
            kc2.onActionUpdate && kc2.onActionUpdate(oauth["kc_action_status"]);
          }
          if (error2) {
            if (prompt != "none") {
              var errorData = {error: error2, error_description: oauth.error_description};
              kc2.onAuthError && kc2.onAuthError(errorData);
              promise && promise.setError(errorData);
            } else {
              promise && promise.setSuccess();
            }
            return;
          } else if (kc2.flow != "standard" && (oauth.access_token || oauth.id_token)) {
            authSuccess(oauth.access_token, null, oauth.id_token, true);
          }
          if (kc2.flow != "implicit" && code2) {
            var params = "code=" + code2 + "&grant_type=authorization_code";
            var url = kc2.endpoints.token();
            var req = new XMLHttpRequest();
            req.open("POST", url, true);
            req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            params += "&client_id=" + encodeURIComponent(kc2.clientId);
            params += "&redirect_uri=" + oauth.redirectUri;
            if (oauth.pkceCodeVerifier) {
              params += "&code_verifier=" + oauth.pkceCodeVerifier;
            }
            req.withCredentials = true;
            req.onreadystatechange = function() {
              if (req.readyState == 4) {
                if (req.status == 200) {
                  var tokenResponse = JSON.parse(req.responseText);
                  authSuccess(tokenResponse["access_token"], tokenResponse["refresh_token"], tokenResponse["id_token"], kc2.flow === "standard");
                  scheduleCheckIframe();
                } else {
                  kc2.onAuthError && kc2.onAuthError();
                  promise && promise.setError();
                }
              }
            };
            req.send(params);
          }
          function authSuccess(accessToken, refreshToken, idToken, fulfillPromise) {
            timeLocal = (timeLocal + new Date().getTime()) / 2;
            setToken(accessToken, refreshToken, idToken, timeLocal);
            if (useNonce && (kc2.tokenParsed && kc2.tokenParsed.nonce != oauth.storedNonce || kc2.refreshTokenParsed && kc2.refreshTokenParsed.nonce != oauth.storedNonce || kc2.idTokenParsed && kc2.idTokenParsed.nonce != oauth.storedNonce)) {
              logInfo("[KEYCLOAK] Invalid nonce, clearing token");
              kc2.clearToken();
              promise && promise.setError();
            } else {
              if (fulfillPromise) {
                kc2.onAuthSuccess && kc2.onAuthSuccess();
                promise && promise.setSuccess();
              }
            }
          }
        }
        function loadConfig(url) {
          var promise = createPromise();
          var configUrl;
          if (!config2) {
            configUrl = "keycloak.json";
          } else if (typeof config2 === "string") {
            configUrl = config2;
          }
          function setupOidcEndoints(oidcConfiguration) {
            if (!oidcConfiguration) {
              kc2.endpoints = {
                authorize: function() {
                  return getRealmUrl() + "/protocol/openid-connect/auth";
                },
                token: function() {
                  return getRealmUrl() + "/protocol/openid-connect/token";
                },
                logout: function() {
                  return getRealmUrl() + "/protocol/openid-connect/logout";
                },
                checkSessionIframe: function() {
                  var src = getRealmUrl() + "/protocol/openid-connect/login-status-iframe.html";
                  if (kc2.iframeVersion) {
                    src = src + "?version=" + kc2.iframeVersion;
                  }
                  return src;
                },
                thirdPartyCookiesIframe: function() {
                  var src = getRealmUrl() + "/protocol/openid-connect/3p-cookies/step1.html";
                  if (kc2.iframeVersion) {
                    src = src + "?version=" + kc2.iframeVersion;
                  }
                  return src;
                },
                register: function() {
                  return getRealmUrl() + "/protocol/openid-connect/registrations";
                },
                userinfo: function() {
                  return getRealmUrl() + "/protocol/openid-connect/userinfo";
                }
              };
            } else {
              kc2.endpoints = {
                authorize: function() {
                  return oidcConfiguration.authorization_endpoint;
                },
                token: function() {
                  return oidcConfiguration.token_endpoint;
                },
                logout: function() {
                  if (!oidcConfiguration.end_session_endpoint) {
                    throw "Not supported by the OIDC server";
                  }
                  return oidcConfiguration.end_session_endpoint;
                },
                checkSessionIframe: function() {
                  if (!oidcConfiguration.check_session_iframe) {
                    throw "Not supported by the OIDC server";
                  }
                  return oidcConfiguration.check_session_iframe;
                },
                register: function() {
                  throw 'Redirection to "Register user" page not supported in standard OIDC mode';
                },
                userinfo: function() {
                  if (!oidcConfiguration.userinfo_endpoint) {
                    throw "Not supported by the OIDC server";
                  }
                  return oidcConfiguration.userinfo_endpoint;
                }
              };
            }
          }
          if (configUrl) {
            var req = new XMLHttpRequest();
            req.open("GET", configUrl, true);
            req.setRequestHeader("Accept", "application/json");
            req.onreadystatechange = function() {
              if (req.readyState == 4) {
                if (req.status == 200 || fileLoaded(req)) {
                  var config3 = JSON.parse(req.responseText);
                  kc2.authServerUrl = config3["auth-server-url"];
                  kc2.realm = config3["realm"];
                  kc2.clientId = config3["resource"];
                  setupOidcEndoints(null);
                  promise.setSuccess();
                } else {
                  promise.setError();
                }
              }
            };
            req.send();
          } else {
            if (!config2.clientId) {
              throw "clientId missing";
            }
            kc2.clientId = config2.clientId;
            var oidcProvider = config2["oidcProvider"];
            if (!oidcProvider) {
              if (!config2["url"]) {
                var scripts2 = document.getElementsByTagName("script");
                for (var i4 = 0; i4 < scripts2.length; i4++) {
                  if (scripts2[i4].src.match(/.*keycloak\.js/)) {
                    config2.url = scripts2[i4].src.substr(0, scripts2[i4].src.indexOf("/js/keycloak.js"));
                    break;
                  }
                }
              }
              if (!config2.realm) {
                throw "realm missing";
              }
              kc2.authServerUrl = config2.url;
              kc2.realm = config2.realm;
              setupOidcEndoints(null);
              promise.setSuccess();
            } else {
              if (typeof oidcProvider === "string") {
                var oidcProviderConfigUrl;
                if (oidcProvider.charAt(oidcProvider.length - 1) == "/") {
                  oidcProviderConfigUrl = oidcProvider + ".well-known/openid-configuration";
                } else {
                  oidcProviderConfigUrl = oidcProvider + "/.well-known/openid-configuration";
                }
                var req = new XMLHttpRequest();
                req.open("GET", oidcProviderConfigUrl, true);
                req.setRequestHeader("Accept", "application/json");
                req.onreadystatechange = function() {
                  if (req.readyState == 4) {
                    if (req.status == 200 || fileLoaded(req)) {
                      var oidcProviderConfig = JSON.parse(req.responseText);
                      setupOidcEndoints(oidcProviderConfig);
                      promise.setSuccess();
                    } else {
                      promise.setError();
                    }
                  }
                };
                req.send();
              } else {
                setupOidcEndoints(oidcProvider);
                promise.setSuccess();
              }
            }
          }
          return promise.promise;
        }
        function fileLoaded(xhr2) {
          return xhr2.status == 0 && xhr2.responseText && xhr2.responseURL.startsWith("file:");
        }
        function setToken(token2, refreshToken, idToken, timeLocal) {
          if (kc2.tokenTimeoutHandle) {
            clearTimeout(kc2.tokenTimeoutHandle);
            kc2.tokenTimeoutHandle = null;
          }
          if (refreshToken) {
            kc2.refreshToken = refreshToken;
            kc2.refreshTokenParsed = decodeToken(refreshToken);
          } else {
            delete kc2.refreshToken;
            delete kc2.refreshTokenParsed;
          }
          if (idToken) {
            kc2.idToken = idToken;
            kc2.idTokenParsed = decodeToken(idToken);
          } else {
            delete kc2.idToken;
            delete kc2.idTokenParsed;
          }
          if (token2) {
            kc2.token = token2;
            kc2.tokenParsed = decodeToken(token2);
            kc2.sessionId = kc2.tokenParsed.session_state;
            kc2.authenticated = true;
            kc2.subject = kc2.tokenParsed.sub;
            kc2.realmAccess = kc2.tokenParsed.realm_access;
            kc2.resourceAccess = kc2.tokenParsed.resource_access;
            if (timeLocal) {
              kc2.timeSkew = Math.floor(timeLocal / 1e3) - kc2.tokenParsed.iat;
            }
            if (kc2.timeSkew != null) {
              logInfo("[KEYCLOAK] Estimated time difference between browser and server is " + kc2.timeSkew + " seconds");
              if (kc2.onTokenExpired) {
                var expiresIn = (kc2.tokenParsed["exp"] - new Date().getTime() / 1e3 + kc2.timeSkew) * 1e3;
                logInfo("[KEYCLOAK] Token expires in " + Math.round(expiresIn / 1e3) + " s");
                if (expiresIn <= 0) {
                  kc2.onTokenExpired();
                } else {
                  kc2.tokenTimeoutHandle = setTimeout(kc2.onTokenExpired, expiresIn);
                }
              }
            }
          } else {
            delete kc2.token;
            delete kc2.tokenParsed;
            delete kc2.subject;
            delete kc2.realmAccess;
            delete kc2.resourceAccess;
            kc2.authenticated = false;
          }
        }
        function decodeToken(str) {
          str = str.split(".")[1];
          str = str.replace(/-/g, "+");
          str = str.replace(/_/g, "/");
          switch (str.length % 4) {
            case 0:
              break;
            case 2:
              str += "==";
              break;
            case 3:
              str += "=";
              break;
            default:
              throw "Invalid token";
          }
          str = decodeURIComponent(escape(atob(str)));
          str = JSON.parse(str);
          return str;
        }
        function createUUID() {
          var hexDigits = "0123456789abcdef";
          var s2 = generateRandomString(36, hexDigits).split("");
          s2[14] = "4";
          s2[19] = hexDigits.substr(s2[19] & 3 | 8, 1);
          s2[8] = s2[13] = s2[18] = s2[23] = "-";
          var uuid = s2.join("");
          return uuid;
        }
        function parseCallback(url) {
          var oauth = parseCallbackUrl(url);
          if (!oauth) {
            return;
          }
          var oauthState = callbackStorage.get(oauth.state);
          if (oauthState) {
            oauth.valid = true;
            oauth.redirectUri = oauthState.redirectUri;
            oauth.storedNonce = oauthState.nonce;
            oauth.prompt = oauthState.prompt;
            oauth.pkceCodeVerifier = oauthState.pkceCodeVerifier;
          }
          return oauth;
        }
        function parseCallbackUrl(url) {
          var supportedParams;
          switch (kc2.flow) {
            case "standard":
              supportedParams = ["code", "state", "session_state", "kc_action_status"];
              break;
            case "implicit":
              supportedParams = ["access_token", "token_type", "id_token", "state", "session_state", "expires_in", "kc_action_status"];
              break;
            case "hybrid":
              supportedParams = ["access_token", "token_type", "id_token", "code", "state", "session_state", "expires_in", "kc_action_status"];
              break;
          }
          supportedParams.push("error");
          supportedParams.push("error_description");
          supportedParams.push("error_uri");
          var queryIndex = url.indexOf("?");
          var fragmentIndex = url.indexOf("#");
          var newUrl;
          var parsed;
          if (kc2.responseMode === "query" && queryIndex !== -1) {
            newUrl = url.substring(0, queryIndex);
            parsed = parseCallbackParams(url.substring(queryIndex + 1, fragmentIndex !== -1 ? fragmentIndex : url.length), supportedParams);
            if (parsed.paramsString !== "") {
              newUrl += "?" + parsed.paramsString;
            }
            if (fragmentIndex !== -1) {
              newUrl += url.substring(fragmentIndex);
            }
          } else if (kc2.responseMode === "fragment" && fragmentIndex !== -1) {
            newUrl = url.substring(0, fragmentIndex);
            parsed = parseCallbackParams(url.substring(fragmentIndex + 1), supportedParams);
            if (parsed.paramsString !== "") {
              newUrl += "#" + parsed.paramsString;
            }
          }
          if (parsed && parsed.oauthParams) {
            if (kc2.flow === "standard" || kc2.flow === "hybrid") {
              if ((parsed.oauthParams.code || parsed.oauthParams.error) && parsed.oauthParams.state) {
                parsed.oauthParams.newUrl = newUrl;
                return parsed.oauthParams;
              }
            } else if (kc2.flow === "implicit") {
              if ((parsed.oauthParams.access_token || parsed.oauthParams.error) && parsed.oauthParams.state) {
                parsed.oauthParams.newUrl = newUrl;
                return parsed.oauthParams;
              }
            }
          }
        }
        function parseCallbackParams(paramsString, supportedParams) {
          var p2 = paramsString.split("&");
          var result = {
            paramsString: "",
            oauthParams: {}
          };
          for (var i4 = 0; i4 < p2.length; i4++) {
            var split2 = p2[i4].indexOf("=");
            var key = p2[i4].slice(0, split2);
            if (supportedParams.indexOf(key) !== -1) {
              result.oauthParams[key] = p2[i4].slice(split2 + 1);
            } else {
              if (result.paramsString !== "") {
                result.paramsString += "&";
              }
              result.paramsString += p2[i4];
            }
          }
          return result;
        }
        function createPromise() {
          var p2 = {
            setSuccess: function(result) {
              p2.resolve(result);
            },
            setError: function(result) {
              p2.reject(result);
            }
          };
          p2.promise = new Promise(function(resolve2, reject) {
            p2.resolve = resolve2;
            p2.reject = reject;
          });
          p2.promise.success = function(callback) {
            logPromiseDeprecation();
            this.then(function handleSuccess(value) {
              callback(value);
            });
            return this;
          };
          p2.promise.error = function(callback) {
            logPromiseDeprecation();
            this.catch(function handleError(error2) {
              callback(error2);
            });
            return this;
          };
          return p2;
        }
        function applyTimeoutToPromise(promise, timeout3, errorMessage) {
          var timeoutHandle = null;
          var timeoutPromise = new Promise(function(resolve2, reject) {
            timeoutHandle = setTimeout(function() {
              reject({error: errorMessage || "Promise is not settled within timeout of " + timeout3 + "ms"});
            }, timeout3);
          });
          return Promise.race([promise, timeoutPromise]).finally(function() {
            clearTimeout(timeoutHandle);
          });
        }
        function setupCheckLoginIframe() {
          var promise = createPromise();
          if (!loginIframe.enable) {
            promise.setSuccess();
            return promise.promise;
          }
          if (loginIframe.iframe) {
            promise.setSuccess();
            return promise.promise;
          }
          var iframe = document.createElement("iframe");
          loginIframe.iframe = iframe;
          iframe.onload = function() {
            var authUrl = kc2.endpoints.authorize();
            if (authUrl.charAt(0) === "/") {
              loginIframe.iframeOrigin = getOrigin();
            } else {
              loginIframe.iframeOrigin = authUrl.substring(0, authUrl.indexOf("/", 8));
            }
            promise.setSuccess();
          };
          var src = kc2.endpoints.checkSessionIframe();
          iframe.setAttribute("src", src);
          iframe.setAttribute("title", "keycloak-session-iframe");
          iframe.style.display = "none";
          document.body.appendChild(iframe);
          var messageCallback = function(event) {
            if (event.origin !== loginIframe.iframeOrigin || loginIframe.iframe.contentWindow !== event.source) {
              return;
            }
            if (!(event.data == "unchanged" || event.data == "changed" || event.data == "error")) {
              return;
            }
            if (event.data != "unchanged") {
              kc2.clearToken();
            }
            var callbacks = loginIframe.callbackList.splice(0, loginIframe.callbackList.length);
            for (var i4 = callbacks.length - 1; i4 >= 0; --i4) {
              var promise2 = callbacks[i4];
              if (event.data == "error") {
                promise2.setError();
              } else {
                promise2.setSuccess(event.data == "unchanged");
              }
            }
          };
          window.addEventListener("message", messageCallback, false);
          return promise.promise;
        }
        function scheduleCheckIframe() {
          if (loginIframe.enable) {
            if (kc2.token) {
              setTimeout(function() {
                checkLoginIframe().then(function(unchanged) {
                  if (unchanged) {
                    scheduleCheckIframe();
                  }
                });
              }, loginIframe.interval * 1e3);
            }
          }
        }
        function checkLoginIframe() {
          var promise = createPromise();
          if (loginIframe.iframe && loginIframe.iframeOrigin) {
            var msg = kc2.clientId + " " + (kc2.sessionId ? kc2.sessionId : "");
            loginIframe.callbackList.push(promise);
            var origin = loginIframe.iframeOrigin;
            if (loginIframe.callbackList.length == 1) {
              loginIframe.iframe.contentWindow.postMessage(msg, origin);
            }
          } else {
            promise.setSuccess();
          }
          return promise.promise;
        }
        function check3pCookiesSupported() {
          var promise = createPromise();
          if (loginIframe.enable || kc2.silentCheckSsoRedirectUri) {
            var iframe = document.createElement("iframe");
            iframe.setAttribute("src", kc2.endpoints.thirdPartyCookiesIframe());
            iframe.setAttribute("title", "keycloak-3p-check-iframe");
            iframe.style.display = "none";
            document.body.appendChild(iframe);
            var messageCallback = function(event) {
              if (iframe.contentWindow !== event.source) {
                return;
              }
              if (event.data !== "supported" && event.data !== "unsupported") {
                return;
              } else if (event.data === "unsupported") {
                loginIframe.enable = false;
                if (kc2.silentCheckSsoFallback) {
                  kc2.silentCheckSsoRedirectUri = false;
                }
                logWarn("[KEYCLOAK] 3rd party cookies aren't supported by this browser. checkLoginIframe and silent check-sso are not available.");
              }
              document.body.removeChild(iframe);
              window.removeEventListener("message", messageCallback);
              promise.setSuccess();
            };
            window.addEventListener("message", messageCallback, false);
          } else {
            promise.setSuccess();
          }
          return applyTimeoutToPromise(promise.promise, kc2.messageReceiveTimeout, "Timeout when waiting for 3rd party check iframe message.");
        }
        function loadAdapter(type) {
          if (!type || type == "default") {
            return {
              login: function(options) {
                window.location.replace(kc2.createLoginUrl(options));
                return createPromise().promise;
              },
              logout: function(options) {
                window.location.replace(kc2.createLogoutUrl(options));
                return createPromise().promise;
              },
              register: function(options) {
                window.location.replace(kc2.createRegisterUrl(options));
                return createPromise().promise;
              },
              accountManagement: function() {
                var accountUrl = kc2.createAccountUrl();
                if (typeof accountUrl !== "undefined") {
                  window.location.href = accountUrl;
                } else {
                  throw "Not supported by the OIDC server";
                }
                return createPromise().promise;
              },
              redirectUri: function(options, encodeHash) {
                if (options && options.redirectUri) {
                  return options.redirectUri;
                } else if (kc2.redirectUri) {
                  return kc2.redirectUri;
                } else {
                  return location.href;
                }
              }
            };
          }
          if (type == "cordova") {
            loginIframe.enable = false;
            var cordovaOpenWindowWrapper = function(loginUrl, target, options) {
              if (window.cordova && window.cordova.InAppBrowser) {
                return window.cordova.InAppBrowser.open(loginUrl, target, options);
              } else {
                return window.open(loginUrl, target, options);
              }
            };
            var shallowCloneCordovaOptions = function(userOptions) {
              if (userOptions && userOptions.cordovaOptions) {
                return Object.keys(userOptions.cordovaOptions).reduce(function(options, optionName) {
                  options[optionName] = userOptions.cordovaOptions[optionName];
                  return options;
                }, {});
              } else {
                return {};
              }
            };
            var formatCordovaOptions = function(cordovaOptions) {
              return Object.keys(cordovaOptions).reduce(function(options, optionName) {
                options.push(optionName + "=" + cordovaOptions[optionName]);
                return options;
              }, []).join(",");
            };
            var createCordovaOptions = function(userOptions) {
              var cordovaOptions = shallowCloneCordovaOptions(userOptions);
              cordovaOptions.location = "no";
              if (userOptions && userOptions.prompt == "none") {
                cordovaOptions.hidden = "yes";
              }
              return formatCordovaOptions(cordovaOptions);
            };
            return {
              login: function(options) {
                var promise = createPromise();
                var cordovaOptions = createCordovaOptions(options);
                var loginUrl = kc2.createLoginUrl(options);
                var ref = cordovaOpenWindowWrapper(loginUrl, "_blank", cordovaOptions);
                var completed = false;
                var closed = false;
                var closeBrowser = function() {
                  closed = true;
                  ref.close();
                };
                ref.addEventListener("loadstart", function(event) {
                  if (event.url.indexOf("http://localhost") == 0) {
                    var callback = parseCallback(event.url);
                    processCallback(callback, promise);
                    closeBrowser();
                    completed = true;
                  }
                });
                ref.addEventListener("loaderror", function(event) {
                  if (!completed) {
                    if (event.url.indexOf("http://localhost") == 0) {
                      var callback = parseCallback(event.url);
                      processCallback(callback, promise);
                      closeBrowser();
                      completed = true;
                    } else {
                      promise.setError();
                      closeBrowser();
                    }
                  }
                });
                ref.addEventListener("exit", function(event) {
                  if (!closed) {
                    promise.setError({
                      reason: "closed_by_user"
                    });
                  }
                });
                return promise.promise;
              },
              logout: function(options) {
                var promise = createPromise();
                var logoutUrl = kc2.createLogoutUrl(options);
                var ref = cordovaOpenWindowWrapper(logoutUrl, "_blank", "location=no,hidden=yes");
                var error2;
                ref.addEventListener("loadstart", function(event) {
                  if (event.url.indexOf("http://localhost") == 0) {
                    ref.close();
                  }
                });
                ref.addEventListener("loaderror", function(event) {
                  if (event.url.indexOf("http://localhost") == 0) {
                    ref.close();
                  } else {
                    error2 = true;
                    ref.close();
                  }
                });
                ref.addEventListener("exit", function(event) {
                  if (error2) {
                    promise.setError();
                  } else {
                    kc2.clearToken();
                    promise.setSuccess();
                  }
                });
                return promise.promise;
              },
              register: function(options) {
                var promise = createPromise();
                var registerUrl = kc2.createRegisterUrl();
                var cordovaOptions = createCordovaOptions(options);
                var ref = cordovaOpenWindowWrapper(registerUrl, "_blank", cordovaOptions);
                ref.addEventListener("loadstart", function(event) {
                  if (event.url.indexOf("http://localhost") == 0) {
                    ref.close();
                    var oauth = parseCallback(event.url);
                    processCallback(oauth, promise);
                  }
                });
                return promise.promise;
              },
              accountManagement: function() {
                var accountUrl = kc2.createAccountUrl();
                if (typeof accountUrl !== "undefined") {
                  var ref = cordovaOpenWindowWrapper(accountUrl, "_blank", "location=no");
                  ref.addEventListener("loadstart", function(event) {
                    if (event.url.indexOf("http://localhost") == 0) {
                      ref.close();
                    }
                  });
                } else {
                  throw "Not supported by the OIDC server";
                }
              },
              redirectUri: function(options) {
                return "http://localhost";
              }
            };
          }
          if (type == "cordova-native") {
            loginIframe.enable = false;
            return {
              login: function(options) {
                var promise = createPromise();
                var loginUrl = kc2.createLoginUrl(options);
                universalLinks.subscribe("keycloak", function(event) {
                  universalLinks.unsubscribe("keycloak");
                  window.cordova.plugins.browsertab.close();
                  var oauth = parseCallback(event.url);
                  processCallback(oauth, promise);
                });
                window.cordova.plugins.browsertab.openUrl(loginUrl);
                return promise.promise;
              },
              logout: function(options) {
                var promise = createPromise();
                var logoutUrl = kc2.createLogoutUrl(options);
                universalLinks.subscribe("keycloak", function(event) {
                  universalLinks.unsubscribe("keycloak");
                  window.cordova.plugins.browsertab.close();
                  kc2.clearToken();
                  promise.setSuccess();
                });
                window.cordova.plugins.browsertab.openUrl(logoutUrl);
                return promise.promise;
              },
              register: function(options) {
                var promise = createPromise();
                var registerUrl = kc2.createRegisterUrl(options);
                universalLinks.subscribe("keycloak", function(event) {
                  universalLinks.unsubscribe("keycloak");
                  window.cordova.plugins.browsertab.close();
                  var oauth = parseCallback(event.url);
                  processCallback(oauth, promise);
                });
                window.cordova.plugins.browsertab.openUrl(registerUrl);
                return promise.promise;
              },
              accountManagement: function() {
                var accountUrl = kc2.createAccountUrl();
                if (typeof accountUrl !== "undefined") {
                  window.cordova.plugins.browsertab.openUrl(accountUrl);
                } else {
                  throw "Not supported by the OIDC server";
                }
              },
              redirectUri: function(options) {
                if (options && options.redirectUri) {
                  return options.redirectUri;
                } else if (kc2.redirectUri) {
                  return kc2.redirectUri;
                } else {
                  return "http://localhost";
                }
              }
            };
          }
          throw "invalid adapter type: " + type;
        }
        var LocalStorage = function() {
          if (!(this instanceof LocalStorage)) {
            return new LocalStorage();
          }
          localStorage.setItem("kc-test", "test");
          localStorage.removeItem("kc-test");
          var cs = this;
          function clearExpired() {
            var time2 = new Date().getTime();
            for (var i4 = 0; i4 < localStorage.length; i4++) {
              var key = localStorage.key(i4);
              if (key && key.indexOf("kc-callback-") == 0) {
                var value = localStorage.getItem(key);
                if (value) {
                  try {
                    var expires2 = JSON.parse(value).expires;
                    if (!expires2 || expires2 < time2) {
                      localStorage.removeItem(key);
                    }
                  } catch (err) {
                    localStorage.removeItem(key);
                  }
                }
              }
            }
          }
          cs.get = function(state) {
            if (!state) {
              return;
            }
            var key = "kc-callback-" + state;
            var value = localStorage.getItem(key);
            if (value) {
              localStorage.removeItem(key);
              value = JSON.parse(value);
            }
            clearExpired();
            return value;
          };
          cs.add = function(state) {
            clearExpired();
            var key = "kc-callback-" + state.state;
            state.expires = new Date().getTime() + 60 * 60 * 1e3;
            localStorage.setItem(key, JSON.stringify(state));
          };
        };
        var CookieStorage = function() {
          if (!(this instanceof CookieStorage)) {
            return new CookieStorage();
          }
          var cs = this;
          cs.get = function(state) {
            if (!state) {
              return;
            }
            var value = getCookie("kc-callback-" + state);
            setCookie("kc-callback-" + state, "", cookieExpiration(-100));
            if (value) {
              return JSON.parse(value);
            }
          };
          cs.add = function(state) {
            setCookie("kc-callback-" + state.state, JSON.stringify(state), cookieExpiration(60));
          };
          cs.removeItem = function(key) {
            setCookie(key, "", cookieExpiration(-100));
          };
          var cookieExpiration = function(minutes) {
            var exp = new Date();
            exp.setTime(exp.getTime() + minutes * 60 * 1e3);
            return exp;
          };
          var getCookie = function(key) {
            var name = key + "=";
            var ca2 = document.cookie.split(";");
            for (var i4 = 0; i4 < ca2.length; i4++) {
              var c3 = ca2[i4];
              while (c3.charAt(0) == " ") {
                c3 = c3.substring(1);
              }
              if (c3.indexOf(name) == 0) {
                return c3.substring(name.length, c3.length);
              }
            }
            return "";
          };
          var setCookie = function(key, value, expirationDate) {
            var cookie = key + "=" + value + "; expires=" + expirationDate.toUTCString() + "; ";
            document.cookie = cookie;
          };
        };
        function createCallbackStorage() {
          try {
            return new LocalStorage();
          } catch (err) {
          }
          return new CookieStorage();
        }
        function createLogger(fn) {
          return function() {
            if (kc2.enableLogging) {
              fn.apply(console, Array.prototype.slice.call(arguments));
            }
          };
        }
      }
      return Keycloak;
    });
  });
  var client = createCommonjsModule(function(module2, exports2) {
    var __createBinding = commonjsGlobal && commonjsGlobal.__createBinding || (Object.create ? function(o, m2, k2, k22) {
      if (k22 === void 0)
        k22 = k2;
      Object.defineProperty(o, k22, {enumerable: true, get: function() {
        return m2[k2];
      }});
    } : function(o, m2, k2, k22) {
      if (k22 === void 0)
        k22 = k2;
      o[k22] = m2[k2];
    });
    var __setModuleDefault = commonjsGlobal && commonjsGlobal.__setModuleDefault || (Object.create ? function(o, v2) {
      Object.defineProperty(o, "default", {enumerable: true, value: v2});
    } : function(o, v2) {
      o["default"] = v2;
    });
    var __importStar = commonjsGlobal && commonjsGlobal.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k2 in mod)
          if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2))
            __createBinding(result, mod, k2);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    var __awaiter3 = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P2, generator) {
      function adopt(value) {
        return value instanceof P2 ? value : new P2(function(resolve2) {
          resolve2(value);
        });
      }
      return new (P2 || (P2 = Promise))(function(resolve2, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e2) {
            reject(e2);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e2) {
            reject(e2);
          }
        }
        function step(result) {
          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __generator2 = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
      var _23 = {label: 0, sent: function() {
        if (t5[0] & 1)
          throw t5[1];
        return t5[1];
      }, trys: [], ops: []}, f2, y3, t5, g2;
      return g2 = {next: verb(0), throw: verb(1), return: verb(2)}, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
        return this;
      }), g2;
      function verb(n3) {
        return function(v2) {
          return step([n3, v2]);
        };
      }
      function step(op) {
        if (f2)
          throw new TypeError("Generator is already executing.");
        while (_23)
          try {
            if (f2 = 1, y3 && (t5 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t5 = y3["return"]) && t5.call(y3), 0) : y3.next) && !(t5 = t5.call(y3, op[1])).done)
              return t5;
            if (y3 = 0, t5)
              op = [op[0] & 2, t5.value];
            switch (op[0]) {
              case 0:
              case 1:
                t5 = op;
                break;
              case 4:
                _23.label++;
                return {value: op[1], done: false};
              case 5:
                _23.label++;
                y3 = op[1];
                op = [0];
                continue;
              case 7:
                op = _23.ops.pop();
                _23.trys.pop();
                continue;
              default:
                if (!(t5 = _23.trys, t5 = t5.length > 0 && t5[t5.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                  _23 = 0;
                  continue;
                }
                if (op[0] === 3 && (!t5 || op[1] > t5[0] && op[1] < t5[3])) {
                  _23.label = op[1];
                  break;
                }
                if (op[0] === 6 && _23.label < t5[1]) {
                  _23.label = t5[1];
                  t5 = op;
                  break;
                }
                if (t5 && _23.label < t5[2]) {
                  _23.label = t5[2];
                  _23.ops.push(op);
                  break;
                }
                if (t5[2])
                  _23.ops.pop();
                _23.trys.pop();
                continue;
            }
            op = body.call(thisArg, _23);
          } catch (e2) {
            op = [6, e2];
            y3 = 0;
          } finally {
            f2 = t5 = 0;
          }
        if (op[0] & 5)
          throw op[1];
        return {value: op[0] ? op[1] : void 0, done: true};
      }
    };
    exports2.__esModule = true;
    exports2.KeycloakAdminClient = void 0;
    var KeycloakAdminClient = function() {
      function KeycloakAdminClient2(connectionConfig) {
        this.baseUrl = connectionConfig && connectionConfig.baseUrl || constants.defaultBaseUrl;
        this.realmName = connectionConfig && connectionConfig.realmName || constants.defaultRealm;
        this.requestConfig = connectionConfig && connectionConfig.requestConfig;
        this.users = new users.Users(this);
        this.userStorageProvider = new userStorageProvider.UserStorageProvider(this);
        this.groups = new groups.Groups(this);
        this.roles = new roles.Roles(this);
        this.clients = new clients.Clients(this);
        this.realms = new realms.Realms(this);
        this.clientScopes = new clientScopes.ClientScopes(this);
        this.clientPolicies = new clientPolicies.ClientPolicies(this);
        this.identityProviders = new identityProviders.IdentityProviders(this);
        this.components = new components.Components(this);
        this.authenticationManagement = new authenticationManagement.AuthenticationManagement(this);
        this.serverInfo = new serverInfo.ServerInfo(this);
        this.whoAmI = new whoAmI.WhoAmI(this);
        this.sessions = new sessions.Sessions(this);
        this.attackDetection = new attackDetection.AttackDetection(this);
        this.cache = new cache.Cache(this);
      }
      KeycloakAdminClient2.prototype.auth = function(credentials) {
        return __awaiter3(this, void 0, void 0, function() {
          var _a, accessToken, refreshToken;
          return __generator2(this, function(_b) {
            switch (_b.label) {
              case 0:
                return [4, (0, auth.getToken)({
                  baseUrl: this.baseUrl,
                  realmName: this.realmName,
                  credentials,
                  requestConfig: this.requestConfig
                })];
              case 1:
                _a = _b.sent(), accessToken = _a.accessToken, refreshToken = _a.refreshToken;
                this.accessToken = accessToken;
                this.refreshToken = refreshToken;
                return [2];
            }
          });
        });
      };
      KeycloakAdminClient2.prototype.init = function(init4, config2) {
        return __awaiter3(this, void 0, void 0, function() {
          var Keycloak;
          return __generator2(this, function(_a) {
            switch (_a.label) {
              case 0:
                if (typeof window === "undefined") {
                  return [2];
                }
                return [4, Promise.resolve().then(function() {
                  return __importStar(keycloak);
                })];
              case 1:
                Keycloak = _a.sent()["default"];
                this.keycloak = Keycloak(config2);
                if (!init4)
                  return [3, 3];
                return [4, this.keycloak.init(init4)];
              case 2:
                _a.sent();
                _a.label = 3;
              case 3:
                if (this.keycloak.authServerUrl) {
                  this.baseUrl = this.keycloak.authServerUrl;
                }
                return [2];
            }
          });
        });
      };
      KeycloakAdminClient2.prototype.setAccessToken = function(token2) {
        this.accessToken = token2;
      };
      KeycloakAdminClient2.prototype.getAccessToken = function() {
        return __awaiter3(this, void 0, void 0, function() {
          return __generator2(this, function(_a) {
            switch (_a.label) {
              case 0:
                if (!this.keycloak)
                  return [3, 5];
                _a.label = 1;
              case 1:
                _a.trys.push([1, 3, , 4]);
                return [4, this.keycloak.updateToken(5)];
              case 2:
                _a.sent();
                return [3, 4];
              case 3:
                _a.sent();
                this.keycloak.login();
                return [3, 4];
              case 4:
                return [2, this.keycloak.token];
              case 5:
                return [2, this.accessToken];
            }
          });
        });
      };
      KeycloakAdminClient2.prototype.getRequestConfig = function() {
        return this.requestConfig;
      };
      KeycloakAdminClient2.prototype.setConfig = function(connectionConfig) {
        if (typeof connectionConfig.baseUrl === "string" && connectionConfig.baseUrl) {
          this.baseUrl = connectionConfig.baseUrl;
        }
        if (typeof connectionConfig.realmName === "string" && connectionConfig.realmName) {
          this.realmName = connectionConfig.realmName;
        }
        this.requestConfig = connectionConfig.requestConfig;
      };
      return KeycloakAdminClient2;
    }();
    exports2.KeycloakAdminClient = KeycloakAdminClient;
  });
  var lib = createCommonjsModule(function(module2, exports2) {
    exports2.__esModule = true;
    exports2.requiredAction = void 0;
    exports2.requiredAction = requiredActionProviderRepresentation.RequiredActionAlias;
    exports2["default"] = client.KeycloakAdminClient;
  });
  var __pika_web_default_export_for_treeshaking__ = /* @__PURE__ */ getDefaultExportFromCjs(lib);
  var keycloak_admin_client_default = __pika_web_default_export_for_treeshaking__;
});

// build/_snowpack/env.js
var env_exports = {};
__export(env_exports, {
  MODE: () => MODE,
  NODE_ENV: () => NODE_ENV,
  SSR: () => SSR
});
var MODE = "production";
var NODE_ENV = "production";
var SSR = false;

// build/_snowpack/pkg/common/_commonjsHelpers-4f955397.js
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs(x2) {
  return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
}
function createCommonjsModule(fn, basedir, module2) {
  return module2 = {
    path: basedir,
    exports: {},
    require: function(path, base) {
      return commonjsRequire(path, base === void 0 || base === null ? module2.path : base);
    }
  }, fn(module2, module2.exports), module2.exports;
}
function commonjsRequire() {
  throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");
}

// build/_snowpack/pkg/common/index-7cda8b13.js
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
  if (val === null || val === void 0) {
    throw new TypeError("Object.assign cannot be called with null or undefined");
  }
  return Object(val);
}
function shouldUseNative() {
  try {
    if (!Object.assign) {
      return false;
    }
    var test1 = new String("abc");
    test1[5] = "de";
    if (Object.getOwnPropertyNames(test1)[0] === "5") {
      return false;
    }
    var test2 = {};
    for (var i3 = 0; i3 < 10; i3++) {
      test2["_" + String.fromCharCode(i3)] = i3;
    }
    var order22 = Object.getOwnPropertyNames(test2).map(function(n3) {
      return test2[n3];
    });
    if (order22.join("") !== "0123456789") {
      return false;
    }
    var test3 = {};
    "abcdefghijklmnopqrst".split("").forEach(function(letter) {
      test3[letter] = letter;
    });
    if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
      return false;
    }
    return true;
  } catch (err) {
    return false;
  }
}
var objectAssign = shouldUseNative() ? Object.assign : function(target, source2) {
  var from;
  var to = toObject(target);
  var symbols;
  for (var s2 = 1; s2 < arguments.length; s2++) {
    from = Object(arguments[s2]);
    for (var key in from) {
      if (hasOwnProperty.call(from, key)) {
        to[key] = from[key];
      }
    }
    if (getOwnPropertySymbols) {
      symbols = getOwnPropertySymbols(from);
      for (var i3 = 0; i3 < symbols.length; i3++) {
        if (propIsEnumerable.call(from, symbols[i3])) {
          to[symbols[i3]] = from[symbols[i3]];
        }
      }
    }
  }
  return to;
};
var react_production_min = createCommonjsModule(function(module2, exports2) {
  var n3 = 60103, p2 = 60106;
  exports2.Fragment = 60107;
  exports2.StrictMode = 60108;
  exports2.Profiler = 60114;
  var q2 = 60109, r3 = 60110, t5 = 60112;
  exports2.Suspense = 60113;
  var u = 60115, v2 = 60116;
  if (typeof Symbol === "function" && Symbol.for) {
    var w2 = Symbol.for;
    n3 = w2("react.element");
    p2 = w2("react.portal");
    exports2.Fragment = w2("react.fragment");
    exports2.StrictMode = w2("react.strict_mode");
    exports2.Profiler = w2("react.profiler");
    q2 = w2("react.provider");
    r3 = w2("react.context");
    t5 = w2("react.forward_ref");
    exports2.Suspense = w2("react.suspense");
    u = w2("react.memo");
    v2 = w2("react.lazy");
  }
  var x2 = typeof Symbol === "function" && Symbol.iterator;
  function y3(a2) {
    if (a2 === null || typeof a2 !== "object")
      return null;
    a2 = x2 && a2[x2] || a2["@@iterator"];
    return typeof a2 === "function" ? a2 : null;
  }
  function z2(a2) {
    for (var b2 = "https://reactjs.org/docs/error-decoder.html?invariant=" + a2, c3 = 1; c3 < arguments.length; c3++)
      b2 += "&args[]=" + encodeURIComponent(arguments[c3]);
    return "Minified React error #" + a2 + "; visit " + b2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
  }
  var A2 = {isMounted: function() {
    return false;
  }, enqueueForceUpdate: function() {
  }, enqueueReplaceState: function() {
  }, enqueueSetState: function() {
  }}, B2 = {};
  function C(a2, b2, c3) {
    this.props = a2;
    this.context = b2;
    this.refs = B2;
    this.updater = c3 || A2;
  }
  C.prototype.isReactComponent = {};
  C.prototype.setState = function(a2, b2) {
    if (typeof a2 !== "object" && typeof a2 !== "function" && a2 != null)
      throw Error(z2(85));
    this.updater.enqueueSetState(this, a2, b2, "setState");
  };
  C.prototype.forceUpdate = function(a2) {
    this.updater.enqueueForceUpdate(this, a2, "forceUpdate");
  };
  function D2() {
  }
  D2.prototype = C.prototype;
  function E(a2, b2, c3) {
    this.props = a2;
    this.context = b2;
    this.refs = B2;
    this.updater = c3 || A2;
  }
  var F2 = E.prototype = new D2();
  F2.constructor = E;
  objectAssign(F2, C.prototype);
  F2.isPureReactComponent = true;
  var G2 = {current: null}, H2 = Object.prototype.hasOwnProperty, I2 = {key: true, ref: true, __self: true, __source: true};
  function J(a2, b2, c3) {
    var e2, d2 = {}, k2 = null, h2 = null;
    if (b2 != null)
      for (e2 in b2.ref !== void 0 && (h2 = b2.ref), b2.key !== void 0 && (k2 = "" + b2.key), b2)
        H2.call(b2, e2) && !I2.hasOwnProperty(e2) && (d2[e2] = b2[e2]);
    var g2 = arguments.length - 2;
    if (g2 === 1)
      d2.children = c3;
    else if (1 < g2) {
      for (var f2 = Array(g2), m2 = 0; m2 < g2; m2++)
        f2[m2] = arguments[m2 + 2];
      d2.children = f2;
    }
    if (a2 && a2.defaultProps)
      for (e2 in g2 = a2.defaultProps, g2)
        d2[e2] === void 0 && (d2[e2] = g2[e2]);
    return {$$typeof: n3, type: a2, key: k2, ref: h2, props: d2, _owner: G2.current};
  }
  function K(a2, b2) {
    return {$$typeof: n3, type: a2.type, key: b2, ref: a2.ref, props: a2.props, _owner: a2._owner};
  }
  function L(a2) {
    return typeof a2 === "object" && a2 !== null && a2.$$typeof === n3;
  }
  function escape4(a2) {
    var b2 = {"=": "=0", ":": "=2"};
    return "$" + a2.replace(/[=:]/g, function(a3) {
      return b2[a3];
    });
  }
  var M2 = /\/+/g;
  function N2(a2, b2) {
    return typeof a2 === "object" && a2 !== null && a2.key != null ? escape4("" + a2.key) : b2.toString(36);
  }
  function O2(a2, b2, c3, e2, d2) {
    var k2 = typeof a2;
    if (k2 === "undefined" || k2 === "boolean")
      a2 = null;
    var h2 = false;
    if (a2 === null)
      h2 = true;
    else
      switch (k2) {
        case "string":
        case "number":
          h2 = true;
          break;
        case "object":
          switch (a2.$$typeof) {
            case n3:
            case p2:
              h2 = true;
          }
      }
    if (h2)
      return h2 = a2, d2 = d2(h2), a2 = e2 === "" ? "." + N2(h2, 0) : e2, Array.isArray(d2) ? (c3 = "", a2 != null && (c3 = a2.replace(M2, "$&/") + "/"), O2(d2, b2, c3, "", function(a3) {
        return a3;
      })) : d2 != null && (L(d2) && (d2 = K(d2, c3 + (!d2.key || h2 && h2.key === d2.key ? "" : ("" + d2.key).replace(M2, "$&/") + "/") + a2)), b2.push(d2)), 1;
    h2 = 0;
    e2 = e2 === "" ? "." : e2 + ":";
    if (Array.isArray(a2))
      for (var g2 = 0; g2 < a2.length; g2++) {
        k2 = a2[g2];
        var f2 = e2 + N2(k2, g2);
        h2 += O2(k2, b2, c3, f2, d2);
      }
    else if (f2 = y3(a2), typeof f2 === "function")
      for (a2 = f2.call(a2), g2 = 0; !(k2 = a2.next()).done; )
        k2 = k2.value, f2 = e2 + N2(k2, g2++), h2 += O2(k2, b2, c3, f2, d2);
    else if (k2 === "object")
      throw b2 = "" + a2, Error(z2(31, b2 === "[object Object]" ? "object with keys {" + Object.keys(a2).join(", ") + "}" : b2));
    return h2;
  }
  function P2(a2, b2, c3) {
    if (a2 == null)
      return a2;
    var e2 = [], d2 = 0;
    O2(a2, e2, "", "", function(a3) {
      return b2.call(c3, a3, d2++);
    });
    return e2;
  }
  function Q(a2) {
    if (a2._status === -1) {
      var b2 = a2._result;
      b2 = b2();
      a2._status = 0;
      a2._result = b2;
      b2.then(function(b3) {
        a2._status === 0 && (b3 = b3.default, a2._status = 1, a2._result = b3);
      }, function(b3) {
        a2._status === 0 && (a2._status = 2, a2._result = b3);
      });
    }
    if (a2._status === 1)
      return a2._result;
    throw a2._result;
  }
  var R2 = {current: null};
  function S2() {
    var a2 = R2.current;
    if (a2 === null)
      throw Error(z2(321));
    return a2;
  }
  var T6 = {ReactCurrentDispatcher: R2, ReactCurrentBatchConfig: {transition: 0}, ReactCurrentOwner: G2, IsSomeRendererActing: {current: false}, assign: objectAssign};
  exports2.Children = {map: P2, forEach: function(a2, b2, c3) {
    P2(a2, function() {
      b2.apply(this, arguments);
    }, c3);
  }, count: function(a2) {
    var b2 = 0;
    P2(a2, function() {
      b2++;
    });
    return b2;
  }, toArray: function(a2) {
    return P2(a2, function(a3) {
      return a3;
    }) || [];
  }, only: function(a2) {
    if (!L(a2))
      throw Error(z2(143));
    return a2;
  }};
  exports2.Component = C;
  exports2.PureComponent = E;
  exports2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = T6;
  exports2.cloneElement = function(a2, b2, c3) {
    if (a2 === null || a2 === void 0)
      throw Error(z2(267, a2));
    var e2 = objectAssign({}, a2.props), d2 = a2.key, k2 = a2.ref, h2 = a2._owner;
    if (b2 != null) {
      b2.ref !== void 0 && (k2 = b2.ref, h2 = G2.current);
      b2.key !== void 0 && (d2 = "" + b2.key);
      if (a2.type && a2.type.defaultProps)
        var g2 = a2.type.defaultProps;
      for (f2 in b2)
        H2.call(b2, f2) && !I2.hasOwnProperty(f2) && (e2[f2] = b2[f2] === void 0 && g2 !== void 0 ? g2[f2] : b2[f2]);
    }
    var f2 = arguments.length - 2;
    if (f2 === 1)
      e2.children = c3;
    else if (1 < f2) {
      g2 = Array(f2);
      for (var m2 = 0; m2 < f2; m2++)
        g2[m2] = arguments[m2 + 2];
      e2.children = g2;
    }
    return {
      $$typeof: n3,
      type: a2.type,
      key: d2,
      ref: k2,
      props: e2,
      _owner: h2
    };
  };
  exports2.createContext = function(a2, b2) {
    b2 === void 0 && (b2 = null);
    a2 = {$$typeof: r3, _calculateChangedBits: b2, _currentValue: a2, _currentValue2: a2, _threadCount: 0, Provider: null, Consumer: null};
    a2.Provider = {$$typeof: q2, _context: a2};
    return a2.Consumer = a2;
  };
  exports2.createElement = J;
  exports2.createFactory = function(a2) {
    var b2 = J.bind(null, a2);
    b2.type = a2;
    return b2;
  };
  exports2.createRef = function() {
    return {current: null};
  };
  exports2.forwardRef = function(a2) {
    return {$$typeof: t5, render: a2};
  };
  exports2.isValidElement = L;
  exports2.lazy = function(a2) {
    return {$$typeof: v2, _payload: {_status: -1, _result: a2}, _init: Q};
  };
  exports2.memo = function(a2, b2) {
    return {$$typeof: u, type: a2, compare: b2 === void 0 ? null : b2};
  };
  exports2.useCallback = function(a2, b2) {
    return S2().useCallback(a2, b2);
  };
  exports2.useContext = function(a2, b2) {
    return S2().useContext(a2, b2);
  };
  exports2.useDebugValue = function() {
  };
  exports2.useEffect = function(a2, b2) {
    return S2().useEffect(a2, b2);
  };
  exports2.useImperativeHandle = function(a2, b2, c3) {
    return S2().useImperativeHandle(a2, b2, c3);
  };
  exports2.useLayoutEffect = function(a2, b2) {
    return S2().useLayoutEffect(a2, b2);
  };
  exports2.useMemo = function(a2, b2) {
    return S2().useMemo(a2, b2);
  };
  exports2.useReducer = function(a2, b2, c3) {
    return S2().useReducer(a2, b2, c3);
  };
  exports2.useRef = function(a2) {
    return S2().useRef(a2);
  };
  exports2.useState = function(a2) {
    return S2().useState(a2);
  };
  exports2.version = "17.0.2";
});
var react = createCommonjsModule(function(module2) {
  {
    module2.exports = react_production_min;
  }
});

// build/_snowpack/pkg/react.js
var Children = react.Children;
var Fragment = react.Fragment;
var StrictMode = react.StrictMode;
var Suspense = react.Suspense;
var cloneElement = react.cloneElement;
var createContext = react.createContext;
var isValidElement = react.isValidElement;
var lazy = react.lazy;
var memo = react.memo;
var useCallback = react.useCallback;
var useContext = react.useContext;
var useEffect = react.useEffect;
var useMemo = react.useMemo;
var useRef = react.useRef;
var useState = react.useState;

// build/_snowpack/pkg/common/index-916de6ed.js
var scheduler_production_min = createCommonjsModule(function(module2, exports2) {
  var f2, g2, h2, k2;
  if (typeof performance === "object" && typeof performance.now === "function") {
    var l2 = performance;
    exports2.unstable_now = function() {
      return l2.now();
    };
  } else {
    var p2 = Date, q2 = p2.now();
    exports2.unstable_now = function() {
      return p2.now() - q2;
    };
  }
  if (typeof window === "undefined" || typeof MessageChannel !== "function") {
    var t5 = null, u = null, w2 = function() {
      if (t5 !== null)
        try {
          var a2 = exports2.unstable_now();
          t5(true, a2);
          t5 = null;
        } catch (b2) {
          throw setTimeout(w2, 0), b2;
        }
    };
    f2 = function(a2) {
      t5 !== null ? setTimeout(f2, 0, a2) : (t5 = a2, setTimeout(w2, 0));
    };
    g2 = function(a2, b2) {
      u = setTimeout(a2, b2);
    };
    h2 = function() {
      clearTimeout(u);
    };
    exports2.unstable_shouldYield = function() {
      return false;
    };
    k2 = exports2.unstable_forceFrameRate = function() {
    };
  } else {
    var x2 = window.setTimeout, y3 = window.clearTimeout;
    if (typeof console !== "undefined") {
      var z2 = window.cancelAnimationFrame;
      typeof window.requestAnimationFrame !== "function" && console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills");
      typeof z2 !== "function" && console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills");
    }
    var A2 = false, B2 = null, C = -1, D2 = 5, E = 0;
    exports2.unstable_shouldYield = function() {
      return exports2.unstable_now() >= E;
    };
    k2 = function() {
    };
    exports2.unstable_forceFrameRate = function(a2) {
      0 > a2 || 125 < a2 ? console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported") : D2 = 0 < a2 ? Math.floor(1e3 / a2) : 5;
    };
    var F2 = new MessageChannel(), G2 = F2.port2;
    F2.port1.onmessage = function() {
      if (B2 !== null) {
        var a2 = exports2.unstable_now();
        E = a2 + D2;
        try {
          B2(true, a2) ? G2.postMessage(null) : (A2 = false, B2 = null);
        } catch (b2) {
          throw G2.postMessage(null), b2;
        }
      } else
        A2 = false;
    };
    f2 = function(a2) {
      B2 = a2;
      A2 || (A2 = true, G2.postMessage(null));
    };
    g2 = function(a2, b2) {
      C = x2(function() {
        a2(exports2.unstable_now());
      }, b2);
    };
    h2 = function() {
      y3(C);
      C = -1;
    };
  }
  function H2(a2, b2) {
    var c3 = a2.length;
    a2.push(b2);
    a:
      for (; ; ) {
        var d2 = c3 - 1 >>> 1, e2 = a2[d2];
        if (e2 !== void 0 && 0 < I2(e2, b2))
          a2[d2] = b2, a2[c3] = e2, c3 = d2;
        else
          break a;
      }
  }
  function J(a2) {
    a2 = a2[0];
    return a2 === void 0 ? null : a2;
  }
  function K(a2) {
    var b2 = a2[0];
    if (b2 !== void 0) {
      var c3 = a2.pop();
      if (c3 !== b2) {
        a2[0] = c3;
        a:
          for (var d2 = 0, e2 = a2.length; d2 < e2; ) {
            var m2 = 2 * (d2 + 1) - 1, n3 = a2[m2], v2 = m2 + 1, r3 = a2[v2];
            if (n3 !== void 0 && 0 > I2(n3, c3))
              r3 !== void 0 && 0 > I2(r3, n3) ? (a2[d2] = r3, a2[v2] = c3, d2 = v2) : (a2[d2] = n3, a2[m2] = c3, d2 = m2);
            else if (r3 !== void 0 && 0 > I2(r3, c3))
              a2[d2] = r3, a2[v2] = c3, d2 = v2;
            else
              break a;
          }
      }
      return b2;
    }
    return null;
  }
  function I2(a2, b2) {
    var c3 = a2.sortIndex - b2.sortIndex;
    return c3 !== 0 ? c3 : a2.id - b2.id;
  }
  var L = [], M2 = [], N2 = 1, O2 = null, P2 = 3, Q = false, R2 = false, S2 = false;
  function T6(a2) {
    for (var b2 = J(M2); b2 !== null; ) {
      if (b2.callback === null)
        K(M2);
      else if (b2.startTime <= a2)
        K(M2), b2.sortIndex = b2.expirationTime, H2(L, b2);
      else
        break;
      b2 = J(M2);
    }
  }
  function U2(a2) {
    S2 = false;
    T6(a2);
    if (!R2)
      if (J(L) !== null)
        R2 = true, f2(V2);
      else {
        var b2 = J(M2);
        b2 !== null && g2(U2, b2.startTime - a2);
      }
  }
  function V2(a2, b2) {
    R2 = false;
    S2 && (S2 = false, h2());
    Q = true;
    var c3 = P2;
    try {
      T6(b2);
      for (O2 = J(L); O2 !== null && (!(O2.expirationTime > b2) || a2 && !exports2.unstable_shouldYield()); ) {
        var d2 = O2.callback;
        if (typeof d2 === "function") {
          O2.callback = null;
          P2 = O2.priorityLevel;
          var e2 = d2(O2.expirationTime <= b2);
          b2 = exports2.unstable_now();
          typeof e2 === "function" ? O2.callback = e2 : O2 === J(L) && K(L);
          T6(b2);
        } else
          K(L);
        O2 = J(L);
      }
      if (O2 !== null)
        var m2 = true;
      else {
        var n3 = J(M2);
        n3 !== null && g2(U2, n3.startTime - b2);
        m2 = false;
      }
      return m2;
    } finally {
      O2 = null, P2 = c3, Q = false;
    }
  }
  var W2 = k2;
  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(a2) {
    a2.callback = null;
  };
  exports2.unstable_continueExecution = function() {
    R2 || Q || (R2 = true, f2(V2));
  };
  exports2.unstable_getCurrentPriorityLevel = function() {
    return P2;
  };
  exports2.unstable_getFirstCallbackNode = function() {
    return J(L);
  };
  exports2.unstable_next = function(a2) {
    switch (P2) {
      case 1:
      case 2:
      case 3:
        var b2 = 3;
        break;
      default:
        b2 = P2;
    }
    var c3 = P2;
    P2 = b2;
    try {
      return a2();
    } finally {
      P2 = c3;
    }
  };
  exports2.unstable_pauseExecution = function() {
  };
  exports2.unstable_requestPaint = W2;
  exports2.unstable_runWithPriority = function(a2, b2) {
    switch (a2) {
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
        break;
      default:
        a2 = 3;
    }
    var c3 = P2;
    P2 = a2;
    try {
      return b2();
    } finally {
      P2 = c3;
    }
  };
  exports2.unstable_scheduleCallback = function(a2, b2, c3) {
    var d2 = exports2.unstable_now();
    typeof c3 === "object" && c3 !== null ? (c3 = c3.delay, c3 = typeof c3 === "number" && 0 < c3 ? d2 + c3 : d2) : c3 = d2;
    switch (a2) {
      case 1:
        var e2 = -1;
        break;
      case 2:
        e2 = 250;
        break;
      case 5:
        e2 = 1073741823;
        break;
      case 4:
        e2 = 1e4;
        break;
      default:
        e2 = 5e3;
    }
    e2 = c3 + e2;
    a2 = {id: N2++, callback: b2, priorityLevel: a2, startTime: c3, expirationTime: e2, sortIndex: -1};
    c3 > d2 ? (a2.sortIndex = c3, H2(M2, a2), J(L) === null && a2 === J(M2) && (S2 ? h2() : S2 = true, g2(U2, c3 - d2))) : (a2.sortIndex = e2, H2(L, a2), R2 || Q || (R2 = true, f2(V2)));
    return a2;
  };
  exports2.unstable_wrapCallback = function(a2) {
    var b2 = P2;
    return function() {
      var c3 = P2;
      P2 = b2;
      try {
        return a2.apply(this, arguments);
      } finally {
        P2 = c3;
      }
    };
  };
});
var scheduler = createCommonjsModule(function(module2) {
  {
    module2.exports = scheduler_production_min;
  }
});
function y(a2) {
  for (var b2 = "https://reactjs.org/docs/error-decoder.html?invariant=" + a2, c3 = 1; c3 < arguments.length; c3++)
    b2 += "&args[]=" + encodeURIComponent(arguments[c3]);
  return "Minified React error #" + a2 + "; visit " + b2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
}
if (!react)
  throw Error(y(227));
var ba = new Set();
var ca = {};
function da(a2, b2) {
  ea(a2, b2);
  ea(a2 + "Capture", b2);
}
function ea(a2, b2) {
  ca[a2] = b2;
  for (a2 = 0; a2 < b2.length; a2++)
    ba.add(b2[a2]);
}
var fa = !(typeof window === "undefined" || typeof window.document === "undefined" || typeof window.document.createElement === "undefined");
var ha = /^[: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]*$/;
var ia = Object.prototype.hasOwnProperty;
var ja = {};
var ka = {};
function la(a2) {
  if (ia.call(ka, a2))
    return true;
  if (ia.call(ja, a2))
    return false;
  if (ha.test(a2))
    return ka[a2] = true;
  ja[a2] = true;
  return false;
}
function ma(a2, b2, c3, d2) {
  if (c3 !== null && c3.type === 0)
    return false;
  switch (typeof b2) {
    case "function":
    case "symbol":
      return true;
    case "boolean":
      if (d2)
        return false;
      if (c3 !== null)
        return !c3.acceptsBooleans;
      a2 = a2.toLowerCase().slice(0, 5);
      return a2 !== "data-" && a2 !== "aria-";
    default:
      return false;
  }
}
function na(a2, b2, c3, d2) {
  if (b2 === null || typeof b2 === "undefined" || ma(a2, b2, c3, d2))
    return true;
  if (d2)
    return false;
  if (c3 !== null)
    switch (c3.type) {
      case 3:
        return !b2;
      case 4:
        return b2 === false;
      case 5:
        return isNaN(b2);
      case 6:
        return isNaN(b2) || 1 > b2;
    }
  return false;
}
function B(a2, b2, c3, d2, e2, f2, g2) {
  this.acceptsBooleans = b2 === 2 || b2 === 3 || b2 === 4;
  this.attributeName = d2;
  this.attributeNamespace = e2;
  this.mustUseProperty = c3;
  this.propertyName = a2;
  this.type = b2;
  this.sanitizeURL = f2;
  this.removeEmptyString = g2;
}
var D = {};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a2) {
  D[a2] = new B(a2, 0, false, a2, null, false, false);
});
[["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(a2) {
  var b2 = a2[0];
  D[b2] = new B(b2, 1, false, a2[1], null, false, false);
});
["contentEditable", "draggable", "spellCheck", "value"].forEach(function(a2) {
  D[a2] = new B(a2, 2, false, a2.toLowerCase(), null, false, false);
});
["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(a2) {
  D[a2] = new B(a2, 2, false, a2, null, false, false);
});
"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a2) {
  D[a2] = new B(a2, 3, false, a2.toLowerCase(), null, false, false);
});
["checked", "multiple", "muted", "selected"].forEach(function(a2) {
  D[a2] = new B(a2, 3, true, a2, null, false, false);
});
["capture", "download"].forEach(function(a2) {
  D[a2] = new B(a2, 4, false, a2, null, false, false);
});
["cols", "rows", "size", "span"].forEach(function(a2) {
  D[a2] = new B(a2, 6, false, a2, null, false, false);
});
["rowSpan", "start"].forEach(function(a2) {
  D[a2] = new B(a2, 5, false, a2.toLowerCase(), null, false, false);
});
var oa = /[\-:]([a-z])/g;
function pa(a2) {
  return a2[1].toUpperCase();
}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a2) {
  var b2 = a2.replace(oa, pa);
  D[b2] = new B(b2, 1, false, a2, null, false, false);
});
"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a2) {
  var b2 = a2.replace(oa, pa);
  D[b2] = new B(b2, 1, false, a2, "http://www.w3.org/1999/xlink", false, false);
});
["xml:base", "xml:lang", "xml:space"].forEach(function(a2) {
  var b2 = a2.replace(oa, pa);
  D[b2] = new B(b2, 1, false, a2, "http://www.w3.org/XML/1998/namespace", false, false);
});
["tabIndex", "crossOrigin"].forEach(function(a2) {
  D[a2] = new B(a2, 1, false, a2.toLowerCase(), null, false, false);
});
D.xlinkHref = new B("xlinkHref", 1, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false);
["src", "href", "action", "formAction"].forEach(function(a2) {
  D[a2] = new B(a2, 1, false, a2.toLowerCase(), null, true, true);
});
function qa(a2, b2, c3, d2) {
  var e2 = D.hasOwnProperty(b2) ? D[b2] : null;
  var f2 = e2 !== null ? e2.type === 0 : d2 ? false : !(2 < b2.length) || b2[0] !== "o" && b2[0] !== "O" || b2[1] !== "n" && b2[1] !== "N" ? false : true;
  f2 || (na(b2, c3, e2, d2) && (c3 = null), d2 || e2 === null ? la(b2) && (c3 === null ? a2.removeAttribute(b2) : a2.setAttribute(b2, "" + c3)) : e2.mustUseProperty ? a2[e2.propertyName] = c3 === null ? e2.type === 3 ? false : "" : c3 : (b2 = e2.attributeName, d2 = e2.attributeNamespace, c3 === null ? a2.removeAttribute(b2) : (e2 = e2.type, c3 = e2 === 3 || e2 === 4 && c3 === true ? "" : "" + c3, d2 ? a2.setAttributeNS(d2, b2, c3) : a2.setAttribute(b2, c3))));
}
var ra = react.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
var sa = 60103;
var ta = 60106;
var ua = 60107;
var wa = 60108;
var xa = 60114;
var ya = 60109;
var za = 60110;
var Aa = 60112;
var Ba = 60113;
var Ca = 60120;
var Da = 60115;
var Ea = 60116;
var Fa = 60121;
var Ga = 60128;
var Ha = 60129;
var Ia = 60130;
var Ja = 60131;
if (typeof Symbol === "function" && Symbol.for) {
  E = Symbol.for;
  sa = E("react.element");
  ta = E("react.portal");
  ua = E("react.fragment");
  wa = E("react.strict_mode");
  xa = E("react.profiler");
  ya = E("react.provider");
  za = E("react.context");
  Aa = E("react.forward_ref");
  Ba = E("react.suspense");
  Ca = E("react.suspense_list");
  Da = E("react.memo");
  Ea = E("react.lazy");
  Fa = E("react.block");
  E("react.scope");
  Ga = E("react.opaque.id");
  Ha = E("react.debug_trace_mode");
  Ia = E("react.offscreen");
  Ja = E("react.legacy_hidden");
}
var E;
var Ka = typeof Symbol === "function" && Symbol.iterator;
function La(a2) {
  if (a2 === null || typeof a2 !== "object")
    return null;
  a2 = Ka && a2[Ka] || a2["@@iterator"];
  return typeof a2 === "function" ? a2 : null;
}
var Ma;
function Na(a2) {
  if (Ma === void 0)
    try {
      throw Error();
    } catch (c3) {
      var b2 = c3.stack.trim().match(/\n( *(at )?)/);
      Ma = b2 && b2[1] || "";
    }
  return "\n" + Ma + a2;
}
var Oa = false;
function Pa(a2, b2) {
  if (!a2 || Oa)
    return "";
  Oa = true;
  var c3 = Error.prepareStackTrace;
  Error.prepareStackTrace = void 0;
  try {
    if (b2)
      if (b2 = function() {
        throw Error();
      }, Object.defineProperty(b2.prototype, "props", {set: function() {
        throw Error();
      }}), typeof Reflect === "object" && Reflect.construct) {
        try {
          Reflect.construct(b2, []);
        } catch (k2) {
          var d2 = k2;
        }
        Reflect.construct(a2, [], b2);
      } else {
        try {
          b2.call();
        } catch (k2) {
          d2 = k2;
        }
        a2.call(b2.prototype);
      }
    else {
      try {
        throw Error();
      } catch (k2) {
        d2 = k2;
      }
      a2();
    }
  } catch (k2) {
    if (k2 && d2 && typeof k2.stack === "string") {
      for (var e2 = k2.stack.split("\n"), f2 = d2.stack.split("\n"), g2 = e2.length - 1, h2 = f2.length - 1; 1 <= g2 && 0 <= h2 && e2[g2] !== f2[h2]; )
        h2--;
      for (; 1 <= g2 && 0 <= h2; g2--, h2--)
        if (e2[g2] !== f2[h2]) {
          if (g2 !== 1 || h2 !== 1) {
            do
              if (g2--, h2--, 0 > h2 || e2[g2] !== f2[h2])
                return "\n" + e2[g2].replace(" at new ", " at ");
            while (1 <= g2 && 0 <= h2);
          }
          break;
        }
    }
  } finally {
    Oa = false, Error.prepareStackTrace = c3;
  }
  return (a2 = a2 ? a2.displayName || a2.name : "") ? Na(a2) : "";
}
function Qa(a2) {
  switch (a2.tag) {
    case 5:
      return Na(a2.type);
    case 16:
      return Na("Lazy");
    case 13:
      return Na("Suspense");
    case 19:
      return Na("SuspenseList");
    case 0:
    case 2:
    case 15:
      return a2 = Pa(a2.type, false), a2;
    case 11:
      return a2 = Pa(a2.type.render, false), a2;
    case 22:
      return a2 = Pa(a2.type._render, false), a2;
    case 1:
      return a2 = Pa(a2.type, true), a2;
    default:
      return "";
  }
}
function Ra(a2) {
  if (a2 == null)
    return null;
  if (typeof a2 === "function")
    return a2.displayName || a2.name || null;
  if (typeof a2 === "string")
    return a2;
  switch (a2) {
    case ua:
      return "Fragment";
    case ta:
      return "Portal";
    case xa:
      return "Profiler";
    case wa:
      return "StrictMode";
    case Ba:
      return "Suspense";
    case Ca:
      return "SuspenseList";
  }
  if (typeof a2 === "object")
    switch (a2.$$typeof) {
      case za:
        return (a2.displayName || "Context") + ".Consumer";
      case ya:
        return (a2._context.displayName || "Context") + ".Provider";
      case Aa:
        var b2 = a2.render;
        b2 = b2.displayName || b2.name || "";
        return a2.displayName || (b2 !== "" ? "ForwardRef(" + b2 + ")" : "ForwardRef");
      case Da:
        return Ra(a2.type);
      case Fa:
        return Ra(a2._render);
      case Ea:
        b2 = a2._payload;
        a2 = a2._init;
        try {
          return Ra(a2(b2));
        } catch (c3) {
        }
    }
  return null;
}
function Sa(a2) {
  switch (typeof a2) {
    case "boolean":
    case "number":
    case "object":
    case "string":
    case "undefined":
      return a2;
    default:
      return "";
  }
}
function Ta(a2) {
  var b2 = a2.type;
  return (a2 = a2.nodeName) && a2.toLowerCase() === "input" && (b2 === "checkbox" || b2 === "radio");
}
function Ua(a2) {
  var b2 = Ta(a2) ? "checked" : "value", c3 = Object.getOwnPropertyDescriptor(a2.constructor.prototype, b2), d2 = "" + a2[b2];
  if (!a2.hasOwnProperty(b2) && typeof c3 !== "undefined" && typeof c3.get === "function" && typeof c3.set === "function") {
    var e2 = c3.get, f2 = c3.set;
    Object.defineProperty(a2, b2, {configurable: true, get: function() {
      return e2.call(this);
    }, set: function(a3) {
      d2 = "" + a3;
      f2.call(this, a3);
    }});
    Object.defineProperty(a2, b2, {enumerable: c3.enumerable});
    return {getValue: function() {
      return d2;
    }, setValue: function(a3) {
      d2 = "" + a3;
    }, stopTracking: function() {
      a2._valueTracker = null;
      delete a2[b2];
    }};
  }
}
function Va(a2) {
  a2._valueTracker || (a2._valueTracker = Ua(a2));
}
function Wa(a2) {
  if (!a2)
    return false;
  var b2 = a2._valueTracker;
  if (!b2)
    return true;
  var c3 = b2.getValue();
  var d2 = "";
  a2 && (d2 = Ta(a2) ? a2.checked ? "true" : "false" : a2.value);
  a2 = d2;
  return a2 !== c3 ? (b2.setValue(a2), true) : false;
}
function Xa(a2) {
  a2 = a2 || (typeof document !== "undefined" ? document : void 0);
  if (typeof a2 === "undefined")
    return null;
  try {
    return a2.activeElement || a2.body;
  } catch (b2) {
    return a2.body;
  }
}
function Ya(a2, b2) {
  var c3 = b2.checked;
  return objectAssign({}, b2, {defaultChecked: void 0, defaultValue: void 0, value: void 0, checked: c3 != null ? c3 : a2._wrapperState.initialChecked});
}
function Za(a2, b2) {
  var c3 = b2.defaultValue == null ? "" : b2.defaultValue, d2 = b2.checked != null ? b2.checked : b2.defaultChecked;
  c3 = Sa(b2.value != null ? b2.value : c3);
  a2._wrapperState = {initialChecked: d2, initialValue: c3, controlled: b2.type === "checkbox" || b2.type === "radio" ? b2.checked != null : b2.value != null};
}
function $a(a2, b2) {
  b2 = b2.checked;
  b2 != null && qa(a2, "checked", b2, false);
}
function ab(a2, b2) {
  $a(a2, b2);
  var c3 = Sa(b2.value), d2 = b2.type;
  if (c3 != null)
    if (d2 === "number") {
      if (c3 === 0 && a2.value === "" || a2.value != c3)
        a2.value = "" + c3;
    } else
      a2.value !== "" + c3 && (a2.value = "" + c3);
  else if (d2 === "submit" || d2 === "reset") {
    a2.removeAttribute("value");
    return;
  }
  b2.hasOwnProperty("value") ? bb(a2, b2.type, c3) : b2.hasOwnProperty("defaultValue") && bb(a2, b2.type, Sa(b2.defaultValue));
  b2.checked == null && b2.defaultChecked != null && (a2.defaultChecked = !!b2.defaultChecked);
}
function cb(a2, b2, c3) {
  if (b2.hasOwnProperty("value") || b2.hasOwnProperty("defaultValue")) {
    var d2 = b2.type;
    if (!(d2 !== "submit" && d2 !== "reset" || b2.value !== void 0 && b2.value !== null))
      return;
    b2 = "" + a2._wrapperState.initialValue;
    c3 || b2 === a2.value || (a2.value = b2);
    a2.defaultValue = b2;
  }
  c3 = a2.name;
  c3 !== "" && (a2.name = "");
  a2.defaultChecked = !!a2._wrapperState.initialChecked;
  c3 !== "" && (a2.name = c3);
}
function bb(a2, b2, c3) {
  if (b2 !== "number" || Xa(a2.ownerDocument) !== a2)
    c3 == null ? a2.defaultValue = "" + a2._wrapperState.initialValue : a2.defaultValue !== "" + c3 && (a2.defaultValue = "" + c3);
}
function db(a2) {
  var b2 = "";
  react.Children.forEach(a2, function(a3) {
    a3 != null && (b2 += a3);
  });
  return b2;
}
function eb(a2, b2) {
  a2 = objectAssign({children: void 0}, b2);
  if (b2 = db(b2.children))
    a2.children = b2;
  return a2;
}
function fb(a2, b2, c3, d2) {
  a2 = a2.options;
  if (b2) {
    b2 = {};
    for (var e2 = 0; e2 < c3.length; e2++)
      b2["$" + c3[e2]] = true;
    for (c3 = 0; c3 < a2.length; c3++)
      e2 = b2.hasOwnProperty("$" + a2[c3].value), a2[c3].selected !== e2 && (a2[c3].selected = e2), e2 && d2 && (a2[c3].defaultSelected = true);
  } else {
    c3 = "" + Sa(c3);
    b2 = null;
    for (e2 = 0; e2 < a2.length; e2++) {
      if (a2[e2].value === c3) {
        a2[e2].selected = true;
        d2 && (a2[e2].defaultSelected = true);
        return;
      }
      b2 !== null || a2[e2].disabled || (b2 = a2[e2]);
    }
    b2 !== null && (b2.selected = true);
  }
}
function gb(a2, b2) {
  if (b2.dangerouslySetInnerHTML != null)
    throw Error(y(91));
  return objectAssign({}, b2, {value: void 0, defaultValue: void 0, children: "" + a2._wrapperState.initialValue});
}
function hb(a2, b2) {
  var c3 = b2.value;
  if (c3 == null) {
    c3 = b2.children;
    b2 = b2.defaultValue;
    if (c3 != null) {
      if (b2 != null)
        throw Error(y(92));
      if (Array.isArray(c3)) {
        if (!(1 >= c3.length))
          throw Error(y(93));
        c3 = c3[0];
      }
      b2 = c3;
    }
    b2 == null && (b2 = "");
    c3 = b2;
  }
  a2._wrapperState = {initialValue: Sa(c3)};
}
function ib(a2, b2) {
  var c3 = Sa(b2.value), d2 = Sa(b2.defaultValue);
  c3 != null && (c3 = "" + c3, c3 !== a2.value && (a2.value = c3), b2.defaultValue == null && a2.defaultValue !== c3 && (a2.defaultValue = c3));
  d2 != null && (a2.defaultValue = "" + d2);
}
function jb(a2) {
  var b2 = a2.textContent;
  b2 === a2._wrapperState.initialValue && b2 !== "" && b2 !== null && (a2.value = b2);
}
var kb = {html: "http://www.w3.org/1999/xhtml", mathml: "http://www.w3.org/1998/Math/MathML", svg: "http://www.w3.org/2000/svg"};
function lb(a2) {
  switch (a2) {
    case "svg":
      return "http://www.w3.org/2000/svg";
    case "math":
      return "http://www.w3.org/1998/Math/MathML";
    default:
      return "http://www.w3.org/1999/xhtml";
  }
}
function mb(a2, b2) {
  return a2 == null || a2 === "http://www.w3.org/1999/xhtml" ? lb(b2) : a2 === "http://www.w3.org/2000/svg" && b2 === "foreignObject" ? "http://www.w3.org/1999/xhtml" : a2;
}
var nb;
var ob = function(a2) {
  return typeof MSApp !== "undefined" && MSApp.execUnsafeLocalFunction ? function(b2, c3, d2, e2) {
    MSApp.execUnsafeLocalFunction(function() {
      return a2(b2, c3, d2, e2);
    });
  } : a2;
}(function(a2, b2) {
  if (a2.namespaceURI !== kb.svg || "innerHTML" in a2)
    a2.innerHTML = b2;
  else {
    nb = nb || document.createElement("div");
    nb.innerHTML = "<svg>" + b2.valueOf().toString() + "</svg>";
    for (b2 = nb.firstChild; a2.firstChild; )
      a2.removeChild(a2.firstChild);
    for (; b2.firstChild; )
      a2.appendChild(b2.firstChild);
  }
});
function pb(a2, b2) {
  if (b2) {
    var c3 = a2.firstChild;
    if (c3 && c3 === a2.lastChild && c3.nodeType === 3) {
      c3.nodeValue = b2;
      return;
    }
  }
  a2.textContent = b2;
}
var qb = {
  animationIterationCount: true,
  borderImageOutset: true,
  borderImageSlice: true,
  borderImageWidth: true,
  boxFlex: true,
  boxFlexGroup: true,
  boxOrdinalGroup: true,
  columnCount: true,
  columns: true,
  flex: true,
  flexGrow: true,
  flexPositive: true,
  flexShrink: true,
  flexNegative: true,
  flexOrder: true,
  gridArea: true,
  gridRow: true,
  gridRowEnd: true,
  gridRowSpan: true,
  gridRowStart: true,
  gridColumn: true,
  gridColumnEnd: true,
  gridColumnSpan: true,
  gridColumnStart: true,
  fontWeight: true,
  lineClamp: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  tabSize: true,
  widows: true,
  zIndex: true,
  zoom: true,
  fillOpacity: true,
  floodOpacity: true,
  stopOpacity: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true
};
var rb = ["Webkit", "ms", "Moz", "O"];
Object.keys(qb).forEach(function(a2) {
  rb.forEach(function(b2) {
    b2 = b2 + a2.charAt(0).toUpperCase() + a2.substring(1);
    qb[b2] = qb[a2];
  });
});
function sb(a2, b2, c3) {
  return b2 == null || typeof b2 === "boolean" || b2 === "" ? "" : c3 || typeof b2 !== "number" || b2 === 0 || qb.hasOwnProperty(a2) && qb[a2] ? ("" + b2).trim() : b2 + "px";
}
function tb(a2, b2) {
  a2 = a2.style;
  for (var c3 in b2)
    if (b2.hasOwnProperty(c3)) {
      var d2 = c3.indexOf("--") === 0, e2 = sb(c3, b2[c3], d2);
      c3 === "float" && (c3 = "cssFloat");
      d2 ? a2.setProperty(c3, e2) : a2[c3] = e2;
    }
}
var ub = objectAssign({menuitem: true}, {area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true});
function vb(a2, b2) {
  if (b2) {
    if (ub[a2] && (b2.children != null || b2.dangerouslySetInnerHTML != null))
      throw Error(y(137, a2));
    if (b2.dangerouslySetInnerHTML != null) {
      if (b2.children != null)
        throw Error(y(60));
      if (!(typeof b2.dangerouslySetInnerHTML === "object" && "__html" in b2.dangerouslySetInnerHTML))
        throw Error(y(61));
    }
    if (b2.style != null && typeof b2.style !== "object")
      throw Error(y(62));
  }
}
function wb(a2, b2) {
  if (a2.indexOf("-") === -1)
    return typeof b2.is === "string";
  switch (a2) {
    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 xb(a2) {
  a2 = a2.target || a2.srcElement || window;
  a2.correspondingUseElement && (a2 = a2.correspondingUseElement);
  return a2.nodeType === 3 ? a2.parentNode : a2;
}
var yb = null;
var zb = null;
var Ab = null;
function Bb(a2) {
  if (a2 = Cb(a2)) {
    if (typeof yb !== "function")
      throw Error(y(280));
    var b2 = a2.stateNode;
    b2 && (b2 = Db(b2), yb(a2.stateNode, a2.type, b2));
  }
}
function Eb(a2) {
  zb ? Ab ? Ab.push(a2) : Ab = [a2] : zb = a2;
}
function Fb() {
  if (zb) {
    var a2 = zb, b2 = Ab;
    Ab = zb = null;
    Bb(a2);
    if (b2)
      for (a2 = 0; a2 < b2.length; a2++)
        Bb(b2[a2]);
  }
}
function Gb(a2, b2) {
  return a2(b2);
}
function Hb(a2, b2, c3, d2, e2) {
  return a2(b2, c3, d2, e2);
}
function Ib() {
}
var Jb = Gb;
var Kb = false;
var Lb = false;
function Mb() {
  if (zb !== null || Ab !== null)
    Ib(), Fb();
}
function Nb(a2, b2, c3) {
  if (Lb)
    return a2(b2, c3);
  Lb = true;
  try {
    return Jb(a2, b2, c3);
  } finally {
    Lb = false, Mb();
  }
}
function Ob(a2, b2) {
  var c3 = a2.stateNode;
  if (c3 === null)
    return null;
  var d2 = Db(c3);
  if (d2 === null)
    return null;
  c3 = d2[b2];
  a:
    switch (b2) {
      case "onClick":
      case "onClickCapture":
      case "onDoubleClick":
      case "onDoubleClickCapture":
      case "onMouseDown":
      case "onMouseDownCapture":
      case "onMouseMove":
      case "onMouseMoveCapture":
      case "onMouseUp":
      case "onMouseUpCapture":
      case "onMouseEnter":
        (d2 = !d2.disabled) || (a2 = a2.type, d2 = !(a2 === "button" || a2 === "input" || a2 === "select" || a2 === "textarea"));
        a2 = !d2;
        break a;
      default:
        a2 = false;
    }
  if (a2)
    return null;
  if (c3 && typeof c3 !== "function")
    throw Error(y(231, b2, typeof c3));
  return c3;
}
var Pb = false;
if (fa)
  try {
    Qb = {};
    Object.defineProperty(Qb, "passive", {get: function() {
      Pb = true;
    }});
    window.addEventListener("test", Qb, Qb);
    window.removeEventListener("test", Qb, Qb);
  } catch (a2) {
    Pb = false;
  }
var Qb;
function Rb(a2, b2, c3, d2, e2, f2, g2, h2, k2) {
  var l2 = Array.prototype.slice.call(arguments, 3);
  try {
    b2.apply(c3, l2);
  } catch (n3) {
    this.onError(n3);
  }
}
var Sb = false;
var Tb = null;
var Ub = false;
var Vb = null;
var Wb = {onError: function(a2) {
  Sb = true;
  Tb = a2;
}};
function Xb(a2, b2, c3, d2, e2, f2, g2, h2, k2) {
  Sb = false;
  Tb = null;
  Rb.apply(Wb, arguments);
}
function Yb(a2, b2, c3, d2, e2, f2, g2, h2, k2) {
  Xb.apply(this, arguments);
  if (Sb) {
    if (Sb) {
      var l2 = Tb;
      Sb = false;
      Tb = null;
    } else
      throw Error(y(198));
    Ub || (Ub = true, Vb = l2);
  }
}
function Zb(a2) {
  var b2 = a2, c3 = a2;
  if (a2.alternate)
    for (; b2.return; )
      b2 = b2.return;
  else {
    a2 = b2;
    do
      b2 = a2, (b2.flags & 1026) !== 0 && (c3 = b2.return), a2 = b2.return;
    while (a2);
  }
  return b2.tag === 3 ? c3 : null;
}
function $b(a2) {
  if (a2.tag === 13) {
    var b2 = a2.memoizedState;
    b2 === null && (a2 = a2.alternate, a2 !== null && (b2 = a2.memoizedState));
    if (b2 !== null)
      return b2.dehydrated;
  }
  return null;
}
function ac(a2) {
  if (Zb(a2) !== a2)
    throw Error(y(188));
}
function bc(a2) {
  var b2 = a2.alternate;
  if (!b2) {
    b2 = Zb(a2);
    if (b2 === null)
      throw Error(y(188));
    return b2 !== a2 ? null : a2;
  }
  for (var c3 = a2, d2 = b2; ; ) {
    var e2 = c3.return;
    if (e2 === null)
      break;
    var f2 = e2.alternate;
    if (f2 === null) {
      d2 = e2.return;
      if (d2 !== null) {
        c3 = d2;
        continue;
      }
      break;
    }
    if (e2.child === f2.child) {
      for (f2 = e2.child; f2; ) {
        if (f2 === c3)
          return ac(e2), a2;
        if (f2 === d2)
          return ac(e2), b2;
        f2 = f2.sibling;
      }
      throw Error(y(188));
    }
    if (c3.return !== d2.return)
      c3 = e2, d2 = f2;
    else {
      for (var g2 = false, h2 = e2.child; h2; ) {
        if (h2 === c3) {
          g2 = true;
          c3 = e2;
          d2 = f2;
          break;
        }
        if (h2 === d2) {
          g2 = true;
          d2 = e2;
          c3 = f2;
          break;
        }
        h2 = h2.sibling;
      }
      if (!g2) {
        for (h2 = f2.child; h2; ) {
          if (h2 === c3) {
            g2 = true;
            c3 = f2;
            d2 = e2;
            break;
          }
          if (h2 === d2) {
            g2 = true;
            d2 = f2;
            c3 = e2;
            break;
          }
          h2 = h2.sibling;
        }
        if (!g2)
          throw Error(y(189));
      }
    }
    if (c3.alternate !== d2)
      throw Error(y(190));
  }
  if (c3.tag !== 3)
    throw Error(y(188));
  return c3.stateNode.current === c3 ? a2 : b2;
}
function cc(a2) {
  a2 = bc(a2);
  if (!a2)
    return null;
  for (var b2 = a2; ; ) {
    if (b2.tag === 5 || b2.tag === 6)
      return b2;
    if (b2.child)
      b2.child.return = b2, b2 = b2.child;
    else {
      if (b2 === a2)
        break;
      for (; !b2.sibling; ) {
        if (!b2.return || b2.return === a2)
          return null;
        b2 = b2.return;
      }
      b2.sibling.return = b2.return;
      b2 = b2.sibling;
    }
  }
  return null;
}
function dc(a2, b2) {
  for (var c3 = a2.alternate; b2 !== null; ) {
    if (b2 === a2 || b2 === c3)
      return true;
    b2 = b2.return;
  }
  return false;
}
var ec;
var fc;
var gc;
var hc;
var ic = false;
var jc = [];
var kc = null;
var lc = null;
var mc = null;
var nc = new Map();
var oc = new Map();
var pc = [];
var qc = "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 submit".split(" ");
function rc(a2, b2, c3, d2, e2) {
  return {blockedOn: a2, domEventName: b2, eventSystemFlags: c3 | 16, nativeEvent: e2, targetContainers: [d2]};
}
function sc(a2, b2) {
  switch (a2) {
    case "focusin":
    case "focusout":
      kc = null;
      break;
    case "dragenter":
    case "dragleave":
      lc = null;
      break;
    case "mouseover":
    case "mouseout":
      mc = null;
      break;
    case "pointerover":
    case "pointerout":
      nc.delete(b2.pointerId);
      break;
    case "gotpointercapture":
    case "lostpointercapture":
      oc.delete(b2.pointerId);
  }
}
function tc(a2, b2, c3, d2, e2, f2) {
  if (a2 === null || a2.nativeEvent !== f2)
    return a2 = rc(b2, c3, d2, e2, f2), b2 !== null && (b2 = Cb(b2), b2 !== null && fc(b2)), a2;
  a2.eventSystemFlags |= d2;
  b2 = a2.targetContainers;
  e2 !== null && b2.indexOf(e2) === -1 && b2.push(e2);
  return a2;
}
function uc(a2, b2, c3, d2, e2) {
  switch (b2) {
    case "focusin":
      return kc = tc(kc, a2, b2, c3, d2, e2), true;
    case "dragenter":
      return lc = tc(lc, a2, b2, c3, d2, e2), true;
    case "mouseover":
      return mc = tc(mc, a2, b2, c3, d2, e2), true;
    case "pointerover":
      var f2 = e2.pointerId;
      nc.set(f2, tc(nc.get(f2) || null, a2, b2, c3, d2, e2));
      return true;
    case "gotpointercapture":
      return f2 = e2.pointerId, oc.set(f2, tc(oc.get(f2) || null, a2, b2, c3, d2, e2)), true;
  }
  return false;
}
function vc(a2) {
  var b2 = wc(a2.target);
  if (b2 !== null) {
    var c3 = Zb(b2);
    if (c3 !== null) {
      if (b2 = c3.tag, b2 === 13) {
        if (b2 = $b(c3), b2 !== null) {
          a2.blockedOn = b2;
          hc(a2.lanePriority, function() {
            scheduler.unstable_runWithPriority(a2.priority, function() {
              gc(c3);
            });
          });
          return;
        }
      } else if (b2 === 3 && c3.stateNode.hydrate) {
        a2.blockedOn = c3.tag === 3 ? c3.stateNode.containerInfo : null;
        return;
      }
    }
  }
  a2.blockedOn = null;
}
function xc(a2) {
  if (a2.blockedOn !== null)
    return false;
  for (var b2 = a2.targetContainers; 0 < b2.length; ) {
    var c3 = yc(a2.domEventName, a2.eventSystemFlags, b2[0], a2.nativeEvent);
    if (c3 !== null)
      return b2 = Cb(c3), b2 !== null && fc(b2), a2.blockedOn = c3, false;
    b2.shift();
  }
  return true;
}
function zc(a2, b2, c3) {
  xc(a2) && c3.delete(b2);
}
function Ac() {
  for (ic = false; 0 < jc.length; ) {
    var a2 = jc[0];
    if (a2.blockedOn !== null) {
      a2 = Cb(a2.blockedOn);
      a2 !== null && ec(a2);
      break;
    }
    for (var b2 = a2.targetContainers; 0 < b2.length; ) {
      var c3 = yc(a2.domEventName, a2.eventSystemFlags, b2[0], a2.nativeEvent);
      if (c3 !== null) {
        a2.blockedOn = c3;
        break;
      }
      b2.shift();
    }
    a2.blockedOn === null && jc.shift();
  }
  kc !== null && xc(kc) && (kc = null);
  lc !== null && xc(lc) && (lc = null);
  mc !== null && xc(mc) && (mc = null);
  nc.forEach(zc);
  oc.forEach(zc);
}
function Bc(a2, b2) {
  a2.blockedOn === b2 && (a2.blockedOn = null, ic || (ic = true, scheduler.unstable_scheduleCallback(scheduler.unstable_NormalPriority, Ac)));
}
function Cc(a2) {
  function b2(b3) {
    return Bc(b3, a2);
  }
  if (0 < jc.length) {
    Bc(jc[0], a2);
    for (var c3 = 1; c3 < jc.length; c3++) {
      var d2 = jc[c3];
      d2.blockedOn === a2 && (d2.blockedOn = null);
    }
  }
  kc !== null && Bc(kc, a2);
  lc !== null && Bc(lc, a2);
  mc !== null && Bc(mc, a2);
  nc.forEach(b2);
  oc.forEach(b2);
  for (c3 = 0; c3 < pc.length; c3++)
    d2 = pc[c3], d2.blockedOn === a2 && (d2.blockedOn = null);
  for (; 0 < pc.length && (c3 = pc[0], c3.blockedOn === null); )
    vc(c3), c3.blockedOn === null && pc.shift();
}
function Dc(a2, b2) {
  var c3 = {};
  c3[a2.toLowerCase()] = b2.toLowerCase();
  c3["Webkit" + a2] = "webkit" + b2;
  c3["Moz" + a2] = "moz" + b2;
  return c3;
}
var Ec = {animationend: Dc("Animation", "AnimationEnd"), animationiteration: Dc("Animation", "AnimationIteration"), animationstart: Dc("Animation", "AnimationStart"), transitionend: Dc("Transition", "TransitionEnd")};
var Fc = {};
var Gc = {};
fa && (Gc = document.createElement("div").style, "AnimationEvent" in window || (delete Ec.animationend.animation, delete Ec.animationiteration.animation, delete Ec.animationstart.animation), "TransitionEvent" in window || delete Ec.transitionend.transition);
function Hc(a2) {
  if (Fc[a2])
    return Fc[a2];
  if (!Ec[a2])
    return a2;
  var b2 = Ec[a2], c3;
  for (c3 in b2)
    if (b2.hasOwnProperty(c3) && c3 in Gc)
      return Fc[a2] = b2[c3];
  return a2;
}
var Ic = Hc("animationend");
var Jc = Hc("animationiteration");
var Kc = Hc("animationstart");
var Lc = Hc("transitionend");
var Mc = new Map();
var Nc = new Map();
var Oc = [
  "abort",
  "abort",
  Ic,
  "animationEnd",
  Jc,
  "animationIteration",
  Kc,
  "animationStart",
  "canplay",
  "canPlay",
  "canplaythrough",
  "canPlayThrough",
  "durationchange",
  "durationChange",
  "emptied",
  "emptied",
  "encrypted",
  "encrypted",
  "ended",
  "ended",
  "error",
  "error",
  "gotpointercapture",
  "gotPointerCapture",
  "load",
  "load",
  "loadeddata",
  "loadedData",
  "loadedmetadata",
  "loadedMetadata",
  "loadstart",
  "loadStart",
  "lostpointercapture",
  "lostPointerCapture",
  "playing",
  "playing",
  "progress",
  "progress",
  "seeking",
  "seeking",
  "stalled",
  "stalled",
  "suspend",
  "suspend",
  "timeupdate",
  "timeUpdate",
  Lc,
  "transitionEnd",
  "waiting",
  "waiting"
];
function Pc(a2, b2) {
  for (var c3 = 0; c3 < a2.length; c3 += 2) {
    var d2 = a2[c3], e2 = a2[c3 + 1];
    e2 = "on" + (e2[0].toUpperCase() + e2.slice(1));
    Nc.set(d2, b2);
    Mc.set(d2, e2);
    da(e2, [d2]);
  }
}
var Qc = scheduler.unstable_now;
Qc();
var F = 8;
function Rc(a2) {
  if ((1 & a2) !== 0)
    return F = 15, 1;
  if ((2 & a2) !== 0)
    return F = 14, 2;
  if ((4 & a2) !== 0)
    return F = 13, 4;
  var b2 = 24 & a2;
  if (b2 !== 0)
    return F = 12, b2;
  if ((a2 & 32) !== 0)
    return F = 11, 32;
  b2 = 192 & a2;
  if (b2 !== 0)
    return F = 10, b2;
  if ((a2 & 256) !== 0)
    return F = 9, 256;
  b2 = 3584 & a2;
  if (b2 !== 0)
    return F = 8, b2;
  if ((a2 & 4096) !== 0)
    return F = 7, 4096;
  b2 = 4186112 & a2;
  if (b2 !== 0)
    return F = 6, b2;
  b2 = 62914560 & a2;
  if (b2 !== 0)
    return F = 5, b2;
  if (a2 & 67108864)
    return F = 4, 67108864;
  if ((a2 & 134217728) !== 0)
    return F = 3, 134217728;
  b2 = 805306368 & a2;
  if (b2 !== 0)
    return F = 2, b2;
  if ((1073741824 & a2) !== 0)
    return F = 1, 1073741824;
  F = 8;
  return a2;
}
function Sc(a2) {
  switch (a2) {
    case 99:
      return 15;
    case 98:
      return 10;
    case 97:
    case 96:
      return 8;
    case 95:
      return 2;
    default:
      return 0;
  }
}
function Tc(a2) {
  switch (a2) {
    case 15:
    case 14:
      return 99;
    case 13:
    case 12:
    case 11:
    case 10:
      return 98;
    case 9:
    case 8:
    case 7:
    case 6:
    case 4:
    case 5:
      return 97;
    case 3:
    case 2:
    case 1:
      return 95;
    case 0:
      return 90;
    default:
      throw Error(y(358, a2));
  }
}
function Uc(a2, b2) {
  var c3 = a2.pendingLanes;
  if (c3 === 0)
    return F = 0;
  var d2 = 0, e2 = 0, f2 = a2.expiredLanes, g2 = a2.suspendedLanes, h2 = a2.pingedLanes;
  if (f2 !== 0)
    d2 = f2, e2 = F = 15;
  else if (f2 = c3 & 134217727, f2 !== 0) {
    var k2 = f2 & ~g2;
    k2 !== 0 ? (d2 = Rc(k2), e2 = F) : (h2 &= f2, h2 !== 0 && (d2 = Rc(h2), e2 = F));
  } else
    f2 = c3 & ~g2, f2 !== 0 ? (d2 = Rc(f2), e2 = F) : h2 !== 0 && (d2 = Rc(h2), e2 = F);
  if (d2 === 0)
    return 0;
  d2 = 31 - Vc(d2);
  d2 = c3 & ((0 > d2 ? 0 : 1 << d2) << 1) - 1;
  if (b2 !== 0 && b2 !== d2 && (b2 & g2) === 0) {
    Rc(b2);
    if (e2 <= F)
      return b2;
    F = e2;
  }
  b2 = a2.entangledLanes;
  if (b2 !== 0)
    for (a2 = a2.entanglements, b2 &= d2; 0 < b2; )
      c3 = 31 - Vc(b2), e2 = 1 << c3, d2 |= a2[c3], b2 &= ~e2;
  return d2;
}
function Wc(a2) {
  a2 = a2.pendingLanes & -1073741825;
  return a2 !== 0 ? a2 : a2 & 1073741824 ? 1073741824 : 0;
}
function Xc(a2, b2) {
  switch (a2) {
    case 15:
      return 1;
    case 14:
      return 2;
    case 12:
      return a2 = Yc(24 & ~b2), a2 === 0 ? Xc(10, b2) : a2;
    case 10:
      return a2 = Yc(192 & ~b2), a2 === 0 ? Xc(8, b2) : a2;
    case 8:
      return a2 = Yc(3584 & ~b2), a2 === 0 && (a2 = Yc(4186112 & ~b2), a2 === 0 && (a2 = 512)), a2;
    case 2:
      return b2 = Yc(805306368 & ~b2), b2 === 0 && (b2 = 268435456), b2;
  }
  throw Error(y(358, a2));
}
function Yc(a2) {
  return a2 & -a2;
}
function Zc(a2) {
  for (var b2 = [], c3 = 0; 31 > c3; c3++)
    b2.push(a2);
  return b2;
}
function $c(a2, b2, c3) {
  a2.pendingLanes |= b2;
  var d2 = b2 - 1;
  a2.suspendedLanes &= d2;
  a2.pingedLanes &= d2;
  a2 = a2.eventTimes;
  b2 = 31 - Vc(b2);
  a2[b2] = c3;
}
var Vc = Math.clz32 ? Math.clz32 : ad;
var bd = Math.log;
var cd = Math.LN2;
function ad(a2) {
  return a2 === 0 ? 32 : 31 - (bd(a2) / cd | 0) | 0;
}
var dd = scheduler.unstable_UserBlockingPriority;
var ed = scheduler.unstable_runWithPriority;
var fd = true;
function gd(a2, b2, c3, d2) {
  Kb || Ib();
  var e2 = hd, f2 = Kb;
  Kb = true;
  try {
    Hb(e2, a2, b2, c3, d2);
  } finally {
    (Kb = f2) || Mb();
  }
}
function id(a2, b2, c3, d2) {
  ed(dd, hd.bind(null, a2, b2, c3, d2));
}
function hd(a2, b2, c3, d2) {
  if (fd) {
    var e2;
    if ((e2 = (b2 & 4) === 0) && 0 < jc.length && -1 < qc.indexOf(a2))
      a2 = rc(null, a2, b2, c3, d2), jc.push(a2);
    else {
      var f2 = yc(a2, b2, c3, d2);
      if (f2 === null)
        e2 && sc(a2, d2);
      else {
        if (e2) {
          if (-1 < qc.indexOf(a2)) {
            a2 = rc(f2, a2, b2, c3, d2);
            jc.push(a2);
            return;
          }
          if (uc(f2, a2, b2, c3, d2))
            return;
          sc(a2, d2);
        }
        jd(a2, b2, d2, null, c3);
      }
    }
  }
}
function yc(a2, b2, c3, d2) {
  var e2 = xb(d2);
  e2 = wc(e2);
  if (e2 !== null) {
    var f2 = Zb(e2);
    if (f2 === null)
      e2 = null;
    else {
      var g2 = f2.tag;
      if (g2 === 13) {
        e2 = $b(f2);
        if (e2 !== null)
          return e2;
        e2 = null;
      } else if (g2 === 3) {
        if (f2.stateNode.hydrate)
          return f2.tag === 3 ? f2.stateNode.containerInfo : null;
        e2 = null;
      } else
        f2 !== e2 && (e2 = null);
    }
  }
  jd(a2, b2, d2, e2, c3);
  return null;
}
var kd = null;
var ld = null;
var md = null;
function nd() {
  if (md)
    return md;
  var a2, b2 = ld, c3 = b2.length, d2, e2 = "value" in kd ? kd.value : kd.textContent, f2 = e2.length;
  for (a2 = 0; a2 < c3 && b2[a2] === e2[a2]; a2++)
    ;
  var g2 = c3 - a2;
  for (d2 = 1; d2 <= g2 && b2[c3 - d2] === e2[f2 - d2]; d2++)
    ;
  return md = e2.slice(a2, 1 < d2 ? 1 - d2 : void 0);
}
function od(a2) {
  var b2 = a2.keyCode;
  "charCode" in a2 ? (a2 = a2.charCode, a2 === 0 && b2 === 13 && (a2 = 13)) : a2 = b2;
  a2 === 10 && (a2 = 13);
  return 32 <= a2 || a2 === 13 ? a2 : 0;
}
function pd() {
  return true;
}
function qd() {
  return false;
}
function rd(a2) {
  function b2(b3, d2, e2, f2, g2) {
    this._reactName = b3;
    this._targetInst = e2;
    this.type = d2;
    this.nativeEvent = f2;
    this.target = g2;
    this.currentTarget = null;
    for (var c3 in a2)
      a2.hasOwnProperty(c3) && (b3 = a2[c3], this[c3] = b3 ? b3(f2) : f2[c3]);
    this.isDefaultPrevented = (f2.defaultPrevented != null ? f2.defaultPrevented : f2.returnValue === false) ? pd : qd;
    this.isPropagationStopped = qd;
    return this;
  }
  objectAssign(b2.prototype, {preventDefault: function() {
    this.defaultPrevented = true;
    var a3 = this.nativeEvent;
    a3 && (a3.preventDefault ? a3.preventDefault() : typeof a3.returnValue !== "unknown" && (a3.returnValue = false), this.isDefaultPrevented = pd);
  }, stopPropagation: function() {
    var a3 = this.nativeEvent;
    a3 && (a3.stopPropagation ? a3.stopPropagation() : typeof a3.cancelBubble !== "unknown" && (a3.cancelBubble = true), this.isPropagationStopped = pd);
  }, persist: function() {
  }, isPersistent: pd});
  return b2;
}
var sd = {eventPhase: 0, bubbles: 0, cancelable: 0, timeStamp: function(a2) {
  return a2.timeStamp || Date.now();
}, defaultPrevented: 0, isTrusted: 0};
var td = rd(sd);
var ud = objectAssign({}, sd, {view: 0, detail: 0});
var vd = rd(ud);
var wd;
var xd;
var yd;
var Ad = objectAssign({}, ud, {screenX: 0, screenY: 0, clientX: 0, clientY: 0, pageX: 0, pageY: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, getModifierState: zd, button: 0, buttons: 0, relatedTarget: function(a2) {
  return a2.relatedTarget === void 0 ? a2.fromElement === a2.srcElement ? a2.toElement : a2.fromElement : a2.relatedTarget;
}, movementX: function(a2) {
  if ("movementX" in a2)
    return a2.movementX;
  a2 !== yd && (yd && a2.type === "mousemove" ? (wd = a2.screenX - yd.screenX, xd = a2.screenY - yd.screenY) : xd = wd = 0, yd = a2);
  return wd;
}, movementY: function(a2) {
  return "movementY" in a2 ? a2.movementY : xd;
}});
var Bd = rd(Ad);
var Cd = objectAssign({}, Ad, {dataTransfer: 0});
var Dd = rd(Cd);
var Ed = objectAssign({}, ud, {relatedTarget: 0});
var Fd = rd(Ed);
var Gd = objectAssign({}, sd, {animationName: 0, elapsedTime: 0, pseudoElement: 0});
var Hd = rd(Gd);
var Id = objectAssign({}, sd, {clipboardData: function(a2) {
  return "clipboardData" in a2 ? a2.clipboardData : window.clipboardData;
}});
var Jd = rd(Id);
var Kd = objectAssign({}, sd, {data: 0});
var Ld = rd(Kd);
var Md = {
  Esc: "Escape",
  Spacebar: " ",
  Left: "ArrowLeft",
  Up: "ArrowUp",
  Right: "ArrowRight",
  Down: "ArrowDown",
  Del: "Delete",
  Win: "OS",
  Menu: "ContextMenu",
  Apps: "ContextMenu",
  Scroll: "ScrollLock",
  MozPrintableKey: "Unidentified"
};
var Nd = {
  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"
};
var Od = {Alt: "altKey", Control: "ctrlKey", Meta: "metaKey", Shift: "shiftKey"};
function Pd(a2) {
  var b2 = this.nativeEvent;
  return b2.getModifierState ? b2.getModifierState(a2) : (a2 = Od[a2]) ? !!b2[a2] : false;
}
function zd() {
  return Pd;
}
var Qd = objectAssign({}, ud, {key: function(a2) {
  if (a2.key) {
    var b2 = Md[a2.key] || a2.key;
    if (b2 !== "Unidentified")
      return b2;
  }
  return a2.type === "keypress" ? (a2 = od(a2), a2 === 13 ? "Enter" : String.fromCharCode(a2)) : a2.type === "keydown" || a2.type === "keyup" ? Nd[a2.keyCode] || "Unidentified" : "";
}, code: 0, location: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, repeat: 0, locale: 0, getModifierState: zd, charCode: function(a2) {
  return a2.type === "keypress" ? od(a2) : 0;
}, keyCode: function(a2) {
  return a2.type === "keydown" || a2.type === "keyup" ? a2.keyCode : 0;
}, which: function(a2) {
  return a2.type === "keypress" ? od(a2) : a2.type === "keydown" || a2.type === "keyup" ? a2.keyCode : 0;
}});
var Rd = rd(Qd);
var Sd = objectAssign({}, Ad, {pointerId: 0, width: 0, height: 0, pressure: 0, tangentialPressure: 0, tiltX: 0, tiltY: 0, twist: 0, pointerType: 0, isPrimary: 0});
var Td = rd(Sd);
var Ud = objectAssign({}, ud, {touches: 0, targetTouches: 0, changedTouches: 0, altKey: 0, metaKey: 0, ctrlKey: 0, shiftKey: 0, getModifierState: zd});
var Vd = rd(Ud);
var Wd = objectAssign({}, sd, {propertyName: 0, elapsedTime: 0, pseudoElement: 0});
var Xd = rd(Wd);
var Yd = objectAssign({}, Ad, {
  deltaX: function(a2) {
    return "deltaX" in a2 ? a2.deltaX : "wheelDeltaX" in a2 ? -a2.wheelDeltaX : 0;
  },
  deltaY: function(a2) {
    return "deltaY" in a2 ? a2.deltaY : "wheelDeltaY" in a2 ? -a2.wheelDeltaY : "wheelDelta" in a2 ? -a2.wheelDelta : 0;
  },
  deltaZ: 0,
  deltaMode: 0
});
var Zd = rd(Yd);
var $d = [9, 13, 27, 32];
var ae = fa && "CompositionEvent" in window;
var be = null;
fa && "documentMode" in document && (be = document.documentMode);
var ce = fa && "TextEvent" in window && !be;
var de = fa && (!ae || be && 8 < be && 11 >= be);
var ee = String.fromCharCode(32);
var fe = false;
function ge(a2, b2) {
  switch (a2) {
    case "keyup":
      return $d.indexOf(b2.keyCode) !== -1;
    case "keydown":
      return b2.keyCode !== 229;
    case "keypress":
    case "mousedown":
    case "focusout":
      return true;
    default:
      return false;
  }
}
function he(a2) {
  a2 = a2.detail;
  return typeof a2 === "object" && "data" in a2 ? a2.data : null;
}
var ie = false;
function je(a2, b2) {
  switch (a2) {
    case "compositionend":
      return he(b2);
    case "keypress":
      if (b2.which !== 32)
        return null;
      fe = true;
      return ee;
    case "textInput":
      return a2 = b2.data, a2 === ee && fe ? null : a2;
    default:
      return null;
  }
}
function ke(a2, b2) {
  if (ie)
    return a2 === "compositionend" || !ae && ge(a2, b2) ? (a2 = nd(), md = ld = kd = null, ie = false, a2) : null;
  switch (a2) {
    case "paste":
      return null;
    case "keypress":
      if (!(b2.ctrlKey || b2.altKey || b2.metaKey) || b2.ctrlKey && b2.altKey) {
        if (b2.char && 1 < b2.char.length)
          return b2.char;
        if (b2.which)
          return String.fromCharCode(b2.which);
      }
      return null;
    case "compositionend":
      return de && b2.locale !== "ko" ? null : b2.data;
    default:
      return null;
  }
}
var le = {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};
function me(a2) {
  var b2 = a2 && a2.nodeName && a2.nodeName.toLowerCase();
  return b2 === "input" ? !!le[a2.type] : b2 === "textarea" ? true : false;
}
function ne(a2, b2, c3, d2) {
  Eb(d2);
  b2 = oe(b2, "onChange");
  0 < b2.length && (c3 = new td("onChange", "change", null, c3, d2), a2.push({event: c3, listeners: b2}));
}
var pe = null;
var qe = null;
function re(a2) {
  se(a2, 0);
}
function te(a2) {
  var b2 = ue(a2);
  if (Wa(b2))
    return a2;
}
function ve(a2, b2) {
  if (a2 === "change")
    return b2;
}
var we = false;
if (fa) {
  if (fa) {
    ye = "oninput" in document;
    if (!ye) {
      ze = document.createElement("div");
      ze.setAttribute("oninput", "return;");
      ye = typeof ze.oninput === "function";
    }
    xe = ye;
  } else
    xe = false;
  we = xe && (!document.documentMode || 9 < document.documentMode);
}
var xe;
var ye;
var ze;
function Ae() {
  pe && (pe.detachEvent("onpropertychange", Be), qe = pe = null);
}
function Be(a2) {
  if (a2.propertyName === "value" && te(qe)) {
    var b2 = [];
    ne(b2, qe, a2, xb(a2));
    a2 = re;
    if (Kb)
      a2(b2);
    else {
      Kb = true;
      try {
        Gb(a2, b2);
      } finally {
        Kb = false, Mb();
      }
    }
  }
}
function Ce(a2, b2, c3) {
  a2 === "focusin" ? (Ae(), pe = b2, qe = c3, pe.attachEvent("onpropertychange", Be)) : a2 === "focusout" && Ae();
}
function De(a2) {
  if (a2 === "selectionchange" || a2 === "keyup" || a2 === "keydown")
    return te(qe);
}
function Ee(a2, b2) {
  if (a2 === "click")
    return te(b2);
}
function Fe(a2, b2) {
  if (a2 === "input" || a2 === "change")
    return te(b2);
}
function Ge(a2, b2) {
  return a2 === b2 && (a2 !== 0 || 1 / a2 === 1 / b2) || a2 !== a2 && b2 !== b2;
}
var He = typeof Object.is === "function" ? Object.is : Ge;
var Ie = Object.prototype.hasOwnProperty;
function Je(a2, b2) {
  if (He(a2, b2))
    return true;
  if (typeof a2 !== "object" || a2 === null || typeof b2 !== "object" || b2 === null)
    return false;
  var c3 = Object.keys(a2), d2 = Object.keys(b2);
  if (c3.length !== d2.length)
    return false;
  for (d2 = 0; d2 < c3.length; d2++)
    if (!Ie.call(b2, c3[d2]) || !He(a2[c3[d2]], b2[c3[d2]]))
      return false;
  return true;
}
function Ke(a2) {
  for (; a2 && a2.firstChild; )
    a2 = a2.firstChild;
  return a2;
}
function Le(a2, b2) {
  var c3 = Ke(a2);
  a2 = 0;
  for (var d2; c3; ) {
    if (c3.nodeType === 3) {
      d2 = a2 + c3.textContent.length;
      if (a2 <= b2 && d2 >= b2)
        return {node: c3, offset: b2 - a2};
      a2 = d2;
    }
    a: {
      for (; c3; ) {
        if (c3.nextSibling) {
          c3 = c3.nextSibling;
          break a;
        }
        c3 = c3.parentNode;
      }
      c3 = void 0;
    }
    c3 = Ke(c3);
  }
}
function Me(a2, b2) {
  return a2 && b2 ? a2 === b2 ? true : a2 && a2.nodeType === 3 ? false : b2 && b2.nodeType === 3 ? Me(a2, b2.parentNode) : "contains" in a2 ? a2.contains(b2) : a2.compareDocumentPosition ? !!(a2.compareDocumentPosition(b2) & 16) : false : false;
}
function Ne() {
  for (var a2 = window, b2 = Xa(); b2 instanceof a2.HTMLIFrameElement; ) {
    try {
      var c3 = typeof b2.contentWindow.location.href === "string";
    } catch (d2) {
      c3 = false;
    }
    if (c3)
      a2 = b2.contentWindow;
    else
      break;
    b2 = Xa(a2.document);
  }
  return b2;
}
function Oe(a2) {
  var b2 = a2 && a2.nodeName && a2.nodeName.toLowerCase();
  return b2 && (b2 === "input" && (a2.type === "text" || a2.type === "search" || a2.type === "tel" || a2.type === "url" || a2.type === "password") || b2 === "textarea" || a2.contentEditable === "true");
}
var Pe = fa && "documentMode" in document && 11 >= document.documentMode;
var Qe = null;
var Re = null;
var Se = null;
var Te = false;
function Ue(a2, b2, c3) {
  var d2 = c3.window === c3 ? c3.document : c3.nodeType === 9 ? c3 : c3.ownerDocument;
  Te || Qe == null || Qe !== Xa(d2) || (d2 = Qe, "selectionStart" in d2 && Oe(d2) ? d2 = {start: d2.selectionStart, end: d2.selectionEnd} : (d2 = (d2.ownerDocument && d2.ownerDocument.defaultView || window).getSelection(), d2 = {anchorNode: d2.anchorNode, anchorOffset: d2.anchorOffset, focusNode: d2.focusNode, focusOffset: d2.focusOffset}), Se && Je(Se, d2) || (Se = d2, d2 = oe(Re, "onSelect"), 0 < d2.length && (b2 = new td("onSelect", "select", null, b2, c3), a2.push({event: b2, listeners: d2}), b2.target = Qe)));
}
Pc("cancel cancel click click close close contextmenu contextMenu copy copy cut cut auxclick auxClick dblclick doubleClick dragend dragEnd dragstart dragStart drop drop focusin focus focusout blur input input invalid invalid keydown keyDown keypress keyPress keyup keyUp mousedown mouseDown mouseup mouseUp paste paste pause pause play play pointercancel pointerCancel pointerdown pointerDown pointerup pointerUp ratechange rateChange reset reset seeked seeked submit submit touchcancel touchCancel touchend touchEnd touchstart touchStart volumechange volumeChange".split(" "), 0);
Pc("drag drag dragenter dragEnter dragexit dragExit dragleave dragLeave dragover dragOver mousemove mouseMove mouseout mouseOut mouseover mouseOver pointermove pointerMove pointerout pointerOut pointerover pointerOver scroll scroll toggle toggle touchmove touchMove wheel wheel".split(" "), 1);
Pc(Oc, 2);
for (var Ve = "change selectionchange textInput compositionstart compositionend compositionupdate".split(" "), We = 0; We < Ve.length; We++)
  Nc.set(Ve[We], 0);
ea("onMouseEnter", ["mouseout", "mouseover"]);
ea("onMouseLeave", ["mouseout", "mouseover"]);
ea("onPointerEnter", ["pointerout", "pointerover"]);
ea("onPointerLeave", ["pointerout", "pointerover"]);
da("onChange", "change click focusin focusout input keydown keyup selectionchange".split(" "));
da("onSelect", "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));
da("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]);
da("onCompositionEnd", "compositionend focusout keydown keypress keyup mousedown".split(" "));
da("onCompositionStart", "compositionstart focusout keydown keypress keyup mousedown".split(" "));
da("onCompositionUpdate", "compositionupdate focusout keydown keypress keyup mousedown".split(" "));
var Xe = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" ");
var Ye = new Set("cancel close invalid load scroll toggle".split(" ").concat(Xe));
function Ze(a2, b2, c3) {
  var d2 = a2.type || "unknown-event";
  a2.currentTarget = c3;
  Yb(d2, b2, void 0, a2);
  a2.currentTarget = null;
}
function se(a2, b2) {
  b2 = (b2 & 4) !== 0;
  for (var c3 = 0; c3 < a2.length; c3++) {
    var d2 = a2[c3], e2 = d2.event;
    d2 = d2.listeners;
    a: {
      var f2 = void 0;
      if (b2)
        for (var g2 = d2.length - 1; 0 <= g2; g2--) {
          var h2 = d2[g2], k2 = h2.instance, l2 = h2.currentTarget;
          h2 = h2.listener;
          if (k2 !== f2 && e2.isPropagationStopped())
            break a;
          Ze(e2, h2, l2);
          f2 = k2;
        }
      else
        for (g2 = 0; g2 < d2.length; g2++) {
          h2 = d2[g2];
          k2 = h2.instance;
          l2 = h2.currentTarget;
          h2 = h2.listener;
          if (k2 !== f2 && e2.isPropagationStopped())
            break a;
          Ze(e2, h2, l2);
          f2 = k2;
        }
    }
  }
  if (Ub)
    throw a2 = Vb, Ub = false, Vb = null, a2;
}
function G(a2, b2) {
  var c3 = $e(b2), d2 = a2 + "__bubble";
  c3.has(d2) || (af(b2, a2, 2, false), c3.add(d2));
}
var bf = "_reactListening" + Math.random().toString(36).slice(2);
function cf(a2) {
  a2[bf] || (a2[bf] = true, ba.forEach(function(b2) {
    Ye.has(b2) || df(b2, false, a2, null);
    df(b2, true, a2, null);
  }));
}
function df(a2, b2, c3, d2) {
  var e2 = 4 < arguments.length && arguments[4] !== void 0 ? arguments[4] : 0, f2 = c3;
  a2 === "selectionchange" && c3.nodeType !== 9 && (f2 = c3.ownerDocument);
  if (d2 !== null && !b2 && Ye.has(a2)) {
    if (a2 !== "scroll")
      return;
    e2 |= 2;
    f2 = d2;
  }
  var g2 = $e(f2), h2 = a2 + "__" + (b2 ? "capture" : "bubble");
  g2.has(h2) || (b2 && (e2 |= 4), af(f2, a2, e2, b2), g2.add(h2));
}
function af(a2, b2, c3, d2) {
  var e2 = Nc.get(b2);
  switch (e2 === void 0 ? 2 : e2) {
    case 0:
      e2 = gd;
      break;
    case 1:
      e2 = id;
      break;
    default:
      e2 = hd;
  }
  c3 = e2.bind(null, b2, c3, a2);
  e2 = void 0;
  !Pb || b2 !== "touchstart" && b2 !== "touchmove" && b2 !== "wheel" || (e2 = true);
  d2 ? e2 !== void 0 ? a2.addEventListener(b2, c3, {capture: true, passive: e2}) : a2.addEventListener(b2, c3, true) : e2 !== void 0 ? a2.addEventListener(b2, c3, {passive: e2}) : a2.addEventListener(b2, c3, false);
}
function jd(a2, b2, c3, d2, e2) {
  var f2 = d2;
  if ((b2 & 1) === 0 && (b2 & 2) === 0 && d2 !== null)
    a:
      for (; ; ) {
        if (d2 === null)
          return;
        var g2 = d2.tag;
        if (g2 === 3 || g2 === 4) {
          var h2 = d2.stateNode.containerInfo;
          if (h2 === e2 || h2.nodeType === 8 && h2.parentNode === e2)
            break;
          if (g2 === 4)
            for (g2 = d2.return; g2 !== null; ) {
              var k2 = g2.tag;
              if (k2 === 3 || k2 === 4) {
                if (k2 = g2.stateNode.containerInfo, k2 === e2 || k2.nodeType === 8 && k2.parentNode === e2)
                  return;
              }
              g2 = g2.return;
            }
          for (; h2 !== null; ) {
            g2 = wc(h2);
            if (g2 === null)
              return;
            k2 = g2.tag;
            if (k2 === 5 || k2 === 6) {
              d2 = f2 = g2;
              continue a;
            }
            h2 = h2.parentNode;
          }
        }
        d2 = d2.return;
      }
  Nb(function() {
    var d3 = f2, e3 = xb(c3), g3 = [];
    a: {
      var h3 = Mc.get(a2);
      if (h3 !== void 0) {
        var k3 = td, x2 = a2;
        switch (a2) {
          case "keypress":
            if (od(c3) === 0)
              break a;
          case "keydown":
          case "keyup":
            k3 = Rd;
            break;
          case "focusin":
            x2 = "focus";
            k3 = Fd;
            break;
          case "focusout":
            x2 = "blur";
            k3 = Fd;
            break;
          case "beforeblur":
          case "afterblur":
            k3 = Fd;
            break;
          case "click":
            if (c3.button === 2)
              break a;
          case "auxclick":
          case "dblclick":
          case "mousedown":
          case "mousemove":
          case "mouseup":
          case "mouseout":
          case "mouseover":
          case "contextmenu":
            k3 = Bd;
            break;
          case "drag":
          case "dragend":
          case "dragenter":
          case "dragexit":
          case "dragleave":
          case "dragover":
          case "dragstart":
          case "drop":
            k3 = Dd;
            break;
          case "touchcancel":
          case "touchend":
          case "touchmove":
          case "touchstart":
            k3 = Vd;
            break;
          case Ic:
          case Jc:
          case Kc:
            k3 = Hd;
            break;
          case Lc:
            k3 = Xd;
            break;
          case "scroll":
            k3 = vd;
            break;
          case "wheel":
            k3 = Zd;
            break;
          case "copy":
          case "cut":
          case "paste":
            k3 = Jd;
            break;
          case "gotpointercapture":
          case "lostpointercapture":
          case "pointercancel":
          case "pointerdown":
          case "pointermove":
          case "pointerout":
          case "pointerover":
          case "pointerup":
            k3 = Td;
        }
        var w2 = (b2 & 4) !== 0, z2 = !w2 && a2 === "scroll", u = w2 ? h3 !== null ? h3 + "Capture" : null : h3;
        w2 = [];
        for (var t5 = d3, q2; t5 !== null; ) {
          q2 = t5;
          var v2 = q2.stateNode;
          q2.tag === 5 && v2 !== null && (q2 = v2, u !== null && (v2 = Ob(t5, u), v2 != null && w2.push(ef(t5, v2, q2))));
          if (z2)
            break;
          t5 = t5.return;
        }
        0 < w2.length && (h3 = new k3(h3, x2, null, c3, e3), g3.push({event: h3, listeners: w2}));
      }
    }
    if ((b2 & 7) === 0) {
      a: {
        h3 = a2 === "mouseover" || a2 === "pointerover";
        k3 = a2 === "mouseout" || a2 === "pointerout";
        if (h3 && (b2 & 16) === 0 && (x2 = c3.relatedTarget || c3.fromElement) && (wc(x2) || x2[ff]))
          break a;
        if (k3 || h3) {
          h3 = e3.window === e3 ? e3 : (h3 = e3.ownerDocument) ? h3.defaultView || h3.parentWindow : window;
          if (k3) {
            if (x2 = c3.relatedTarget || c3.toElement, k3 = d3, x2 = x2 ? wc(x2) : null, x2 !== null && (z2 = Zb(x2), x2 !== z2 || x2.tag !== 5 && x2.tag !== 6))
              x2 = null;
          } else
            k3 = null, x2 = d3;
          if (k3 !== x2) {
            w2 = Bd;
            v2 = "onMouseLeave";
            u = "onMouseEnter";
            t5 = "mouse";
            if (a2 === "pointerout" || a2 === "pointerover")
              w2 = Td, v2 = "onPointerLeave", u = "onPointerEnter", t5 = "pointer";
            z2 = k3 == null ? h3 : ue(k3);
            q2 = x2 == null ? h3 : ue(x2);
            h3 = new w2(v2, t5 + "leave", k3, c3, e3);
            h3.target = z2;
            h3.relatedTarget = q2;
            v2 = null;
            wc(e3) === d3 && (w2 = new w2(u, t5 + "enter", x2, c3, e3), w2.target = q2, w2.relatedTarget = z2, v2 = w2);
            z2 = v2;
            if (k3 && x2)
              b: {
                w2 = k3;
                u = x2;
                t5 = 0;
                for (q2 = w2; q2; q2 = gf(q2))
                  t5++;
                q2 = 0;
                for (v2 = u; v2; v2 = gf(v2))
                  q2++;
                for (; 0 < t5 - q2; )
                  w2 = gf(w2), t5--;
                for (; 0 < q2 - t5; )
                  u = gf(u), q2--;
                for (; t5--; ) {
                  if (w2 === u || u !== null && w2 === u.alternate)
                    break b;
                  w2 = gf(w2);
                  u = gf(u);
                }
                w2 = null;
              }
            else
              w2 = null;
            k3 !== null && hf(g3, h3, k3, w2, false);
            x2 !== null && z2 !== null && hf(g3, z2, x2, w2, true);
          }
        }
      }
      a: {
        h3 = d3 ? ue(d3) : window;
        k3 = h3.nodeName && h3.nodeName.toLowerCase();
        if (k3 === "select" || k3 === "input" && h3.type === "file")
          var J = ve;
        else if (me(h3))
          if (we)
            J = Fe;
          else {
            J = De;
            var K = Ce;
          }
        else
          (k3 = h3.nodeName) && k3.toLowerCase() === "input" && (h3.type === "checkbox" || h3.type === "radio") && (J = Ee);
        if (J && (J = J(a2, d3))) {
          ne(g3, J, c3, e3);
          break a;
        }
        K && K(a2, h3, d3);
        a2 === "focusout" && (K = h3._wrapperState) && K.controlled && h3.type === "number" && bb(h3, "number", h3.value);
      }
      K = d3 ? ue(d3) : window;
      switch (a2) {
        case "focusin":
          if (me(K) || K.contentEditable === "true")
            Qe = K, Re = d3, Se = null;
          break;
        case "focusout":
          Se = Re = Qe = null;
          break;
        case "mousedown":
          Te = true;
          break;
        case "contextmenu":
        case "mouseup":
        case "dragend":
          Te = false;
          Ue(g3, c3, e3);
          break;
        case "selectionchange":
          if (Pe)
            break;
        case "keydown":
        case "keyup":
          Ue(g3, c3, e3);
      }
      var Q;
      if (ae)
        b: {
          switch (a2) {
            case "compositionstart":
              var L = "onCompositionStart";
              break b;
            case "compositionend":
              L = "onCompositionEnd";
              break b;
            case "compositionupdate":
              L = "onCompositionUpdate";
              break b;
          }
          L = void 0;
        }
      else
        ie ? ge(a2, c3) && (L = "onCompositionEnd") : a2 === "keydown" && c3.keyCode === 229 && (L = "onCompositionStart");
      L && (de && c3.locale !== "ko" && (ie || L !== "onCompositionStart" ? L === "onCompositionEnd" && ie && (Q = nd()) : (kd = e3, ld = "value" in kd ? kd.value : kd.textContent, ie = true)), K = oe(d3, L), 0 < K.length && (L = new Ld(L, a2, null, c3, e3), g3.push({event: L, listeners: K}), Q ? L.data = Q : (Q = he(c3), Q !== null && (L.data = Q))));
      if (Q = ce ? je(a2, c3) : ke(a2, c3))
        d3 = oe(d3, "onBeforeInput"), 0 < d3.length && (e3 = new Ld("onBeforeInput", "beforeinput", null, c3, e3), g3.push({event: e3, listeners: d3}), e3.data = Q);
    }
    se(g3, b2);
  });
}
function ef(a2, b2, c3) {
  return {instance: a2, listener: b2, currentTarget: c3};
}
function oe(a2, b2) {
  for (var c3 = b2 + "Capture", d2 = []; a2 !== null; ) {
    var e2 = a2, f2 = e2.stateNode;
    e2.tag === 5 && f2 !== null && (e2 = f2, f2 = Ob(a2, c3), f2 != null && d2.unshift(ef(a2, f2, e2)), f2 = Ob(a2, b2), f2 != null && d2.push(ef(a2, f2, e2)));
    a2 = a2.return;
  }
  return d2;
}
function gf(a2) {
  if (a2 === null)
    return null;
  do
    a2 = a2.return;
  while (a2 && a2.tag !== 5);
  return a2 ? a2 : null;
}
function hf(a2, b2, c3, d2, e2) {
  for (var f2 = b2._reactName, g2 = []; c3 !== null && c3 !== d2; ) {
    var h2 = c3, k2 = h2.alternate, l2 = h2.stateNode;
    if (k2 !== null && k2 === d2)
      break;
    h2.tag === 5 && l2 !== null && (h2 = l2, e2 ? (k2 = Ob(c3, f2), k2 != null && g2.unshift(ef(c3, k2, h2))) : e2 || (k2 = Ob(c3, f2), k2 != null && g2.push(ef(c3, k2, h2))));
    c3 = c3.return;
  }
  g2.length !== 0 && a2.push({event: b2, listeners: g2});
}
function jf() {
}
var kf = null;
var lf = null;
function mf(a2, b2) {
  switch (a2) {
    case "button":
    case "input":
    case "select":
    case "textarea":
      return !!b2.autoFocus;
  }
  return false;
}
function nf(a2, b2) {
  return a2 === "textarea" || a2 === "option" || a2 === "noscript" || typeof b2.children === "string" || typeof b2.children === "number" || typeof b2.dangerouslySetInnerHTML === "object" && b2.dangerouslySetInnerHTML !== null && b2.dangerouslySetInnerHTML.__html != null;
}
var of = typeof setTimeout === "function" ? setTimeout : void 0;
var pf = typeof clearTimeout === "function" ? clearTimeout : void 0;
function qf(a2) {
  a2.nodeType === 1 ? a2.textContent = "" : a2.nodeType === 9 && (a2 = a2.body, a2 != null && (a2.textContent = ""));
}
function rf(a2) {
  for (; a2 != null; a2 = a2.nextSibling) {
    var b2 = a2.nodeType;
    if (b2 === 1 || b2 === 3)
      break;
  }
  return a2;
}
function sf(a2) {
  a2 = a2.previousSibling;
  for (var b2 = 0; a2; ) {
    if (a2.nodeType === 8) {
      var c3 = a2.data;
      if (c3 === "$" || c3 === "$!" || c3 === "$?") {
        if (b2 === 0)
          return a2;
        b2--;
      } else
        c3 === "/$" && b2++;
    }
    a2 = a2.previousSibling;
  }
  return null;
}
var tf = 0;
function uf(a2) {
  return {$$typeof: Ga, toString: a2, valueOf: a2};
}
var vf = Math.random().toString(36).slice(2);
var wf = "__reactFiber$" + vf;
var xf = "__reactProps$" + vf;
var ff = "__reactContainer$" + vf;
var yf = "__reactEvents$" + vf;
function wc(a2) {
  var b2 = a2[wf];
  if (b2)
    return b2;
  for (var c3 = a2.parentNode; c3; ) {
    if (b2 = c3[ff] || c3[wf]) {
      c3 = b2.alternate;
      if (b2.child !== null || c3 !== null && c3.child !== null)
        for (a2 = sf(a2); a2 !== null; ) {
          if (c3 = a2[wf])
            return c3;
          a2 = sf(a2);
        }
      return b2;
    }
    a2 = c3;
    c3 = a2.parentNode;
  }
  return null;
}
function Cb(a2) {
  a2 = a2[wf] || a2[ff];
  return !a2 || a2.tag !== 5 && a2.tag !== 6 && a2.tag !== 13 && a2.tag !== 3 ? null : a2;
}
function ue(a2) {
  if (a2.tag === 5 || a2.tag === 6)
    return a2.stateNode;
  throw Error(y(33));
}
function Db(a2) {
  return a2[xf] || null;
}
function $e(a2) {
  var b2 = a2[yf];
  b2 === void 0 && (b2 = a2[yf] = new Set());
  return b2;
}
var zf = [];
var Af = -1;
function Bf(a2) {
  return {current: a2};
}
function H(a2) {
  0 > Af || (a2.current = zf[Af], zf[Af] = null, Af--);
}
function I(a2, b2) {
  Af++;
  zf[Af] = a2.current;
  a2.current = b2;
}
var Cf = {};
var M = Bf(Cf);
var N = Bf(false);
var Df = Cf;
function Ef(a2, b2) {
  var c3 = a2.type.contextTypes;
  if (!c3)
    return Cf;
  var d2 = a2.stateNode;
  if (d2 && d2.__reactInternalMemoizedUnmaskedChildContext === b2)
    return d2.__reactInternalMemoizedMaskedChildContext;
  var e2 = {}, f2;
  for (f2 in c3)
    e2[f2] = b2[f2];
  d2 && (a2 = a2.stateNode, a2.__reactInternalMemoizedUnmaskedChildContext = b2, a2.__reactInternalMemoizedMaskedChildContext = e2);
  return e2;
}
function Ff(a2) {
  a2 = a2.childContextTypes;
  return a2 !== null && a2 !== void 0;
}
function Gf() {
  H(N);
  H(M);
}
function Hf(a2, b2, c3) {
  if (M.current !== Cf)
    throw Error(y(168));
  I(M, b2);
  I(N, c3);
}
function If(a2, b2, c3) {
  var d2 = a2.stateNode;
  a2 = b2.childContextTypes;
  if (typeof d2.getChildContext !== "function")
    return c3;
  d2 = d2.getChildContext();
  for (var e2 in d2)
    if (!(e2 in a2))
      throw Error(y(108, Ra(b2) || "Unknown", e2));
  return objectAssign({}, c3, d2);
}
function Jf(a2) {
  a2 = (a2 = a2.stateNode) && a2.__reactInternalMemoizedMergedChildContext || Cf;
  Df = M.current;
  I(M, a2);
  I(N, N.current);
  return true;
}
function Kf(a2, b2, c3) {
  var d2 = a2.stateNode;
  if (!d2)
    throw Error(y(169));
  c3 ? (a2 = If(a2, b2, Df), d2.__reactInternalMemoizedMergedChildContext = a2, H(N), H(M), I(M, a2)) : H(N);
  I(N, c3);
}
var Lf = null;
var Mf = null;
var Nf = scheduler.unstable_runWithPriority;
var Of = scheduler.unstable_scheduleCallback;
var Pf = scheduler.unstable_cancelCallback;
var Qf = scheduler.unstable_shouldYield;
var Rf = scheduler.unstable_requestPaint;
var Sf = scheduler.unstable_now;
var Tf = scheduler.unstable_getCurrentPriorityLevel;
var Uf = scheduler.unstable_ImmediatePriority;
var Vf = scheduler.unstable_UserBlockingPriority;
var Wf = scheduler.unstable_NormalPriority;
var Xf = scheduler.unstable_LowPriority;
var Yf = scheduler.unstable_IdlePriority;
var Zf = {};
var $f = Rf !== void 0 ? Rf : function() {
};
var ag = null;
var bg = null;
var cg = false;
var dg = Sf();
var O = 1e4 > dg ? Sf : function() {
  return Sf() - dg;
};
function eg() {
  switch (Tf()) {
    case Uf:
      return 99;
    case Vf:
      return 98;
    case Wf:
      return 97;
    case Xf:
      return 96;
    case Yf:
      return 95;
    default:
      throw Error(y(332));
  }
}
function fg(a2) {
  switch (a2) {
    case 99:
      return Uf;
    case 98:
      return Vf;
    case 97:
      return Wf;
    case 96:
      return Xf;
    case 95:
      return Yf;
    default:
      throw Error(y(332));
  }
}
function gg(a2, b2) {
  a2 = fg(a2);
  return Nf(a2, b2);
}
function hg(a2, b2, c3) {
  a2 = fg(a2);
  return Of(a2, b2, c3);
}
function ig() {
  if (bg !== null) {
    var a2 = bg;
    bg = null;
    Pf(a2);
  }
  jg();
}
function jg() {
  if (!cg && ag !== null) {
    cg = true;
    var a2 = 0;
    try {
      var b2 = ag;
      gg(99, function() {
        for (; a2 < b2.length; a2++) {
          var c3 = b2[a2];
          do
            c3 = c3(true);
          while (c3 !== null);
        }
      });
      ag = null;
    } catch (c3) {
      throw ag !== null && (ag = ag.slice(a2 + 1)), Of(Uf, ig), c3;
    } finally {
      cg = false;
    }
  }
}
var kg = ra.ReactCurrentBatchConfig;
function lg(a2, b2) {
  if (a2 && a2.defaultProps) {
    b2 = objectAssign({}, b2);
    a2 = a2.defaultProps;
    for (var c3 in a2)
      b2[c3] === void 0 && (b2[c3] = a2[c3]);
    return b2;
  }
  return b2;
}
var mg = Bf(null);
var ng = null;
var og = null;
var pg = null;
function qg() {
  pg = og = ng = null;
}
function rg(a2) {
  var b2 = mg.current;
  H(mg);
  a2.type._context._currentValue = b2;
}
function sg(a2, b2) {
  for (; a2 !== null; ) {
    var c3 = a2.alternate;
    if ((a2.childLanes & b2) === b2)
      if (c3 === null || (c3.childLanes & b2) === b2)
        break;
      else
        c3.childLanes |= b2;
    else
      a2.childLanes |= b2, c3 !== null && (c3.childLanes |= b2);
    a2 = a2.return;
  }
}
function tg(a2, b2) {
  ng = a2;
  pg = og = null;
  a2 = a2.dependencies;
  a2 !== null && a2.firstContext !== null && ((a2.lanes & b2) !== 0 && (ug = true), a2.firstContext = null);
}
function vg(a2, b2) {
  if (pg !== a2 && b2 !== false && b2 !== 0) {
    if (typeof b2 !== "number" || b2 === 1073741823)
      pg = a2, b2 = 1073741823;
    b2 = {context: a2, observedBits: b2, next: null};
    if (og === null) {
      if (ng === null)
        throw Error(y(308));
      og = b2;
      ng.dependencies = {lanes: 0, firstContext: b2, responders: null};
    } else
      og = og.next = b2;
  }
  return a2._currentValue;
}
var wg = false;
function xg(a2) {
  a2.updateQueue = {baseState: a2.memoizedState, firstBaseUpdate: null, lastBaseUpdate: null, shared: {pending: null}, effects: null};
}
function yg(a2, b2) {
  a2 = a2.updateQueue;
  b2.updateQueue === a2 && (b2.updateQueue = {baseState: a2.baseState, firstBaseUpdate: a2.firstBaseUpdate, lastBaseUpdate: a2.lastBaseUpdate, shared: a2.shared, effects: a2.effects});
}
function zg(a2, b2) {
  return {eventTime: a2, lane: b2, tag: 0, payload: null, callback: null, next: null};
}
function Ag(a2, b2) {
  a2 = a2.updateQueue;
  if (a2 !== null) {
    a2 = a2.shared;
    var c3 = a2.pending;
    c3 === null ? b2.next = b2 : (b2.next = c3.next, c3.next = b2);
    a2.pending = b2;
  }
}
function Bg(a2, b2) {
  var c3 = a2.updateQueue, d2 = a2.alternate;
  if (d2 !== null && (d2 = d2.updateQueue, c3 === d2)) {
    var e2 = null, f2 = null;
    c3 = c3.firstBaseUpdate;
    if (c3 !== null) {
      do {
        var g2 = {eventTime: c3.eventTime, lane: c3.lane, tag: c3.tag, payload: c3.payload, callback: c3.callback, next: null};
        f2 === null ? e2 = f2 = g2 : f2 = f2.next = g2;
        c3 = c3.next;
      } while (c3 !== null);
      f2 === null ? e2 = f2 = b2 : f2 = f2.next = b2;
    } else
      e2 = f2 = b2;
    c3 = {baseState: d2.baseState, firstBaseUpdate: e2, lastBaseUpdate: f2, shared: d2.shared, effects: d2.effects};
    a2.updateQueue = c3;
    return;
  }
  a2 = c3.lastBaseUpdate;
  a2 === null ? c3.firstBaseUpdate = b2 : a2.next = b2;
  c3.lastBaseUpdate = b2;
}
function Cg(a2, b2, c3, d2) {
  var e2 = a2.updateQueue;
  wg = false;
  var f2 = e2.firstBaseUpdate, g2 = e2.lastBaseUpdate, h2 = e2.shared.pending;
  if (h2 !== null) {
    e2.shared.pending = null;
    var k2 = h2, l2 = k2.next;
    k2.next = null;
    g2 === null ? f2 = l2 : g2.next = l2;
    g2 = k2;
    var n3 = a2.alternate;
    if (n3 !== null) {
      n3 = n3.updateQueue;
      var A2 = n3.lastBaseUpdate;
      A2 !== g2 && (A2 === null ? n3.firstBaseUpdate = l2 : A2.next = l2, n3.lastBaseUpdate = k2);
    }
  }
  if (f2 !== null) {
    A2 = e2.baseState;
    g2 = 0;
    n3 = l2 = k2 = null;
    do {
      h2 = f2.lane;
      var p2 = f2.eventTime;
      if ((d2 & h2) === h2) {
        n3 !== null && (n3 = n3.next = {
          eventTime: p2,
          lane: 0,
          tag: f2.tag,
          payload: f2.payload,
          callback: f2.callback,
          next: null
        });
        a: {
          var C = a2, x2 = f2;
          h2 = b2;
          p2 = c3;
          switch (x2.tag) {
            case 1:
              C = x2.payload;
              if (typeof C === "function") {
                A2 = C.call(p2, A2, h2);
                break a;
              }
              A2 = C;
              break a;
            case 3:
              C.flags = C.flags & -4097 | 64;
            case 0:
              C = x2.payload;
              h2 = typeof C === "function" ? C.call(p2, A2, h2) : C;
              if (h2 === null || h2 === void 0)
                break a;
              A2 = objectAssign({}, A2, h2);
              break a;
            case 2:
              wg = true;
          }
        }
        f2.callback !== null && (a2.flags |= 32, h2 = e2.effects, h2 === null ? e2.effects = [f2] : h2.push(f2));
      } else
        p2 = {eventTime: p2, lane: h2, tag: f2.tag, payload: f2.payload, callback: f2.callback, next: null}, n3 === null ? (l2 = n3 = p2, k2 = A2) : n3 = n3.next = p2, g2 |= h2;
      f2 = f2.next;
      if (f2 === null)
        if (h2 = e2.shared.pending, h2 === null)
          break;
        else
          f2 = h2.next, h2.next = null, e2.lastBaseUpdate = h2, e2.shared.pending = null;
    } while (1);
    n3 === null && (k2 = A2);
    e2.baseState = k2;
    e2.firstBaseUpdate = l2;
    e2.lastBaseUpdate = n3;
    Dg |= g2;
    a2.lanes = g2;
    a2.memoizedState = A2;
  }
}
function Eg(a2, b2, c3) {
  a2 = b2.effects;
  b2.effects = null;
  if (a2 !== null)
    for (b2 = 0; b2 < a2.length; b2++) {
      var d2 = a2[b2], e2 = d2.callback;
      if (e2 !== null) {
        d2.callback = null;
        d2 = c3;
        if (typeof e2 !== "function")
          throw Error(y(191, e2));
        e2.call(d2);
      }
    }
}
var Fg = new react.Component().refs;
function Gg(a2, b2, c3, d2) {
  b2 = a2.memoizedState;
  c3 = c3(d2, b2);
  c3 = c3 === null || c3 === void 0 ? b2 : objectAssign({}, b2, c3);
  a2.memoizedState = c3;
  a2.lanes === 0 && (a2.updateQueue.baseState = c3);
}
var Kg = {isMounted: function(a2) {
  return (a2 = a2._reactInternals) ? Zb(a2) === a2 : false;
}, enqueueSetState: function(a2, b2, c3) {
  a2 = a2._reactInternals;
  var d2 = Hg(), e2 = Ig(a2), f2 = zg(d2, e2);
  f2.payload = b2;
  c3 !== void 0 && c3 !== null && (f2.callback = c3);
  Ag(a2, f2);
  Jg(a2, e2, d2);
}, enqueueReplaceState: function(a2, b2, c3) {
  a2 = a2._reactInternals;
  var d2 = Hg(), e2 = Ig(a2), f2 = zg(d2, e2);
  f2.tag = 1;
  f2.payload = b2;
  c3 !== void 0 && c3 !== null && (f2.callback = c3);
  Ag(a2, f2);
  Jg(a2, e2, d2);
}, enqueueForceUpdate: function(a2, b2) {
  a2 = a2._reactInternals;
  var c3 = Hg(), d2 = Ig(a2), e2 = zg(c3, d2);
  e2.tag = 2;
  b2 !== void 0 && b2 !== null && (e2.callback = b2);
  Ag(a2, e2);
  Jg(a2, d2, c3);
}};
function Lg(a2, b2, c3, d2, e2, f2, g2) {
  a2 = a2.stateNode;
  return typeof a2.shouldComponentUpdate === "function" ? a2.shouldComponentUpdate(d2, f2, g2) : b2.prototype && b2.prototype.isPureReactComponent ? !Je(c3, d2) || !Je(e2, f2) : true;
}
function Mg(a2, b2, c3) {
  var d2 = false, e2 = Cf;
  var f2 = b2.contextType;
  typeof f2 === "object" && f2 !== null ? f2 = vg(f2) : (e2 = Ff(b2) ? Df : M.current, d2 = b2.contextTypes, f2 = (d2 = d2 !== null && d2 !== void 0) ? Ef(a2, e2) : Cf);
  b2 = new b2(c3, f2);
  a2.memoizedState = b2.state !== null && b2.state !== void 0 ? b2.state : null;
  b2.updater = Kg;
  a2.stateNode = b2;
  b2._reactInternals = a2;
  d2 && (a2 = a2.stateNode, a2.__reactInternalMemoizedUnmaskedChildContext = e2, a2.__reactInternalMemoizedMaskedChildContext = f2);
  return b2;
}
function Ng(a2, b2, c3, d2) {
  a2 = b2.state;
  typeof b2.componentWillReceiveProps === "function" && b2.componentWillReceiveProps(c3, d2);
  typeof b2.UNSAFE_componentWillReceiveProps === "function" && b2.UNSAFE_componentWillReceiveProps(c3, d2);
  b2.state !== a2 && Kg.enqueueReplaceState(b2, b2.state, null);
}
function Og(a2, b2, c3, d2) {
  var e2 = a2.stateNode;
  e2.props = c3;
  e2.state = a2.memoizedState;
  e2.refs = Fg;
  xg(a2);
  var f2 = b2.contextType;
  typeof f2 === "object" && f2 !== null ? e2.context = vg(f2) : (f2 = Ff(b2) ? Df : M.current, e2.context = Ef(a2, f2));
  Cg(a2, c3, e2, d2);
  e2.state = a2.memoizedState;
  f2 = b2.getDerivedStateFromProps;
  typeof f2 === "function" && (Gg(a2, b2, f2, c3), e2.state = a2.memoizedState);
  typeof b2.getDerivedStateFromProps === "function" || typeof e2.getSnapshotBeforeUpdate === "function" || typeof e2.UNSAFE_componentWillMount !== "function" && typeof e2.componentWillMount !== "function" || (b2 = e2.state, typeof e2.componentWillMount === "function" && e2.componentWillMount(), typeof e2.UNSAFE_componentWillMount === "function" && e2.UNSAFE_componentWillMount(), b2 !== e2.state && Kg.enqueueReplaceState(e2, e2.state, null), Cg(a2, c3, e2, d2), e2.state = a2.memoizedState);
  typeof e2.componentDidMount === "function" && (a2.flags |= 4);
}
var Pg = Array.isArray;
function Qg(a2, b2, c3) {
  a2 = c3.ref;
  if (a2 !== null && typeof a2 !== "function" && typeof a2 !== "object") {
    if (c3._owner) {
      c3 = c3._owner;
      if (c3) {
        if (c3.tag !== 1)
          throw Error(y(309));
        var d2 = c3.stateNode;
      }
      if (!d2)
        throw Error(y(147, a2));
      var e2 = "" + a2;
      if (b2 !== null && b2.ref !== null && typeof b2.ref === "function" && b2.ref._stringRef === e2)
        return b2.ref;
      b2 = function(a3) {
        var b3 = d2.refs;
        b3 === Fg && (b3 = d2.refs = {});
        a3 === null ? delete b3[e2] : b3[e2] = a3;
      };
      b2._stringRef = e2;
      return b2;
    }
    if (typeof a2 !== "string")
      throw Error(y(284));
    if (!c3._owner)
      throw Error(y(290, a2));
  }
  return a2;
}
function Rg(a2, b2) {
  if (a2.type !== "textarea")
    throw Error(y(31, Object.prototype.toString.call(b2) === "[object Object]" ? "object with keys {" + Object.keys(b2).join(", ") + "}" : b2));
}
function Sg(a2) {
  function b2(b3, c4) {
    if (a2) {
      var d3 = b3.lastEffect;
      d3 !== null ? (d3.nextEffect = c4, b3.lastEffect = c4) : b3.firstEffect = b3.lastEffect = c4;
      c4.nextEffect = null;
      c4.flags = 8;
    }
  }
  function c3(c4, d3) {
    if (!a2)
      return null;
    for (; d3 !== null; )
      b2(c4, d3), d3 = d3.sibling;
    return null;
  }
  function d2(a3, b3) {
    for (a3 = new Map(); b3 !== null; )
      b3.key !== null ? a3.set(b3.key, b3) : a3.set(b3.index, b3), b3 = b3.sibling;
    return a3;
  }
  function e2(a3, b3) {
    a3 = Tg(a3, b3);
    a3.index = 0;
    a3.sibling = null;
    return a3;
  }
  function f2(b3, c4, d3) {
    b3.index = d3;
    if (!a2)
      return c4;
    d3 = b3.alternate;
    if (d3 !== null)
      return d3 = d3.index, d3 < c4 ? (b3.flags = 2, c4) : d3;
    b3.flags = 2;
    return c4;
  }
  function g2(b3) {
    a2 && b3.alternate === null && (b3.flags = 2);
    return b3;
  }
  function h2(a3, b3, c4, d3) {
    if (b3 === null || b3.tag !== 6)
      return b3 = Ug(c4, a3.mode, d3), b3.return = a3, b3;
    b3 = e2(b3, c4);
    b3.return = a3;
    return b3;
  }
  function k2(a3, b3, c4, d3) {
    if (b3 !== null && b3.elementType === c4.type)
      return d3 = e2(b3, c4.props), d3.ref = Qg(a3, b3, c4), d3.return = a3, d3;
    d3 = Vg(c4.type, c4.key, c4.props, null, a3.mode, d3);
    d3.ref = Qg(a3, b3, c4);
    d3.return = a3;
    return d3;
  }
  function l2(a3, b3, c4, d3) {
    if (b3 === null || b3.tag !== 4 || b3.stateNode.containerInfo !== c4.containerInfo || b3.stateNode.implementation !== c4.implementation)
      return b3 = Wg(c4, a3.mode, d3), b3.return = a3, b3;
    b3 = e2(b3, c4.children || []);
    b3.return = a3;
    return b3;
  }
  function n3(a3, b3, c4, d3, f3) {
    if (b3 === null || b3.tag !== 7)
      return b3 = Xg(c4, a3.mode, d3, f3), b3.return = a3, b3;
    b3 = e2(b3, c4);
    b3.return = a3;
    return b3;
  }
  function A2(a3, b3, c4) {
    if (typeof b3 === "string" || typeof b3 === "number")
      return b3 = Ug("" + b3, a3.mode, c4), b3.return = a3, b3;
    if (typeof b3 === "object" && b3 !== null) {
      switch (b3.$$typeof) {
        case sa:
          return c4 = Vg(b3.type, b3.key, b3.props, null, a3.mode, c4), c4.ref = Qg(a3, null, b3), c4.return = a3, c4;
        case ta:
          return b3 = Wg(b3, a3.mode, c4), b3.return = a3, b3;
      }
      if (Pg(b3) || La(b3))
        return b3 = Xg(b3, a3.mode, c4, null), b3.return = a3, b3;
      Rg(a3, b3);
    }
    return null;
  }
  function p2(a3, b3, c4, d3) {
    var e3 = b3 !== null ? b3.key : null;
    if (typeof c4 === "string" || typeof c4 === "number")
      return e3 !== null ? null : h2(a3, b3, "" + c4, d3);
    if (typeof c4 === "object" && c4 !== null) {
      switch (c4.$$typeof) {
        case sa:
          return c4.key === e3 ? c4.type === ua ? n3(a3, b3, c4.props.children, d3, e3) : k2(a3, b3, c4, d3) : null;
        case ta:
          return c4.key === e3 ? l2(a3, b3, c4, d3) : null;
      }
      if (Pg(c4) || La(c4))
        return e3 !== null ? null : n3(a3, b3, c4, d3, null);
      Rg(a3, c4);
    }
    return null;
  }
  function C(a3, b3, c4, d3, e3) {
    if (typeof d3 === "string" || typeof d3 === "number")
      return a3 = a3.get(c4) || null, h2(b3, a3, "" + d3, e3);
    if (typeof d3 === "object" && d3 !== null) {
      switch (d3.$$typeof) {
        case sa:
          return a3 = a3.get(d3.key === null ? c4 : d3.key) || null, d3.type === ua ? n3(b3, a3, d3.props.children, e3, d3.key) : k2(b3, a3, d3, e3);
        case ta:
          return a3 = a3.get(d3.key === null ? c4 : d3.key) || null, l2(b3, a3, d3, e3);
      }
      if (Pg(d3) || La(d3))
        return a3 = a3.get(c4) || null, n3(b3, a3, d3, e3, null);
      Rg(b3, d3);
    }
    return null;
  }
  function x2(e3, g3, h3, k3) {
    for (var l3 = null, t5 = null, u = g3, z2 = g3 = 0, q2 = null; u !== null && z2 < h3.length; z2++) {
      u.index > z2 ? (q2 = u, u = null) : q2 = u.sibling;
      var n4 = p2(e3, u, h3[z2], k3);
      if (n4 === null) {
        u === null && (u = q2);
        break;
      }
      a2 && u && n4.alternate === null && b2(e3, u);
      g3 = f2(n4, g3, z2);
      t5 === null ? l3 = n4 : t5.sibling = n4;
      t5 = n4;
      u = q2;
    }
    if (z2 === h3.length)
      return c3(e3, u), l3;
    if (u === null) {
      for (; z2 < h3.length; z2++)
        u = A2(e3, h3[z2], k3), u !== null && (g3 = f2(u, g3, z2), t5 === null ? l3 = u : t5.sibling = u, t5 = u);
      return l3;
    }
    for (u = d2(e3, u); z2 < h3.length; z2++)
      q2 = C(u, e3, z2, h3[z2], k3), q2 !== null && (a2 && q2.alternate !== null && u.delete(q2.key === null ? z2 : q2.key), g3 = f2(q2, g3, z2), t5 === null ? l3 = q2 : t5.sibling = q2, t5 = q2);
    a2 && u.forEach(function(a3) {
      return b2(e3, a3);
    });
    return l3;
  }
  function w2(e3, g3, h3, k3) {
    var l3 = La(h3);
    if (typeof l3 !== "function")
      throw Error(y(150));
    h3 = l3.call(h3);
    if (h3 == null)
      throw Error(y(151));
    for (var t5 = l3 = null, u = g3, z2 = g3 = 0, q2 = null, n4 = h3.next(); u !== null && !n4.done; z2++, n4 = h3.next()) {
      u.index > z2 ? (q2 = u, u = null) : q2 = u.sibling;
      var w3 = p2(e3, u, n4.value, k3);
      if (w3 === null) {
        u === null && (u = q2);
        break;
      }
      a2 && u && w3.alternate === null && b2(e3, u);
      g3 = f2(w3, g3, z2);
      t5 === null ? l3 = w3 : t5.sibling = w3;
      t5 = w3;
      u = q2;
    }
    if (n4.done)
      return c3(e3, u), l3;
    if (u === null) {
      for (; !n4.done; z2++, n4 = h3.next())
        n4 = A2(e3, n4.value, k3), n4 !== null && (g3 = f2(n4, g3, z2), t5 === null ? l3 = n4 : t5.sibling = n4, t5 = n4);
      return l3;
    }
    for (u = d2(e3, u); !n4.done; z2++, n4 = h3.next())
      n4 = C(u, e3, z2, n4.value, k3), n4 !== null && (a2 && n4.alternate !== null && u.delete(n4.key === null ? z2 : n4.key), g3 = f2(n4, g3, z2), t5 === null ? l3 = n4 : t5.sibling = n4, t5 = n4);
    a2 && u.forEach(function(a3) {
      return b2(e3, a3);
    });
    return l3;
  }
  return function(a3, d3, f3, h3) {
    var k3 = typeof f3 === "object" && f3 !== null && f3.type === ua && f3.key === null;
    k3 && (f3 = f3.props.children);
    var l3 = typeof f3 === "object" && f3 !== null;
    if (l3)
      switch (f3.$$typeof) {
        case sa:
          a: {
            l3 = f3.key;
            for (k3 = d3; k3 !== null; ) {
              if (k3.key === l3) {
                switch (k3.tag) {
                  case 7:
                    if (f3.type === ua) {
                      c3(a3, k3.sibling);
                      d3 = e2(k3, f3.props.children);
                      d3.return = a3;
                      a3 = d3;
                      break a;
                    }
                    break;
                  default:
                    if (k3.elementType === f3.type) {
                      c3(a3, k3.sibling);
                      d3 = e2(k3, f3.props);
                      d3.ref = Qg(a3, k3, f3);
                      d3.return = a3;
                      a3 = d3;
                      break a;
                    }
                }
                c3(a3, k3);
                break;
              } else
                b2(a3, k3);
              k3 = k3.sibling;
            }
            f3.type === ua ? (d3 = Xg(f3.props.children, a3.mode, h3, f3.key), d3.return = a3, a3 = d3) : (h3 = Vg(f3.type, f3.key, f3.props, null, a3.mode, h3), h3.ref = Qg(a3, d3, f3), h3.return = a3, a3 = h3);
          }
          return g2(a3);
        case ta:
          a: {
            for (k3 = f3.key; d3 !== null; ) {
              if (d3.key === k3)
                if (d3.tag === 4 && d3.stateNode.containerInfo === f3.containerInfo && d3.stateNode.implementation === f3.implementation) {
                  c3(a3, d3.sibling);
                  d3 = e2(d3, f3.children || []);
                  d3.return = a3;
                  a3 = d3;
                  break a;
                } else {
                  c3(a3, d3);
                  break;
                }
              else
                b2(a3, d3);
              d3 = d3.sibling;
            }
            d3 = Wg(f3, a3.mode, h3);
            d3.return = a3;
            a3 = d3;
          }
          return g2(a3);
      }
    if (typeof f3 === "string" || typeof f3 === "number")
      return f3 = "" + f3, d3 !== null && d3.tag === 6 ? (c3(a3, d3.sibling), d3 = e2(d3, f3), d3.return = a3, a3 = d3) : (c3(a3, d3), d3 = Ug(f3, a3.mode, h3), d3.return = a3, a3 = d3), g2(a3);
    if (Pg(f3))
      return x2(a3, d3, f3, h3);
    if (La(f3))
      return w2(a3, d3, f3, h3);
    l3 && Rg(a3, f3);
    if (typeof f3 === "undefined" && !k3)
      switch (a3.tag) {
        case 1:
        case 22:
        case 0:
        case 11:
        case 15:
          throw Error(y(152, Ra(a3.type) || "Component"));
      }
    return c3(a3, d3);
  };
}
var Yg = Sg(true);
var Zg = Sg(false);
var $g = {};
var ah = Bf($g);
var bh = Bf($g);
var ch = Bf($g);
function dh(a2) {
  if (a2 === $g)
    throw Error(y(174));
  return a2;
}
function eh(a2, b2) {
  I(ch, b2);
  I(bh, a2);
  I(ah, $g);
  a2 = b2.nodeType;
  switch (a2) {
    case 9:
    case 11:
      b2 = (b2 = b2.documentElement) ? b2.namespaceURI : mb(null, "");
      break;
    default:
      a2 = a2 === 8 ? b2.parentNode : b2, b2 = a2.namespaceURI || null, a2 = a2.tagName, b2 = mb(b2, a2);
  }
  H(ah);
  I(ah, b2);
}
function fh() {
  H(ah);
  H(bh);
  H(ch);
}
function gh(a2) {
  dh(ch.current);
  var b2 = dh(ah.current);
  var c3 = mb(b2, a2.type);
  b2 !== c3 && (I(bh, a2), I(ah, c3));
}
function hh(a2) {
  bh.current === a2 && (H(ah), H(bh));
}
var P = Bf(0);
function ih(a2) {
  for (var b2 = a2; b2 !== null; ) {
    if (b2.tag === 13) {
      var c3 = b2.memoizedState;
      if (c3 !== null && (c3 = c3.dehydrated, c3 === null || c3.data === "$?" || c3.data === "$!"))
        return b2;
    } else if (b2.tag === 19 && b2.memoizedProps.revealOrder !== void 0) {
      if ((b2.flags & 64) !== 0)
        return b2;
    } else if (b2.child !== null) {
      b2.child.return = b2;
      b2 = b2.child;
      continue;
    }
    if (b2 === a2)
      break;
    for (; b2.sibling === null; ) {
      if (b2.return === null || b2.return === a2)
        return null;
      b2 = b2.return;
    }
    b2.sibling.return = b2.return;
    b2 = b2.sibling;
  }
  return null;
}
var jh = null;
var kh = null;
var lh = false;
function mh(a2, b2) {
  var c3 = nh(5, null, null, 0);
  c3.elementType = "DELETED";
  c3.type = "DELETED";
  c3.stateNode = b2;
  c3.return = a2;
  c3.flags = 8;
  a2.lastEffect !== null ? (a2.lastEffect.nextEffect = c3, a2.lastEffect = c3) : a2.firstEffect = a2.lastEffect = c3;
}
function oh(a2, b2) {
  switch (a2.tag) {
    case 5:
      var c3 = a2.type;
      b2 = b2.nodeType !== 1 || c3.toLowerCase() !== b2.nodeName.toLowerCase() ? null : b2;
      return b2 !== null ? (a2.stateNode = b2, true) : false;
    case 6:
      return b2 = a2.pendingProps === "" || b2.nodeType !== 3 ? null : b2, b2 !== null ? (a2.stateNode = b2, true) : false;
    case 13:
      return false;
    default:
      return false;
  }
}
function ph(a2) {
  if (lh) {
    var b2 = kh;
    if (b2) {
      var c3 = b2;
      if (!oh(a2, b2)) {
        b2 = rf(c3.nextSibling);
        if (!b2 || !oh(a2, b2)) {
          a2.flags = a2.flags & -1025 | 2;
          lh = false;
          jh = a2;
          return;
        }
        mh(jh, c3);
      }
      jh = a2;
      kh = rf(b2.firstChild);
    } else
      a2.flags = a2.flags & -1025 | 2, lh = false, jh = a2;
  }
}
function qh(a2) {
  for (a2 = a2.return; a2 !== null && a2.tag !== 5 && a2.tag !== 3 && a2.tag !== 13; )
    a2 = a2.return;
  jh = a2;
}
function rh(a2) {
  if (a2 !== jh)
    return false;
  if (!lh)
    return qh(a2), lh = true, false;
  var b2 = a2.type;
  if (a2.tag !== 5 || b2 !== "head" && b2 !== "body" && !nf(b2, a2.memoizedProps))
    for (b2 = kh; b2; )
      mh(a2, b2), b2 = rf(b2.nextSibling);
  qh(a2);
  if (a2.tag === 13) {
    a2 = a2.memoizedState;
    a2 = a2 !== null ? a2.dehydrated : null;
    if (!a2)
      throw Error(y(317));
    a: {
      a2 = a2.nextSibling;
      for (b2 = 0; a2; ) {
        if (a2.nodeType === 8) {
          var c3 = a2.data;
          if (c3 === "/$") {
            if (b2 === 0) {
              kh = rf(a2.nextSibling);
              break a;
            }
            b2--;
          } else
            c3 !== "$" && c3 !== "$!" && c3 !== "$?" || b2++;
        }
        a2 = a2.nextSibling;
      }
      kh = null;
    }
  } else
    kh = jh ? rf(a2.stateNode.nextSibling) : null;
  return true;
}
function sh() {
  kh = jh = null;
  lh = false;
}
var th = [];
function uh() {
  for (var a2 = 0; a2 < th.length; a2++)
    th[a2]._workInProgressVersionPrimary = null;
  th.length = 0;
}
var vh = ra.ReactCurrentDispatcher;
var wh = ra.ReactCurrentBatchConfig;
var xh = 0;
var R = null;
var S = null;
var T = null;
var yh = false;
var zh = false;
function Ah() {
  throw Error(y(321));
}
function Bh(a2, b2) {
  if (b2 === null)
    return false;
  for (var c3 = 0; c3 < b2.length && c3 < a2.length; c3++)
    if (!He(a2[c3], b2[c3]))
      return false;
  return true;
}
function Ch(a2, b2, c3, d2, e2, f2) {
  xh = f2;
  R = b2;
  b2.memoizedState = null;
  b2.updateQueue = null;
  b2.lanes = 0;
  vh.current = a2 === null || a2.memoizedState === null ? Dh : Eh;
  a2 = c3(d2, e2);
  if (zh) {
    f2 = 0;
    do {
      zh = false;
      if (!(25 > f2))
        throw Error(y(301));
      f2 += 1;
      T = S = null;
      b2.updateQueue = null;
      vh.current = Fh;
      a2 = c3(d2, e2);
    } while (zh);
  }
  vh.current = Gh;
  b2 = S !== null && S.next !== null;
  xh = 0;
  T = S = R = null;
  yh = false;
  if (b2)
    throw Error(y(300));
  return a2;
}
function Hh() {
  var a2 = {memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null};
  T === null ? R.memoizedState = T = a2 : T = T.next = a2;
  return T;
}
function Ih() {
  if (S === null) {
    var a2 = R.alternate;
    a2 = a2 !== null ? a2.memoizedState : null;
  } else
    a2 = S.next;
  var b2 = T === null ? R.memoizedState : T.next;
  if (b2 !== null)
    T = b2, S = a2;
  else {
    if (a2 === null)
      throw Error(y(310));
    S = a2;
    a2 = {memoizedState: S.memoizedState, baseState: S.baseState, baseQueue: S.baseQueue, queue: S.queue, next: null};
    T === null ? R.memoizedState = T = a2 : T = T.next = a2;
  }
  return T;
}
function Jh(a2, b2) {
  return typeof b2 === "function" ? b2(a2) : b2;
}
function Kh(a2) {
  var b2 = Ih(), c3 = b2.queue;
  if (c3 === null)
    throw Error(y(311));
  c3.lastRenderedReducer = a2;
  var d2 = S, e2 = d2.baseQueue, f2 = c3.pending;
  if (f2 !== null) {
    if (e2 !== null) {
      var g2 = e2.next;
      e2.next = f2.next;
      f2.next = g2;
    }
    d2.baseQueue = e2 = f2;
    c3.pending = null;
  }
  if (e2 !== null) {
    e2 = e2.next;
    d2 = d2.baseState;
    var h2 = g2 = f2 = null, k2 = e2;
    do {
      var l2 = k2.lane;
      if ((xh & l2) === l2)
        h2 !== null && (h2 = h2.next = {lane: 0, action: k2.action, eagerReducer: k2.eagerReducer, eagerState: k2.eagerState, next: null}), d2 = k2.eagerReducer === a2 ? k2.eagerState : a2(d2, k2.action);
      else {
        var n3 = {
          lane: l2,
          action: k2.action,
          eagerReducer: k2.eagerReducer,
          eagerState: k2.eagerState,
          next: null
        };
        h2 === null ? (g2 = h2 = n3, f2 = d2) : h2 = h2.next = n3;
        R.lanes |= l2;
        Dg |= l2;
      }
      k2 = k2.next;
    } while (k2 !== null && k2 !== e2);
    h2 === null ? f2 = d2 : h2.next = g2;
    He(d2, b2.memoizedState) || (ug = true);
    b2.memoizedState = d2;
    b2.baseState = f2;
    b2.baseQueue = h2;
    c3.lastRenderedState = d2;
  }
  return [b2.memoizedState, c3.dispatch];
}
function Lh(a2) {
  var b2 = Ih(), c3 = b2.queue;
  if (c3 === null)
    throw Error(y(311));
  c3.lastRenderedReducer = a2;
  var d2 = c3.dispatch, e2 = c3.pending, f2 = b2.memoizedState;
  if (e2 !== null) {
    c3.pending = null;
    var g2 = e2 = e2.next;
    do
      f2 = a2(f2, g2.action), g2 = g2.next;
    while (g2 !== e2);
    He(f2, b2.memoizedState) || (ug = true);
    b2.memoizedState = f2;
    b2.baseQueue === null && (b2.baseState = f2);
    c3.lastRenderedState = f2;
  }
  return [f2, d2];
}
function Mh(a2, b2, c3) {
  var d2 = b2._getVersion;
  d2 = d2(b2._source);
  var e2 = b2._workInProgressVersionPrimary;
  if (e2 !== null)
    a2 = e2 === d2;
  else if (a2 = a2.mutableReadLanes, a2 = (xh & a2) === a2)
    b2._workInProgressVersionPrimary = d2, th.push(b2);
  if (a2)
    return c3(b2._source);
  th.push(b2);
  throw Error(y(350));
}
function Nh(a2, b2, c3, d2) {
  var e2 = U;
  if (e2 === null)
    throw Error(y(349));
  var f2 = b2._getVersion, g2 = f2(b2._source), h2 = vh.current, k2 = h2.useState(function() {
    return Mh(e2, b2, c3);
  }), l2 = k2[1], n3 = k2[0];
  k2 = T;
  var A2 = a2.memoizedState, p2 = A2.refs, C = p2.getSnapshot, x2 = A2.source;
  A2 = A2.subscribe;
  var w2 = R;
  a2.memoizedState = {refs: p2, source: b2, subscribe: d2};
  h2.useEffect(function() {
    p2.getSnapshot = c3;
    p2.setSnapshot = l2;
    var a3 = f2(b2._source);
    if (!He(g2, a3)) {
      a3 = c3(b2._source);
      He(n3, a3) || (l2(a3), a3 = Ig(w2), e2.mutableReadLanes |= a3 & e2.pendingLanes);
      a3 = e2.mutableReadLanes;
      e2.entangledLanes |= a3;
      for (var d3 = e2.entanglements, h3 = a3; 0 < h3; ) {
        var k3 = 31 - Vc(h3), v2 = 1 << k3;
        d3[k3] |= a3;
        h3 &= ~v2;
      }
    }
  }, [c3, b2, d2]);
  h2.useEffect(function() {
    return d2(b2._source, function() {
      var a3 = p2.getSnapshot, c4 = p2.setSnapshot;
      try {
        c4(a3(b2._source));
        var d3 = Ig(w2);
        e2.mutableReadLanes |= d3 & e2.pendingLanes;
      } catch (q2) {
        c4(function() {
          throw q2;
        });
      }
    });
  }, [b2, d2]);
  He(C, c3) && He(x2, b2) && He(A2, d2) || (a2 = {pending: null, dispatch: null, lastRenderedReducer: Jh, lastRenderedState: n3}, a2.dispatch = l2 = Oh.bind(null, R, a2), k2.queue = a2, k2.baseQueue = null, n3 = Mh(e2, b2, c3), k2.memoizedState = k2.baseState = n3);
  return n3;
}
function Ph(a2, b2, c3) {
  var d2 = Ih();
  return Nh(d2, a2, b2, c3);
}
function Qh(a2) {
  var b2 = Hh();
  typeof a2 === "function" && (a2 = a2());
  b2.memoizedState = b2.baseState = a2;
  a2 = b2.queue = {pending: null, dispatch: null, lastRenderedReducer: Jh, lastRenderedState: a2};
  a2 = a2.dispatch = Oh.bind(null, R, a2);
  return [b2.memoizedState, a2];
}
function Rh(a2, b2, c3, d2) {
  a2 = {tag: a2, create: b2, destroy: c3, deps: d2, next: null};
  b2 = R.updateQueue;
  b2 === null ? (b2 = {lastEffect: null}, R.updateQueue = b2, b2.lastEffect = a2.next = a2) : (c3 = b2.lastEffect, c3 === null ? b2.lastEffect = a2.next = a2 : (d2 = c3.next, c3.next = a2, a2.next = d2, b2.lastEffect = a2));
  return a2;
}
function Sh(a2) {
  var b2 = Hh();
  a2 = {current: a2};
  return b2.memoizedState = a2;
}
function Th() {
  return Ih().memoizedState;
}
function Uh(a2, b2, c3, d2) {
  var e2 = Hh();
  R.flags |= a2;
  e2.memoizedState = Rh(1 | b2, c3, void 0, d2 === void 0 ? null : d2);
}
function Vh(a2, b2, c3, d2) {
  var e2 = Ih();
  d2 = d2 === void 0 ? null : d2;
  var f2 = void 0;
  if (S !== null) {
    var g2 = S.memoizedState;
    f2 = g2.destroy;
    if (d2 !== null && Bh(d2, g2.deps)) {
      Rh(b2, c3, f2, d2);
      return;
    }
  }
  R.flags |= a2;
  e2.memoizedState = Rh(1 | b2, c3, f2, d2);
}
function Wh(a2, b2) {
  return Uh(516, 4, a2, b2);
}
function Xh(a2, b2) {
  return Vh(516, 4, a2, b2);
}
function Yh(a2, b2) {
  return Vh(4, 2, a2, b2);
}
function Zh(a2, b2) {
  if (typeof b2 === "function")
    return a2 = a2(), b2(a2), function() {
      b2(null);
    };
  if (b2 !== null && b2 !== void 0)
    return a2 = a2(), b2.current = a2, function() {
      b2.current = null;
    };
}
function $h(a2, b2, c3) {
  c3 = c3 !== null && c3 !== void 0 ? c3.concat([a2]) : null;
  return Vh(4, 2, Zh.bind(null, b2, a2), c3);
}
function ai() {
}
function bi(a2, b2) {
  var c3 = Ih();
  b2 = b2 === void 0 ? null : b2;
  var d2 = c3.memoizedState;
  if (d2 !== null && b2 !== null && Bh(b2, d2[1]))
    return d2[0];
  c3.memoizedState = [a2, b2];
  return a2;
}
function ci(a2, b2) {
  var c3 = Ih();
  b2 = b2 === void 0 ? null : b2;
  var d2 = c3.memoizedState;
  if (d2 !== null && b2 !== null && Bh(b2, d2[1]))
    return d2[0];
  a2 = a2();
  c3.memoizedState = [a2, b2];
  return a2;
}
function di(a2, b2) {
  var c3 = eg();
  gg(98 > c3 ? 98 : c3, function() {
    a2(true);
  });
  gg(97 < c3 ? 97 : c3, function() {
    var c4 = wh.transition;
    wh.transition = 1;
    try {
      a2(false), b2();
    } finally {
      wh.transition = c4;
    }
  });
}
function Oh(a2, b2, c3) {
  var d2 = Hg(), e2 = Ig(a2), f2 = {lane: e2, action: c3, eagerReducer: null, eagerState: null, next: null}, g2 = b2.pending;
  g2 === null ? f2.next = f2 : (f2.next = g2.next, g2.next = f2);
  b2.pending = f2;
  g2 = a2.alternate;
  if (a2 === R || g2 !== null && g2 === R)
    zh = yh = true;
  else {
    if (a2.lanes === 0 && (g2 === null || g2.lanes === 0) && (g2 = b2.lastRenderedReducer, g2 !== null))
      try {
        var h2 = b2.lastRenderedState, k2 = g2(h2, c3);
        f2.eagerReducer = g2;
        f2.eagerState = k2;
        if (He(k2, h2))
          return;
      } catch (l2) {
      } finally {
      }
    Jg(a2, e2, d2);
  }
}
var Gh = {readContext: vg, useCallback: Ah, useContext: Ah, useEffect: Ah, useImperativeHandle: Ah, useLayoutEffect: Ah, useMemo: Ah, useReducer: Ah, useRef: Ah, useState: Ah, useDebugValue: Ah, useDeferredValue: Ah, useTransition: Ah, useMutableSource: Ah, useOpaqueIdentifier: Ah, unstable_isNewReconciler: false};
var Dh = {readContext: vg, useCallback: function(a2, b2) {
  Hh().memoizedState = [a2, b2 === void 0 ? null : b2];
  return a2;
}, useContext: vg, useEffect: Wh, useImperativeHandle: function(a2, b2, c3) {
  c3 = c3 !== null && c3 !== void 0 ? c3.concat([a2]) : null;
  return Uh(4, 2, Zh.bind(null, b2, a2), c3);
}, useLayoutEffect: function(a2, b2) {
  return Uh(4, 2, a2, b2);
}, useMemo: function(a2, b2) {
  var c3 = Hh();
  b2 = b2 === void 0 ? null : b2;
  a2 = a2();
  c3.memoizedState = [a2, b2];
  return a2;
}, useReducer: function(a2, b2, c3) {
  var d2 = Hh();
  b2 = c3 !== void 0 ? c3(b2) : b2;
  d2.memoizedState = d2.baseState = b2;
  a2 = d2.queue = {pending: null, dispatch: null, lastRenderedReducer: a2, lastRenderedState: b2};
  a2 = a2.dispatch = Oh.bind(null, R, a2);
  return [d2.memoizedState, a2];
}, useRef: Sh, useState: Qh, useDebugValue: ai, useDeferredValue: function(a2) {
  var b2 = Qh(a2), c3 = b2[0], d2 = b2[1];
  Wh(function() {
    var b3 = wh.transition;
    wh.transition = 1;
    try {
      d2(a2);
    } finally {
      wh.transition = b3;
    }
  }, [a2]);
  return c3;
}, useTransition: function() {
  var a2 = Qh(false), b2 = a2[0];
  a2 = di.bind(null, a2[1]);
  Sh(a2);
  return [a2, b2];
}, useMutableSource: function(a2, b2, c3) {
  var d2 = Hh();
  d2.memoizedState = {refs: {getSnapshot: b2, setSnapshot: null}, source: a2, subscribe: c3};
  return Nh(d2, a2, b2, c3);
}, useOpaqueIdentifier: function() {
  if (lh) {
    var a2 = false, b2 = uf(function() {
      a2 || (a2 = true, c3("r:" + (tf++).toString(36)));
      throw Error(y(355));
    }), c3 = Qh(b2)[1];
    (R.mode & 2) === 0 && (R.flags |= 516, Rh(5, function() {
      c3("r:" + (tf++).toString(36));
    }, void 0, null));
    return b2;
  }
  b2 = "r:" + (tf++).toString(36);
  Qh(b2);
  return b2;
}, unstable_isNewReconciler: false};
var Eh = {readContext: vg, useCallback: bi, useContext: vg, useEffect: Xh, useImperativeHandle: $h, useLayoutEffect: Yh, useMemo: ci, useReducer: Kh, useRef: Th, useState: function() {
  return Kh(Jh);
}, useDebugValue: ai, useDeferredValue: function(a2) {
  var b2 = Kh(Jh), c3 = b2[0], d2 = b2[1];
  Xh(function() {
    var b3 = wh.transition;
    wh.transition = 1;
    try {
      d2(a2);
    } finally {
      wh.transition = b3;
    }
  }, [a2]);
  return c3;
}, useTransition: function() {
  var a2 = Kh(Jh)[0];
  return [
    Th().current,
    a2
  ];
}, useMutableSource: Ph, useOpaqueIdentifier: function() {
  return Kh(Jh)[0];
}, unstable_isNewReconciler: false};
var Fh = {readContext: vg, useCallback: bi, useContext: vg, useEffect: Xh, useImperativeHandle: $h, useLayoutEffect: Yh, useMemo: ci, useReducer: Lh, useRef: Th, useState: function() {
  return Lh(Jh);
}, useDebugValue: ai, useDeferredValue: function(a2) {
  var b2 = Lh(Jh), c3 = b2[0], d2 = b2[1];
  Xh(function() {
    var b3 = wh.transition;
    wh.transition = 1;
    try {
      d2(a2);
    } finally {
      wh.transition = b3;
    }
  }, [a2]);
  return c3;
}, useTransition: function() {
  var a2 = Lh(Jh)[0];
  return [
    Th().current,
    a2
  ];
}, useMutableSource: Ph, useOpaqueIdentifier: function() {
  return Lh(Jh)[0];
}, unstable_isNewReconciler: false};
var ei = ra.ReactCurrentOwner;
var ug = false;
function fi(a2, b2, c3, d2) {
  b2.child = a2 === null ? Zg(b2, null, c3, d2) : Yg(b2, a2.child, c3, d2);
}
function gi(a2, b2, c3, d2, e2) {
  c3 = c3.render;
  var f2 = b2.ref;
  tg(b2, e2);
  d2 = Ch(a2, b2, c3, d2, f2, e2);
  if (a2 !== null && !ug)
    return b2.updateQueue = a2.updateQueue, b2.flags &= -517, a2.lanes &= ~e2, hi(a2, b2, e2);
  b2.flags |= 1;
  fi(a2, b2, d2, e2);
  return b2.child;
}
function ii(a2, b2, c3, d2, e2, f2) {
  if (a2 === null) {
    var g2 = c3.type;
    if (typeof g2 === "function" && !ji(g2) && g2.defaultProps === void 0 && c3.compare === null && c3.defaultProps === void 0)
      return b2.tag = 15, b2.type = g2, ki(a2, b2, g2, d2, e2, f2);
    a2 = Vg(c3.type, null, d2, b2, b2.mode, f2);
    a2.ref = b2.ref;
    a2.return = b2;
    return b2.child = a2;
  }
  g2 = a2.child;
  if ((e2 & f2) === 0 && (e2 = g2.memoizedProps, c3 = c3.compare, c3 = c3 !== null ? c3 : Je, c3(e2, d2) && a2.ref === b2.ref))
    return hi(a2, b2, f2);
  b2.flags |= 1;
  a2 = Tg(g2, d2);
  a2.ref = b2.ref;
  a2.return = b2;
  return b2.child = a2;
}
function ki(a2, b2, c3, d2, e2, f2) {
  if (a2 !== null && Je(a2.memoizedProps, d2) && a2.ref === b2.ref)
    if (ug = false, (f2 & e2) !== 0)
      (a2.flags & 16384) !== 0 && (ug = true);
    else
      return b2.lanes = a2.lanes, hi(a2, b2, f2);
  return li(a2, b2, c3, d2, f2);
}
function mi(a2, b2, c3) {
  var d2 = b2.pendingProps, e2 = d2.children, f2 = a2 !== null ? a2.memoizedState : null;
  if (d2.mode === "hidden" || d2.mode === "unstable-defer-without-hiding")
    if ((b2.mode & 4) === 0)
      b2.memoizedState = {baseLanes: 0}, ni(b2, c3);
    else if ((c3 & 1073741824) !== 0)
      b2.memoizedState = {baseLanes: 0}, ni(b2, f2 !== null ? f2.baseLanes : c3);
    else
      return a2 = f2 !== null ? f2.baseLanes | c3 : c3, b2.lanes = b2.childLanes = 1073741824, b2.memoizedState = {baseLanes: a2}, ni(b2, a2), null;
  else
    f2 !== null ? (d2 = f2.baseLanes | c3, b2.memoizedState = null) : d2 = c3, ni(b2, d2);
  fi(a2, b2, e2, c3);
  return b2.child;
}
function oi(a2, b2) {
  var c3 = b2.ref;
  if (a2 === null && c3 !== null || a2 !== null && a2.ref !== c3)
    b2.flags |= 128;
}
function li(a2, b2, c3, d2, e2) {
  var f2 = Ff(c3) ? Df : M.current;
  f2 = Ef(b2, f2);
  tg(b2, e2);
  c3 = Ch(a2, b2, c3, d2, f2, e2);
  if (a2 !== null && !ug)
    return b2.updateQueue = a2.updateQueue, b2.flags &= -517, a2.lanes &= ~e2, hi(a2, b2, e2);
  b2.flags |= 1;
  fi(a2, b2, c3, e2);
  return b2.child;
}
function pi(a2, b2, c3, d2, e2) {
  if (Ff(c3)) {
    var f2 = true;
    Jf(b2);
  } else
    f2 = false;
  tg(b2, e2);
  if (b2.stateNode === null)
    a2 !== null && (a2.alternate = null, b2.alternate = null, b2.flags |= 2), Mg(b2, c3, d2), Og(b2, c3, d2, e2), d2 = true;
  else if (a2 === null) {
    var g2 = b2.stateNode, h2 = b2.memoizedProps;
    g2.props = h2;
    var k2 = g2.context, l2 = c3.contextType;
    typeof l2 === "object" && l2 !== null ? l2 = vg(l2) : (l2 = Ff(c3) ? Df : M.current, l2 = Ef(b2, l2));
    var n3 = c3.getDerivedStateFromProps, A2 = typeof n3 === "function" || typeof g2.getSnapshotBeforeUpdate === "function";
    A2 || typeof g2.UNSAFE_componentWillReceiveProps !== "function" && typeof g2.componentWillReceiveProps !== "function" || (h2 !== d2 || k2 !== l2) && Ng(b2, g2, d2, l2);
    wg = false;
    var p2 = b2.memoizedState;
    g2.state = p2;
    Cg(b2, d2, g2, e2);
    k2 = b2.memoizedState;
    h2 !== d2 || p2 !== k2 || N.current || wg ? (typeof n3 === "function" && (Gg(b2, c3, n3, d2), k2 = b2.memoizedState), (h2 = wg || Lg(b2, c3, h2, d2, p2, k2, l2)) ? (A2 || typeof g2.UNSAFE_componentWillMount !== "function" && typeof g2.componentWillMount !== "function" || (typeof g2.componentWillMount === "function" && g2.componentWillMount(), typeof g2.UNSAFE_componentWillMount === "function" && g2.UNSAFE_componentWillMount()), typeof g2.componentDidMount === "function" && (b2.flags |= 4)) : (typeof g2.componentDidMount === "function" && (b2.flags |= 4), b2.memoizedProps = d2, b2.memoizedState = k2), g2.props = d2, g2.state = k2, g2.context = l2, d2 = h2) : (typeof g2.componentDidMount === "function" && (b2.flags |= 4), d2 = false);
  } else {
    g2 = b2.stateNode;
    yg(a2, b2);
    h2 = b2.memoizedProps;
    l2 = b2.type === b2.elementType ? h2 : lg(b2.type, h2);
    g2.props = l2;
    A2 = b2.pendingProps;
    p2 = g2.context;
    k2 = c3.contextType;
    typeof k2 === "object" && k2 !== null ? k2 = vg(k2) : (k2 = Ff(c3) ? Df : M.current, k2 = Ef(b2, k2));
    var C = c3.getDerivedStateFromProps;
    (n3 = typeof C === "function" || typeof g2.getSnapshotBeforeUpdate === "function") || typeof g2.UNSAFE_componentWillReceiveProps !== "function" && typeof g2.componentWillReceiveProps !== "function" || (h2 !== A2 || p2 !== k2) && Ng(b2, g2, d2, k2);
    wg = false;
    p2 = b2.memoizedState;
    g2.state = p2;
    Cg(b2, d2, g2, e2);
    var x2 = b2.memoizedState;
    h2 !== A2 || p2 !== x2 || N.current || wg ? (typeof C === "function" && (Gg(b2, c3, C, d2), x2 = b2.memoizedState), (l2 = wg || Lg(b2, c3, l2, d2, p2, x2, k2)) ? (n3 || typeof g2.UNSAFE_componentWillUpdate !== "function" && typeof g2.componentWillUpdate !== "function" || (typeof g2.componentWillUpdate === "function" && g2.componentWillUpdate(d2, x2, k2), typeof g2.UNSAFE_componentWillUpdate === "function" && g2.UNSAFE_componentWillUpdate(d2, x2, k2)), typeof g2.componentDidUpdate === "function" && (b2.flags |= 4), typeof g2.getSnapshotBeforeUpdate === "function" && (b2.flags |= 256)) : (typeof g2.componentDidUpdate !== "function" || h2 === a2.memoizedProps && p2 === a2.memoizedState || (b2.flags |= 4), typeof g2.getSnapshotBeforeUpdate !== "function" || h2 === a2.memoizedProps && p2 === a2.memoizedState || (b2.flags |= 256), b2.memoizedProps = d2, b2.memoizedState = x2), g2.props = d2, g2.state = x2, g2.context = k2, d2 = l2) : (typeof g2.componentDidUpdate !== "function" || h2 === a2.memoizedProps && p2 === a2.memoizedState || (b2.flags |= 4), typeof g2.getSnapshotBeforeUpdate !== "function" || h2 === a2.memoizedProps && p2 === a2.memoizedState || (b2.flags |= 256), d2 = false);
  }
  return qi(a2, b2, c3, d2, f2, e2);
}
function qi(a2, b2, c3, d2, e2, f2) {
  oi(a2, b2);
  var g2 = (b2.flags & 64) !== 0;
  if (!d2 && !g2)
    return e2 && Kf(b2, c3, false), hi(a2, b2, f2);
  d2 = b2.stateNode;
  ei.current = b2;
  var h2 = g2 && typeof c3.getDerivedStateFromError !== "function" ? null : d2.render();
  b2.flags |= 1;
  a2 !== null && g2 ? (b2.child = Yg(b2, a2.child, null, f2), b2.child = Yg(b2, null, h2, f2)) : fi(a2, b2, h2, f2);
  b2.memoizedState = d2.state;
  e2 && Kf(b2, c3, true);
  return b2.child;
}
function ri(a2) {
  var b2 = a2.stateNode;
  b2.pendingContext ? Hf(a2, b2.pendingContext, b2.pendingContext !== b2.context) : b2.context && Hf(a2, b2.context, false);
  eh(a2, b2.containerInfo);
}
var si = {dehydrated: null, retryLane: 0};
function ti(a2, b2, c3) {
  var d2 = b2.pendingProps, e2 = P.current, f2 = false, g2;
  (g2 = (b2.flags & 64) !== 0) || (g2 = a2 !== null && a2.memoizedState === null ? false : (e2 & 2) !== 0);
  g2 ? (f2 = true, b2.flags &= -65) : a2 !== null && a2.memoizedState === null || d2.fallback === void 0 || d2.unstable_avoidThisFallback === true || (e2 |= 1);
  I(P, e2 & 1);
  if (a2 === null) {
    d2.fallback !== void 0 && ph(b2);
    a2 = d2.children;
    e2 = d2.fallback;
    if (f2)
      return a2 = ui(b2, a2, e2, c3), b2.child.memoizedState = {baseLanes: c3}, b2.memoizedState = si, a2;
    if (typeof d2.unstable_expectedLoadTime === "number")
      return a2 = ui(b2, a2, e2, c3), b2.child.memoizedState = {baseLanes: c3}, b2.memoizedState = si, b2.lanes = 33554432, a2;
    c3 = vi({mode: "visible", children: a2}, b2.mode, c3, null);
    c3.return = b2;
    return b2.child = c3;
  }
  if (a2.memoizedState !== null) {
    if (f2)
      return d2 = wi(a2, b2, d2.children, d2.fallback, c3), f2 = b2.child, e2 = a2.child.memoizedState, f2.memoizedState = e2 === null ? {baseLanes: c3} : {baseLanes: e2.baseLanes | c3}, f2.childLanes = a2.childLanes & ~c3, b2.memoizedState = si, d2;
    c3 = xi(a2, b2, d2.children, c3);
    b2.memoizedState = null;
    return c3;
  }
  if (f2)
    return d2 = wi(a2, b2, d2.children, d2.fallback, c3), f2 = b2.child, e2 = a2.child.memoizedState, f2.memoizedState = e2 === null ? {baseLanes: c3} : {baseLanes: e2.baseLanes | c3}, f2.childLanes = a2.childLanes & ~c3, b2.memoizedState = si, d2;
  c3 = xi(a2, b2, d2.children, c3);
  b2.memoizedState = null;
  return c3;
}
function ui(a2, b2, c3, d2) {
  var e2 = a2.mode, f2 = a2.child;
  b2 = {mode: "hidden", children: b2};
  (e2 & 2) === 0 && f2 !== null ? (f2.childLanes = 0, f2.pendingProps = b2) : f2 = vi(b2, e2, 0, null);
  c3 = Xg(c3, e2, d2, null);
  f2.return = a2;
  c3.return = a2;
  f2.sibling = c3;
  a2.child = f2;
  return c3;
}
function xi(a2, b2, c3, d2) {
  var e2 = a2.child;
  a2 = e2.sibling;
  c3 = Tg(e2, {mode: "visible", children: c3});
  (b2.mode & 2) === 0 && (c3.lanes = d2);
  c3.return = b2;
  c3.sibling = null;
  a2 !== null && (a2.nextEffect = null, a2.flags = 8, b2.firstEffect = b2.lastEffect = a2);
  return b2.child = c3;
}
function wi(a2, b2, c3, d2, e2) {
  var f2 = b2.mode, g2 = a2.child;
  a2 = g2.sibling;
  var h2 = {mode: "hidden", children: c3};
  (f2 & 2) === 0 && b2.child !== g2 ? (c3 = b2.child, c3.childLanes = 0, c3.pendingProps = h2, g2 = c3.lastEffect, g2 !== null ? (b2.firstEffect = c3.firstEffect, b2.lastEffect = g2, g2.nextEffect = null) : b2.firstEffect = b2.lastEffect = null) : c3 = Tg(g2, h2);
  a2 !== null ? d2 = Tg(a2, d2) : (d2 = Xg(d2, f2, e2, null), d2.flags |= 2);
  d2.return = b2;
  c3.return = b2;
  c3.sibling = d2;
  b2.child = c3;
  return d2;
}
function yi(a2, b2) {
  a2.lanes |= b2;
  var c3 = a2.alternate;
  c3 !== null && (c3.lanes |= b2);
  sg(a2.return, b2);
}
function zi(a2, b2, c3, d2, e2, f2) {
  var g2 = a2.memoizedState;
  g2 === null ? a2.memoizedState = {isBackwards: b2, rendering: null, renderingStartTime: 0, last: d2, tail: c3, tailMode: e2, lastEffect: f2} : (g2.isBackwards = b2, g2.rendering = null, g2.renderingStartTime = 0, g2.last = d2, g2.tail = c3, g2.tailMode = e2, g2.lastEffect = f2);
}
function Ai(a2, b2, c3) {
  var d2 = b2.pendingProps, e2 = d2.revealOrder, f2 = d2.tail;
  fi(a2, b2, d2.children, c3);
  d2 = P.current;
  if ((d2 & 2) !== 0)
    d2 = d2 & 1 | 2, b2.flags |= 64;
  else {
    if (a2 !== null && (a2.flags & 64) !== 0)
      a:
        for (a2 = b2.child; a2 !== null; ) {
          if (a2.tag === 13)
            a2.memoizedState !== null && yi(a2, c3);
          else if (a2.tag === 19)
            yi(a2, c3);
          else if (a2.child !== null) {
            a2.child.return = a2;
            a2 = a2.child;
            continue;
          }
          if (a2 === b2)
            break a;
          for (; a2.sibling === null; ) {
            if (a2.return === null || a2.return === b2)
              break a;
            a2 = a2.return;
          }
          a2.sibling.return = a2.return;
          a2 = a2.sibling;
        }
    d2 &= 1;
  }
  I(P, d2);
  if ((b2.mode & 2) === 0)
    b2.memoizedState = null;
  else
    switch (e2) {
      case "forwards":
        c3 = b2.child;
        for (e2 = null; c3 !== null; )
          a2 = c3.alternate, a2 !== null && ih(a2) === null && (e2 = c3), c3 = c3.sibling;
        c3 = e2;
        c3 === null ? (e2 = b2.child, b2.child = null) : (e2 = c3.sibling, c3.sibling = null);
        zi(b2, false, e2, c3, f2, b2.lastEffect);
        break;
      case "backwards":
        c3 = null;
        e2 = b2.child;
        for (b2.child = null; e2 !== null; ) {
          a2 = e2.alternate;
          if (a2 !== null && ih(a2) === null) {
            b2.child = e2;
            break;
          }
          a2 = e2.sibling;
          e2.sibling = c3;
          c3 = e2;
          e2 = a2;
        }
        zi(b2, true, c3, null, f2, b2.lastEffect);
        break;
      case "together":
        zi(b2, false, null, null, void 0, b2.lastEffect);
        break;
      default:
        b2.memoizedState = null;
    }
  return b2.child;
}
function hi(a2, b2, c3) {
  a2 !== null && (b2.dependencies = a2.dependencies);
  Dg |= b2.lanes;
  if ((c3 & b2.childLanes) !== 0) {
    if (a2 !== null && b2.child !== a2.child)
      throw Error(y(153));
    if (b2.child !== null) {
      a2 = b2.child;
      c3 = Tg(a2, a2.pendingProps);
      b2.child = c3;
      for (c3.return = b2; a2.sibling !== null; )
        a2 = a2.sibling, c3 = c3.sibling = Tg(a2, a2.pendingProps), c3.return = b2;
      c3.sibling = null;
    }
    return b2.child;
  }
  return null;
}
var Bi;
var Ci;
var Di;
var Ei;
Bi = function(a2, b2) {
  for (var c3 = b2.child; c3 !== null; ) {
    if (c3.tag === 5 || c3.tag === 6)
      a2.appendChild(c3.stateNode);
    else if (c3.tag !== 4 && c3.child !== null) {
      c3.child.return = c3;
      c3 = c3.child;
      continue;
    }
    if (c3 === b2)
      break;
    for (; c3.sibling === null; ) {
      if (c3.return === null || c3.return === b2)
        return;
      c3 = c3.return;
    }
    c3.sibling.return = c3.return;
    c3 = c3.sibling;
  }
};
Ci = function() {
};
Di = function(a2, b2, c3, d2) {
  var e2 = a2.memoizedProps;
  if (e2 !== d2) {
    a2 = b2.stateNode;
    dh(ah.current);
    var f2 = null;
    switch (c3) {
      case "input":
        e2 = Ya(a2, e2);
        d2 = Ya(a2, d2);
        f2 = [];
        break;
      case "option":
        e2 = eb(a2, e2);
        d2 = eb(a2, d2);
        f2 = [];
        break;
      case "select":
        e2 = objectAssign({}, e2, {value: void 0});
        d2 = objectAssign({}, d2, {value: void 0});
        f2 = [];
        break;
      case "textarea":
        e2 = gb(a2, e2);
        d2 = gb(a2, d2);
        f2 = [];
        break;
      default:
        typeof e2.onClick !== "function" && typeof d2.onClick === "function" && (a2.onclick = jf);
    }
    vb(c3, d2);
    var g2;
    c3 = null;
    for (l2 in e2)
      if (!d2.hasOwnProperty(l2) && e2.hasOwnProperty(l2) && e2[l2] != null)
        if (l2 === "style") {
          var h2 = e2[l2];
          for (g2 in h2)
            h2.hasOwnProperty(g2) && (c3 || (c3 = {}), c3[g2] = "");
        } else
          l2 !== "dangerouslySetInnerHTML" && l2 !== "children" && l2 !== "suppressContentEditableWarning" && l2 !== "suppressHydrationWarning" && l2 !== "autoFocus" && (ca.hasOwnProperty(l2) ? f2 || (f2 = []) : (f2 = f2 || []).push(l2, null));
    for (l2 in d2) {
      var k2 = d2[l2];
      h2 = e2 != null ? e2[l2] : void 0;
      if (d2.hasOwnProperty(l2) && k2 !== h2 && (k2 != null || h2 != null))
        if (l2 === "style")
          if (h2) {
            for (g2 in h2)
              !h2.hasOwnProperty(g2) || k2 && k2.hasOwnProperty(g2) || (c3 || (c3 = {}), c3[g2] = "");
            for (g2 in k2)
              k2.hasOwnProperty(g2) && h2[g2] !== k2[g2] && (c3 || (c3 = {}), c3[g2] = k2[g2]);
          } else
            c3 || (f2 || (f2 = []), f2.push(l2, c3)), c3 = k2;
        else
          l2 === "dangerouslySetInnerHTML" ? (k2 = k2 ? k2.__html : void 0, h2 = h2 ? h2.__html : void 0, k2 != null && h2 !== k2 && (f2 = f2 || []).push(l2, k2)) : l2 === "children" ? typeof k2 !== "string" && typeof k2 !== "number" || (f2 = f2 || []).push(l2, "" + k2) : l2 !== "suppressContentEditableWarning" && l2 !== "suppressHydrationWarning" && (ca.hasOwnProperty(l2) ? (k2 != null && l2 === "onScroll" && G("scroll", a2), f2 || h2 === k2 || (f2 = [])) : typeof k2 === "object" && k2 !== null && k2.$$typeof === Ga ? k2.toString() : (f2 = f2 || []).push(l2, k2));
    }
    c3 && (f2 = f2 || []).push("style", c3);
    var l2 = f2;
    if (b2.updateQueue = l2)
      b2.flags |= 4;
  }
};
Ei = function(a2, b2, c3, d2) {
  c3 !== d2 && (b2.flags |= 4);
};
function Fi(a2, b2) {
  if (!lh)
    switch (a2.tailMode) {
      case "hidden":
        b2 = a2.tail;
        for (var c3 = null; b2 !== null; )
          b2.alternate !== null && (c3 = b2), b2 = b2.sibling;
        c3 === null ? a2.tail = null : c3.sibling = null;
        break;
      case "collapsed":
        c3 = a2.tail;
        for (var d2 = null; c3 !== null; )
          c3.alternate !== null && (d2 = c3), c3 = c3.sibling;
        d2 === null ? b2 || a2.tail === null ? a2.tail = null : a2.tail.sibling = null : d2.sibling = null;
    }
}
function Gi(a2, b2, c3) {
  var d2 = b2.pendingProps;
  switch (b2.tag) {
    case 2:
    case 16:
    case 15:
    case 0:
    case 11:
    case 7:
    case 8:
    case 12:
    case 9:
    case 14:
      return null;
    case 1:
      return Ff(b2.type) && Gf(), null;
    case 3:
      fh();
      H(N);
      H(M);
      uh();
      d2 = b2.stateNode;
      d2.pendingContext && (d2.context = d2.pendingContext, d2.pendingContext = null);
      if (a2 === null || a2.child === null)
        rh(b2) ? b2.flags |= 4 : d2.hydrate || (b2.flags |= 256);
      Ci(b2);
      return null;
    case 5:
      hh(b2);
      var e2 = dh(ch.current);
      c3 = b2.type;
      if (a2 !== null && b2.stateNode != null)
        Di(a2, b2, c3, d2, e2), a2.ref !== b2.ref && (b2.flags |= 128);
      else {
        if (!d2) {
          if (b2.stateNode === null)
            throw Error(y(166));
          return null;
        }
        a2 = dh(ah.current);
        if (rh(b2)) {
          d2 = b2.stateNode;
          c3 = b2.type;
          var f2 = b2.memoizedProps;
          d2[wf] = b2;
          d2[xf] = f2;
          switch (c3) {
            case "dialog":
              G("cancel", d2);
              G("close", d2);
              break;
            case "iframe":
            case "object":
            case "embed":
              G("load", d2);
              break;
            case "video":
            case "audio":
              for (a2 = 0; a2 < Xe.length; a2++)
                G(Xe[a2], d2);
              break;
            case "source":
              G("error", d2);
              break;
            case "img":
            case "image":
            case "link":
              G("error", d2);
              G("load", d2);
              break;
            case "details":
              G("toggle", d2);
              break;
            case "input":
              Za(d2, f2);
              G("invalid", d2);
              break;
            case "select":
              d2._wrapperState = {wasMultiple: !!f2.multiple};
              G("invalid", d2);
              break;
            case "textarea":
              hb(d2, f2), G("invalid", d2);
          }
          vb(c3, f2);
          a2 = null;
          for (var g2 in f2)
            f2.hasOwnProperty(g2) && (e2 = f2[g2], g2 === "children" ? typeof e2 === "string" ? d2.textContent !== e2 && (a2 = ["children", e2]) : typeof e2 === "number" && d2.textContent !== "" + e2 && (a2 = ["children", "" + e2]) : ca.hasOwnProperty(g2) && e2 != null && g2 === "onScroll" && G("scroll", d2));
          switch (c3) {
            case "input":
              Va(d2);
              cb(d2, f2, true);
              break;
            case "textarea":
              Va(d2);
              jb(d2);
              break;
            case "select":
            case "option":
              break;
            default:
              typeof f2.onClick === "function" && (d2.onclick = jf);
          }
          d2 = a2;
          b2.updateQueue = d2;
          d2 !== null && (b2.flags |= 4);
        } else {
          g2 = e2.nodeType === 9 ? e2 : e2.ownerDocument;
          a2 === kb.html && (a2 = lb(c3));
          a2 === kb.html ? c3 === "script" ? (a2 = g2.createElement("div"), a2.innerHTML = "<script></script>", a2 = a2.removeChild(a2.firstChild)) : typeof d2.is === "string" ? a2 = g2.createElement(c3, {is: d2.is}) : (a2 = g2.createElement(c3), c3 === "select" && (g2 = a2, d2.multiple ? g2.multiple = true : d2.size && (g2.size = d2.size))) : a2 = g2.createElementNS(a2, c3);
          a2[wf] = b2;
          a2[xf] = d2;
          Bi(a2, b2, false, false);
          b2.stateNode = a2;
          g2 = wb(c3, d2);
          switch (c3) {
            case "dialog":
              G("cancel", a2);
              G("close", a2);
              e2 = d2;
              break;
            case "iframe":
            case "object":
            case "embed":
              G("load", a2);
              e2 = d2;
              break;
            case "video":
            case "audio":
              for (e2 = 0; e2 < Xe.length; e2++)
                G(Xe[e2], a2);
              e2 = d2;
              break;
            case "source":
              G("error", a2);
              e2 = d2;
              break;
            case "img":
            case "image":
            case "link":
              G("error", a2);
              G("load", a2);
              e2 = d2;
              break;
            case "details":
              G("toggle", a2);
              e2 = d2;
              break;
            case "input":
              Za(a2, d2);
              e2 = Ya(a2, d2);
              G("invalid", a2);
              break;
            case "option":
              e2 = eb(a2, d2);
              break;
            case "select":
              a2._wrapperState = {wasMultiple: !!d2.multiple};
              e2 = objectAssign({}, d2, {value: void 0});
              G("invalid", a2);
              break;
            case "textarea":
              hb(a2, d2);
              e2 = gb(a2, d2);
              G("invalid", a2);
              break;
            default:
              e2 = d2;
          }
          vb(c3, e2);
          var h2 = e2;
          for (f2 in h2)
            if (h2.hasOwnProperty(f2)) {
              var k2 = h2[f2];
              f2 === "style" ? tb(a2, k2) : f2 === "dangerouslySetInnerHTML" ? (k2 = k2 ? k2.__html : void 0, k2 != null && ob(a2, k2)) : f2 === "children" ? typeof k2 === "string" ? (c3 !== "textarea" || k2 !== "") && pb(a2, k2) : typeof k2 === "number" && pb(a2, "" + k2) : f2 !== "suppressContentEditableWarning" && f2 !== "suppressHydrationWarning" && f2 !== "autoFocus" && (ca.hasOwnProperty(f2) ? k2 != null && f2 === "onScroll" && G("scroll", a2) : k2 != null && qa(a2, f2, k2, g2));
            }
          switch (c3) {
            case "input":
              Va(a2);
              cb(a2, d2, false);
              break;
            case "textarea":
              Va(a2);
              jb(a2);
              break;
            case "option":
              d2.value != null && a2.setAttribute("value", "" + Sa(d2.value));
              break;
            case "select":
              a2.multiple = !!d2.multiple;
              f2 = d2.value;
              f2 != null ? fb(a2, !!d2.multiple, f2, false) : d2.defaultValue != null && fb(a2, !!d2.multiple, d2.defaultValue, true);
              break;
            default:
              typeof e2.onClick === "function" && (a2.onclick = jf);
          }
          mf(c3, d2) && (b2.flags |= 4);
        }
        b2.ref !== null && (b2.flags |= 128);
      }
      return null;
    case 6:
      if (a2 && b2.stateNode != null)
        Ei(a2, b2, a2.memoizedProps, d2);
      else {
        if (typeof d2 !== "string" && b2.stateNode === null)
          throw Error(y(166));
        c3 = dh(ch.current);
        dh(ah.current);
        rh(b2) ? (d2 = b2.stateNode, c3 = b2.memoizedProps, d2[wf] = b2, d2.nodeValue !== c3 && (b2.flags |= 4)) : (d2 = (c3.nodeType === 9 ? c3 : c3.ownerDocument).createTextNode(d2), d2[wf] = b2, b2.stateNode = d2);
      }
      return null;
    case 13:
      H(P);
      d2 = b2.memoizedState;
      if ((b2.flags & 64) !== 0)
        return b2.lanes = c3, b2;
      d2 = d2 !== null;
      c3 = false;
      a2 === null ? b2.memoizedProps.fallback !== void 0 && rh(b2) : c3 = a2.memoizedState !== null;
      if (d2 && !c3 && (b2.mode & 2) !== 0)
        if (a2 === null && b2.memoizedProps.unstable_avoidThisFallback !== true || (P.current & 1) !== 0)
          V === 0 && (V = 3);
        else {
          if (V === 0 || V === 3)
            V = 4;
          U === null || (Dg & 134217727) === 0 && (Hi & 134217727) === 0 || Ii(U, W);
        }
      if (d2 || c3)
        b2.flags |= 4;
      return null;
    case 4:
      return fh(), Ci(b2), a2 === null && cf(b2.stateNode.containerInfo), null;
    case 10:
      return rg(b2), null;
    case 17:
      return Ff(b2.type) && Gf(), null;
    case 19:
      H(P);
      d2 = b2.memoizedState;
      if (d2 === null)
        return null;
      f2 = (b2.flags & 64) !== 0;
      g2 = d2.rendering;
      if (g2 === null)
        if (f2)
          Fi(d2, false);
        else {
          if (V !== 0 || a2 !== null && (a2.flags & 64) !== 0)
            for (a2 = b2.child; a2 !== null; ) {
              g2 = ih(a2);
              if (g2 !== null) {
                b2.flags |= 64;
                Fi(d2, false);
                f2 = g2.updateQueue;
                f2 !== null && (b2.updateQueue = f2, b2.flags |= 4);
                d2.lastEffect === null && (b2.firstEffect = null);
                b2.lastEffect = d2.lastEffect;
                d2 = c3;
                for (c3 = b2.child; c3 !== null; )
                  f2 = c3, a2 = d2, f2.flags &= 2, f2.nextEffect = null, f2.firstEffect = null, f2.lastEffect = null, g2 = f2.alternate, g2 === null ? (f2.childLanes = 0, f2.lanes = a2, f2.child = null, f2.memoizedProps = null, f2.memoizedState = null, f2.updateQueue = null, f2.dependencies = null, f2.stateNode = null) : (f2.childLanes = g2.childLanes, f2.lanes = g2.lanes, f2.child = g2.child, f2.memoizedProps = g2.memoizedProps, f2.memoizedState = g2.memoizedState, f2.updateQueue = g2.updateQueue, f2.type = g2.type, a2 = g2.dependencies, f2.dependencies = a2 === null ? null : {lanes: a2.lanes, firstContext: a2.firstContext}), c3 = c3.sibling;
                I(P, P.current & 1 | 2);
                return b2.child;
              }
              a2 = a2.sibling;
            }
          d2.tail !== null && O() > Ji && (b2.flags |= 64, f2 = true, Fi(d2, false), b2.lanes = 33554432);
        }
      else {
        if (!f2)
          if (a2 = ih(g2), a2 !== null) {
            if (b2.flags |= 64, f2 = true, c3 = a2.updateQueue, c3 !== null && (b2.updateQueue = c3, b2.flags |= 4), Fi(d2, true), d2.tail === null && d2.tailMode === "hidden" && !g2.alternate && !lh)
              return b2 = b2.lastEffect = d2.lastEffect, b2 !== null && (b2.nextEffect = null), null;
          } else
            2 * O() - d2.renderingStartTime > Ji && c3 !== 1073741824 && (b2.flags |= 64, f2 = true, Fi(d2, false), b2.lanes = 33554432);
        d2.isBackwards ? (g2.sibling = b2.child, b2.child = g2) : (c3 = d2.last, c3 !== null ? c3.sibling = g2 : b2.child = g2, d2.last = g2);
      }
      return d2.tail !== null ? (c3 = d2.tail, d2.rendering = c3, d2.tail = c3.sibling, d2.lastEffect = b2.lastEffect, d2.renderingStartTime = O(), c3.sibling = null, b2 = P.current, I(P, f2 ? b2 & 1 | 2 : b2 & 1), c3) : null;
    case 23:
    case 24:
      return Ki(), a2 !== null && a2.memoizedState !== null !== (b2.memoizedState !== null) && d2.mode !== "unstable-defer-without-hiding" && (b2.flags |= 4), null;
  }
  throw Error(y(156, b2.tag));
}
function Li(a2) {
  switch (a2.tag) {
    case 1:
      Ff(a2.type) && Gf();
      var b2 = a2.flags;
      return b2 & 4096 ? (a2.flags = b2 & -4097 | 64, a2) : null;
    case 3:
      fh();
      H(N);
      H(M);
      uh();
      b2 = a2.flags;
      if ((b2 & 64) !== 0)
        throw Error(y(285));
      a2.flags = b2 & -4097 | 64;
      return a2;
    case 5:
      return hh(a2), null;
    case 13:
      return H(P), b2 = a2.flags, b2 & 4096 ? (a2.flags = b2 & -4097 | 64, a2) : null;
    case 19:
      return H(P), null;
    case 4:
      return fh(), null;
    case 10:
      return rg(a2), null;
    case 23:
    case 24:
      return Ki(), null;
    default:
      return null;
  }
}
function Mi(a2, b2) {
  try {
    var c3 = "", d2 = b2;
    do
      c3 += Qa(d2), d2 = d2.return;
    while (d2);
    var e2 = c3;
  } catch (f2) {
    e2 = "\nError generating stack: " + f2.message + "\n" + f2.stack;
  }
  return {value: a2, source: b2, stack: e2};
}
function Ni(a2, b2) {
  try {
    console.error(b2.value);
  } catch (c3) {
    setTimeout(function() {
      throw c3;
    });
  }
}
var Oi = typeof WeakMap === "function" ? WeakMap : Map;
function Pi(a2, b2, c3) {
  c3 = zg(-1, c3);
  c3.tag = 3;
  c3.payload = {element: null};
  var d2 = b2.value;
  c3.callback = function() {
    Qi || (Qi = true, Ri = d2);
    Ni(a2, b2);
  };
  return c3;
}
function Si(a2, b2, c3) {
  c3 = zg(-1, c3);
  c3.tag = 3;
  var d2 = a2.type.getDerivedStateFromError;
  if (typeof d2 === "function") {
    var e2 = b2.value;
    c3.payload = function() {
      Ni(a2, b2);
      return d2(e2);
    };
  }
  var f2 = a2.stateNode;
  f2 !== null && typeof f2.componentDidCatch === "function" && (c3.callback = function() {
    typeof d2 !== "function" && (Ti === null ? Ti = new Set([this]) : Ti.add(this), Ni(a2, b2));
    var c4 = b2.stack;
    this.componentDidCatch(b2.value, {componentStack: c4 !== null ? c4 : ""});
  });
  return c3;
}
var Ui = typeof WeakSet === "function" ? WeakSet : Set;
function Vi(a2) {
  var b2 = a2.ref;
  if (b2 !== null)
    if (typeof b2 === "function")
      try {
        b2(null);
      } catch (c3) {
        Wi(a2, c3);
      }
    else
      b2.current = null;
}
function Xi(a2, b2) {
  switch (b2.tag) {
    case 0:
    case 11:
    case 15:
    case 22:
      return;
    case 1:
      if (b2.flags & 256 && a2 !== null) {
        var c3 = a2.memoizedProps, d2 = a2.memoizedState;
        a2 = b2.stateNode;
        b2 = a2.getSnapshotBeforeUpdate(b2.elementType === b2.type ? c3 : lg(b2.type, c3), d2);
        a2.__reactInternalSnapshotBeforeUpdate = b2;
      }
      return;
    case 3:
      b2.flags & 256 && qf(b2.stateNode.containerInfo);
      return;
    case 5:
    case 6:
    case 4:
    case 17:
      return;
  }
  throw Error(y(163));
}
function Yi(a2, b2, c3) {
  switch (c3.tag) {
    case 0:
    case 11:
    case 15:
    case 22:
      b2 = c3.updateQueue;
      b2 = b2 !== null ? b2.lastEffect : null;
      if (b2 !== null) {
        a2 = b2 = b2.next;
        do {
          if ((a2.tag & 3) === 3) {
            var d2 = a2.create;
            a2.destroy = d2();
          }
          a2 = a2.next;
        } while (a2 !== b2);
      }
      b2 = c3.updateQueue;
      b2 = b2 !== null ? b2.lastEffect : null;
      if (b2 !== null) {
        a2 = b2 = b2.next;
        do {
          var e2 = a2;
          d2 = e2.next;
          e2 = e2.tag;
          (e2 & 4) !== 0 && (e2 & 1) !== 0 && (Zi(c3, a2), $i(c3, a2));
          a2 = d2;
        } while (a2 !== b2);
      }
      return;
    case 1:
      a2 = c3.stateNode;
      c3.flags & 4 && (b2 === null ? a2.componentDidMount() : (d2 = c3.elementType === c3.type ? b2.memoizedProps : lg(c3.type, b2.memoizedProps), a2.componentDidUpdate(d2, b2.memoizedState, a2.__reactInternalSnapshotBeforeUpdate)));
      b2 = c3.updateQueue;
      b2 !== null && Eg(c3, b2, a2);
      return;
    case 3:
      b2 = c3.updateQueue;
      if (b2 !== null) {
        a2 = null;
        if (c3.child !== null)
          switch (c3.child.tag) {
            case 5:
              a2 = c3.child.stateNode;
              break;
            case 1:
              a2 = c3.child.stateNode;
          }
        Eg(c3, b2, a2);
      }
      return;
    case 5:
      a2 = c3.stateNode;
      b2 === null && c3.flags & 4 && mf(c3.type, c3.memoizedProps) && a2.focus();
      return;
    case 6:
      return;
    case 4:
      return;
    case 12:
      return;
    case 13:
      c3.memoizedState === null && (c3 = c3.alternate, c3 !== null && (c3 = c3.memoizedState, c3 !== null && (c3 = c3.dehydrated, c3 !== null && Cc(c3))));
      return;
    case 19:
    case 17:
    case 20:
    case 21:
    case 23:
    case 24:
      return;
  }
  throw Error(y(163));
}
function aj(a2, b2) {
  for (var c3 = a2; ; ) {
    if (c3.tag === 5) {
      var d2 = c3.stateNode;
      if (b2)
        d2 = d2.style, typeof d2.setProperty === "function" ? d2.setProperty("display", "none", "important") : d2.display = "none";
      else {
        d2 = c3.stateNode;
        var e2 = c3.memoizedProps.style;
        e2 = e2 !== void 0 && e2 !== null && e2.hasOwnProperty("display") ? e2.display : null;
        d2.style.display = sb("display", e2);
      }
    } else if (c3.tag === 6)
      c3.stateNode.nodeValue = b2 ? "" : c3.memoizedProps;
    else if ((c3.tag !== 23 && c3.tag !== 24 || c3.memoizedState === null || c3 === a2) && c3.child !== null) {
      c3.child.return = c3;
      c3 = c3.child;
      continue;
    }
    if (c3 === a2)
      break;
    for (; c3.sibling === null; ) {
      if (c3.return === null || c3.return === a2)
        return;
      c3 = c3.return;
    }
    c3.sibling.return = c3.return;
    c3 = c3.sibling;
  }
}
function bj(a2, b2) {
  if (Mf && typeof Mf.onCommitFiberUnmount === "function")
    try {
      Mf.onCommitFiberUnmount(Lf, b2);
    } catch (f2) {
    }
  switch (b2.tag) {
    case 0:
    case 11:
    case 14:
    case 15:
    case 22:
      a2 = b2.updateQueue;
      if (a2 !== null && (a2 = a2.lastEffect, a2 !== null)) {
        var c3 = a2 = a2.next;
        do {
          var d2 = c3, e2 = d2.destroy;
          d2 = d2.tag;
          if (e2 !== void 0)
            if ((d2 & 4) !== 0)
              Zi(b2, c3);
            else {
              d2 = b2;
              try {
                e2();
              } catch (f2) {
                Wi(d2, f2);
              }
            }
          c3 = c3.next;
        } while (c3 !== a2);
      }
      break;
    case 1:
      Vi(b2);
      a2 = b2.stateNode;
      if (typeof a2.componentWillUnmount === "function")
        try {
          a2.props = b2.memoizedProps, a2.state = b2.memoizedState, a2.componentWillUnmount();
        } catch (f2) {
          Wi(b2, f2);
        }
      break;
    case 5:
      Vi(b2);
      break;
    case 4:
      cj(a2, b2);
  }
}
function dj(a2) {
  a2.alternate = null;
  a2.child = null;
  a2.dependencies = null;
  a2.firstEffect = null;
  a2.lastEffect = null;
  a2.memoizedProps = null;
  a2.memoizedState = null;
  a2.pendingProps = null;
  a2.return = null;
  a2.updateQueue = null;
}
function ej(a2) {
  return a2.tag === 5 || a2.tag === 3 || a2.tag === 4;
}
function fj(a2) {
  a: {
    for (var b2 = a2.return; b2 !== null; ) {
      if (ej(b2))
        break a;
      b2 = b2.return;
    }
    throw Error(y(160));
  }
  var c3 = b2;
  b2 = c3.stateNode;
  switch (c3.tag) {
    case 5:
      var d2 = false;
      break;
    case 3:
      b2 = b2.containerInfo;
      d2 = true;
      break;
    case 4:
      b2 = b2.containerInfo;
      d2 = true;
      break;
    default:
      throw Error(y(161));
  }
  c3.flags & 16 && (pb(b2, ""), c3.flags &= -17);
  a:
    b:
      for (c3 = a2; ; ) {
        for (; c3.sibling === null; ) {
          if (c3.return === null || ej(c3.return)) {
            c3 = null;
            break a;
          }
          c3 = c3.return;
        }
        c3.sibling.return = c3.return;
        for (c3 = c3.sibling; c3.tag !== 5 && c3.tag !== 6 && c3.tag !== 18; ) {
          if (c3.flags & 2)
            continue b;
          if (c3.child === null || c3.tag === 4)
            continue b;
          else
            c3.child.return = c3, c3 = c3.child;
        }
        if (!(c3.flags & 2)) {
          c3 = c3.stateNode;
          break a;
        }
      }
  d2 ? gj(a2, c3, b2) : hj(a2, c3, b2);
}
function gj(a2, b2, c3) {
  var d2 = a2.tag, e2 = d2 === 5 || d2 === 6;
  if (e2)
    a2 = e2 ? a2.stateNode : a2.stateNode.instance, b2 ? c3.nodeType === 8 ? c3.parentNode.insertBefore(a2, b2) : c3.insertBefore(a2, b2) : (c3.nodeType === 8 ? (b2 = c3.parentNode, b2.insertBefore(a2, c3)) : (b2 = c3, b2.appendChild(a2)), c3 = c3._reactRootContainer, c3 !== null && c3 !== void 0 || b2.onclick !== null || (b2.onclick = jf));
  else if (d2 !== 4 && (a2 = a2.child, a2 !== null))
    for (gj(a2, b2, c3), a2 = a2.sibling; a2 !== null; )
      gj(a2, b2, c3), a2 = a2.sibling;
}
function hj(a2, b2, c3) {
  var d2 = a2.tag, e2 = d2 === 5 || d2 === 6;
  if (e2)
    a2 = e2 ? a2.stateNode : a2.stateNode.instance, b2 ? c3.insertBefore(a2, b2) : c3.appendChild(a2);
  else if (d2 !== 4 && (a2 = a2.child, a2 !== null))
    for (hj(a2, b2, c3), a2 = a2.sibling; a2 !== null; )
      hj(a2, b2, c3), a2 = a2.sibling;
}
function cj(a2, b2) {
  for (var c3 = b2, d2 = false, e2, f2; ; ) {
    if (!d2) {
      d2 = c3.return;
      a:
        for (; ; ) {
          if (d2 === null)
            throw Error(y(160));
          e2 = d2.stateNode;
          switch (d2.tag) {
            case 5:
              f2 = false;
              break a;
            case 3:
              e2 = e2.containerInfo;
              f2 = true;
              break a;
            case 4:
              e2 = e2.containerInfo;
              f2 = true;
              break a;
          }
          d2 = d2.return;
        }
      d2 = true;
    }
    if (c3.tag === 5 || c3.tag === 6) {
      a:
        for (var g2 = a2, h2 = c3, k2 = h2; ; )
          if (bj(g2, k2), k2.child !== null && k2.tag !== 4)
            k2.child.return = k2, k2 = k2.child;
          else {
            if (k2 === h2)
              break a;
            for (; k2.sibling === null; ) {
              if (k2.return === null || k2.return === h2)
                break a;
              k2 = k2.return;
            }
            k2.sibling.return = k2.return;
            k2 = k2.sibling;
          }
      f2 ? (g2 = e2, h2 = c3.stateNode, g2.nodeType === 8 ? g2.parentNode.removeChild(h2) : g2.removeChild(h2)) : e2.removeChild(c3.stateNode);
    } else if (c3.tag === 4) {
      if (c3.child !== null) {
        e2 = c3.stateNode.containerInfo;
        f2 = true;
        c3.child.return = c3;
        c3 = c3.child;
        continue;
      }
    } else if (bj(a2, c3), c3.child !== null) {
      c3.child.return = c3;
      c3 = c3.child;
      continue;
    }
    if (c3 === b2)
      break;
    for (; c3.sibling === null; ) {
      if (c3.return === null || c3.return === b2)
        return;
      c3 = c3.return;
      c3.tag === 4 && (d2 = false);
    }
    c3.sibling.return = c3.return;
    c3 = c3.sibling;
  }
}
function ij(a2, b2) {
  switch (b2.tag) {
    case 0:
    case 11:
    case 14:
    case 15:
    case 22:
      var c3 = b2.updateQueue;
      c3 = c3 !== null ? c3.lastEffect : null;
      if (c3 !== null) {
        var d2 = c3 = c3.next;
        do
          (d2.tag & 3) === 3 && (a2 = d2.destroy, d2.destroy = void 0, a2 !== void 0 && a2()), d2 = d2.next;
        while (d2 !== c3);
      }
      return;
    case 1:
      return;
    case 5:
      c3 = b2.stateNode;
      if (c3 != null) {
        d2 = b2.memoizedProps;
        var e2 = a2 !== null ? a2.memoizedProps : d2;
        a2 = b2.type;
        var f2 = b2.updateQueue;
        b2.updateQueue = null;
        if (f2 !== null) {
          c3[xf] = d2;
          a2 === "input" && d2.type === "radio" && d2.name != null && $a(c3, d2);
          wb(a2, e2);
          b2 = wb(a2, d2);
          for (e2 = 0; e2 < f2.length; e2 += 2) {
            var g2 = f2[e2], h2 = f2[e2 + 1];
            g2 === "style" ? tb(c3, h2) : g2 === "dangerouslySetInnerHTML" ? ob(c3, h2) : g2 === "children" ? pb(c3, h2) : qa(c3, g2, h2, b2);
          }
          switch (a2) {
            case "input":
              ab(c3, d2);
              break;
            case "textarea":
              ib(c3, d2);
              break;
            case "select":
              a2 = c3._wrapperState.wasMultiple, c3._wrapperState.wasMultiple = !!d2.multiple, f2 = d2.value, f2 != null ? fb(c3, !!d2.multiple, f2, false) : a2 !== !!d2.multiple && (d2.defaultValue != null ? fb(c3, !!d2.multiple, d2.defaultValue, true) : fb(c3, !!d2.multiple, d2.multiple ? [] : "", false));
          }
        }
      }
      return;
    case 6:
      if (b2.stateNode === null)
        throw Error(y(162));
      b2.stateNode.nodeValue = b2.memoizedProps;
      return;
    case 3:
      c3 = b2.stateNode;
      c3.hydrate && (c3.hydrate = false, Cc(c3.containerInfo));
      return;
    case 12:
      return;
    case 13:
      b2.memoizedState !== null && (jj = O(), aj(b2.child, true));
      kj(b2);
      return;
    case 19:
      kj(b2);
      return;
    case 17:
      return;
    case 23:
    case 24:
      aj(b2, b2.memoizedState !== null);
      return;
  }
  throw Error(y(163));
}
function kj(a2) {
  var b2 = a2.updateQueue;
  if (b2 !== null) {
    a2.updateQueue = null;
    var c3 = a2.stateNode;
    c3 === null && (c3 = a2.stateNode = new Ui());
    b2.forEach(function(b3) {
      var d2 = lj.bind(null, a2, b3);
      c3.has(b3) || (c3.add(b3), b3.then(d2, d2));
    });
  }
}
function mj(a2, b2) {
  return a2 !== null && (a2 = a2.memoizedState, a2 === null || a2.dehydrated !== null) ? (b2 = b2.memoizedState, b2 !== null && b2.dehydrated === null) : false;
}
var nj = Math.ceil;
var oj = ra.ReactCurrentDispatcher;
var pj = ra.ReactCurrentOwner;
var X = 0;
var U = null;
var Y = null;
var W = 0;
var qj = 0;
var rj = Bf(0);
var V = 0;
var sj = null;
var tj = 0;
var Dg = 0;
var Hi = 0;
var uj = 0;
var vj = null;
var jj = 0;
var Ji = Infinity;
function wj() {
  Ji = O() + 500;
}
var Z = null;
var Qi = false;
var Ri = null;
var Ti = null;
var xj = false;
var yj = null;
var zj = 90;
var Aj = [];
var Bj = [];
var Cj = null;
var Dj = 0;
var Ej = null;
var Fj = -1;
var Gj = 0;
var Hj = 0;
var Ij = null;
var Jj = false;
function Hg() {
  return (X & 48) !== 0 ? O() : Fj !== -1 ? Fj : Fj = O();
}
function Ig(a2) {
  a2 = a2.mode;
  if ((a2 & 2) === 0)
    return 1;
  if ((a2 & 4) === 0)
    return eg() === 99 ? 1 : 2;
  Gj === 0 && (Gj = tj);
  if (kg.transition !== 0) {
    Hj !== 0 && (Hj = vj !== null ? vj.pendingLanes : 0);
    a2 = Gj;
    var b2 = 4186112 & ~Hj;
    b2 &= -b2;
    b2 === 0 && (a2 = 4186112 & ~a2, b2 = a2 & -a2, b2 === 0 && (b2 = 8192));
    return b2;
  }
  a2 = eg();
  (X & 4) !== 0 && a2 === 98 ? a2 = Xc(12, Gj) : (a2 = Sc(a2), a2 = Xc(a2, Gj));
  return a2;
}
function Jg(a2, b2, c3) {
  if (50 < Dj)
    throw Dj = 0, Ej = null, Error(y(185));
  a2 = Kj(a2, b2);
  if (a2 === null)
    return null;
  $c(a2, b2, c3);
  a2 === U && (Hi |= b2, V === 4 && Ii(a2, W));
  var d2 = eg();
  b2 === 1 ? (X & 8) !== 0 && (X & 48) === 0 ? Lj(a2) : (Mj(a2, c3), X === 0 && (wj(), ig())) : ((X & 4) === 0 || d2 !== 98 && d2 !== 99 || (Cj === null ? Cj = new Set([a2]) : Cj.add(a2)), Mj(a2, c3));
  vj = a2;
}
function Kj(a2, b2) {
  a2.lanes |= b2;
  var c3 = a2.alternate;
  c3 !== null && (c3.lanes |= b2);
  c3 = a2;
  for (a2 = a2.return; a2 !== null; )
    a2.childLanes |= b2, c3 = a2.alternate, c3 !== null && (c3.childLanes |= b2), c3 = a2, a2 = a2.return;
  return c3.tag === 3 ? c3.stateNode : null;
}
function Mj(a2, b2) {
  for (var c3 = a2.callbackNode, d2 = a2.suspendedLanes, e2 = a2.pingedLanes, f2 = a2.expirationTimes, g2 = a2.pendingLanes; 0 < g2; ) {
    var h2 = 31 - Vc(g2), k2 = 1 << h2, l2 = f2[h2];
    if (l2 === -1) {
      if ((k2 & d2) === 0 || (k2 & e2) !== 0) {
        l2 = b2;
        Rc(k2);
        var n3 = F;
        f2[h2] = 10 <= n3 ? l2 + 250 : 6 <= n3 ? l2 + 5e3 : -1;
      }
    } else
      l2 <= b2 && (a2.expiredLanes |= k2);
    g2 &= ~k2;
  }
  d2 = Uc(a2, a2 === U ? W : 0);
  b2 = F;
  if (d2 === 0)
    c3 !== null && (c3 !== Zf && Pf(c3), a2.callbackNode = null, a2.callbackPriority = 0);
  else {
    if (c3 !== null) {
      if (a2.callbackPriority === b2)
        return;
      c3 !== Zf && Pf(c3);
    }
    b2 === 15 ? (c3 = Lj.bind(null, a2), ag === null ? (ag = [c3], bg = Of(Uf, jg)) : ag.push(c3), c3 = Zf) : b2 === 14 ? c3 = hg(99, Lj.bind(null, a2)) : (c3 = Tc(b2), c3 = hg(c3, Nj.bind(null, a2)));
    a2.callbackPriority = b2;
    a2.callbackNode = c3;
  }
}
function Nj(a2) {
  Fj = -1;
  Hj = Gj = 0;
  if ((X & 48) !== 0)
    throw Error(y(327));
  var b2 = a2.callbackNode;
  if (Oj() && a2.callbackNode !== b2)
    return null;
  var c3 = Uc(a2, a2 === U ? W : 0);
  if (c3 === 0)
    return null;
  var d2 = c3;
  var e2 = X;
  X |= 16;
  var f2 = Pj();
  if (U !== a2 || W !== d2)
    wj(), Qj(a2, d2);
  do
    try {
      Rj();
      break;
    } catch (h2) {
      Sj(a2, h2);
    }
  while (1);
  qg();
  oj.current = f2;
  X = e2;
  Y !== null ? d2 = 0 : (U = null, W = 0, d2 = V);
  if ((tj & Hi) !== 0)
    Qj(a2, 0);
  else if (d2 !== 0) {
    d2 === 2 && (X |= 64, a2.hydrate && (a2.hydrate = false, qf(a2.containerInfo)), c3 = Wc(a2), c3 !== 0 && (d2 = Tj(a2, c3)));
    if (d2 === 1)
      throw b2 = sj, Qj(a2, 0), Ii(a2, c3), Mj(a2, O()), b2;
    a2.finishedWork = a2.current.alternate;
    a2.finishedLanes = c3;
    switch (d2) {
      case 0:
      case 1:
        throw Error(y(345));
      case 2:
        Uj(a2);
        break;
      case 3:
        Ii(a2, c3);
        if ((c3 & 62914560) === c3 && (d2 = jj + 500 - O(), 10 < d2)) {
          if (Uc(a2, 0) !== 0)
            break;
          e2 = a2.suspendedLanes;
          if ((e2 & c3) !== c3) {
            Hg();
            a2.pingedLanes |= a2.suspendedLanes & e2;
            break;
          }
          a2.timeoutHandle = of(Uj.bind(null, a2), d2);
          break;
        }
        Uj(a2);
        break;
      case 4:
        Ii(a2, c3);
        if ((c3 & 4186112) === c3)
          break;
        d2 = a2.eventTimes;
        for (e2 = -1; 0 < c3; ) {
          var g2 = 31 - Vc(c3);
          f2 = 1 << g2;
          g2 = d2[g2];
          g2 > e2 && (e2 = g2);
          c3 &= ~f2;
        }
        c3 = e2;
        c3 = O() - c3;
        c3 = (120 > c3 ? 120 : 480 > c3 ? 480 : 1080 > c3 ? 1080 : 1920 > c3 ? 1920 : 3e3 > c3 ? 3e3 : 4320 > c3 ? 4320 : 1960 * nj(c3 / 1960)) - c3;
        if (10 < c3) {
          a2.timeoutHandle = of(Uj.bind(null, a2), c3);
          break;
        }
        Uj(a2);
        break;
      case 5:
        Uj(a2);
        break;
      default:
        throw Error(y(329));
    }
  }
  Mj(a2, O());
  return a2.callbackNode === b2 ? Nj.bind(null, a2) : null;
}
function Ii(a2, b2) {
  b2 &= ~uj;
  b2 &= ~Hi;
  a2.suspendedLanes |= b2;
  a2.pingedLanes &= ~b2;
  for (a2 = a2.expirationTimes; 0 < b2; ) {
    var c3 = 31 - Vc(b2), d2 = 1 << c3;
    a2[c3] = -1;
    b2 &= ~d2;
  }
}
function Lj(a2) {
  if ((X & 48) !== 0)
    throw Error(y(327));
  Oj();
  if (a2 === U && (a2.expiredLanes & W) !== 0) {
    var b2 = W;
    var c3 = Tj(a2, b2);
    (tj & Hi) !== 0 && (b2 = Uc(a2, b2), c3 = Tj(a2, b2));
  } else
    b2 = Uc(a2, 0), c3 = Tj(a2, b2);
  a2.tag !== 0 && c3 === 2 && (X |= 64, a2.hydrate && (a2.hydrate = false, qf(a2.containerInfo)), b2 = Wc(a2), b2 !== 0 && (c3 = Tj(a2, b2)));
  if (c3 === 1)
    throw c3 = sj, Qj(a2, 0), Ii(a2, b2), Mj(a2, O()), c3;
  a2.finishedWork = a2.current.alternate;
  a2.finishedLanes = b2;
  Uj(a2);
  Mj(a2, O());
  return null;
}
function Vj() {
  if (Cj !== null) {
    var a2 = Cj;
    Cj = null;
    a2.forEach(function(a3) {
      a3.expiredLanes |= 24 & a3.pendingLanes;
      Mj(a3, O());
    });
  }
  ig();
}
function Wj(a2, b2) {
  var c3 = X;
  X |= 1;
  try {
    return a2(b2);
  } finally {
    X = c3, X === 0 && (wj(), ig());
  }
}
function Xj(a2, b2) {
  var c3 = X;
  X &= -2;
  X |= 8;
  try {
    return a2(b2);
  } finally {
    X = c3, X === 0 && (wj(), ig());
  }
}
function ni(a2, b2) {
  I(rj, qj);
  qj |= b2;
  tj |= b2;
}
function Ki() {
  qj = rj.current;
  H(rj);
}
function Qj(a2, b2) {
  a2.finishedWork = null;
  a2.finishedLanes = 0;
  var c3 = a2.timeoutHandle;
  c3 !== -1 && (a2.timeoutHandle = -1, pf(c3));
  if (Y !== null)
    for (c3 = Y.return; c3 !== null; ) {
      var d2 = c3;
      switch (d2.tag) {
        case 1:
          d2 = d2.type.childContextTypes;
          d2 !== null && d2 !== void 0 && Gf();
          break;
        case 3:
          fh();
          H(N);
          H(M);
          uh();
          break;
        case 5:
          hh(d2);
          break;
        case 4:
          fh();
          break;
        case 13:
          H(P);
          break;
        case 19:
          H(P);
          break;
        case 10:
          rg(d2);
          break;
        case 23:
        case 24:
          Ki();
      }
      c3 = c3.return;
    }
  U = a2;
  Y = Tg(a2.current, null);
  W = qj = tj = b2;
  V = 0;
  sj = null;
  uj = Hi = Dg = 0;
}
function Sj(a2, b2) {
  do {
    var c3 = Y;
    try {
      qg();
      vh.current = Gh;
      if (yh) {
        for (var d2 = R.memoizedState; d2 !== null; ) {
          var e2 = d2.queue;
          e2 !== null && (e2.pending = null);
          d2 = d2.next;
        }
        yh = false;
      }
      xh = 0;
      T = S = R = null;
      zh = false;
      pj.current = null;
      if (c3 === null || c3.return === null) {
        V = 1;
        sj = b2;
        Y = null;
        break;
      }
      a: {
        var f2 = a2, g2 = c3.return, h2 = c3, k2 = b2;
        b2 = W;
        h2.flags |= 2048;
        h2.firstEffect = h2.lastEffect = null;
        if (k2 !== null && typeof k2 === "object" && typeof k2.then === "function") {
          var l2 = k2;
          if ((h2.mode & 2) === 0) {
            var n3 = h2.alternate;
            n3 ? (h2.updateQueue = n3.updateQueue, h2.memoizedState = n3.memoizedState, h2.lanes = n3.lanes) : (h2.updateQueue = null, h2.memoizedState = null);
          }
          var A2 = (P.current & 1) !== 0, p2 = g2;
          do {
            var C;
            if (C = p2.tag === 13) {
              var x2 = p2.memoizedState;
              if (x2 !== null)
                C = x2.dehydrated !== null ? true : false;
              else {
                var w2 = p2.memoizedProps;
                C = w2.fallback === void 0 ? false : w2.unstable_avoidThisFallback !== true ? true : A2 ? false : true;
              }
            }
            if (C) {
              var z2 = p2.updateQueue;
              if (z2 === null) {
                var u = new Set();
                u.add(l2);
                p2.updateQueue = u;
              } else
                z2.add(l2);
              if ((p2.mode & 2) === 0) {
                p2.flags |= 64;
                h2.flags |= 16384;
                h2.flags &= -2981;
                if (h2.tag === 1)
                  if (h2.alternate === null)
                    h2.tag = 17;
                  else {
                    var t5 = zg(-1, 1);
                    t5.tag = 2;
                    Ag(h2, t5);
                  }
                h2.lanes |= 1;
                break a;
              }
              k2 = void 0;
              h2 = b2;
              var q2 = f2.pingCache;
              q2 === null ? (q2 = f2.pingCache = new Oi(), k2 = new Set(), q2.set(l2, k2)) : (k2 = q2.get(l2), k2 === void 0 && (k2 = new Set(), q2.set(l2, k2)));
              if (!k2.has(h2)) {
                k2.add(h2);
                var v2 = Yj.bind(null, f2, l2, h2);
                l2.then(v2, v2);
              }
              p2.flags |= 4096;
              p2.lanes = b2;
              break a;
            }
            p2 = p2.return;
          } while (p2 !== null);
          k2 = Error((Ra(h2.type) || "A React component") + " suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.");
        }
        V !== 5 && (V = 2);
        k2 = Mi(k2, h2);
        p2 = g2;
        do {
          switch (p2.tag) {
            case 3:
              f2 = k2;
              p2.flags |= 4096;
              b2 &= -b2;
              p2.lanes |= b2;
              var J = Pi(p2, f2, b2);
              Bg(p2, J);
              break a;
            case 1:
              f2 = k2;
              var K = p2.type, Q = p2.stateNode;
              if ((p2.flags & 64) === 0 && (typeof K.getDerivedStateFromError === "function" || Q !== null && typeof Q.componentDidCatch === "function" && (Ti === null || !Ti.has(Q)))) {
                p2.flags |= 4096;
                b2 &= -b2;
                p2.lanes |= b2;
                var L = Si(p2, f2, b2);
                Bg(p2, L);
                break a;
              }
          }
          p2 = p2.return;
        } while (p2 !== null);
      }
      Zj(c3);
    } catch (va) {
      b2 = va;
      Y === c3 && c3 !== null && (Y = c3 = c3.return);
      continue;
    }
    break;
  } while (1);
}
function Pj() {
  var a2 = oj.current;
  oj.current = Gh;
  return a2 === null ? Gh : a2;
}
function Tj(a2, b2) {
  var c3 = X;
  X |= 16;
  var d2 = Pj();
  U === a2 && W === b2 || Qj(a2, b2);
  do
    try {
      ak();
      break;
    } catch (e2) {
      Sj(a2, e2);
    }
  while (1);
  qg();
  X = c3;
  oj.current = d2;
  if (Y !== null)
    throw Error(y(261));
  U = null;
  W = 0;
  return V;
}
function ak() {
  for (; Y !== null; )
    bk(Y);
}
function Rj() {
  for (; Y !== null && !Qf(); )
    bk(Y);
}
function bk(a2) {
  var b2 = ck(a2.alternate, a2, qj);
  a2.memoizedProps = a2.pendingProps;
  b2 === null ? Zj(a2) : Y = b2;
  pj.current = null;
}
function Zj(a2) {
  var b2 = a2;
  do {
    var c3 = b2.alternate;
    a2 = b2.return;
    if ((b2.flags & 2048) === 0) {
      c3 = Gi(c3, b2, qj);
      if (c3 !== null) {
        Y = c3;
        return;
      }
      c3 = b2;
      if (c3.tag !== 24 && c3.tag !== 23 || c3.memoizedState === null || (qj & 1073741824) !== 0 || (c3.mode & 4) === 0) {
        for (var d2 = 0, e2 = c3.child; e2 !== null; )
          d2 |= e2.lanes | e2.childLanes, e2 = e2.sibling;
        c3.childLanes = d2;
      }
      a2 !== null && (a2.flags & 2048) === 0 && (a2.firstEffect === null && (a2.firstEffect = b2.firstEffect), b2.lastEffect !== null && (a2.lastEffect !== null && (a2.lastEffect.nextEffect = b2.firstEffect), a2.lastEffect = b2.lastEffect), 1 < b2.flags && (a2.lastEffect !== null ? a2.lastEffect.nextEffect = b2 : a2.firstEffect = b2, a2.lastEffect = b2));
    } else {
      c3 = Li(b2);
      if (c3 !== null) {
        c3.flags &= 2047;
        Y = c3;
        return;
      }
      a2 !== null && (a2.firstEffect = a2.lastEffect = null, a2.flags |= 2048);
    }
    b2 = b2.sibling;
    if (b2 !== null) {
      Y = b2;
      return;
    }
    Y = b2 = a2;
  } while (b2 !== null);
  V === 0 && (V = 5);
}
function Uj(a2) {
  var b2 = eg();
  gg(99, dk.bind(null, a2, b2));
  return null;
}
function dk(a2, b2) {
  do
    Oj();
  while (yj !== null);
  if ((X & 48) !== 0)
    throw Error(y(327));
  var c3 = a2.finishedWork;
  if (c3 === null)
    return null;
  a2.finishedWork = null;
  a2.finishedLanes = 0;
  if (c3 === a2.current)
    throw Error(y(177));
  a2.callbackNode = null;
  var d2 = c3.lanes | c3.childLanes, e2 = d2, f2 = a2.pendingLanes & ~e2;
  a2.pendingLanes = e2;
  a2.suspendedLanes = 0;
  a2.pingedLanes = 0;
  a2.expiredLanes &= e2;
  a2.mutableReadLanes &= e2;
  a2.entangledLanes &= e2;
  e2 = a2.entanglements;
  for (var g2 = a2.eventTimes, h2 = a2.expirationTimes; 0 < f2; ) {
    var k2 = 31 - Vc(f2), l2 = 1 << k2;
    e2[k2] = 0;
    g2[k2] = -1;
    h2[k2] = -1;
    f2 &= ~l2;
  }
  Cj !== null && (d2 & 24) === 0 && Cj.has(a2) && Cj.delete(a2);
  a2 === U && (Y = U = null, W = 0);
  1 < c3.flags ? c3.lastEffect !== null ? (c3.lastEffect.nextEffect = c3, d2 = c3.firstEffect) : d2 = c3 : d2 = c3.firstEffect;
  if (d2 !== null) {
    e2 = X;
    X |= 32;
    pj.current = null;
    kf = fd;
    g2 = Ne();
    if (Oe(g2)) {
      if ("selectionStart" in g2)
        h2 = {start: g2.selectionStart, end: g2.selectionEnd};
      else
        a:
          if (h2 = (h2 = g2.ownerDocument) && h2.defaultView || window, (l2 = h2.getSelection && h2.getSelection()) && l2.rangeCount !== 0) {
            h2 = l2.anchorNode;
            f2 = l2.anchorOffset;
            k2 = l2.focusNode;
            l2 = l2.focusOffset;
            try {
              h2.nodeType, k2.nodeType;
            } catch (va) {
              h2 = null;
              break a;
            }
            var n3 = 0, A2 = -1, p2 = -1, C = 0, x2 = 0, w2 = g2, z2 = null;
            b:
              for (; ; ) {
                for (var u; ; ) {
                  w2 !== h2 || f2 !== 0 && w2.nodeType !== 3 || (A2 = n3 + f2);
                  w2 !== k2 || l2 !== 0 && w2.nodeType !== 3 || (p2 = n3 + l2);
                  w2.nodeType === 3 && (n3 += w2.nodeValue.length);
                  if ((u = w2.firstChild) === null)
                    break;
                  z2 = w2;
                  w2 = u;
                }
                for (; ; ) {
                  if (w2 === g2)
                    break b;
                  z2 === h2 && ++C === f2 && (A2 = n3);
                  z2 === k2 && ++x2 === l2 && (p2 = n3);
                  if ((u = w2.nextSibling) !== null)
                    break;
                  w2 = z2;
                  z2 = w2.parentNode;
                }
                w2 = u;
              }
            h2 = A2 === -1 || p2 === -1 ? null : {start: A2, end: p2};
          } else
            h2 = null;
      h2 = h2 || {start: 0, end: 0};
    } else
      h2 = null;
    lf = {focusedElem: g2, selectionRange: h2};
    fd = false;
    Ij = null;
    Jj = false;
    Z = d2;
    do
      try {
        ek();
      } catch (va) {
        if (Z === null)
          throw Error(y(330));
        Wi(Z, va);
        Z = Z.nextEffect;
      }
    while (Z !== null);
    Ij = null;
    Z = d2;
    do
      try {
        for (g2 = a2; Z !== null; ) {
          var t5 = Z.flags;
          t5 & 16 && pb(Z.stateNode, "");
          if (t5 & 128) {
            var q2 = Z.alternate;
            if (q2 !== null) {
              var v2 = q2.ref;
              v2 !== null && (typeof v2 === "function" ? v2(null) : v2.current = null);
            }
          }
          switch (t5 & 1038) {
            case 2:
              fj(Z);
              Z.flags &= -3;
              break;
            case 6:
              fj(Z);
              Z.flags &= -3;
              ij(Z.alternate, Z);
              break;
            case 1024:
              Z.flags &= -1025;
              break;
            case 1028:
              Z.flags &= -1025;
              ij(Z.alternate, Z);
              break;
            case 4:
              ij(Z.alternate, Z);
              break;
            case 8:
              h2 = Z;
              cj(g2, h2);
              var J = h2.alternate;
              dj(h2);
              J !== null && dj(J);
          }
          Z = Z.nextEffect;
        }
      } catch (va) {
        if (Z === null)
          throw Error(y(330));
        Wi(Z, va);
        Z = Z.nextEffect;
      }
    while (Z !== null);
    v2 = lf;
    q2 = Ne();
    t5 = v2.focusedElem;
    g2 = v2.selectionRange;
    if (q2 !== t5 && t5 && t5.ownerDocument && Me(t5.ownerDocument.documentElement, t5)) {
      g2 !== null && Oe(t5) && (q2 = g2.start, v2 = g2.end, v2 === void 0 && (v2 = q2), "selectionStart" in t5 ? (t5.selectionStart = q2, t5.selectionEnd = Math.min(v2, t5.value.length)) : (v2 = (q2 = t5.ownerDocument || document) && q2.defaultView || window, v2.getSelection && (v2 = v2.getSelection(), h2 = t5.textContent.length, J = Math.min(g2.start, h2), g2 = g2.end === void 0 ? J : Math.min(g2.end, h2), !v2.extend && J > g2 && (h2 = g2, g2 = J, J = h2), h2 = Le(t5, J), f2 = Le(t5, g2), h2 && f2 && (v2.rangeCount !== 1 || v2.anchorNode !== h2.node || v2.anchorOffset !== h2.offset || v2.focusNode !== f2.node || v2.focusOffset !== f2.offset) && (q2 = q2.createRange(), q2.setStart(h2.node, h2.offset), v2.removeAllRanges(), J > g2 ? (v2.addRange(q2), v2.extend(f2.node, f2.offset)) : (q2.setEnd(f2.node, f2.offset), v2.addRange(q2))))));
      q2 = [];
      for (v2 = t5; v2 = v2.parentNode; )
        v2.nodeType === 1 && q2.push({element: v2, left: v2.scrollLeft, top: v2.scrollTop});
      typeof t5.focus === "function" && t5.focus();
      for (t5 = 0; t5 < q2.length; t5++)
        v2 = q2[t5], v2.element.scrollLeft = v2.left, v2.element.scrollTop = v2.top;
    }
    fd = !!kf;
    lf = kf = null;
    a2.current = c3;
    Z = d2;
    do
      try {
        for (t5 = a2; Z !== null; ) {
          var K = Z.flags;
          K & 36 && Yi(t5, Z.alternate, Z);
          if (K & 128) {
            q2 = void 0;
            var Q = Z.ref;
            if (Q !== null) {
              var L = Z.stateNode;
              switch (Z.tag) {
                case 5:
                  q2 = L;
                  break;
                default:
                  q2 = L;
              }
              typeof Q === "function" ? Q(q2) : Q.current = q2;
            }
          }
          Z = Z.nextEffect;
        }
      } catch (va) {
        if (Z === null)
          throw Error(y(330));
        Wi(Z, va);
        Z = Z.nextEffect;
      }
    while (Z !== null);
    Z = null;
    $f();
    X = e2;
  } else
    a2.current = c3;
  if (xj)
    xj = false, yj = a2, zj = b2;
  else
    for (Z = d2; Z !== null; )
      b2 = Z.nextEffect, Z.nextEffect = null, Z.flags & 8 && (K = Z, K.sibling = null, K.stateNode = null), Z = b2;
  d2 = a2.pendingLanes;
  d2 === 0 && (Ti = null);
  d2 === 1 ? a2 === Ej ? Dj++ : (Dj = 0, Ej = a2) : Dj = 0;
  c3 = c3.stateNode;
  if (Mf && typeof Mf.onCommitFiberRoot === "function")
    try {
      Mf.onCommitFiberRoot(Lf, c3, void 0, (c3.current.flags & 64) === 64);
    } catch (va) {
    }
  Mj(a2, O());
  if (Qi)
    throw Qi = false, a2 = Ri, Ri = null, a2;
  if ((X & 8) !== 0)
    return null;
  ig();
  return null;
}
function ek() {
  for (; Z !== null; ) {
    var a2 = Z.alternate;
    Jj || Ij === null || ((Z.flags & 8) !== 0 ? dc(Z, Ij) && (Jj = true) : Z.tag === 13 && mj(a2, Z) && dc(Z, Ij) && (Jj = true));
    var b2 = Z.flags;
    (b2 & 256) !== 0 && Xi(a2, Z);
    (b2 & 512) === 0 || xj || (xj = true, hg(97, function() {
      Oj();
      return null;
    }));
    Z = Z.nextEffect;
  }
}
function Oj() {
  if (zj !== 90) {
    var a2 = 97 < zj ? 97 : zj;
    zj = 90;
    return gg(a2, fk);
  }
  return false;
}
function $i(a2, b2) {
  Aj.push(b2, a2);
  xj || (xj = true, hg(97, function() {
    Oj();
    return null;
  }));
}
function Zi(a2, b2) {
  Bj.push(b2, a2);
  xj || (xj = true, hg(97, function() {
    Oj();
    return null;
  }));
}
function fk() {
  if (yj === null)
    return false;
  var a2 = yj;
  yj = null;
  if ((X & 48) !== 0)
    throw Error(y(331));
  var b2 = X;
  X |= 32;
  var c3 = Bj;
  Bj = [];
  for (var d2 = 0; d2 < c3.length; d2 += 2) {
    var e2 = c3[d2], f2 = c3[d2 + 1], g2 = e2.destroy;
    e2.destroy = void 0;
    if (typeof g2 === "function")
      try {
        g2();
      } catch (k2) {
        if (f2 === null)
          throw Error(y(330));
        Wi(f2, k2);
      }
  }
  c3 = Aj;
  Aj = [];
  for (d2 = 0; d2 < c3.length; d2 += 2) {
    e2 = c3[d2];
    f2 = c3[d2 + 1];
    try {
      var h2 = e2.create;
      e2.destroy = h2();
    } catch (k2) {
      if (f2 === null)
        throw Error(y(330));
      Wi(f2, k2);
    }
  }
  for (h2 = a2.current.firstEffect; h2 !== null; )
    a2 = h2.nextEffect, h2.nextEffect = null, h2.flags & 8 && (h2.sibling = null, h2.stateNode = null), h2 = a2;
  X = b2;
  ig();
  return true;
}
function gk(a2, b2, c3) {
  b2 = Mi(c3, b2);
  b2 = Pi(a2, b2, 1);
  Ag(a2, b2);
  b2 = Hg();
  a2 = Kj(a2, 1);
  a2 !== null && ($c(a2, 1, b2), Mj(a2, b2));
}
function Wi(a2, b2) {
  if (a2.tag === 3)
    gk(a2, a2, b2);
  else
    for (var c3 = a2.return; c3 !== null; ) {
      if (c3.tag === 3) {
        gk(c3, a2, b2);
        break;
      } else if (c3.tag === 1) {
        var d2 = c3.stateNode;
        if (typeof c3.type.getDerivedStateFromError === "function" || typeof d2.componentDidCatch === "function" && (Ti === null || !Ti.has(d2))) {
          a2 = Mi(b2, a2);
          var e2 = Si(c3, a2, 1);
          Ag(c3, e2);
          e2 = Hg();
          c3 = Kj(c3, 1);
          if (c3 !== null)
            $c(c3, 1, e2), Mj(c3, e2);
          else if (typeof d2.componentDidCatch === "function" && (Ti === null || !Ti.has(d2)))
            try {
              d2.componentDidCatch(b2, a2);
            } catch (f2) {
            }
          break;
        }
      }
      c3 = c3.return;
    }
}
function Yj(a2, b2, c3) {
  var d2 = a2.pingCache;
  d2 !== null && d2.delete(b2);
  b2 = Hg();
  a2.pingedLanes |= a2.suspendedLanes & c3;
  U === a2 && (W & c3) === c3 && (V === 4 || V === 3 && (W & 62914560) === W && 500 > O() - jj ? Qj(a2, 0) : uj |= c3);
  Mj(a2, b2);
}
function lj(a2, b2) {
  var c3 = a2.stateNode;
  c3 !== null && c3.delete(b2);
  b2 = 0;
  b2 === 0 && (b2 = a2.mode, (b2 & 2) === 0 ? b2 = 1 : (b2 & 4) === 0 ? b2 = eg() === 99 ? 1 : 2 : (Gj === 0 && (Gj = tj), b2 = Yc(62914560 & ~Gj), b2 === 0 && (b2 = 4194304)));
  c3 = Hg();
  a2 = Kj(a2, b2);
  a2 !== null && ($c(a2, b2, c3), Mj(a2, c3));
}
var ck;
ck = function(a2, b2, c3) {
  var d2 = b2.lanes;
  if (a2 !== null)
    if (a2.memoizedProps !== b2.pendingProps || N.current)
      ug = true;
    else if ((c3 & d2) !== 0)
      ug = (a2.flags & 16384) !== 0 ? true : false;
    else {
      ug = false;
      switch (b2.tag) {
        case 3:
          ri(b2);
          sh();
          break;
        case 5:
          gh(b2);
          break;
        case 1:
          Ff(b2.type) && Jf(b2);
          break;
        case 4:
          eh(b2, b2.stateNode.containerInfo);
          break;
        case 10:
          d2 = b2.memoizedProps.value;
          var e2 = b2.type._context;
          I(mg, e2._currentValue);
          e2._currentValue = d2;
          break;
        case 13:
          if (b2.memoizedState !== null) {
            if ((c3 & b2.child.childLanes) !== 0)
              return ti(a2, b2, c3);
            I(P, P.current & 1);
            b2 = hi(a2, b2, c3);
            return b2 !== null ? b2.sibling : null;
          }
          I(P, P.current & 1);
          break;
        case 19:
          d2 = (c3 & b2.childLanes) !== 0;
          if ((a2.flags & 64) !== 0) {
            if (d2)
              return Ai(a2, b2, c3);
            b2.flags |= 64;
          }
          e2 = b2.memoizedState;
          e2 !== null && (e2.rendering = null, e2.tail = null, e2.lastEffect = null);
          I(P, P.current);
          if (d2)
            break;
          else
            return null;
        case 23:
        case 24:
          return b2.lanes = 0, mi(a2, b2, c3);
      }
      return hi(a2, b2, c3);
    }
  else
    ug = false;
  b2.lanes = 0;
  switch (b2.tag) {
    case 2:
      d2 = b2.type;
      a2 !== null && (a2.alternate = null, b2.alternate = null, b2.flags |= 2);
      a2 = b2.pendingProps;
      e2 = Ef(b2, M.current);
      tg(b2, c3);
      e2 = Ch(null, b2, d2, a2, e2, c3);
      b2.flags |= 1;
      if (typeof e2 === "object" && e2 !== null && typeof e2.render === "function" && e2.$$typeof === void 0) {
        b2.tag = 1;
        b2.memoizedState = null;
        b2.updateQueue = null;
        if (Ff(d2)) {
          var f2 = true;
          Jf(b2);
        } else
          f2 = false;
        b2.memoizedState = e2.state !== null && e2.state !== void 0 ? e2.state : null;
        xg(b2);
        var g2 = d2.getDerivedStateFromProps;
        typeof g2 === "function" && Gg(b2, d2, g2, a2);
        e2.updater = Kg;
        b2.stateNode = e2;
        e2._reactInternals = b2;
        Og(b2, d2, a2, c3);
        b2 = qi(null, b2, d2, true, f2, c3);
      } else
        b2.tag = 0, fi(null, b2, e2, c3), b2 = b2.child;
      return b2;
    case 16:
      e2 = b2.elementType;
      a: {
        a2 !== null && (a2.alternate = null, b2.alternate = null, b2.flags |= 2);
        a2 = b2.pendingProps;
        f2 = e2._init;
        e2 = f2(e2._payload);
        b2.type = e2;
        f2 = b2.tag = hk(e2);
        a2 = lg(e2, a2);
        switch (f2) {
          case 0:
            b2 = li(null, b2, e2, a2, c3);
            break a;
          case 1:
            b2 = pi(null, b2, e2, a2, c3);
            break a;
          case 11:
            b2 = gi(null, b2, e2, a2, c3);
            break a;
          case 14:
            b2 = ii(null, b2, e2, lg(e2.type, a2), d2, c3);
            break a;
        }
        throw Error(y(306, e2, ""));
      }
      return b2;
    case 0:
      return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : lg(d2, e2), li(a2, b2, d2, e2, c3);
    case 1:
      return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : lg(d2, e2), pi(a2, b2, d2, e2, c3);
    case 3:
      ri(b2);
      d2 = b2.updateQueue;
      if (a2 === null || d2 === null)
        throw Error(y(282));
      d2 = b2.pendingProps;
      e2 = b2.memoizedState;
      e2 = e2 !== null ? e2.element : null;
      yg(a2, b2);
      Cg(b2, d2, null, c3);
      d2 = b2.memoizedState.element;
      if (d2 === e2)
        sh(), b2 = hi(a2, b2, c3);
      else {
        e2 = b2.stateNode;
        if (f2 = e2.hydrate)
          kh = rf(b2.stateNode.containerInfo.firstChild), jh = b2, f2 = lh = true;
        if (f2) {
          a2 = e2.mutableSourceEagerHydrationData;
          if (a2 != null)
            for (e2 = 0; e2 < a2.length; e2 += 2)
              f2 = a2[e2], f2._workInProgressVersionPrimary = a2[e2 + 1], th.push(f2);
          c3 = Zg(b2, null, d2, c3);
          for (b2.child = c3; c3; )
            c3.flags = c3.flags & -3 | 1024, c3 = c3.sibling;
        } else
          fi(a2, b2, d2, c3), sh();
        b2 = b2.child;
      }
      return b2;
    case 5:
      return gh(b2), a2 === null && ph(b2), d2 = b2.type, e2 = b2.pendingProps, f2 = a2 !== null ? a2.memoizedProps : null, g2 = e2.children, nf(d2, e2) ? g2 = null : f2 !== null && nf(d2, f2) && (b2.flags |= 16), oi(a2, b2), fi(a2, b2, g2, c3), b2.child;
    case 6:
      return a2 === null && ph(b2), null;
    case 13:
      return ti(a2, b2, c3);
    case 4:
      return eh(b2, b2.stateNode.containerInfo), d2 = b2.pendingProps, a2 === null ? b2.child = Yg(b2, null, d2, c3) : fi(a2, b2, d2, c3), b2.child;
    case 11:
      return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : lg(d2, e2), gi(a2, b2, d2, e2, c3);
    case 7:
      return fi(a2, b2, b2.pendingProps, c3), b2.child;
    case 8:
      return fi(a2, b2, b2.pendingProps.children, c3), b2.child;
    case 12:
      return fi(a2, b2, b2.pendingProps.children, c3), b2.child;
    case 10:
      a: {
        d2 = b2.type._context;
        e2 = b2.pendingProps;
        g2 = b2.memoizedProps;
        f2 = e2.value;
        var h2 = b2.type._context;
        I(mg, h2._currentValue);
        h2._currentValue = f2;
        if (g2 !== null)
          if (h2 = g2.value, f2 = He(h2, f2) ? 0 : (typeof d2._calculateChangedBits === "function" ? d2._calculateChangedBits(h2, f2) : 1073741823) | 0, f2 === 0) {
            if (g2.children === e2.children && !N.current) {
              b2 = hi(a2, b2, c3);
              break a;
            }
          } else
            for (h2 = b2.child, h2 !== null && (h2.return = b2); h2 !== null; ) {
              var k2 = h2.dependencies;
              if (k2 !== null) {
                g2 = h2.child;
                for (var l2 = k2.firstContext; l2 !== null; ) {
                  if (l2.context === d2 && (l2.observedBits & f2) !== 0) {
                    h2.tag === 1 && (l2 = zg(-1, c3 & -c3), l2.tag = 2, Ag(h2, l2));
                    h2.lanes |= c3;
                    l2 = h2.alternate;
                    l2 !== null && (l2.lanes |= c3);
                    sg(h2.return, c3);
                    k2.lanes |= c3;
                    break;
                  }
                  l2 = l2.next;
                }
              } else
                g2 = h2.tag === 10 ? h2.type === b2.type ? null : h2.child : h2.child;
              if (g2 !== null)
                g2.return = h2;
              else
                for (g2 = h2; g2 !== null; ) {
                  if (g2 === b2) {
                    g2 = null;
                    break;
                  }
                  h2 = g2.sibling;
                  if (h2 !== null) {
                    h2.return = g2.return;
                    g2 = h2;
                    break;
                  }
                  g2 = g2.return;
                }
              h2 = g2;
            }
        fi(a2, b2, e2.children, c3);
        b2 = b2.child;
      }
      return b2;
    case 9:
      return e2 = b2.type, f2 = b2.pendingProps, d2 = f2.children, tg(b2, c3), e2 = vg(e2, f2.unstable_observedBits), d2 = d2(e2), b2.flags |= 1, fi(a2, b2, d2, c3), b2.child;
    case 14:
      return e2 = b2.type, f2 = lg(e2, b2.pendingProps), f2 = lg(e2.type, f2), ii(a2, b2, e2, f2, d2, c3);
    case 15:
      return ki(a2, b2, b2.type, b2.pendingProps, d2, c3);
    case 17:
      return d2 = b2.type, e2 = b2.pendingProps, e2 = b2.elementType === d2 ? e2 : lg(d2, e2), a2 !== null && (a2.alternate = null, b2.alternate = null, b2.flags |= 2), b2.tag = 1, Ff(d2) ? (a2 = true, Jf(b2)) : a2 = false, tg(b2, c3), Mg(b2, d2, e2), Og(b2, d2, e2, c3), qi(null, b2, d2, true, a2, c3);
    case 19:
      return Ai(a2, b2, c3);
    case 23:
      return mi(a2, b2, c3);
    case 24:
      return mi(a2, b2, c3);
  }
  throw Error(y(156, b2.tag));
};
function ik(a2, b2, c3, d2) {
  this.tag = a2;
  this.key = c3;
  this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
  this.index = 0;
  this.ref = null;
  this.pendingProps = b2;
  this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
  this.mode = d2;
  this.flags = 0;
  this.lastEffect = this.firstEffect = this.nextEffect = null;
  this.childLanes = this.lanes = 0;
  this.alternate = null;
}
function nh(a2, b2, c3, d2) {
  return new ik(a2, b2, c3, d2);
}
function ji(a2) {
  a2 = a2.prototype;
  return !(!a2 || !a2.isReactComponent);
}
function hk(a2) {
  if (typeof a2 === "function")
    return ji(a2) ? 1 : 0;
  if (a2 !== void 0 && a2 !== null) {
    a2 = a2.$$typeof;
    if (a2 === Aa)
      return 11;
    if (a2 === Da)
      return 14;
  }
  return 2;
}
function Tg(a2, b2) {
  var c3 = a2.alternate;
  c3 === null ? (c3 = nh(a2.tag, b2, a2.key, a2.mode), c3.elementType = a2.elementType, c3.type = a2.type, c3.stateNode = a2.stateNode, c3.alternate = a2, a2.alternate = c3) : (c3.pendingProps = b2, c3.type = a2.type, c3.flags = 0, c3.nextEffect = null, c3.firstEffect = null, c3.lastEffect = null);
  c3.childLanes = a2.childLanes;
  c3.lanes = a2.lanes;
  c3.child = a2.child;
  c3.memoizedProps = a2.memoizedProps;
  c3.memoizedState = a2.memoizedState;
  c3.updateQueue = a2.updateQueue;
  b2 = a2.dependencies;
  c3.dependencies = b2 === null ? null : {lanes: b2.lanes, firstContext: b2.firstContext};
  c3.sibling = a2.sibling;
  c3.index = a2.index;
  c3.ref = a2.ref;
  return c3;
}
function Vg(a2, b2, c3, d2, e2, f2) {
  var g2 = 2;
  d2 = a2;
  if (typeof a2 === "function")
    ji(a2) && (g2 = 1);
  else if (typeof a2 === "string")
    g2 = 5;
  else
    a:
      switch (a2) {
        case ua:
          return Xg(c3.children, e2, f2, b2);
        case Ha:
          g2 = 8;
          e2 |= 16;
          break;
        case wa:
          g2 = 8;
          e2 |= 1;
          break;
        case xa:
          return a2 = nh(12, c3, b2, e2 | 8), a2.elementType = xa, a2.type = xa, a2.lanes = f2, a2;
        case Ba:
          return a2 = nh(13, c3, b2, e2), a2.type = Ba, a2.elementType = Ba, a2.lanes = f2, a2;
        case Ca:
          return a2 = nh(19, c3, b2, e2), a2.elementType = Ca, a2.lanes = f2, a2;
        case Ia:
          return vi(c3, e2, f2, b2);
        case Ja:
          return a2 = nh(24, c3, b2, e2), a2.elementType = Ja, a2.lanes = f2, a2;
        default:
          if (typeof a2 === "object" && a2 !== null)
            switch (a2.$$typeof) {
              case ya:
                g2 = 10;
                break a;
              case za:
                g2 = 9;
                break a;
              case Aa:
                g2 = 11;
                break a;
              case Da:
                g2 = 14;
                break a;
              case Ea:
                g2 = 16;
                d2 = null;
                break a;
              case Fa:
                g2 = 22;
                break a;
            }
          throw Error(y(130, a2 == null ? a2 : typeof a2, ""));
      }
  b2 = nh(g2, c3, b2, e2);
  b2.elementType = a2;
  b2.type = d2;
  b2.lanes = f2;
  return b2;
}
function Xg(a2, b2, c3, d2) {
  a2 = nh(7, a2, d2, b2);
  a2.lanes = c3;
  return a2;
}
function vi(a2, b2, c3, d2) {
  a2 = nh(23, a2, d2, b2);
  a2.elementType = Ia;
  a2.lanes = c3;
  return a2;
}
function Ug(a2, b2, c3) {
  a2 = nh(6, a2, null, b2);
  a2.lanes = c3;
  return a2;
}
function Wg(a2, b2, c3) {
  b2 = nh(4, a2.children !== null ? a2.children : [], a2.key, b2);
  b2.lanes = c3;
  b2.stateNode = {containerInfo: a2.containerInfo, pendingChildren: null, implementation: a2.implementation};
  return b2;
}
function jk(a2, b2, c3) {
  this.tag = b2;
  this.containerInfo = a2;
  this.finishedWork = this.pingCache = this.current = this.pendingChildren = null;
  this.timeoutHandle = -1;
  this.pendingContext = this.context = null;
  this.hydrate = c3;
  this.callbackNode = null;
  this.callbackPriority = 0;
  this.eventTimes = Zc(0);
  this.expirationTimes = Zc(-1);
  this.entangledLanes = this.finishedLanes = this.mutableReadLanes = this.expiredLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
  this.entanglements = Zc(0);
  this.mutableSourceEagerHydrationData = null;
}
function kk(a2, b2, c3) {
  var d2 = 3 < arguments.length && arguments[3] !== void 0 ? arguments[3] : null;
  return {$$typeof: ta, key: d2 == null ? null : "" + d2, children: a2, containerInfo: b2, implementation: c3};
}
function lk(a2, b2, c3, d2) {
  var e2 = b2.current, f2 = Hg(), g2 = Ig(e2);
  a:
    if (c3) {
      c3 = c3._reactInternals;
      b: {
        if (Zb(c3) !== c3 || c3.tag !== 1)
          throw Error(y(170));
        var h2 = c3;
        do {
          switch (h2.tag) {
            case 3:
              h2 = h2.stateNode.context;
              break b;
            case 1:
              if (Ff(h2.type)) {
                h2 = h2.stateNode.__reactInternalMemoizedMergedChildContext;
                break b;
              }
          }
          h2 = h2.return;
        } while (h2 !== null);
        throw Error(y(171));
      }
      if (c3.tag === 1) {
        var k2 = c3.type;
        if (Ff(k2)) {
          c3 = If(c3, k2, h2);
          break a;
        }
      }
      c3 = h2;
    } else
      c3 = Cf;
  b2.context === null ? b2.context = c3 : b2.pendingContext = c3;
  b2 = zg(f2, g2);
  b2.payload = {element: a2};
  d2 = d2 === void 0 ? null : d2;
  d2 !== null && (b2.callback = d2);
  Ag(e2, b2);
  Jg(e2, g2, f2);
  return g2;
}
function mk(a2) {
  a2 = a2.current;
  if (!a2.child)
    return null;
  switch (a2.child.tag) {
    case 5:
      return a2.child.stateNode;
    default:
      return a2.child.stateNode;
  }
}
function nk(a2, b2) {
  a2 = a2.memoizedState;
  if (a2 !== null && a2.dehydrated !== null) {
    var c3 = a2.retryLane;
    a2.retryLane = c3 !== 0 && c3 < b2 ? c3 : b2;
  }
}
function ok(a2, b2) {
  nk(a2, b2);
  (a2 = a2.alternate) && nk(a2, b2);
}
function pk() {
  return null;
}
function qk(a2, b2, c3) {
  var d2 = c3 != null && c3.hydrationOptions != null && c3.hydrationOptions.mutableSources || null;
  c3 = new jk(a2, b2, c3 != null && c3.hydrate === true);
  b2 = nh(3, null, null, b2 === 2 ? 7 : b2 === 1 ? 3 : 0);
  c3.current = b2;
  b2.stateNode = c3;
  xg(b2);
  a2[ff] = c3.current;
  cf(a2.nodeType === 8 ? a2.parentNode : a2);
  if (d2)
    for (a2 = 0; a2 < d2.length; a2++) {
      b2 = d2[a2];
      var e2 = b2._getVersion;
      e2 = e2(b2._source);
      c3.mutableSourceEagerHydrationData == null ? c3.mutableSourceEagerHydrationData = [b2, e2] : c3.mutableSourceEagerHydrationData.push(b2, e2);
    }
  this._internalRoot = c3;
}
qk.prototype.render = function(a2) {
  lk(a2, this._internalRoot, null, null);
};
qk.prototype.unmount = function() {
  var a2 = this._internalRoot, b2 = a2.containerInfo;
  lk(null, a2, null, function() {
    b2[ff] = null;
  });
};
function rk(a2) {
  return !(!a2 || a2.nodeType !== 1 && a2.nodeType !== 9 && a2.nodeType !== 11 && (a2.nodeType !== 8 || a2.nodeValue !== " react-mount-point-unstable "));
}
function sk(a2, b2) {
  b2 || (b2 = a2 ? a2.nodeType === 9 ? a2.documentElement : a2.firstChild : null, b2 = !(!b2 || b2.nodeType !== 1 || !b2.hasAttribute("data-reactroot")));
  if (!b2)
    for (var c3; c3 = a2.lastChild; )
      a2.removeChild(c3);
  return new qk(a2, 0, b2 ? {hydrate: true} : void 0);
}
function tk(a2, b2, c3, d2, e2) {
  var f2 = c3._reactRootContainer;
  if (f2) {
    var g2 = f2._internalRoot;
    if (typeof e2 === "function") {
      var h2 = e2;
      e2 = function() {
        var a3 = mk(g2);
        h2.call(a3);
      };
    }
    lk(b2, g2, a2, e2);
  } else {
    f2 = c3._reactRootContainer = sk(c3, d2);
    g2 = f2._internalRoot;
    if (typeof e2 === "function") {
      var k2 = e2;
      e2 = function() {
        var a3 = mk(g2);
        k2.call(a3);
      };
    }
    Xj(function() {
      lk(b2, g2, a2, e2);
    });
  }
  return mk(g2);
}
ec = function(a2) {
  if (a2.tag === 13) {
    var b2 = Hg();
    Jg(a2, 4, b2);
    ok(a2, 4);
  }
};
fc = function(a2) {
  if (a2.tag === 13) {
    var b2 = Hg();
    Jg(a2, 67108864, b2);
    ok(a2, 67108864);
  }
};
gc = function(a2) {
  if (a2.tag === 13) {
    var b2 = Hg(), c3 = Ig(a2);
    Jg(a2, c3, b2);
    ok(a2, c3);
  }
};
hc = function(a2, b2) {
  return b2();
};
yb = function(a2, b2, c3) {
  switch (b2) {
    case "input":
      ab(a2, c3);
      b2 = c3.name;
      if (c3.type === "radio" && b2 != null) {
        for (c3 = a2; c3.parentNode; )
          c3 = c3.parentNode;
        c3 = c3.querySelectorAll("input[name=" + JSON.stringify("" + b2) + '][type="radio"]');
        for (b2 = 0; b2 < c3.length; b2++) {
          var d2 = c3[b2];
          if (d2 !== a2 && d2.form === a2.form) {
            var e2 = Db(d2);
            if (!e2)
              throw Error(y(90));
            Wa(d2);
            ab(d2, e2);
          }
        }
      }
      break;
    case "textarea":
      ib(a2, c3);
      break;
    case "select":
      b2 = c3.value, b2 != null && fb(a2, !!c3.multiple, b2, false);
  }
};
Gb = Wj;
Hb = function(a2, b2, c3, d2, e2) {
  var f2 = X;
  X |= 4;
  try {
    return gg(98, a2.bind(null, b2, c3, d2, e2));
  } finally {
    X = f2, X === 0 && (wj(), ig());
  }
};
Ib = function() {
  (X & 49) === 0 && (Vj(), Oj());
};
Jb = function(a2, b2) {
  var c3 = X;
  X |= 2;
  try {
    return a2(b2);
  } finally {
    X = c3, X === 0 && (wj(), ig());
  }
};
function uk(a2, b2) {
  var c3 = 2 < arguments.length && arguments[2] !== void 0 ? arguments[2] : null;
  if (!rk(b2))
    throw Error(y(200));
  return kk(a2, b2, null, c3);
}
var vk = {Events: [Cb, ue, Db, Eb, Fb, Oj, {current: false}]};
var wk = {findFiberByHostInstance: wc, bundleType: 0, version: "17.0.2", rendererPackageName: "react-dom"};
var xk = {bundleType: wk.bundleType, version: wk.version, rendererPackageName: wk.rendererPackageName, rendererConfig: wk.rendererConfig, overrideHookState: null, overrideHookStateDeletePath: null, overrideHookStateRenamePath: null, overrideProps: null, overridePropsDeletePath: null, overridePropsRenamePath: null, setSuspenseHandler: null, scheduleUpdate: null, currentDispatcherRef: ra.ReactCurrentDispatcher, findHostInstanceByFiber: function(a2) {
  a2 = cc(a2);
  return a2 === null ? null : a2.stateNode;
}, findFiberByHostInstance: wk.findFiberByHostInstance || pk, findHostInstancesForRefresh: null, scheduleRefresh: null, scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null};
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined") {
  yk = __REACT_DEVTOOLS_GLOBAL_HOOK__;
  if (!yk.isDisabled && yk.supportsFiber)
    try {
      Lf = yk.inject(xk), Mf = yk;
    } catch (a2) {
    }
}
var yk;
var __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = vk;
var createPortal = uk;
var findDOMNode = function(a2) {
  if (a2 == null)
    return null;
  if (a2.nodeType === 1)
    return a2;
  var b2 = a2._reactInternals;
  if (b2 === void 0) {
    if (typeof a2.render === "function")
      throw Error(y(188));
    throw Error(y(268, Object.keys(a2)));
  }
  a2 = cc(b2);
  a2 = a2 === null ? null : a2.stateNode;
  return a2;
};
var flushSync = function(a2, b2) {
  var c3 = X;
  if ((c3 & 48) !== 0)
    return a2(b2);
  X |= 1;
  try {
    if (a2)
      return gg(99, a2.bind(null, b2));
  } finally {
    X = c3, ig();
  }
};
var hydrate = function(a2, b2, c3) {
  if (!rk(b2))
    throw Error(y(200));
  return tk(null, a2, b2, true, c3);
};
var render = function(a2, b2, c3) {
  if (!rk(b2))
    throw Error(y(200));
  return tk(null, a2, b2, false, c3);
};
var unmountComponentAtNode = function(a2) {
  if (!rk(a2))
    throw Error(y(40));
  return a2._reactRootContainer ? (Xj(function() {
    tk(null, null, a2, false, function() {
      a2._reactRootContainer = null;
      a2[ff] = null;
    });
  }), true) : false;
};
var unstable_batchedUpdates = Wj;
var unstable_createPortal = function(a2, b2) {
  return uk(a2, b2, 2 < arguments.length && arguments[2] !== void 0 ? arguments[2] : null);
};
var unstable_renderSubtreeIntoContainer = function(a2, b2, c3, d2) {
  if (!rk(c3))
    throw Error(y(200));
  if (a2 == null || a2._reactInternals === void 0)
    throw Error(y(38));
  return tk(a2, b2, c3, false, d2);
};
var version = "17.0.2";
var reactDom_production_min = {
  __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,
  createPortal,
  findDOMNode,
  flushSync,
  hydrate,
  render,
  unmountComponentAtNode,
  unstable_batchedUpdates,
  unstable_createPortal,
  unstable_renderSubtreeIntoContainer,
  version
};
var reactDom = createCommonjsModule(function(module2) {
  function checkDCE() {
    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") {
      return;
    }
    try {
      __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
    } catch (err) {
      console.error(err);
    }
  }
  {
    checkDCE();
    module2.exports = reactDom_production_min;
  }
});

// build/_snowpack/pkg/common/createIcon-1a4b25a9.js
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

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

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __rest(s2, e2) {
  var t5 = {};
  for (var p2 in s2)
    if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
      t5[p2] = s2[p2];
  if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i3 = 0, p2 = Object.getOwnPropertySymbols(s2); i3 < p2.length; i3++) {
      if (e2.indexOf(p2[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i3]))
        t5[p2[i3]] = s2[p2[i3]];
    }
  return t5;
}
function __awaiter(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _23 = {label: 0, sent: function() {
    if (t5[0] & 1)
      throw t5[1];
    return t5[1];
  }, trys: [], ops: []}, f2, y3, t5, g2;
  return g2 = {next: verb(0), throw: verb(1), return: verb(2)}, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
    return this;
  }), g2;
  function verb(n3) {
    return function(v2) {
      return step([n3, v2]);
    };
  }
  function step(op) {
    if (f2)
      throw new TypeError("Generator is already executing.");
    while (_23)
      try {
        if (f2 = 1, y3 && (t5 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t5 = y3["return"]) && t5.call(y3), 0) : y3.next) && !(t5 = t5.call(y3, op[1])).done)
          return t5;
        if (y3 = 0, t5)
          op = [op[0] & 2, t5.value];
        switch (op[0]) {
          case 0:
          case 1:
            t5 = op;
            break;
          case 4:
            _23.label++;
            return {value: op[1], done: false};
          case 5:
            _23.label++;
            y3 = op[1];
            op = [0];
            continue;
          case 7:
            op = _23.ops.pop();
            _23.trys.pop();
            continue;
          default:
            if (!(t5 = _23.trys, t5 = t5.length > 0 && t5[t5.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _23 = 0;
              continue;
            }
            if (op[0] === 3 && (!t5 || op[1] > t5[0] && op[1] < t5[3])) {
              _23.label = op[1];
              break;
            }
            if (op[0] === 6 && _23.label < t5[1]) {
              _23.label = t5[1];
              t5 = op;
              break;
            }
            if (t5 && _23.label < t5[2]) {
              _23.label = t5[2];
              _23.ops.push(op);
              break;
            }
            if (t5[2])
              _23.ops.pop();
            _23.trys.pop();
            continue;
        }
        op = body.call(thisArg, _23);
      } catch (e2) {
        op = [6, e2];
        y3 = 0;
      } finally {
        f2 = t5 = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return {value: op[0] ? op[1] : void 0, done: true};
  }
}
function __read(o, n3) {
  var m2 = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m2)
    return o;
  var i3 = m2.call(o), r3, ar = [], e2;
  try {
    while ((n3 === void 0 || n3-- > 0) && !(r3 = i3.next()).done)
      ar.push(r3.value);
  } catch (error2) {
    e2 = {error: error2};
  } finally {
    try {
      if (r3 && !r3.done && (m2 = i3["return"]))
        m2.call(i3);
    } finally {
      if (e2)
        throw e2.error;
    }
  }
  return ar;
}
function __spread() {
  for (var ar = [], i3 = 0; i3 < arguments.length; i3++)
    ar = ar.concat(__read(arguments[i3]));
  return ar;
}
var IconSize;
(function(IconSize2) {
  IconSize2["sm"] = "sm";
  IconSize2["md"] = "md";
  IconSize2["lg"] = "lg";
  IconSize2["xl"] = "xl";
})(IconSize || (IconSize = {}));
var getSize = (size2) => {
  switch (size2) {
    case IconSize.sm:
      return "1em";
    case IconSize.md:
      return "1.5em";
    case IconSize.lg:
      return "2em";
    case IconSize.xl:
      return "3em";
    default:
      return "1em";
  }
};
var currentId = 0;
function createIcon({name, xOffset = 0, yOffset = 0, width: width2, height, svgPath}) {
  var _a;
  return _a = class SVGIcon extends react.Component {
    constructor() {
      super(...arguments);
      this.id = `icon-title-${currentId++}`;
    }
    render() {
      const _a2 = this.props, {size: size2, color: color2, title: title3, noVerticalAlign} = _a2, props = __rest(_a2, ["size", "color", "title", "noVerticalAlign"]);
      const hasTitle = Boolean(title3);
      const heightWidth = getSize(size2);
      const baseAlign = -0.125 * Number.parseFloat(heightWidth);
      const style = noVerticalAlign ? null : {verticalAlign: `${baseAlign}em`};
      const viewBox = [xOffset, yOffset, width2, height].join(" ");
      return react.createElement("svg", Object.assign({style, fill: color2, height: heightWidth, width: heightWidth, viewBox, "aria-labelledby": hasTitle ? this.id : null, "aria-hidden": hasTitle ? null : true, role: "img"}, props), hasTitle && react.createElement("title", {id: this.id}, title3), react.createElement("path", {d: svgPath}));
    }
  }, _a.displayName = name, _a.defaultProps = {
    color: "currentColor",
    size: IconSize.sm,
    noVerticalAlign: false
  }, _a;
}

// build/_snowpack/pkg/common/EmptyState-cea4cc03.js
function css(...args) {
  const classes = [];
  const hasOwn = {}.hasOwnProperty;
  args.filter(Boolean).forEach((arg) => {
    const argType = typeof arg;
    if (argType === "string" || argType === "number") {
      classes.push(arg);
    } else if (Array.isArray(arg) && arg.length) {
      const inner = css(...arg);
      if (inner) {
        classes.push(inner);
      }
    } else if (argType === "object") {
      for (const key in arg) {
        if (hasOwn.call(arg, key) && arg[key]) {
          classes.push(key);
        }
      }
    }
  });
  return classes.join(" ");
}
var KEY_CODES = {ARROW_UP: 38, ARROW_DOWN: 40, ESCAPE_KEY: 27, TAB: 9, ENTER: 13, SPACE: 32};
var KEYHANDLER_DIRECTION = {UP: "up", DOWN: "down", RIGHT: "right", LEFT: "left"};
var ValidatedOptions;
(function(ValidatedOptions2) {
  ValidatedOptions2["success"] = "success";
  ValidatedOptions2["error"] = "error";
  ValidatedOptions2["warning"] = "warning";
  ValidatedOptions2["default"] = "default";
})(ValidatedOptions || (ValidatedOptions = {}));
var uid = 0;
var ouiaPrefix = "OUIA-Generated-";
var ouiaIdByRoute = {};
function getOUIAProps(componentType, id3, ouiaSafe = true) {
  return {
    "data-ouia-component-type": `PF4/${componentType}`,
    "data-ouia-safe": ouiaSafe,
    "data-ouia-component-id": id3
  };
}
var useOUIAProps = (componentType, id3, ouiaSafe = true, variant) => ({
  "data-ouia-component-type": `PF4/${componentType}`,
  "data-ouia-safe": ouiaSafe,
  "data-ouia-component-id": useOUIAId(componentType, id3, variant)
});
var useOUIAId = (componentType, id3, variant) => {
  if (id3 !== void 0) {
    return id3;
  }
  return react.useMemo(() => getDefaultOUIAId(componentType, variant), [componentType, variant]);
};
function getDefaultOUIAId(componentType, variant) {
  try {
    const key = `${window.location.href}-${componentType}-${variant || ""}`;
    if (!ouiaIdByRoute[key]) {
      ouiaIdByRoute[key] = 0;
    }
    return `${ouiaPrefix}${componentType}-${variant ? `${variant}-` : ""}${++ouiaIdByRoute[key]}`;
  } catch (exception) {
    return `${ouiaPrefix}${componentType}-${variant ? `${variant}-` : ""}${++uid}`;
  }
}
function capitalize2(input) {
  return input[0].toUpperCase() + input.substring(1);
}
function getUniqueId(prefix2 = "pf") {
  const uid2 = new Date().getTime() + Math.random().toString(36).slice(2);
  return `${prefix2}-${uid2}`;
}
function debounce(func, wait) {
  let timeout3;
  return (...args) => {
    clearTimeout(timeout3);
    timeout3 = setTimeout(() => func.apply(this, args), wait);
  };
}
function isElementInView(container, element, partial) {
  if (!container || !element) {
    return false;
  }
  const containerBounds = container.getBoundingClientRect();
  const elementBounds = element.getBoundingClientRect();
  const containerBoundsLeft = Math.floor(containerBounds.left);
  const containerBoundsRight = Math.floor(containerBounds.right);
  const elementBoundsLeft = Math.floor(elementBounds.left);
  const elementBoundsRight = Math.floor(elementBounds.right);
  const isTotallyInView = elementBoundsLeft >= containerBoundsLeft && elementBoundsRight <= containerBoundsRight;
  const isPartiallyInView = partial && (elementBoundsLeft < containerBoundsLeft && elementBoundsRight > containerBoundsLeft || elementBoundsRight > containerBoundsRight && elementBoundsLeft < containerBoundsRight);
  return isTotallyInView || isPartiallyInView;
}
function fillTemplate(templateString, templateVars) {
  return templateString.replace(/\${(.*?)}/g, (_23, match2) => templateVars[match2] || "");
}
function keyHandler(index3, innerIndex, position2, refsCollection, kids, custom = false) {
  if (!Array.isArray(kids)) {
    return;
  }
  const isMultiDimensional = refsCollection.filter((ref) => ref)[0].constructor === Array;
  let nextIndex = index3;
  let nextInnerIndex = innerIndex;
  if (position2 === "up") {
    if (index3 === 0) {
      nextIndex = kids.length - 1;
    } else {
      nextIndex = index3 - 1;
    }
  } else if (position2 === "down") {
    if (index3 === kids.length - 1) {
      nextIndex = 0;
    } else {
      nextIndex = index3 + 1;
    }
  } else if (position2 === "left") {
    if (innerIndex === 0) {
      nextInnerIndex = refsCollection[index3].length - 1;
    } else {
      nextInnerIndex = innerIndex - 1;
    }
  } else if (position2 === "right") {
    if (innerIndex === refsCollection[index3].length - 1) {
      nextInnerIndex = 0;
    } else {
      nextInnerIndex = innerIndex + 1;
    }
  }
  if (refsCollection[nextIndex] === null || refsCollection[nextIndex] === void 0 || isMultiDimensional && (refsCollection[nextIndex][nextInnerIndex] === null || refsCollection[nextIndex][nextInnerIndex] === void 0)) {
    keyHandler(nextIndex, nextInnerIndex, position2, refsCollection, kids, custom);
  } else if (custom) {
    if (refsCollection[nextIndex].focus) {
      refsCollection[nextIndex].focus();
    }
    const element = reactDom.findDOMNode(refsCollection[nextIndex]);
    element.focus();
  } else if (position2 !== "tab") {
    if (isMultiDimensional) {
      refsCollection[nextIndex][nextInnerIndex].focus();
    } else {
      refsCollection[nextIndex].focus();
    }
  }
}
function getNextIndex(index3, position2, collection) {
  let nextIndex;
  if (position2 === "up") {
    if (index3 === 0) {
      nextIndex = collection.length - 1;
    } else {
      nextIndex = index3 - 1;
    }
  } else if (index3 === collection.length - 1) {
    nextIndex = 0;
  } else {
    nextIndex = index3 + 1;
  }
  if (collection[nextIndex] === void 0 || collection[nextIndex][0] === null) {
    return getNextIndex(nextIndex, position2, collection);
  } else {
    return nextIndex;
  }
}
function pluralize(i3, singular, plural) {
  if (!plural) {
    plural = `${singular}s`;
  }
  return `${i3 || 0} ${i3 === 1 ? singular : plural}`;
}
var setBreakpointCssVars = (mods, cssVar) => Object.entries(mods || {}).reduce((acc, [breakpoint, value]) => breakpoint === "default" ? Object.assign(Object.assign({}, acc), {[cssVar]: value}) : Object.assign(Object.assign({}, acc), {[`${cssVar}-on-${breakpoint}`]: value}), {});
var formatBreakpointMods = (mods, styles6, stylePrefix = "") => Object.entries(mods || {}).map(([breakpoint, mod]) => `${stylePrefix}${mod}${breakpoint !== "default" ? `-on-${breakpoint}` : ""}`).map(toCamel).map((mod) => mod.replace(/-?(\dxl)/gi, (_res, group) => `_${group}`)).map((modifierKey) => styles6.modifiers[modifierKey]).filter(Boolean).join(" ");
var camelize = (s2) => s2.toUpperCase().replace("-", "").replace("_", "");
var toCamel = (s2) => s2.replace(/([-_][a-z])/gi, camelize);
var canUseDOM = !!(typeof window !== "undefined" && window.document && window.document.createElement);
var getTextWidth = (text, node) => {
  const computedStyle = getComputedStyle(node);
  const getFontFromComputedStyle = () => {
    let computedFont = "";
    const fontStretchLookupTable = {
      "50%": "ultra-condensed",
      "62.5%": "extra-condensed",
      "75%": "condensed",
      "87.5%": "semi-condensed",
      "100%": "normal",
      "112.5%": "semi-expanded",
      "125%": "expanded",
      "150%": "extra-expanded",
      "200%": "ultra-expanded"
    };
    let fontStretch;
    if (computedStyle.fontStretch in fontStretchLookupTable) {
      fontStretch = fontStretchLookupTable[computedStyle.fontStretch];
    } else {
      fontStretch = "normal";
    }
    computedFont = computedStyle.fontStyle + " " + computedStyle.fontVariant + " " + computedStyle.fontWeight + " " + fontStretch + " " + computedStyle.fontSize + "/" + computedStyle.lineHeight + " " + computedStyle.fontFamily;
    return computedFont;
  };
  const canvas = document.createElement("canvas");
  const context2 = canvas.getContext("2d");
  context2.font = computedStyle.font || getFontFromComputedStyle();
  return context2.measureText(text).width;
};
var innerDimensions = (node) => {
  const computedStyle = getComputedStyle(node);
  let width2 = node.clientWidth;
  let height = node.clientHeight;
  height -= parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
  width2 -= parseFloat(computedStyle.paddingLeft) + parseFloat(computedStyle.paddingRight);
  return {height, width: width2};
};
var trimLeft = (node, value) => {
  const availableWidth = innerDimensions(node).width;
  let newValue = value;
  if (getTextWidth(value, node) > availableWidth) {
    while (getTextWidth(`...${newValue}`, node) > availableWidth) {
      newValue = newValue.substring(1);
    }
    if (node.value) {
      node.value = `...${newValue}`;
    } else {
      node.innerText = `...${newValue}`;
    }
  } else {
    if (node.value) {
      node.value = value;
    } else {
      node.innerText = value;
    }
  }
};
var preventedEvents = (events) => events.reduce((handlers, eventToPrevent) => Object.assign(Object.assign({}, handlers), {[eventToPrevent]: (event) => {
  event.preventDefault();
}}), {});
var FindRefWrapper = class extends react.Component {
  componentDidMount() {
    const root4 = reactDom.findDOMNode(this);
    this.props.onFoundRef(root4);
  }
  render() {
    return this.props.children || null;
  }
};
FindRefWrapper.displayName = "FindRefWrapper";
function getBoundingClientRect(element) {
  const rect = element.getBoundingClientRect();
  return {
    width: rect.width,
    height: rect.height,
    top: rect.top,
    right: rect.right,
    bottom: rect.bottom,
    left: rect.left,
    x: rect.left,
    y: rect.top
  };
}
function getWindow(node) {
  if (node.toString() !== "[object Window]") {
    const ownerDocument = node.ownerDocument;
    return ownerDocument ? ownerDocument.defaultView : window;
  }
  return node;
}
function getWindowScroll(node) {
  const win = getWindow(node);
  const scrollLeft = win.pageXOffset;
  const scrollTop = win.pageYOffset;
  return {
    scrollLeft,
    scrollTop
  };
}
function isElement(node) {
  const OwnElement = getWindow(node).Element;
  return node instanceof OwnElement || node instanceof Element;
}
function isHTMLElement(node) {
  const OwnElement = getWindow(node).HTMLElement;
  return node instanceof OwnElement || node instanceof HTMLElement;
}
function getHTMLElementScroll(element) {
  return {
    scrollLeft: element.scrollLeft,
    scrollTop: element.scrollTop
  };
}
function getNodeScroll(node) {
  if (node === getWindow(node) || !isHTMLElement(node)) {
    return getWindowScroll(node);
  } else {
    return getHTMLElementScroll(node);
  }
}
function getNodeName(element) {
  return element ? (element.nodeName || "").toLowerCase() : null;
}
function getDocumentElement(element) {
  return (isElement(element) ? element.ownerDocument : element.document).documentElement;
}
function getWindowScrollBarX(element) {
  return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}
function getComputedStyle$1(element) {
  return getWindow(element).getComputedStyle(element);
}
function isScrollParent(element) {
  const {overflow, overflowX, overflowY} = getComputedStyle$1(element);
  return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}
function getCompositeRect(elementOrVirtualElement, offsetParent2, isFixed = false) {
  const documentElement = getDocumentElement(offsetParent2);
  const rect = getBoundingClientRect(elementOrVirtualElement);
  const isOffsetParentAnElement = isHTMLElement(offsetParent2);
  let scroll = {scrollLeft: 0, scrollTop: 0};
  let offsets = {x: 0, y: 0};
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent2) !== "body" || isScrollParent(documentElement)) {
      scroll = getNodeScroll(offsetParent2);
    }
    if (isHTMLElement(offsetParent2)) {
      offsets = getBoundingClientRect(offsetParent2);
      offsets.x += offsetParent2.clientLeft;
      offsets.y += offsetParent2.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 getLayoutRect(element) {
  return {
    x: element.offsetLeft,
    y: element.offsetTop,
    width: element.offsetWidth,
    height: element.offsetHeight
  };
}
function getParentNode(element) {
  if (getNodeName(element) === "html") {
    return element;
  }
  return element.assignedSlot || element.parentNode || element.host || getDocumentElement(element);
}
function getScrollParent(node) {
  if (["html", "body", "#document"].indexOf(getNodeName(node)) >= 0) {
    return node.ownerDocument.body;
  }
  if (isHTMLElement(node) && isScrollParent(node)) {
    return node;
  }
  return getScrollParent(getParentNode(node));
}
function listScrollParents(element, list3 = []) {
  const scrollParent = getScrollParent(element);
  const isBody = getNodeName(scrollParent) === "body";
  const win = getWindow(scrollParent);
  const target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
  const updatedList = list3.concat(target);
  return isBody ? updatedList : updatedList.concat(listScrollParents(getParentNode(target)));
}
function isTableElement(element) {
  return ["table", "td", "th"].indexOf(getNodeName(element)) >= 0;
}
function getTrueOffsetParent(element) {
  if (!isHTMLElement(element) || getComputedStyle$1(element).position === "fixed") {
    return null;
  }
  const offsetParent2 = element.offsetParent;
  if (offsetParent2) {
    const html = getDocumentElement(offsetParent2);
    if (getNodeName(offsetParent2) === "body" && getComputedStyle$1(offsetParent2).position === "static" && getComputedStyle$1(html).position !== "static") {
      return html;
    }
  }
  return offsetParent2;
}
function getContainingBlock(element) {
  let currentNode = getParentNode(element);
  while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) {
    const css2 = getComputedStyle$1(currentNode);
    if (css2.transform !== "none" || css2.perspective !== "none" || css2.willChange && css2.willChange !== "auto") {
      return currentNode;
    } else {
      currentNode = currentNode.parentNode;
    }
  }
  return null;
}
function getOffsetParent(element) {
  const window2 = getWindow(element);
  let offsetParent2 = getTrueOffsetParent(element);
  while (offsetParent2 && isTableElement(offsetParent2) && getComputedStyle$1(offsetParent2).position === "static") {
    offsetParent2 = getTrueOffsetParent(offsetParent2);
  }
  if (offsetParent2 && getNodeName(offsetParent2) === "body" && getComputedStyle$1(offsetParent2).position === "static") {
    return window2;
  }
  return offsetParent2 || getContainingBlock(element) || window2;
}
var top = "top";
var bottom = "bottom";
var right = "right";
var left = "left";
var auto = "auto";
var basePlacements = [top, bottom, right, left];
var start = "start";
var end = "end";
var clippingParents = "clippingParents";
var viewport = "viewport";
var popper = "popper";
var reference = "reference";
var variationPlacements = basePlacements.reduce((acc, placement) => acc.concat([`${placement}-${start}`, `${placement}-${end}`]), []);
var placements = [...basePlacements, auto].reduce((acc, placement) => 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 order(modifiers) {
  const map2 = new Map();
  const visited = new Set();
  const result = [];
  modifiers.forEach((modifier) => {
    map2.set(modifier.name, modifier);
  });
  function sort2(modifier) {
    visited.add(modifier.name);
    const requires = [...modifier.requires || [], ...modifier.requiresIfExists || []];
    requires.forEach((dep) => {
      if (!visited.has(dep)) {
        const depModifier = map2.get(dep);
        if (depModifier) {
          sort2(depModifier);
        }
      }
    });
    result.push(modifier);
  }
  modifiers.forEach((modifier) => {
    if (!visited.has(modifier.name)) {
      sort2(modifier);
    }
  });
  return result;
}
function orderModifiers(modifiers) {
  const orderedModifiers = order(modifiers);
  return modifierPhases.reduce((acc, phase) => acc.concat(orderedModifiers.filter((modifier) => modifier.phase === phase)), []);
}
function debounce$1(fn) {
  let pending;
  return () => {
    if (!pending) {
      pending = new Promise((resolve2) => {
        Promise.resolve().then(() => {
          pending = void 0;
          resolve2(fn());
        });
      });
    }
    return pending;
  };
}
function getBasePlacement(placement) {
  return placement.split("-")[0];
}
function mergeByName(modifiers) {
  const merged = modifiers.reduce((merged2, current) => {
    const existing = merged2[current.name];
    merged2[current.name] = existing ? Object.assign(Object.assign(Object.assign({}, existing), current), {options: Object.assign(Object.assign({}, existing.options), current.options), data: Object.assign(Object.assign({}, existing.data), current.data)}) : current;
    return merged2;
  }, {});
  return Object.keys(merged).map((key) => merged[key]);
}
function getViewportRect(element) {
  const win = getWindow(element);
  const html = getDocumentElement(element);
  const visualViewport = win.visualViewport;
  let width2 = html.clientWidth;
  let height = html.clientHeight;
  let x2 = 0;
  let y3 = 0;
  if (visualViewport) {
    width2 = visualViewport.width;
    height = visualViewport.height;
    if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
      x2 = visualViewport.offsetLeft;
      y3 = visualViewport.offsetTop;
    }
  }
  return {
    width: width2,
    height,
    x: x2 + getWindowScrollBarX(element),
    y: y3
  };
}
function getDocumentRect(element) {
  const html = getDocumentElement(element);
  const winScroll = getWindowScroll(element);
  const body = element.ownerDocument.body;
  const width2 = Math.max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
  const height = Math.max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
  let x2 = -winScroll.scrollLeft + getWindowScrollBarX(element);
  const y3 = -winScroll.scrollTop;
  if (getComputedStyle$1(body || html).direction === "rtl") {
    x2 += Math.max(html.clientWidth, body ? body.clientWidth : 0) - width2;
  }
  return {width: width2, height, x: x2, y: y3};
}
function contains(parent, child) {
  const isShadow = Boolean(child.getRootNode && child.getRootNode().host);
  if (parent.contains(child)) {
    return true;
  } else if (isShadow) {
    let next = child;
    do {
      if (next && parent.isSameNode(next)) {
        return true;
      }
      next = next.parentNode || next.host;
    } while (next);
  }
  return false;
}
function rectToClientRect(rect) {
  return Object.assign(Object.assign({}, rect), {left: rect.x, top: rect.y, right: rect.x + rect.width, bottom: rect.y + rect.height});
}
function getInnerBoundingClientRect(element) {
  const rect = getBoundingClientRect(element);
  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) {
  return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isHTMLElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
}
function getClippingParents(element) {
  const clippingParents2 = listScrollParents(getParentNode(element));
  const canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle$1(element).position) >= 0;
  const clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
  if (!isElement(clipperElement)) {
    return [];
  }
  return clippingParents2.filter((clippingParent) => isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body");
}
function getClippingRect(element, boundary, rootBoundary) {
  const mainClippingParents = boundary === "clippingParents" ? getClippingParents(element) : [].concat(boundary);
  const clippingParents2 = [...mainClippingParents, rootBoundary];
  const firstClippingParent = clippingParents2[0];
  const clippingRect = clippingParents2.reduce((accRect, clippingParent) => {
    const rect = getClientRectFromMixedType(element, clippingParent);
    accRect.top = Math.max(rect.top, accRect.top);
    accRect.right = Math.min(rect.right, accRect.right);
    accRect.bottom = Math.min(rect.bottom, accRect.bottom);
    accRect.left = Math.max(rect.left, accRect.left);
    return accRect;
  }, getClientRectFromMixedType(element, firstClippingParent));
  clippingRect.width = clippingRect.right - clippingRect.left;
  clippingRect.height = clippingRect.bottom - clippingRect.top;
  clippingRect.x = clippingRect.left;
  clippingRect.y = clippingRect.top;
  return clippingRect;
}
function getVariation(placement) {
  return placement.split("-")[1];
}
function getMainAxisFromPlacement(placement) {
  return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y";
}
function computeOffsets({reference: reference2, element, placement}) {
  const basePlacement = placement ? getBasePlacement(placement) : null;
  const variation = placement ? getVariation(placement) : null;
  const commonX = reference2.x + reference2.width / 2 - element.width / 2;
  const commonY = reference2.y + reference2.height / 2 - element.height / 2;
  let 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:
      offsets = {
        x: reference2.x + reference2.width,
        y: commonY
      };
      break;
    case left:
      offsets = {
        x: reference2.x - element.width,
        y: commonY
      };
      break;
    default:
      offsets = {
        x: reference2.x,
        y: reference2.y
      };
  }
  const mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
  if (mainAxis != null) {
    const len2 = mainAxis === "y" ? "height" : "width";
    switch (variation) {
      case start:
        offsets[mainAxis] = Math.floor(offsets[mainAxis]) - Math.floor(reference2[len2] / 2 - element[len2] / 2);
        break;
      case end:
        offsets[mainAxis] = Math.floor(offsets[mainAxis]) + Math.ceil(reference2[len2] / 2 - element[len2] / 2);
        break;
    }
  }
  return offsets;
}
function getFreshSideObject() {
  return {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  };
}
function mergePaddingObject(paddingObject) {
  return Object.assign(Object.assign({}, getFreshSideObject()), paddingObject);
}
function expandToHashMap(value, keys2) {
  return keys2.reduce((hashMap, key) => {
    hashMap[key] = value;
    return hashMap;
  }, {});
}
function detectOverflow(state, options = {}) {
  const {placement = state.placement, boundary = clippingParents, rootBoundary = viewport, elementContext = popper, altBoundary = false, padding = 0} = options;
  const paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements));
  const altContext = elementContext === popper ? reference : popper;
  const referenceElement = state.elements.reference;
  const popperRect = state.rects.popper;
  const element = state.elements[altBoundary ? altContext : elementContext];
  const clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary);
  const referenceClientRect = getBoundingClientRect(referenceElement);
  const popperOffsets2 = computeOffsets({
    reference: referenceClientRect,
    element: popperRect,
    strategy: "absolute",
    placement
  });
  const popperClientRect = rectToClientRect(Object.assign(Object.assign({}, popperRect), popperOffsets2));
  const elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect;
  const 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
  };
  const offsetData = state.modifiersData.offset;
  if (elementContext === popper && offsetData) {
    const offset2 = offsetData[placement];
    Object.keys(overflowOffsets).forEach((key) => {
      const multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
      const axis = [top, bottom].indexOf(key) >= 0 ? "y" : "x";
      overflowOffsets[key] += offset2[axis] * multiply;
    });
  }
  return overflowOffsets;
}
var DEFAULT_OPTIONS = {
  placement: "bottom",
  modifiers: [],
  strategy: "absolute"
};
function areValidElements(...args) {
  return !args.some((element) => !(element && typeof element.getBoundingClientRect === "function"));
}
function popperGenerator(generatorOptions = {}) {
  const {defaultModifiers: defaultModifiers2 = [], defaultOptions: defaultOptions3 = DEFAULT_OPTIONS} = generatorOptions;
  return function createPopper2(reference2, popper2, options = defaultOptions3) {
    let state = {
      placement: "bottom",
      orderedModifiers: [],
      options: Object.assign(Object.assign({}, DEFAULT_OPTIONS), defaultOptions3),
      modifiersData: {},
      elements: {
        reference: reference2,
        popper: popper2
      },
      attributes: {},
      styles: {}
    };
    let effectCleanupFns = [];
    let isDestroyed = false;
    const instance2 = {
      state,
      setOptions(options2) {
        cleanupModifierEffects();
        state.options = Object.assign(Object.assign(Object.assign({}, defaultOptions3), state.options), options2);
        state.scrollParents = {
          reference: isElement(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [],
          popper: listScrollParents(popper2)
        };
        const orderedModifiers = orderModifiers(mergeByName([...defaultModifiers2, ...state.options.modifiers]));
        state.orderedModifiers = orderedModifiers.filter((m2) => m2.enabled);
        runModifierEffects();
        return instance2.update();
      },
      forceUpdate() {
        if (isDestroyed) {
          return;
        }
        const {reference: reference3, popper: popper3} = state.elements;
        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((modifier) => state.modifiersData[modifier.name] = Object.assign({}, modifier.data));
        for (let index3 = 0; index3 < state.orderedModifiers.length; index3++) {
          if (state.reset === true) {
            state.reset = false;
            index3 = -1;
            continue;
          }
          const {fn, options: options2 = {}, name} = state.orderedModifiers[index3];
          if (typeof fn === "function") {
            state = fn({state, options: options2, name, instance: instance2}) || state;
          }
        }
      },
      update: debounce$1(() => new Promise((resolve2) => {
        instance2.forceUpdate();
        resolve2(state);
      })),
      destroy() {
        cleanupModifierEffects();
        isDestroyed = true;
      }
    };
    if (!areValidElements(reference2, popper2)) {
      return instance2;
    }
    instance2.setOptions(options).then((state2) => {
      if (!isDestroyed && options.onFirstUpdate) {
        options.onFirstUpdate(state2);
      }
    });
    function runModifierEffects() {
      state.orderedModifiers.forEach(({name, options: options2 = {}, effect: effect2}) => {
        if (typeof effect2 === "function") {
          const cleanupFn = effect2({state, name, instance: instance2, options: options2});
          const noopFn = () => {
          };
          effectCleanupFns.push(cleanupFn || noopFn);
        }
      });
    }
    function cleanupModifierEffects() {
      effectCleanupFns.forEach((fn) => fn());
      effectCleanupFns = [];
    }
    return instance2;
  };
}
var passive = {passive: true};
function effect({state, instance: instance2, options}) {
  const {scroll = true, resize = true} = options;
  const window2 = getWindow(state.elements.popper);
  const scrollParents = [...state.scrollParents.reference, ...state.scrollParents.popper];
  if (scroll) {
    scrollParents.forEach((scrollParent) => {
      scrollParent.addEventListener("scroll", instance2.update, passive);
    });
  }
  if (resize) {
    window2.addEventListener("resize", instance2.update, passive);
  }
  return () => {
    if (scroll) {
      scrollParents.forEach((scrollParent) => {
        scrollParent.removeEventListener("scroll", instance2.update, passive);
      });
    }
    if (resize) {
      window2.removeEventListener("resize", instance2.update, passive);
    }
  };
}
var eventListeners = {
  name: "eventListeners",
  enabled: true,
  phase: "write",
  fn: () => {
  },
  effect,
  data: {}
};
function popperOffsets({state, name}) {
  state.modifiersData[name] = computeOffsets({
    reference: state.rects.reference,
    element: state.rects.popper,
    strategy: "absolute",
    placement: state.placement
  });
}
var popperOffsets$1 = {
  name: "popperOffsets",
  enabled: true,
  phase: "read",
  fn: popperOffsets,
  data: {}
};
var unsetSides = {
  top: "auto",
  right: "auto",
  bottom: "auto",
  left: "auto"
};
function roundOffsets({x: x2, y: y3}) {
  const win = window;
  const dpr = win.devicePixelRatio || 1;
  return {
    x: Math.round(x2 * dpr) / dpr || 0,
    y: Math.round(y3 * dpr) / dpr || 0
  };
}
function mapToStyles({popper: popper2, popperRect, placement, offsets, position: position2, gpuAcceleration, adaptive}) {
  let {x: x2, y: y3} = roundOffsets(offsets);
  const hasX = offsets.hasOwnProperty("x");
  const hasY = offsets.hasOwnProperty("y");
  let sideX = left;
  let sideY = top;
  const win = window;
  if (adaptive) {
    let offsetParent2 = getOffsetParent(popper2);
    if (offsetParent2 === getWindow(popper2)) {
      offsetParent2 = getDocumentElement(popper2);
    }
    if (placement === top) {
      sideY = bottom;
      y3 -= offsetParent2.clientHeight - popperRect.height;
      y3 *= gpuAcceleration ? 1 : -1;
    }
    if (placement === left) {
      sideX = right;
      x2 -= offsetParent2.clientWidth - popperRect.width;
      x2 *= gpuAcceleration ? 1 : -1;
    }
  }
  const commonStyles = Object.assign({position: position2}, adaptive && unsetSides);
  if (gpuAcceleration) {
    return Object.assign(Object.assign({}, commonStyles), {
      [sideY]: hasY ? "0" : "",
      [sideX]: hasX ? "0" : "",
      transform: (win.devicePixelRatio || 1) < 2 ? `translate(${x2}px, ${y3}px)` : `translate3d(${x2}px, ${y3}px, 0)`
    });
  }
  return Object.assign(Object.assign({}, commonStyles), {[sideY]: hasY ? `${y3}px` : "", [sideX]: hasX ? `${x2}px` : "", transform: ""});
}
function computeStyles({state, options}) {
  const {gpuAcceleration = true, adaptive = true} = options;
  const commonStyles = {
    placement: getBasePlacement(state.placement),
    popper: state.elements.popper,
    popperRect: state.rects.popper,
    gpuAcceleration
  };
  if (state.modifiersData.popperOffsets != null) {
    state.styles.popper = Object.assign(Object.assign({}, state.styles.popper), mapToStyles(Object.assign(Object.assign({}, commonStyles), {offsets: state.modifiersData.popperOffsets, position: state.options.strategy, adaptive})));
  }
  if (state.modifiersData.arrow != null) {
    state.styles.arrow = Object.assign(Object.assign({}, state.styles.arrow), mapToStyles(Object.assign(Object.assign({}, commonStyles), {offsets: state.modifiersData.arrow, position: "absolute", adaptive: false})));
  }
  state.attributes.popper = Object.assign(Object.assign({}, state.attributes.popper), {"data-popper-placement": state.placement});
}
var computeStyles$1 = {
  name: "computeStyles",
  enabled: true,
  phase: "beforeWrite",
  fn: computeStyles,
  data: {}
};
function applyStyles({state}) {
  Object.keys(state.elements).forEach((name) => {
    const style = state.styles[name] || {};
    const attributes = state.attributes[name] || {};
    const element = state.elements[name];
    if (!isHTMLElement(element) || !getNodeName(element)) {
      return;
    }
    Object.assign(element.style, style);
    Object.keys(attributes).forEach((name2) => {
      const value = attributes[name2];
      if (value === false) {
        element.removeAttribute(name2);
      } else {
        element.setAttribute(name2, value === true ? "" : value);
      }
    });
  });
}
function effect$1({state}) {
  const initialStyles = {
    popper: {
      position: state.options.strategy,
      left: "0",
      top: "0",
      margin: "0"
    },
    arrow: {
      position: "absolute"
    },
    reference: {}
  };
  Object.assign(state.elements.popper.style, initialStyles.popper);
  if (state.elements.arrow) {
    Object.assign(state.elements.arrow.style, initialStyles.arrow);
  }
  return () => {
    Object.keys(state.elements).forEach((name) => {
      const element = state.elements[name];
      const attributes = state.attributes[name] || {};
      const styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]);
      const style = styleProperties.reduce((style2, property2) => {
        style2[property2] = "";
        return style2;
      }, {});
      if (!isHTMLElement(element) || !getNodeName(element)) {
        return;
      }
      Object.assign(element.style, style);
      Object.keys(attributes).forEach((attribute) => {
        element.removeAttribute(attribute);
      });
    });
  };
}
var applyStyles$1 = {
  name: "applyStyles",
  enabled: true,
  phase: "write",
  fn: applyStyles,
  effect: effect$1,
  requires: ["computeStyles"]
};
function distanceAndSkiddingToXY(placement, rects, offset2) {
  const basePlacement = getBasePlacement(placement);
  const invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
  let [skidding, distance] = typeof offset2 === "function" ? offset2(Object.assign(Object.assign({}, rects), {placement})) : offset2;
  skidding = skidding || 0;
  distance = (distance || 0) * invertDistance;
  return [left, right].indexOf(basePlacement) >= 0 ? {x: distance, y: skidding} : {x: skidding, y: distance};
}
function offset({state, options, name}) {
  const {offset: offset2 = [0, 0]} = options;
  const data2 = placements.reduce((acc, placement) => {
    acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset2);
    return acc;
  }, {});
  const {x: x2, y: y3} = data2[state.placement];
  if (state.modifiersData.popperOffsets != null) {
    state.modifiersData.popperOffsets.x += x2;
    state.modifiersData.popperOffsets.y += y3;
  }
  state.modifiersData[name] = data2;
}
var offset$1 = {
  name: "offset",
  enabled: true,
  phase: "main",
  requires: ["popperOffsets"],
  fn: offset
};
var hash = {left: "right", right: "left", bottom: "top", top: "bottom"};
function getOppositePlacement(placement) {
  return placement.replace(/left|right|bottom|top/g, (matched) => hash[matched]);
}
var hash$1 = {start: "end", end: "start"};
function getOppositeVariationPlacement(placement) {
  return placement.replace(/start|end/g, (matched) => hash$1[matched]);
}
function computeAutoPlacement(state, options = {}) {
  const {placement, boundary, rootBoundary, padding, flipVariations, allowedAutoPlacements = placements} = options;
  const variation = getVariation(placement);
  const placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter((placement2) => getVariation(placement2) === variation) : basePlacements;
  let allowedPlacements = placements$1.filter((placement2) => allowedAutoPlacements.indexOf(placement2) >= 0);
  if (allowedPlacements.length === 0) {
    allowedPlacements = placements$1;
  }
  const overflows = allowedPlacements.reduce((acc, placement2) => {
    acc[placement2] = detectOverflow(state, {
      placement: placement2,
      boundary,
      rootBoundary,
      padding
    })[getBasePlacement(placement2)];
    return acc;
  }, {});
  return Object.keys(overflows).sort((a2, b2) => overflows[a2] - overflows[b2]);
}
function getExpandedFallbackPlacements(placement) {
  if (getBasePlacement(placement) === auto) {
    return [];
  }
  const oppositePlacement = getOppositePlacement(placement);
  return [
    getOppositeVariationPlacement(placement),
    oppositePlacement,
    getOppositeVariationPlacement(oppositePlacement)
  ];
}
function flip({state, options, name}) {
  if (state.modifiersData[name]._skip) {
    return;
  }
  const {mainAxis: checkMainAxis = true, altAxis: checkAltAxis = true, fallbackPlacements: specifiedFallbackPlacements, padding, boundary, rootBoundary, altBoundary, flipVariations = true, allowedAutoPlacements} = options;
  const preferredPlacement = state.options.placement;
  const basePlacement = getBasePlacement(preferredPlacement);
  const isBasePlacement = basePlacement === preferredPlacement;
  const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
  const placements2 = [preferredPlacement, ...fallbackPlacements].reduce((acc, placement) => acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {
    placement,
    boundary,
    rootBoundary,
    padding,
    flipVariations,
    allowedAutoPlacements
  }) : placement), []);
  const referenceRect = state.rects.reference;
  const popperRect = state.rects.popper;
  const checksMap = new Map();
  let makeFallbackChecks = true;
  let firstFittingPlacement = placements2[0];
  for (let i3 = 0; i3 < placements2.length; i3++) {
    const placement = placements2[i3];
    const basePlacement2 = getBasePlacement(placement);
    const isStartVariation = getVariation(placement) === start;
    const isVertical = [top, bottom].indexOf(basePlacement2) >= 0;
    const len2 = isVertical ? "width" : "height";
    const overflow = detectOverflow(state, {
      placement,
      boundary,
      rootBoundary,
      altBoundary,
      padding
    });
    let mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
    if (referenceRect[len2] > popperRect[len2]) {
      mainVariationSide = getOppositePlacement(mainVariationSide);
    }
    const altVariationSide = getOppositePlacement(mainVariationSide);
    const checks = [];
    if (checkMainAxis) {
      checks.push(overflow[basePlacement2] <= 0);
    }
    if (checkAltAxis) {
      checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
    }
    if (checks.every((check2) => check2)) {
      firstFittingPlacement = placement;
      makeFallbackChecks = false;
      break;
    }
    checksMap.set(placement, checks);
  }
  if (makeFallbackChecks) {
    const numberOfChecks = flipVariations ? 3 : 1;
    for (let i3 = numberOfChecks; i3 > 0; i3--) {
      const fittingPlacement = placements2.find((placement) => {
        const checks = checksMap.get(placement);
        if (checks) {
          return checks.slice(0, i3).every((check2) => check2);
        }
      });
      if (fittingPlacement) {
        firstFittingPlacement = fittingPlacement;
        break;
      }
    }
  }
  if (state.placement !== firstFittingPlacement) {
    state.modifiersData[name]._skip = true;
    state.placement = firstFittingPlacement;
    state.reset = true;
  }
}
var flip$1 = {
  name: "flip",
  enabled: true,
  phase: "main",
  fn: flip,
  requiresIfExists: ["offset"],
  data: {_skip: false}
};
function getAltAxis(axis) {
  return axis === "x" ? "y" : "x";
}
function within(min2, value, max2) {
  return Math.max(min2, Math.min(value, max2));
}
function preventOverflow({state, options, name}) {
  const {mainAxis: checkMainAxis = true, altAxis: checkAltAxis = false, boundary, rootBoundary, altBoundary, padding, tether = true, tetherOffset = 0} = options;
  const overflow = detectOverflow(state, {
    boundary,
    rootBoundary,
    padding,
    altBoundary
  });
  const basePlacement = getBasePlacement(state.placement);
  const variation = getVariation(state.placement);
  const isBasePlacement = !variation;
  const mainAxis = getMainAxisFromPlacement(basePlacement);
  const altAxis = getAltAxis(mainAxis);
  const popperOffsets2 = state.modifiersData.popperOffsets;
  const referenceRect = state.rects.reference;
  const popperRect = state.rects.popper;
  const tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign(Object.assign({}, state.rects), {placement: state.placement})) : tetherOffset;
  const data2 = {x: 0, y: 0};
  if (!popperOffsets2) {
    return;
  }
  if (checkMainAxis) {
    const mainSide = mainAxis === "y" ? top : left;
    const altSide = mainAxis === "y" ? bottom : right;
    const len2 = mainAxis === "y" ? "height" : "width";
    const offset2 = popperOffsets2[mainAxis];
    const min2 = popperOffsets2[mainAxis] + overflow[mainSide];
    const max2 = popperOffsets2[mainAxis] - overflow[altSide];
    const additive = tether ? -popperRect[len2] / 2 : 0;
    const minLen = variation === start ? referenceRect[len2] : popperRect[len2];
    const maxLen = variation === start ? -popperRect[len2] : -referenceRect[len2];
    const arrowElement = state.elements.arrow;
    const arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {width: 0, height: 0};
    const arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject();
    const arrowPaddingMin = arrowPaddingObject[mainSide];
    const arrowPaddingMax = arrowPaddingObject[altSide];
    const arrowLen = within(0, referenceRect[len2], arrowRect[len2]);
    const minOffset = isBasePlacement ? referenceRect[len2] / 2 - additive - arrowLen - arrowPaddingMin - tetherOffsetValue : minLen - arrowLen - arrowPaddingMin - tetherOffsetValue;
    const maxOffset = isBasePlacement ? -referenceRect[len2] / 2 + additive + arrowLen + arrowPaddingMax + tetherOffsetValue : maxLen + arrowLen + arrowPaddingMax + tetherOffsetValue;
    const arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
    const clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
    const offsetModifierValue = state.modifiersData.offset ? state.modifiersData.offset[state.placement][mainAxis] : 0;
    const tetherMin = popperOffsets2[mainAxis] + minOffset - offsetModifierValue - clientOffset;
    const tetherMax = popperOffsets2[mainAxis] + maxOffset - offsetModifierValue;
    const preventedOffset = within(tether ? Math.min(min2, tetherMin) : min2, offset2, tether ? Math.max(max2, tetherMax) : max2);
    popperOffsets2[mainAxis] = preventedOffset;
    data2[mainAxis] = preventedOffset - offset2;
  }
  if (checkAltAxis) {
    const mainSide = mainAxis === "x" ? top : left;
    const altSide = mainAxis === "x" ? bottom : right;
    const offset2 = popperOffsets2[altAxis];
    const min2 = offset2 + overflow[mainSide];
    const max2 = offset2 - overflow[altSide];
    const preventedOffset = within(min2, offset2, max2);
    popperOffsets2[altAxis] = preventedOffset;
    data2[altAxis] = preventedOffset - offset2;
  }
  state.modifiersData[name] = data2;
}
var preventOverflow$1 = {
  name: "preventOverflow",
  enabled: true,
  phase: "main",
  fn: preventOverflow,
  requiresIfExists: ["offset"]
};
function arrow({state, name}) {
  const arrowElement = state.elements.arrow;
  const popperOffsets2 = state.modifiersData.popperOffsets;
  const basePlacement = getBasePlacement(state.placement);
  const axis = getMainAxisFromPlacement(basePlacement);
  const isVertical = [left, right].indexOf(basePlacement) >= 0;
  const len2 = isVertical ? "height" : "width";
  if (!arrowElement || !popperOffsets2) {
    return;
  }
  const paddingObject = state.modifiersData[`${name}#persistent`].padding;
  const arrowRect = getLayoutRect(arrowElement);
  const minProp = axis === "y" ? top : left;
  const maxProp = axis === "y" ? bottom : right;
  const endDiff = state.rects.reference[len2] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len2];
  const startDiff = popperOffsets2[axis] - state.rects.reference[axis];
  const arrowOffsetParent = getOffsetParent(arrowElement);
  const clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
  const centerToReference = endDiff / 2 - startDiff / 2;
  const min2 = paddingObject[minProp];
  const max2 = clientSize - arrowRect[len2] - paddingObject[maxProp];
  const center = clientSize / 2 - arrowRect[len2] / 2 + centerToReference;
  const offset2 = within(min2, center, max2);
  const axisProp = axis;
  state.modifiersData[name] = {
    [axisProp]: offset2,
    centerOffset: offset2 - center
  };
}
function effect$2({state, options, name}) {
  let {element: arrowElement = "[data-popper-arrow]", padding = 0} = options;
  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;
  state.modifiersData[`${name}#persistent`] = {
    padding: mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements))
  };
}
var arrow$1 = {
  name: "arrow",
  enabled: true,
  phase: "main",
  fn: arrow,
  effect: effect$2,
  requires: ["popperOffsets"],
  requiresIfExists: ["preventOverflow"]
};
function getSideOffsets(overflow, rect, 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, bottom, left].some((side) => overflow[side] >= 0);
}
function hide({state, name}) {
  const referenceRect = state.rects.reference;
  const popperRect = state.rects.popper;
  const preventedOffsets = state.modifiersData.preventOverflow;
  const referenceOverflow = detectOverflow(state, {
    elementContext: "reference"
  });
  const popperAltOverflow = detectOverflow(state, {
    altBoundary: true
  });
  const referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
  const popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
  const isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
  const hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
  state.modifiersData[name] = {
    referenceClippingOffsets,
    popperEscapeOffsets,
    isReferenceHidden,
    hasPopperEscaped
  };
  state.attributes.popper = Object.assign(Object.assign({}, state.attributes.popper), {"data-popper-reference-hidden": isReferenceHidden, "data-popper-escaped": hasPopperEscaped});
}
var hide$1 = {
  name: "hide",
  enabled: true,
  phase: "main",
  requiresIfExists: ["preventOverflow"],
  fn: hide
};
var defaultModifiers = [
  eventListeners,
  popperOffsets$1,
  computeStyles$1,
  applyStyles$1,
  offset$1,
  flip$1,
  preventOverflow$1,
  arrow$1,
  hide$1
];
var createPopper = popperGenerator({defaultModifiers});
var useIsomorphicLayoutEffect = canUseDOM ? react.useLayoutEffect : react.useEffect;
var isEqual = (a2, b2) => JSON.stringify(a2) === JSON.stringify(b2);
var fromEntries = (entries) => entries.reduce((acc, [key, value]) => {
  acc[key] = value;
  return acc;
}, {});
var EMPTY_MODIFIERS = [];
var usePopper = (referenceElement, popperElement, options = {}) => {
  const prevOptions = react.useRef(null);
  const optionsWithDefaults = {
    onFirstUpdate: options.onFirstUpdate,
    placement: options.placement || "bottom",
    strategy: options.strategy || "absolute",
    modifiers: options.modifiers || EMPTY_MODIFIERS
  };
  const [state, setState] = react.useState({
    styles: {
      popper: {
        position: optionsWithDefaults.strategy,
        left: "0",
        top: "0"
      }
    },
    attributes: {}
  });
  const updateStateModifier = react.useMemo(() => ({
    name: "updateState",
    enabled: true,
    phase: "write",
    fn: ({state: state2}) => {
      const elements = Object.keys(state2.elements);
      setState({
        styles: fromEntries(elements.map((element) => [element, state2.styles[element] || {}])),
        attributes: fromEntries(elements.map((element) => [element, state2.attributes[element]]))
      });
    },
    requires: ["computeStyles"]
  }), []);
  const popperOptions = react.useMemo(() => {
    const newOptions = {
      onFirstUpdate: optionsWithDefaults.onFirstUpdate,
      placement: optionsWithDefaults.placement,
      strategy: optionsWithDefaults.strategy,
      modifiers: [...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
  ]);
  const popperInstanceRef = react.useRef();
  useIsomorphicLayoutEffect(() => {
    if (popperInstanceRef && popperInstanceRef.current) {
      popperInstanceRef.current.setOptions(popperOptions);
    }
  }, [popperOptions]);
  useIsomorphicLayoutEffect(() => {
    if (referenceElement == null || popperElement == null) {
      return;
    }
    const createPopper$1 = options.createPopper || createPopper;
    const popperInstance = createPopper$1(referenceElement, popperElement, popperOptions);
    popperInstanceRef.current = popperInstance;
    return () => {
      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
  };
};
var hash$2 = {left: "right", right: "left", bottom: "top", top: "bottom"};
var getOppositePlacement$1 = (placement) => placement.replace(/left|right|bottom|top/g, (matched) => hash$2[matched]);
var getOpacityTransition = (animationDuration) => `opacity ${animationDuration}ms cubic-bezier(.54, 1.5, .38, 1.11)`;
var Popper = ({trigger, popper: popper2, popperMatchesTriggerWidth = true, direction = "down", position: position2 = "left", placement, appendTo = () => document.body, zIndex = 9999, isVisible = true, positionModifiers, distance = 0, onMouseEnter, onMouseLeave, onFocus, onBlur, onDocumentClick, onTriggerClick, onTriggerEnter, onPopperClick, onDocumentKeyDown, enableFlip = true, flipBehavior = "flip", reference: reference2}) => {
  const [triggerElement, setTriggerElement] = react.useState(null);
  const [refElement, setRefElement] = react.useState(null);
  const [popperElement, setPopperElement] = react.useState(null);
  const [ready, setReady] = react.useState(false);
  const refOrTrigger = refElement || triggerElement;
  const onDocumentClickCallback = react.useCallback((event) => onDocumentClick(event, refOrTrigger, popperElement), [
    isVisible,
    triggerElement,
    refElement,
    popperElement,
    onDocumentClick
  ]);
  react.useEffect(() => {
    setReady(true);
  }, []);
  react.useEffect(() => {
    if (reference2) {
      if (reference2.current) {
        setRefElement(reference2.current);
      } else if (typeof reference2 === "function") {
        setRefElement(reference2());
      }
    }
  }, [reference2]);
  const addEventListener = (listener, element, event) => {
    if (listener && element) {
      element.addEventListener(event, listener);
    }
  };
  const removeEventListener = (listener, element, event) => {
    if (listener && element) {
      element.removeEventListener(event, listener);
    }
  };
  react.useEffect(() => {
    addEventListener(onMouseEnter, refOrTrigger, "mouseenter");
    addEventListener(onMouseLeave, refOrTrigger, "mouseleave");
    addEventListener(onFocus, refOrTrigger, "focus");
    addEventListener(onBlur, refOrTrigger, "blur");
    addEventListener(onTriggerClick, refOrTrigger, "click");
    addEventListener(onTriggerEnter, refOrTrigger, "keydown");
    addEventListener(onPopperClick, popperElement, "click");
    onDocumentClick && addEventListener(onDocumentClickCallback, document, "click");
    addEventListener(onDocumentKeyDown, document, "keydown");
    return () => {
      removeEventListener(onMouseEnter, refOrTrigger, "mouseenter");
      removeEventListener(onMouseLeave, refOrTrigger, "mouseleave");
      removeEventListener(onFocus, refOrTrigger, "focus");
      removeEventListener(onBlur, refOrTrigger, "blur");
      removeEventListener(onTriggerClick, refOrTrigger, "click");
      removeEventListener(onTriggerEnter, refOrTrigger, "keydown");
      removeEventListener(onPopperClick, popperElement, "click");
      onDocumentClick && removeEventListener(onDocumentClickCallback, document, "click");
      removeEventListener(onDocumentKeyDown, document, "keydown");
    };
  }, [
    triggerElement,
    popperElement,
    onMouseEnter,
    onMouseLeave,
    onFocus,
    onBlur,
    onTriggerClick,
    onTriggerEnter,
    onPopperClick,
    onDocumentClick,
    onDocumentKeyDown,
    refElement
  ]);
  const getPlacement = () => {
    if (placement) {
      return placement;
    }
    let convertedPlacement = direction === "up" ? "top" : "bottom";
    if (position2 !== "center") {
      convertedPlacement = `${convertedPlacement}-${position2 === "right" ? "end" : "start"}`;
    }
    return convertedPlacement;
  };
  const getPlacementMemo = react.useMemo(getPlacement, [direction, position2, placement]);
  const getOppositePlacementMemo = react.useMemo(() => getOppositePlacement$1(getPlacement()), [
    direction,
    position2,
    placement
  ]);
  const sameWidthMod = react.useMemo(() => ({
    name: "sameWidth",
    enabled: popperMatchesTriggerWidth,
    phase: "beforeWrite",
    requires: ["computeStyles"],
    fn: ({state}) => {
      state.styles.popper.width = `${state.rects.reference.width}px`;
    },
    effect: ({state}) => {
      state.elements.popper.style.width = `${state.elements.reference.offsetWidth}px`;
      return () => {
      };
    }
  }), [popperMatchesTriggerWidth]);
  const {styles: popperStyles, attributes, forceUpdate} = usePopper(refOrTrigger, popperElement, {
    placement: getPlacementMemo,
    modifiers: [
      {
        name: "offset",
        options: {
          offset: [0, distance]
        }
      },
      {
        name: "preventOverflow",
        enabled: false
      },
      {
        name: "hide",
        enabled: true
      },
      {
        name: "flip",
        enabled: getPlacementMemo.startsWith("auto") || enableFlip,
        options: {
          fallbackPlacements: flipBehavior === "flip" ? [getOppositePlacementMemo] : flipBehavior
        }
      },
      sameWidthMod
    ]
  });
  react.useEffect(() => {
    forceUpdate && forceUpdate();
  }, [popper2]);
  const modifierFromPopperPosition = () => {
    if (attributes && attributes.popper && attributes.popper["data-popper-placement"]) {
      const popperPlacement = attributes.popper["data-popper-placement"];
      return positionModifiers[popperPlacement];
    }
    return positionModifiers.top;
  };
  const menuWithPopper = react.cloneElement(popper2, Object.assign({className: css(popper2.props && popper2.props.className, positionModifiers && modifierFromPopperPosition()), style: Object.assign(Object.assign(Object.assign({}, popper2.props && popper2.props.style || {}), popperStyles.popper), {zIndex})}, attributes.popper));
  const getTarget = () => {
    if (typeof appendTo === "function") {
      return appendTo();
    }
    return appendTo;
  };
  return react.createElement(react.Fragment, null, !reference2 && trigger && react.createElement(FindRefWrapper, {onFoundRef: (foundRef) => setTriggerElement(foundRef)}, trigger), ready && isVisible && reactDom.createPortal(react.createElement(FindRefWrapper, {onFoundRef: (foundRef) => setPopperElement(foundRef)}, menuWithPopper), getTarget()));
};
Popper.displayName = "Popper";
var title = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    modifiers: {
      "4xl": "pf-m-4xl",
      "3xl": "pf-m-3xl",
      "2xl": "pf-m-2xl",
      xl: "pf-m-xl",
      lg: "pf-m-lg",
      md: "pf-m-md",
      overpassFont: "pf-m-overpass-font"
    },
    title: "pf-c-title"
  };
});
var styles = /* @__PURE__ */ getDefaultExportFromCjs(title);
var TitleSizes;
(function(TitleSizes2) {
  TitleSizes2["md"] = "md";
  TitleSizes2["lg"] = "lg";
  TitleSizes2["xl"] = "xl";
  TitleSizes2["2xl"] = "2xl";
  TitleSizes2["3xl"] = "3xl";
  TitleSizes2["4xl"] = "4xl";
})(TitleSizes || (TitleSizes = {}));
var headingLevelSizeMap;
(function(headingLevelSizeMap2) {
  headingLevelSizeMap2["h1"] = "2xl";
  headingLevelSizeMap2["h2"] = "xl";
  headingLevelSizeMap2["h3"] = "lg";
  headingLevelSizeMap2["h4"] = "md";
  headingLevelSizeMap2["h5"] = "md";
  headingLevelSizeMap2["h6"] = "md";
})(headingLevelSizeMap || (headingLevelSizeMap = {}));
var Title = (_a) => {
  var {className = "", children: children2 = "", headingLevel: HeadingLevel, size: size2 = headingLevelSizeMap[HeadingLevel], ouiaId, ouiaSafe = true} = _a, props = __rest(_a, ["className", "children", "headingLevel", "size", "ouiaId", "ouiaSafe"]);
  const ouiaProps = useOUIAProps(Title.displayName, ouiaId, ouiaSafe);
  return react.createElement(HeadingLevel, Object.assign({}, ouiaProps, props, {className: css(styles.title, size2 && styles.modifiers[size2], className)}), children2);
};
Title.displayName = "Title";
var button = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    buttonIcon: "pf-c-button__icon",
    buttonProgress: "pf-c-button__progress",
    modifiers: {
      active: "pf-m-active",
      block: "pf-m-block",
      small: "pf-m-small",
      primary: "pf-m-primary",
      displayLg: "pf-m-display-lg",
      secondary: "pf-m-secondary",
      tertiary: "pf-m-tertiary",
      link: "pf-m-link",
      inline: "pf-m-inline",
      danger: "pf-m-danger",
      warning: "pf-m-warning",
      control: "pf-m-control",
      expanded: "pf-m-expanded",
      plain: "pf-m-plain",
      disabled: "pf-m-disabled",
      ariaDisabled: "pf-m-aria-disabled",
      progress: "pf-m-progress",
      inProgress: "pf-m-in-progress",
      start: "pf-m-start",
      end: "pf-m-end",
      overpassFont: "pf-m-overpass-font"
    },
    spinner: "pf-c-spinner"
  };
});
var buttonStyles = /* @__PURE__ */ getDefaultExportFromCjs(button);
var spinner = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    modifiers: {
      sm: "pf-m-sm",
      md: "pf-m-md",
      lg: "pf-m-lg",
      xl: "pf-m-xl"
    },
    spinner: "pf-c-spinner",
    spinnerClipper: "pf-c-spinner__clipper",
    spinnerLeadBall: "pf-c-spinner__lead-ball",
    spinnerPath: "pf-c-spinner__path",
    spinnerTailBall: "pf-c-spinner__tail-ball"
  };
});
var styles$1 = /* @__PURE__ */ getDefaultExportFromCjs(spinner);
var spinnerSize;
(function(spinnerSize2) {
  spinnerSize2["sm"] = "sm";
  spinnerSize2["md"] = "md";
  spinnerSize2["lg"] = "lg";
  spinnerSize2["xl"] = "xl";
})(spinnerSize || (spinnerSize = {}));
var Spinner = (_a) => {
  var {
    className = "",
    size: size2 = "xl",
    "aria-valuetext": ariaValueText = "Loading...",
    isSVG = false,
    diameter
  } = _a, props = __rest(_a, ["className", "size", "aria-valuetext", "isSVG", "diameter"]);
  const Component = isSVG ? "svg" : "span";
  return react.createElement(Component, Object.assign({className: css(styles$1.spinner, styles$1.modifiers[size2], className), role: "progressbar", "aria-valuetext": ariaValueText}, isSVG && {viewBox: "0 0 100 100"}, diameter && {style: {"--pf-c-spinner--diameter": diameter}}, props), isSVG ? react.createElement("circle", {className: styles$1.spinnerPath, cx: "50", cy: "50", r: "45", fill: "none"}) : react.createElement(react.Fragment, null, react.createElement("span", {className: css(styles$1.spinnerClipper)}), react.createElement("span", {className: css(styles$1.spinnerLeadBall)}), react.createElement("span", {className: css(styles$1.spinnerTailBall)})));
};
Spinner.displayName = "Spinner";
var ButtonVariant;
(function(ButtonVariant2) {
  ButtonVariant2["primary"] = "primary";
  ButtonVariant2["secondary"] = "secondary";
  ButtonVariant2["tertiary"] = "tertiary";
  ButtonVariant2["danger"] = "danger";
  ButtonVariant2["warning"] = "warning";
  ButtonVariant2["link"] = "link";
  ButtonVariant2["plain"] = "plain";
  ButtonVariant2["control"] = "control";
})(ButtonVariant || (ButtonVariant = {}));
var ButtonType;
(function(ButtonType2) {
  ButtonType2["button"] = "button";
  ButtonType2["submit"] = "submit";
  ButtonType2["reset"] = "reset";
})(ButtonType || (ButtonType = {}));
var ButtonBase = (_a) => {
  var {children: children2 = null, className = "", component = "button", isActive = false, isBlock = false, isDisabled = false, isAriaDisabled = false, isLoading = null, isDanger = false, spinnerAriaValueText, isSmall = false, isLarge = false, inoperableEvents = ["onClick", "onKeyPress"], isInline = false, type = ButtonType.button, variant = ButtonVariant.primary, iconPosition = "left", "aria-label": ariaLabel = null, icon = null, ouiaId, ouiaSafe = true, tabIndex = null, innerRef} = _a, props = __rest(_a, ["children", "className", "component", "isActive", "isBlock", "isDisabled", "isAriaDisabled", "isLoading", "isDanger", "spinnerAriaValueText", "isSmall", "isLarge", "inoperableEvents", "isInline", "type", "variant", "iconPosition", "aria-label", "icon", "ouiaId", "ouiaSafe", "tabIndex", "innerRef"]);
  const ouiaProps = useOUIAProps(Button.displayName, ouiaId, ouiaSafe, variant);
  const Component = component;
  const isButtonElement = Component === "button";
  const isInlineSpan = isInline && Component === "span";
  const preventedEvents2 = inoperableEvents.reduce((handlers, eventToPrevent) => Object.assign(Object.assign({}, handlers), {[eventToPrevent]: (event) => {
    event.preventDefault();
  }}), {});
  const getDefaultTabIdx = () => {
    if (isDisabled) {
      return isButtonElement ? null : -1;
    } else if (isAriaDisabled) {
      return null;
    } else if (isInlineSpan) {
      return 0;
    }
  };
  return react.createElement(Component, Object.assign({}, props, isAriaDisabled ? preventedEvents2 : null, {"aria-disabled": isDisabled || isAriaDisabled, "aria-label": ariaLabel, className: css(buttonStyles.button, buttonStyles.modifiers[variant], isBlock && buttonStyles.modifiers.block, isDisabled && buttonStyles.modifiers.disabled, isAriaDisabled && buttonStyles.modifiers.ariaDisabled, isActive && buttonStyles.modifiers.active, isInline && variant === ButtonVariant.link && buttonStyles.modifiers.inline, isDanger && (variant === ButtonVariant.secondary || variant === ButtonVariant.link) && buttonStyles.modifiers.danger, isLoading !== null && buttonStyles.modifiers.progress, isLoading && buttonStyles.modifiers.inProgress, isSmall && buttonStyles.modifiers.small, isLarge && buttonStyles.modifiers.displayLg, className), disabled: isButtonElement ? isDisabled : null, tabIndex: tabIndex !== null ? tabIndex : getDefaultTabIdx(), type: isButtonElement || isInlineSpan ? type : null, role: isInlineSpan ? "button" : null, ref: innerRef}, ouiaProps), isLoading && react.createElement("span", {className: css(buttonStyles.buttonProgress)}, react.createElement(Spinner, {size: spinnerSize.md, "aria-valuetext": spinnerAriaValueText})), variant !== ButtonVariant.plain && icon && iconPosition === "left" && react.createElement("span", {className: css(buttonStyles.buttonIcon, buttonStyles.modifiers.start)}, icon), children2, variant !== ButtonVariant.plain && icon && iconPosition === "right" && react.createElement("span", {className: css(buttonStyles.buttonIcon, buttonStyles.modifiers.end)}, icon));
};
var Button = react.forwardRef((props, ref) => react.createElement(ButtonBase, Object.assign({innerRef: ref}, props)));
Button.displayName = "Button";
var tooltip = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    modifiers: {
      top: "pf-m-top",
      topLeft: "pf-m-top-left",
      topRight: "pf-m-top-right",
      bottom: "pf-m-bottom",
      bottomLeft: "pf-m-bottom-left",
      bottomRight: "pf-m-bottom-right",
      left: "pf-m-left",
      leftTop: "pf-m-left-top",
      leftBottom: "pf-m-left-bottom",
      right: "pf-m-right",
      rightTop: "pf-m-right-top",
      rightBottom: "pf-m-right-bottom",
      textAlignLeft: "pf-m-text-align-left"
    },
    tooltip: "pf-c-tooltip",
    tooltipArrow: "pf-c-tooltip__arrow",
    tooltipContent: "pf-c-tooltip__content"
  };
});
var styles$2 = /* @__PURE__ */ getDefaultExportFromCjs(tooltip);
var TooltipContent = (_a) => {
  var {className, children: children2, isLeftAligned} = _a, props = __rest(_a, ["className", "children", "isLeftAligned"]);
  return react.createElement("div", Object.assign({className: css(styles$2.tooltipContent, isLeftAligned && styles$2.modifiers.textAlignLeft, className)}, props), children2);
};
TooltipContent.displayName = "TooltipContent";
var TooltipArrow = (_a) => {
  var {className} = _a, props = __rest(_a, ["className"]);
  return react.createElement("div", Object.assign({className: css(styles$2.tooltipArrow, className)}, props));
};
TooltipArrow.displayName = "TooltipArrow";
var c_tooltip_MaxWidth = {
  name: "--pf-c-tooltip--MaxWidth",
  value: "18.75rem",
  var: "var(--pf-c-tooltip--MaxWidth)"
};
var TooltipPosition;
(function(TooltipPosition2) {
  TooltipPosition2["auto"] = "auto";
  TooltipPosition2["top"] = "top";
  TooltipPosition2["bottom"] = "bottom";
  TooltipPosition2["left"] = "left";
  TooltipPosition2["right"] = "right";
})(TooltipPosition || (TooltipPosition = {}));
var pfTooltipIdCounter = 1;
var Tooltip = (_a) => {
  var {
    content: bodyContent,
    position: position2 = "top",
    trigger = "mouseenter focus",
    isVisible = false,
    isContentLeftAligned = false,
    enableFlip = true,
    className = "",
    entryDelay = 300,
    exitDelay = 0,
    appendTo = () => document.body,
    zIndex = 9999,
    maxWidth = c_tooltip_MaxWidth.value,
    distance = 15,
    aria = "describedby",
    flipBehavior = ["top", "right", "bottom", "left", "top", "right", "bottom"],
    id: id3 = `pf-tooltip-${pfTooltipIdCounter++}`,
    children: children2,
    animationDuration = 300,
    reference: reference2,
    boundary,
    isAppLauncher,
    tippyProps
  } = _a, rest = __rest(_a, ["content", "position", "trigger", "isVisible", "isContentLeftAligned", "enableFlip", "className", "entryDelay", "exitDelay", "appendTo", "zIndex", "maxWidth", "distance", "aria", "flipBehavior", "id", "children", "animationDuration", "reference", "boundary", "isAppLauncher", "tippyProps"]);
  const triggerOnMouseenter = trigger.includes("mouseenter");
  const triggerOnFocus = trigger.includes("focus");
  const triggerOnClick = trigger.includes("click");
  const triggerManually = trigger === "manual";
  const [visible, setVisible] = react.useState(false);
  const [opacity, setOpacity] = react.useState(0);
  const transitionTimerRef = react.useRef(null);
  const showTimerRef = react.useRef(null);
  const hideTimerRef = react.useRef(null);
  const clearTimeouts = (timeoutRefs) => {
    timeoutRefs.forEach((ref) => {
      if (ref.current) {
        clearTimeout(ref.current);
      }
    });
  };
  react.useEffect(() => () => {
    clearTimeouts([transitionTimerRef, hideTimerRef, showTimerRef]);
  }, []);
  const onDocumentKeyDown = (event) => {
    if (!triggerManually) {
      if (event.keyCode === KEY_CODES.ESCAPE_KEY && visible) {
        hide3();
      }
    }
  };
  const onTriggerEnter = (event) => {
    if (event.keyCode === KEY_CODES.ENTER) {
      if (!visible) {
        show2();
      } else {
        hide3();
      }
    }
  };
  react.useEffect(() => {
    if (isVisible) {
      show2();
    } else {
      hide3();
    }
  }, [isVisible]);
  const show2 = () => {
    clearTimeouts([transitionTimerRef, hideTimerRef]);
    showTimerRef.current = setTimeout(() => {
      setVisible(true);
      setOpacity(1);
    }, entryDelay);
  };
  const hide3 = () => {
    clearTimeouts([showTimerRef]);
    hideTimerRef.current = setTimeout(() => {
      setOpacity(0);
      transitionTimerRef.current = setTimeout(() => setVisible(false), animationDuration);
    }, exitDelay);
  };
  const positionModifiers = {
    top: styles$2.modifiers.top,
    bottom: styles$2.modifiers.bottom,
    left: styles$2.modifiers.left,
    right: styles$2.modifiers.right
  };
  const hasCustomMaxWidth = maxWidth !== c_tooltip_MaxWidth.value;
  const content2 = react.createElement("div", Object.assign({className: css(styles$2.tooltip, className), role: "tooltip", id: id3, style: {
    maxWidth: hasCustomMaxWidth ? maxWidth : null,
    opacity,
    transition: getOpacityTransition(animationDuration)
  }}, rest), react.createElement(TooltipArrow, null), react.createElement(TooltipContent, {isLeftAligned: isContentLeftAligned}, bodyContent));
  const onDocumentClick = (event, triggerElement) => {
    {
      if (visible) {
        hide3();
      } else if (event.target === triggerElement) {
        show2();
      }
    }
  };
  const addAriaToTrigger = () => {
    if (aria === "describedby" && children2 && children2.props && !children2.props["aria-describedby"]) {
      return react.cloneElement(children2, {"aria-describedby": id3});
    } else if (aria === "labelledby" && children2.props && !children2.props["aria-labelledby"]) {
      return react.cloneElement(children2, {"aria-labelledby": id3});
    }
    return children2;
  };
  return react.createElement(Popper, {trigger: aria !== "none" && visible ? addAriaToTrigger() : children2, reference: reference2, popper: content2, popperMatchesTriggerWidth: false, appendTo, isVisible: visible, positionModifiers, distance, placement: position2, onMouseEnter: triggerOnMouseenter && show2, onMouseLeave: triggerOnMouseenter && hide3, onFocus: triggerOnFocus && show2, onBlur: triggerOnFocus && hide3, onDocumentClick: triggerOnClick && onDocumentClick, onDocumentKeyDown: triggerManually ? null : onDocumentKeyDown, onTriggerEnter: triggerManually ? null : onTriggerEnter, enableFlip, zIndex, flipBehavior});
};
Tooltip.displayName = "Tooltip";
var emptyState = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    emptyState: "pf-c-empty-state",
    emptyStateBody: "pf-c-empty-state__body",
    emptyStateContent: "pf-c-empty-state__content",
    emptyStateIcon: "pf-c-empty-state__icon",
    emptyStatePrimary: "pf-c-empty-state__primary",
    emptyStateSecondary: "pf-c-empty-state__secondary",
    modifiers: {
      xs: "pf-m-xs",
      sm: "pf-m-sm",
      lg: "pf-m-lg",
      xl: "pf-m-xl",
      fullHeight: "pf-m-full-height",
      primary: "pf-m-primary",
      overpassFont: "pf-m-overpass-font"
    },
    title: "pf-c-title"
  };
});
var styles$3 = /* @__PURE__ */ getDefaultExportFromCjs(emptyState);
var EmptyStateVariant;
(function(EmptyStateVariant2) {
  EmptyStateVariant2["xs"] = "xs";
  EmptyStateVariant2["small"] = "small";
  EmptyStateVariant2["large"] = "large";
  EmptyStateVariant2["xl"] = "xl";
  EmptyStateVariant2["full"] = "full";
})(EmptyStateVariant || (EmptyStateVariant = {}));
var EmptyState = (_a) => {
  var {children: children2, className = "", variant = EmptyStateVariant.full, isFullHeight} = _a, props = __rest(_a, ["children", "className", "variant", "isFullHeight"]);
  return react.createElement("div", Object.assign({className: css(styles$3.emptyState, variant === "xs" && styles$3.modifiers.xs, variant === "small" && styles$3.modifiers.sm, variant === "large" && styles$3.modifiers.lg, variant === "xl" && styles$3.modifiers.xl, isFullHeight && styles$3.modifiers.fullHeight, className)}, props), react.createElement("div", {className: css(styles$3.emptyStateContent)}, children2));
};
EmptyState.displayName = "EmptyState";

// build/_snowpack/pkg/common/check-icon-e536b517.js
var TimesIconConfig = {
  name: "TimesIcon",
  height: 512,
  width: 352,
  svgPath: "M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z",
  yOffset: 0,
  xOffset: 0
};
var TimesIcon = createIcon(TimesIconConfig);
var CheckIconConfig = {
  name: "CheckIcon",
  height: 512,
  width: 512,
  svgPath: "M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z",
  yOffset: 0,
  xOffset: 0
};
var CheckIcon = createIcon(CheckIconConfig);

// build/_snowpack/pkg/common/inline-edit-595ec989.js
/*!
* tabbable 5.2.1
* @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
*/
var candidateSelectors = ["input", "select", "textarea", "a[href]", "button", "[tabindex]", "audio[controls]", "video[controls]", '[contenteditable]:not([contenteditable="false"])', "details>summary:first-of-type", "details"];
var candidateSelector = /* @__PURE__ */ candidateSelectors.join(",");
var matches = typeof Element === "undefined" ? function() {
} : Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
var getCandidates = function getCandidates2(el, includeContainer, filter3) {
  var candidates = Array.prototype.slice.apply(el.querySelectorAll(candidateSelector));
  if (includeContainer && matches.call(el, candidateSelector)) {
    candidates.unshift(el);
  }
  candidates = candidates.filter(filter3);
  return candidates;
};
var isContentEditable = function isContentEditable2(node) {
  return node.contentEditable === "true";
};
var getTabindex = function getTabindex2(node) {
  var tabindexAttr = parseInt(node.getAttribute("tabindex"), 10);
  if (!isNaN(tabindexAttr)) {
    return tabindexAttr;
  }
  if (isContentEditable(node)) {
    return 0;
  }
  if ((node.nodeName === "AUDIO" || node.nodeName === "VIDEO" || node.nodeName === "DETAILS") && node.getAttribute("tabindex") === null) {
    return 0;
  }
  return node.tabIndex;
};
var sortOrderedTabbables = function sortOrderedTabbables2(a2, b2) {
  return a2.tabIndex === b2.tabIndex ? a2.documentOrder - b2.documentOrder : a2.tabIndex - b2.tabIndex;
};
var isInput = function isInput2(node) {
  return node.tagName === "INPUT";
};
var isHiddenInput = function isHiddenInput2(node) {
  return isInput(node) && node.type === "hidden";
};
var isDetailsWithSummary = function isDetailsWithSummary2(node) {
  var r3 = node.tagName === "DETAILS" && Array.prototype.slice.apply(node.children).some(function(child) {
    return child.tagName === "SUMMARY";
  });
  return r3;
};
var getCheckedRadio = function getCheckedRadio2(nodes, form2) {
  for (var i3 = 0; i3 < nodes.length; i3++) {
    if (nodes[i3].checked && nodes[i3].form === form2) {
      return nodes[i3];
    }
  }
};
var isTabbableRadio = function isTabbableRadio2(node) {
  if (!node.name) {
    return true;
  }
  var radioScope = node.form || node.ownerDocument;
  var queryRadios = function queryRadios2(name) {
    return radioScope.querySelectorAll('input[type="radio"][name="' + name + '"]');
  };
  var radioSet;
  if (typeof window !== "undefined" && typeof window.CSS !== "undefined" && typeof window.CSS.escape === "function") {
    radioSet = queryRadios(window.CSS.escape(node.name));
  } else {
    try {
      radioSet = queryRadios(node.name);
    } catch (err) {
      console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s", err.message);
      return false;
    }
  }
  var checked = getCheckedRadio(radioSet, node.form);
  return !checked || checked === node;
};
var isRadio = function isRadio2(node) {
  return isInput(node) && node.type === "radio";
};
var isNonTabbableRadio = function isNonTabbableRadio2(node) {
  return isRadio(node) && !isTabbableRadio(node);
};
var isHidden = function isHidden2(node, displayCheck) {
  if (getComputedStyle(node).visibility === "hidden") {
    return true;
  }
  var isDirectSummary = matches.call(node, "details>summary:first-of-type");
  var nodeUnderDetails = isDirectSummary ? node.parentElement : node;
  if (matches.call(nodeUnderDetails, "details:not([open]) *")) {
    return true;
  }
  if (!displayCheck || displayCheck === "full") {
    while (node) {
      if (getComputedStyle(node).display === "none") {
        return true;
      }
      node = node.parentElement;
    }
  } else if (displayCheck === "non-zero-area") {
    var _node$getBoundingClie = node.getBoundingClientRect(), width2 = _node$getBoundingClie.width, height = _node$getBoundingClie.height;
    return width2 === 0 && height === 0;
  }
  return false;
};
var isDisabledFromFieldset = function isDisabledFromFieldset2(node) {
  if (isInput(node) || node.tagName === "SELECT" || node.tagName === "TEXTAREA" || node.tagName === "BUTTON") {
    var parentNode = node.parentElement;
    while (parentNode) {
      if (parentNode.tagName === "FIELDSET" && parentNode.disabled) {
        for (var i3 = 0; i3 < parentNode.children.length; i3++) {
          var child = parentNode.children.item(i3);
          if (child.tagName === "LEGEND") {
            if (child.contains(node)) {
              return false;
            }
            return true;
          }
        }
        return true;
      }
      parentNode = parentNode.parentElement;
    }
  }
  return false;
};
var isNodeMatchingSelectorFocusable = function isNodeMatchingSelectorFocusable2(options, node) {
  if (node.disabled || isHiddenInput(node) || isHidden(node, options.displayCheck) || isDetailsWithSummary(node) || isDisabledFromFieldset(node)) {
    return false;
  }
  return true;
};
var isNodeMatchingSelectorTabbable = function isNodeMatchingSelectorTabbable2(options, node) {
  if (!isNodeMatchingSelectorFocusable(options, node) || isNonTabbableRadio(node) || getTabindex(node) < 0) {
    return false;
  }
  return true;
};
var tabbable = function tabbable2(el, options) {
  options = options || {};
  var regularTabbables = [];
  var orderedTabbables = [];
  var candidates = getCandidates(el, options.includeContainer, isNodeMatchingSelectorTabbable.bind(null, options));
  candidates.forEach(function(candidate, i3) {
    var candidateTabindex = getTabindex(candidate);
    if (candidateTabindex === 0) {
      regularTabbables.push(candidate);
    } else {
      orderedTabbables.push({
        documentOrder: i3,
        tabIndex: candidateTabindex,
        node: candidate
      });
    }
  });
  var tabbableNodes = orderedTabbables.sort(sortOrderedTabbables).map(function(a2) {
    return a2.node;
  }).concat(regularTabbables);
  return tabbableNodes;
};
var focusableCandidateSelector = /* @__PURE__ */ candidateSelectors.concat("iframe").join(",");
var isFocusable = function isFocusable2(node, options) {
  options = options || {};
  if (!node) {
    throw new Error("No node provided");
  }
  if (matches.call(node, focusableCandidateSelector) === false) {
    return false;
  }
  return isNodeMatchingSelectorFocusable(options, node);
};
/*!
* focus-trap 6.2.2
* @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE
*/
function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}
function ownKeys(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly)
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread2(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys(Object(source2), true).forEach(function(key) {
        _defineProperty(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var activeFocusDelay;
var activeFocusTraps = function() {
  var trapQueue = [];
  return {
    activateTrap: function activateTrap(trap) {
      if (trapQueue.length > 0) {
        var activeTrap = trapQueue[trapQueue.length - 1];
        if (activeTrap !== trap) {
          activeTrap.pause();
        }
      }
      var trapIndex = trapQueue.indexOf(trap);
      if (trapIndex === -1) {
        trapQueue.push(trap);
      } else {
        trapQueue.splice(trapIndex, 1);
        trapQueue.push(trap);
      }
    },
    deactivateTrap: function deactivateTrap(trap) {
      var trapIndex = trapQueue.indexOf(trap);
      if (trapIndex !== -1) {
        trapQueue.splice(trapIndex, 1);
      }
      if (trapQueue.length > 0) {
        trapQueue[trapQueue.length - 1].unpause();
      }
    }
  };
}();
var isSelectableInput = function isSelectableInput2(node) {
  return node.tagName && node.tagName.toLowerCase() === "input" && typeof node.select === "function";
};
var isEscapeEvent = function isEscapeEvent2(e2) {
  return e2.key === "Escape" || e2.key === "Esc" || e2.keyCode === 27;
};
var isTabEvent = function isTabEvent2(e2) {
  return e2.key === "Tab" || e2.keyCode === 9;
};
var delay = function delay2(fn) {
  return setTimeout(fn, 0);
};
var createFocusTrap = function createFocusTrap2(elements, userOptions) {
  var doc = document;
  var config2 = _objectSpread2({
    returnFocusOnDeactivate: true,
    escapeDeactivates: true,
    delayInitialFocus: true
  }, userOptions);
  var state = {
    containers: [],
    tabbableGroups: [],
    nodeFocusedBeforeActivation: null,
    mostRecentlyFocusedNode: null,
    active: false,
    paused: false
  };
  var trap;
  var containersContain = function containersContain2(element) {
    return state.containers.some(function(container) {
      return container.contains(element);
    });
  };
  var getNodeForOption = function getNodeForOption2(optionName) {
    var optionValue = config2[optionName];
    if (!optionValue) {
      return null;
    }
    var node = optionValue;
    if (typeof optionValue === "string") {
      node = doc.querySelector(optionValue);
      if (!node) {
        throw new Error("`".concat(optionName, "` refers to no known node"));
      }
    }
    if (typeof optionValue === "function") {
      node = optionValue();
      if (!node) {
        throw new Error("`".concat(optionName, "` did not return a node"));
      }
    }
    return node;
  };
  var getInitialFocusNode = function getInitialFocusNode2() {
    var node;
    if (getNodeForOption("initialFocus") !== null) {
      node = getNodeForOption("initialFocus");
    } else if (containersContain(doc.activeElement)) {
      node = doc.activeElement;
    } else {
      var firstTabbableGroup = state.tabbableGroups[0];
      var firstTabbableNode = firstTabbableGroup && firstTabbableGroup.firstTabbableNode;
      node = firstTabbableNode || getNodeForOption("fallbackFocus");
    }
    if (!node) {
      throw new Error("Your focus-trap needs to have at least one focusable element");
    }
    return node;
  };
  var updateTabbableNodes = function updateTabbableNodes2() {
    state.tabbableGroups = state.containers.map(function(container) {
      var tabbableNodes = tabbable(container);
      if (tabbableNodes.length > 0) {
        return {
          firstTabbableNode: tabbableNodes[0],
          lastTabbableNode: tabbableNodes[tabbableNodes.length - 1]
        };
      }
      return void 0;
    }).filter(function(group) {
      return !!group;
    });
    if (state.tabbableGroups.length <= 0 && !getNodeForOption("fallbackFocus")) {
      throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times");
    }
  };
  var tryFocus = function tryFocus2(node) {
    if (node === doc.activeElement) {
      return;
    }
    if (!node || !node.focus) {
      tryFocus2(getInitialFocusNode());
      return;
    }
    node.focus({
      preventScroll: !!config2.preventScroll
    });
    state.mostRecentlyFocusedNode = node;
    if (isSelectableInput(node)) {
      node.select();
    }
  };
  var getReturnFocusNode = function getReturnFocusNode2(previousActiveElement) {
    var node = getNodeForOption("setReturnFocus");
    return node ? node : previousActiveElement;
  };
  var checkPointerDown = function checkPointerDown2(e2) {
    if (containersContain(e2.target)) {
      return;
    }
    if (config2.clickOutsideDeactivates) {
      trap.deactivate({
        returnFocus: config2.returnFocusOnDeactivate && !isFocusable(e2.target)
      });
      return;
    }
    if (config2.allowOutsideClick && (typeof config2.allowOutsideClick === "boolean" ? config2.allowOutsideClick : config2.allowOutsideClick(e2))) {
      return;
    }
    e2.preventDefault();
  };
  var checkFocusIn = function checkFocusIn2(e2) {
    var targetContained = containersContain(e2.target);
    if (targetContained || e2.target instanceof Document) {
      if (targetContained) {
        state.mostRecentlyFocusedNode = e2.target;
      }
    } else {
      e2.stopImmediatePropagation();
      tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());
    }
  };
  var checkTab = function checkTab2(e2) {
    updateTabbableNodes();
    var destinationNode = null;
    if (state.tabbableGroups.length > 0) {
      if (e2.shiftKey) {
        var startOfGroupIndex = state.tabbableGroups.findIndex(function(_ref) {
          var firstTabbableNode = _ref.firstTabbableNode;
          return e2.target === firstTabbableNode;
        });
        if (startOfGroupIndex >= 0) {
          var destinationGroupIndex = startOfGroupIndex === 0 ? state.tabbableGroups.length - 1 : startOfGroupIndex - 1;
          var destinationGroup = state.tabbableGroups[destinationGroupIndex];
          destinationNode = destinationGroup.lastTabbableNode;
        }
      } else {
        var lastOfGroupIndex = state.tabbableGroups.findIndex(function(_ref2) {
          var lastTabbableNode = _ref2.lastTabbableNode;
          return e2.target === lastTabbableNode;
        });
        if (lastOfGroupIndex >= 0) {
          var _destinationGroupIndex = lastOfGroupIndex === state.tabbableGroups.length - 1 ? 0 : lastOfGroupIndex + 1;
          var _destinationGroup = state.tabbableGroups[_destinationGroupIndex];
          destinationNode = _destinationGroup.firstTabbableNode;
        }
      }
    } else {
      destinationNode = getNodeForOption("fallbackFocus");
    }
    if (destinationNode) {
      e2.preventDefault();
      tryFocus(destinationNode);
    }
  };
  var checkKey = function checkKey2(e2) {
    if (config2.escapeDeactivates !== false && isEscapeEvent(e2)) {
      e2.preventDefault();
      trap.deactivate();
      return;
    }
    if (isTabEvent(e2)) {
      checkTab(e2);
      return;
    }
  };
  var checkClick = function checkClick2(e2) {
    if (config2.clickOutsideDeactivates) {
      return;
    }
    if (containersContain(e2.target)) {
      return;
    }
    if (config2.allowOutsideClick && (typeof config2.allowOutsideClick === "boolean" ? config2.allowOutsideClick : config2.allowOutsideClick(e2))) {
      return;
    }
    e2.preventDefault();
    e2.stopImmediatePropagation();
  };
  var addListeners = function addListeners2() {
    if (!state.active) {
      return;
    }
    activeFocusTraps.activateTrap(trap);
    activeFocusDelay = config2.delayInitialFocus ? delay(function() {
      tryFocus(getInitialFocusNode());
    }) : tryFocus(getInitialFocusNode());
    doc.addEventListener("focusin", checkFocusIn, true);
    doc.addEventListener("mousedown", checkPointerDown, {
      capture: true,
      passive: false
    });
    doc.addEventListener("touchstart", checkPointerDown, {
      capture: true,
      passive: false
    });
    doc.addEventListener("click", checkClick, {
      capture: true,
      passive: false
    });
    doc.addEventListener("keydown", checkKey, {
      capture: true,
      passive: false
    });
    return trap;
  };
  var removeListeners = function removeListeners2() {
    if (!state.active) {
      return;
    }
    doc.removeEventListener("focusin", checkFocusIn, true);
    doc.removeEventListener("mousedown", checkPointerDown, true);
    doc.removeEventListener("touchstart", checkPointerDown, true);
    doc.removeEventListener("click", checkClick, true);
    doc.removeEventListener("keydown", checkKey, true);
    return trap;
  };
  trap = {
    activate: function activate(activateOptions) {
      if (state.active) {
        return this;
      }
      updateTabbableNodes();
      state.active = true;
      state.paused = false;
      state.nodeFocusedBeforeActivation = doc.activeElement;
      var onActivate = activateOptions && activateOptions.onActivate ? activateOptions.onActivate : config2.onActivate;
      if (onActivate) {
        onActivate();
      }
      addListeners();
      return this;
    },
    deactivate: function deactivate(deactivateOptions) {
      if (!state.active) {
        return this;
      }
      clearTimeout(activeFocusDelay);
      removeListeners();
      state.active = false;
      state.paused = false;
      activeFocusTraps.deactivateTrap(trap);
      var onDeactivate = deactivateOptions && deactivateOptions.onDeactivate !== void 0 ? deactivateOptions.onDeactivate : config2.onDeactivate;
      if (onDeactivate) {
        onDeactivate();
      }
      var returnFocus = deactivateOptions && deactivateOptions.returnFocus !== void 0 ? deactivateOptions.returnFocus : config2.returnFocusOnDeactivate;
      if (returnFocus) {
        delay(function() {
          tryFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation));
        });
      }
      return this;
    },
    pause: function pause() {
      if (state.paused || !state.active) {
        return this;
      }
      state.paused = true;
      removeListeners();
      return this;
    },
    unpause: function unpause() {
      if (!state.paused || !state.active) {
        return this;
      }
      state.paused = false;
      updateTabbableNodes();
      addListeners();
      return this;
    },
    updateContainerElements: function updateContainerElements(containerElements) {
      var elementsAsArray = [].concat(containerElements).filter(Boolean);
      state.containers = elementsAsArray.map(function(element) {
        return typeof element === "string" ? doc.querySelector(element) : element;
      });
      if (state.active) {
        updateTabbableNodes();
      }
      return this;
    }
  };
  trap.updateContainerElements(elements);
  return trap;
};
var FocusTrap = class extends react.Component {
  constructor(props) {
    super(props);
    this.divRef = react.createRef();
    if (typeof document !== "undefined") {
      this.previouslyFocusedElement = document.activeElement;
    }
  }
  componentDidMount() {
    this.focusTrap = createFocusTrap(this.divRef.current, Object.assign(Object.assign({}, this.props.focusTrapOptions), {returnFocusOnDeactivate: false}));
    if (this.props.active) {
      this.focusTrap.activate();
    }
    if (this.props.paused) {
      this.focusTrap.pause();
    }
  }
  componentDidUpdate(prevProps) {
    if (prevProps.active && !this.props.active) {
      this.focusTrap.deactivate();
    } else if (!prevProps.active && this.props.active) {
      this.focusTrap.activate();
    }
    if (prevProps.paused && !this.props.paused) {
      this.focusTrap.unpause();
    } else if (!prevProps.paused && this.props.paused) {
      this.focusTrap.pause();
    }
  }
  componentWillUnmount() {
    this.focusTrap.deactivate();
    if (this.props.focusTrapOptions.returnFocusOnDeactivate !== false && this.previouslyFocusedElement && this.previouslyFocusedElement.focus) {
      this.previouslyFocusedElement.focus({preventScroll: this.props.preventScrollOnDeactivate});
    }
  }
  render() {
    const _a = this.props, {children: children2, className, focusTrapOptions, active, paused, preventScrollOnDeactivate} = _a, rest = __rest(_a, ["children", "className", "focusTrapOptions", "active", "paused", "preventScrollOnDeactivate"]);
    return react.createElement("div", Object.assign({ref: this.divRef, className}, rest), children2);
  }
};
FocusTrap.displayName = "FocusTrap";
FocusTrap.defaultProps = {
  active: true,
  paused: false,
  focusTrapOptions: {},
  preventScrollOnDeactivate: false
};
var bullseye = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    bullseye: "pf-l-bullseye"
  };
});
var styles2 = /* @__PURE__ */ getDefaultExportFromCjs(bullseye);
var dropdown = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    badge: "pf-c-badge",
    check: "pf-c-check",
    divider: "pf-c-divider",
    dropdown: "pf-c-dropdown",
    dropdownGroup: "pf-c-dropdown__group",
    dropdownGroupTitle: "pf-c-dropdown__group-title",
    dropdownMenu: "pf-c-dropdown__menu",
    dropdownMenuItem: "pf-c-dropdown__menu-item",
    dropdownMenuItemDescription: "pf-c-dropdown__menu-item-description",
    dropdownMenuItemIcon: "pf-c-dropdown__menu-item-icon",
    dropdownMenuItemMain: "pf-c-dropdown__menu-item-main",
    dropdownToggle: "pf-c-dropdown__toggle",
    dropdownToggleButton: "pf-c-dropdown__toggle-button",
    dropdownToggleCheck: "pf-c-dropdown__toggle-check",
    dropdownToggleIcon: "pf-c-dropdown__toggle-icon",
    dropdownToggleImage: "pf-c-dropdown__toggle-image",
    dropdownToggleText: "pf-c-dropdown__toggle-text",
    menu: "pf-c-menu",
    modifiers: {
      fullHeight: "pf-m-full-height",
      expanded: "pf-m-expanded",
      action: "pf-m-action",
      disabled: "pf-m-disabled",
      plain: "pf-m-plain",
      splitButton: "pf-m-split-button",
      primary: "pf-m-primary",
      active: "pf-m-active",
      secondary: "pf-m-secondary",
      top: "pf-m-top",
      alignRight: "pf-m-align-right",
      alignLeft: "pf-m-align-left",
      alignRightOnSm: "pf-m-align-right-on-sm",
      alignLeftOnSm: "pf-m-align-left-on-sm",
      alignRightOnMd: "pf-m-align-right-on-md",
      alignLeftOnMd: "pf-m-align-left-on-md",
      alignRightOnLg: "pf-m-align-right-on-lg",
      alignLeftOnLg: "pf-m-align-left-on-lg",
      alignRightOnXl: "pf-m-align-right-on-xl",
      alignLeftOnXl: "pf-m-align-left-on-xl",
      alignRightOn_2xl: "pf-m-align-right-on-2xl",
      alignLeftOn_2xl: "pf-m-align-left-on-2xl",
      ariaDisabled: "pf-m-aria-disabled",
      icon: "pf-m-icon",
      description: "pf-m-description",
      text: "pf-m-text"
    }
  };
});
var styles$12 = /* @__PURE__ */ getDefaultExportFromCjs(dropdown);
var DropdownPosition;
(function(DropdownPosition2) {
  DropdownPosition2["right"] = "right";
  DropdownPosition2["left"] = "left";
})(DropdownPosition || (DropdownPosition = {}));
var DropdownDirection;
(function(DropdownDirection2) {
  DropdownDirection2["up"] = "up";
  DropdownDirection2["down"] = "down";
})(DropdownDirection || (DropdownDirection = {}));
var DropdownContext = react.createContext({
  onSelect: (event) => void 0,
  id: "",
  toggleIndicatorClass: "",
  toggleIconClass: "",
  toggleTextClass: "",
  menuClass: "",
  itemClass: "",
  toggleClass: "",
  baseClass: "",
  baseComponent: "div",
  sectionClass: "",
  sectionTitleClass: "",
  sectionComponent: "section",
  disabledClass: "",
  plainTextClass: "",
  menuComponent: "ul"
});
var DropdownArrowContext = react.createContext({
  keyHandler: null,
  sendRef: null
});
var DropdownMenu = class extends react.Component {
  constructor() {
    super(...arguments);
    this.refsCollection = [];
    this.componentWillUnmount = () => {
      document.removeEventListener("keydown", this.onKeyDown);
    };
    this.onKeyDown = (event) => {
      if (!this.props.isOpen || !Array.from(document.activeElement.classList).find((className) => DropdownMenu.validToggleClasses.concat(this.context.toggleClass).includes(className))) {
        return;
      }
      const refs = this.refsCollection;
      if (event.key === "ArrowDown") {
        const firstFocusTargetCollection = refs.find((ref) => ref && ref[0] && !ref[0].hasAttribute("disabled"));
        DropdownMenu.focusFirstRef(firstFocusTargetCollection);
        event.stopPropagation();
      } else if (event.key === "ArrowUp") {
        const collectionLength = refs.length;
        const lastFocusTargetCollection = refs.slice(collectionLength - 1, collectionLength);
        const lastFocusTarget = lastFocusTargetCollection && lastFocusTargetCollection[0];
        DropdownMenu.focusFirstRef(lastFocusTarget);
        event.stopPropagation();
      }
    };
    this.childKeyHandler = (index3, innerIndex, position2, custom = false) => {
      keyHandler(index3, innerIndex, position2, this.refsCollection, this.props.isGrouped ? this.refsCollection : react.Children.toArray(this.props.children), custom);
    };
    this.sendRef = (index3, nodes, isDisabled, isSeparator) => {
      this.refsCollection[index3] = [];
      nodes.map((node, innerIndex) => {
        if (!node) {
          this.refsCollection[index3][innerIndex] = null;
        } else if (!node.getAttribute) {
          this.refsCollection[index3][innerIndex] = reactDom.findDOMNode(node);
        } else if (isSeparator) {
          this.refsCollection[index3][innerIndex] = null;
        } else {
          this.refsCollection[index3][innerIndex] = node;
        }
      });
    };
  }
  componentDidMount() {
    document.addEventListener("keydown", this.onKeyDown);
    const {autoFocus} = this.props;
    if (autoFocus) {
      const focusTargetCollection = this.refsCollection.find((ref) => ref && ref[0] && !ref[0].hasAttribute("disabled"));
      const focusTarget = focusTargetCollection && focusTargetCollection[0];
      if (focusTarget && focusTarget.focus) {
        setTimeout(() => focusTarget.focus());
      }
    }
  }
  shouldComponentUpdate() {
    this.refsCollection = [];
    return true;
  }
  extendChildren() {
    const {children: children2, isGrouped} = this.props;
    if (isGrouped) {
      let index3 = 0;
      return react.Children.map(children2, (groupedChildren) => {
        const group = groupedChildren;
        const props = {};
        if (group.props && group.props.children) {
          if (Array.isArray(group.props.children)) {
            props.children = react.Children.map(group.props.children, (option) => react.cloneElement(option, {
              index: index3++
            }));
          } else {
            props.children = react.cloneElement(group.props.children, {
              index: index3++
            });
          }
        }
        return react.cloneElement(group, props);
      });
    }
    return react.Children.map(children2, (child, index3) => react.cloneElement(child, {
      index: index3
    }));
  }
  render() {
    const _a = this.props, {
      className,
      isOpen,
      position: position2,
      children: children2,
      component,
      isGrouped,
      setMenuComponentRef,
      openedOnEnter,
      alignments
    } = _a, props = __rest(_a, ["className", "isOpen", "position", "children", "component", "isGrouped", "setMenuComponentRef", "openedOnEnter", "alignments"]);
    return react.createElement(DropdownArrowContext.Provider, {value: {
      keyHandler: this.childKeyHandler,
      sendRef: this.sendRef
    }}, component === "div" ? react.createElement(DropdownContext.Consumer, null, ({onSelect, menuClass}) => react.createElement("div", {className: css(menuClass, position2 === DropdownPosition.right && styles$12.modifiers.alignRight, formatBreakpointMods(alignments, styles$12, "align-"), className), hidden: !isOpen, onClick: (event) => onSelect && onSelect(event), ref: setMenuComponentRef}, children2)) : isGrouped && react.createElement(DropdownContext.Consumer, null, ({menuClass, menuComponent}) => {
      const MenuComponent = menuComponent || "div";
      return react.createElement(MenuComponent, Object.assign({}, props, {className: css(menuClass, position2 === DropdownPosition.right && styles$12.modifiers.alignRight, formatBreakpointMods(alignments, styles$12, "align-"), className), hidden: !isOpen, role: "menu", ref: setMenuComponentRef}), this.extendChildren());
    }) || react.createElement(DropdownContext.Consumer, null, ({menuClass, menuComponent}) => {
      const MenuComponent = menuComponent || component;
      return react.createElement(MenuComponent, Object.assign({}, props, {className: css(menuClass, position2 === DropdownPosition.right && styles$12.modifiers.alignRight, formatBreakpointMods(alignments, styles$12, "align-"), className), hidden: !isOpen, role: "menu", ref: setMenuComponentRef}), this.extendChildren());
    }));
  }
};
DropdownMenu.displayName = "DropdownMenu";
DropdownMenu.defaultProps = {
  className: "",
  isOpen: true,
  openedOnEnter: false,
  autoFocus: true,
  position: DropdownPosition.left,
  component: "ul",
  isGrouped: false,
  setMenuComponentRef: null
};
DropdownMenu.validToggleClasses = [styles$12.dropdownToggle, styles$12.dropdownToggleButton];
DropdownMenu.focusFirstRef = (refCollection) => {
  if (refCollection && refCollection[0] && refCollection[0].focus) {
    setTimeout(() => refCollection[0].focus());
  }
};
DropdownMenu.contextType = DropdownContext;
var DropdownWithContext = class extends react.Component {
  constructor(props) {
    super(props);
    this.openedOnEnter = false;
    this.baseComponentRef = react.createRef();
    this.menuComponentRef = react.createRef();
    this.onEnter = () => {
      this.openedOnEnter = true;
    };
    this.setMenuComponentRef = (element) => {
      this.menuComponentRef = element;
    };
    this.getMenuComponentRef = () => this.menuComponentRef;
    if (props.dropdownItems && props.dropdownItems.length > 0 && props.children) {
      console.error("Children and dropdownItems props have been provided. Only the dropdownItems prop items will be rendered");
    }
  }
  componentDidUpdate() {
    if (!this.props.isOpen) {
      this.openedOnEnter = false;
    }
  }
  render() {
    const _a = this.props, {
      children: children2,
      className,
      direction,
      dropdownItems,
      isOpen,
      isPlain,
      isGrouped,
      isFullHeight,
      onSelect,
      position: position2,
      toggle,
      autoFocus,
      menuAppendTo
    } = _a, props = __rest(_a, ["children", "className", "direction", "dropdownItems", "isOpen", "isPlain", "isGrouped", "isFullHeight", "onSelect", "position", "toggle", "autoFocus", "menuAppendTo"]);
    const id3 = toggle.props.id || `pf-dropdown-toggle-id-${DropdownWithContext.currentId++}`;
    let component;
    let renderedContent;
    let ariaHasPopup = false;
    if (dropdownItems && dropdownItems.length > 0) {
      component = "ul";
      renderedContent = dropdownItems;
      ariaHasPopup = true;
    } else {
      component = "div";
      renderedContent = react.Children.toArray(children2);
    }
    const openedOnEnter = this.openedOnEnter;
    return react.createElement(DropdownContext.Consumer, null, ({baseClass, baseComponent, id: contextId, ouiaId, ouiaComponentType, ouiaSafe, alignments}) => {
      const BaseComponent = baseComponent;
      const menuContainer = react.createElement(DropdownMenu, {setMenuComponentRef: this.setMenuComponentRef, component, isOpen, position: position2, "aria-labelledby": contextId ? `${contextId}-toggle` : id3, isGrouped, autoFocus: openedOnEnter && autoFocus, alignments}, renderedContent);
      const popperContainer = react.createElement("div", {className: css(baseClass, direction === DropdownDirection.up && styles$12.modifiers.top, position2 === DropdownPosition.right && styles$12.modifiers.alignRight, isOpen && styles$12.modifiers.expanded, className)}, isOpen && menuContainer);
      const mainContainer = react.createElement(BaseComponent, Object.assign({}, props, {className: css(baseClass, direction === DropdownDirection.up && styles$12.modifiers.top, position2 === DropdownPosition.right && styles$12.modifiers.alignRight, isOpen && styles$12.modifiers.expanded, isFullHeight && styles$12.modifiers.fullHeight, className), ref: this.baseComponentRef}, getOUIAProps(ouiaComponentType, ouiaId, ouiaSafe)), react.Children.map(toggle, (oneToggle) => react.cloneElement(oneToggle, {
        parentRef: this.baseComponentRef,
        getMenuRef: this.getMenuComponentRef,
        isOpen,
        id: id3,
        isPlain,
        "aria-haspopup": ariaHasPopup,
        onEnter: () => {
          this.onEnter();
          oneToggle.props.onEnter && oneToggle.props.onEnter();
        }
      })), menuAppendTo === "inline" && isOpen && menuContainer);
      const getParentElement = () => {
        if (this.baseComponentRef && this.baseComponentRef.current) {
          return this.baseComponentRef.current.parentElement;
        }
        return null;
      };
      return menuAppendTo === "inline" ? mainContainer : react.createElement(Popper, {trigger: mainContainer, popper: popperContainer, direction, position: position2, appendTo: menuAppendTo === "parent" ? getParentElement() : menuAppendTo, isVisible: isOpen});
    });
  }
};
DropdownWithContext.displayName = "DropdownWithContext";
DropdownWithContext.currentId = 0;
DropdownWithContext.defaultProps = {
  className: "",
  dropdownItems: [],
  isOpen: false,
  isPlain: false,
  isGrouped: false,
  position: DropdownPosition.left,
  direction: DropdownDirection.down,
  onSelect: () => void 0,
  autoFocus: true,
  menuAppendTo: "inline"
};
var Dropdown = (_a) => {
  var {
    onSelect,
    ref,
    ouiaId,
    ouiaSafe,
    alignments,
    contextProps
  } = _a, props = __rest(_a, ["onSelect", "ref", "ouiaId", "ouiaSafe", "alignments", "contextProps"]);
  return react.createElement(DropdownContext.Provider, {value: Object.assign({onSelect: (event) => onSelect && onSelect(event), toggleTextClass: styles$12.dropdownToggleText, toggleIconClass: styles$12.dropdownToggleImage, toggleIndicatorClass: styles$12.dropdownToggleIcon, menuClass: styles$12.dropdownMenu, itemClass: styles$12.dropdownMenuItem, toggleClass: styles$12.dropdownToggle, baseClass: styles$12.dropdown, baseComponent: "div", sectionClass: styles$12.dropdownGroup, sectionTitleClass: styles$12.dropdownGroupTitle, sectionComponent: "section", disabledClass: styles$12.modifiers.disabled, plainTextClass: styles$12.modifiers.text, ouiaId: useOUIAId(Dropdown.displayName, ouiaId), ouiaSafe, ouiaComponentType: Dropdown.displayName, alignments}, contextProps)}, react.createElement(DropdownWithContext, Object.assign({}, props)));
};
Dropdown.displayName = "Dropdown";
var InternalDropdownItem = class extends react.Component {
  constructor() {
    super(...arguments);
    this.ref = react.createRef();
    this.additionalRef = react.createRef();
    this.getInnerNode = (node) => node && node.childNodes && node.childNodes.length ? node.childNodes[0] : node;
    this.onKeyDown = (event) => {
      const innerIndex = event.target === this.ref.current ? 0 : 1;
      if (!this.props.customChild) {
        event.preventDefault();
      }
      if (event.key === "ArrowUp") {
        this.props.context.keyHandler(this.props.index, innerIndex, KEYHANDLER_DIRECTION.UP);
        event.stopPropagation();
      } else if (event.key === "ArrowDown") {
        this.props.context.keyHandler(this.props.index, innerIndex, KEYHANDLER_DIRECTION.DOWN);
        event.stopPropagation();
      } else if (event.key === "ArrowRight") {
        this.props.context.keyHandler(this.props.index, innerIndex, KEYHANDLER_DIRECTION.RIGHT);
        event.stopPropagation();
      } else if (event.key === "ArrowLeft") {
        this.props.context.keyHandler(this.props.index, innerIndex, KEYHANDLER_DIRECTION.LEFT);
        event.stopPropagation();
      } else if (event.key === "Enter" || event.key === " ") {
        event.target.click();
        this.props.enterTriggersArrowDown && this.props.context.keyHandler(this.props.index, innerIndex, KEYHANDLER_DIRECTION.DOWN);
      }
    };
    this.componentRef = (element) => {
      this.ref.current = element;
      const {component} = this.props;
      const ref = component.ref;
      if (ref) {
        if (typeof ref === "function") {
          ref(element);
        } else {
          ref.current = element;
        }
      }
    };
  }
  componentDidMount() {
    const {context: context2, index: index3, isDisabled, role, customChild, autoFocus} = this.props;
    const customRef = customChild ? this.getInnerNode(this.ref.current) : this.ref.current;
    context2.sendRef(index3, [customRef, customChild ? customRef : this.additionalRef.current], isDisabled, role === "separator");
    autoFocus && setTimeout(() => customRef.focus());
  }
  componentDidUpdate() {
    const {context: context2, index: index3, isDisabled, role, customChild} = this.props;
    const customRef = customChild ? this.getInnerNode(this.ref.current) : this.ref.current;
    context2.sendRef(index3, [customRef, customChild ? customRef : this.additionalRef.current], isDisabled, role === "separator");
  }
  extendAdditionalChildRef() {
    const {additionalChild} = this.props;
    return react.cloneElement(additionalChild, {
      ref: this.additionalRef
    });
  }
  render() {
    const _a = this.props, {className, children: children2, isHovered, context: context2, onClick, component, role, isDisabled, isAriaDisabled, isPlainText, index: index3, href, tooltip: tooltip2, tooltipProps, id: id3, componentID, listItemClassName, additionalChild, customChild, enterTriggersArrowDown, icon, autoFocus, styleChildren, description, inoperableEvents} = _a, additionalProps = __rest(_a, ["className", "children", "isHovered", "context", "onClick", "component", "role", "isDisabled", "isAriaDisabled", "isPlainText", "index", "href", "tooltip", "tooltipProps", "id", "componentID", "listItemClassName", "additionalChild", "customChild", "enterTriggersArrowDown", "icon", "autoFocus", "styleChildren", "description", "inoperableEvents"]);
    let classes = css(icon && styles$12.modifiers.icon, isAriaDisabled && styles$12.modifiers.ariaDisabled, className);
    if (component === "a") {
      additionalProps["aria-disabled"] = isDisabled || isAriaDisabled;
    } else if (component === "button") {
      additionalProps["aria-disabled"] = isDisabled || isAriaDisabled;
      additionalProps.type = additionalProps.type || "button";
    }
    const renderWithTooltip = (childNode) => tooltip2 ? react.createElement(Tooltip, Object.assign({content: tooltip2}, tooltipProps), childNode) : childNode;
    const renderClonedComponent = (element) => react.cloneElement(element, Object.assign(Object.assign({}, styleChildren && {
      className: css(element.props.className, classes)
    }), this.props.role !== "separator" && {ref: this.componentRef}));
    const renderDefaultComponent = (tag) => {
      const Component = tag;
      const componentContent = description ? react.createElement(react.Fragment, null, react.createElement("div", {className: styles$12.dropdownMenuItemMain}, icon && react.createElement("span", {className: css(styles$12.dropdownMenuItemIcon)}, icon), children2), react.createElement("div", {className: styles$12.dropdownMenuItemDescription}, description)) : react.createElement(react.Fragment, null, icon && react.createElement("span", {className: css(styles$12.dropdownMenuItemIcon)}, icon), children2);
      return react.createElement(Component, Object.assign({}, additionalProps, isDisabled || isAriaDisabled ? preventedEvents(inoperableEvents) : null, {href, ref: this.ref, className: classes, id: componentID}), componentContent);
    };
    return react.createElement(DropdownContext.Consumer, null, ({onSelect, itemClass, disabledClass, plainTextClass}) => {
      if (this.props.role !== "separator") {
        classes = css(classes, isDisabled && disabledClass, isPlainText && plainTextClass, itemClass, description && styles$12.modifiers.description);
      }
      if (customChild) {
        return react.cloneElement(customChild, {
          ref: this.ref,
          onKeyDown: this.onKeyDown
        });
      }
      return react.createElement("li", {className: listItemClassName || null, role, onKeyDown: this.onKeyDown, onClick: (event) => {
        if (!isDisabled && !isAriaDisabled) {
          onClick(event);
          onSelect(event);
        }
      }, id: id3}, renderWithTooltip(react.isValidElement(component) ? renderClonedComponent(component) : renderDefaultComponent(component)), additionalChild && this.extendAdditionalChildRef());
    });
  }
};
InternalDropdownItem.displayName = "InternalDropdownItem";
InternalDropdownItem.defaultProps = {
  className: "",
  isHovered: false,
  component: "a",
  role: "none",
  isDisabled: false,
  isPlainText: false,
  tooltipProps: {},
  onClick: (event) => void 0,
  index: -1,
  context: {
    keyHandler: () => {
    },
    sendRef: () => {
    }
  },
  enterTriggersArrowDown: false,
  icon: null,
  styleChildren: true,
  description: null,
  inoperableEvents: ["onClick", "onKeyPress"]
};
var DropdownItem = (_a) => {
  var {
    children: children2,
    className,
    component = "a",
    isDisabled = false,
    isAriaDisabled = false,
    isPlainText = false,
    isHovered = false,
    href,
    tooltip: tooltip2,
    tooltipProps = {},
    listItemClassName,
    onClick,
    ref,
    additionalChild,
    customChild,
    tabIndex = -1,
    icon = null,
    autoFocus,
    description = null,
    styleChildren,
    ouiaId,
    ouiaSafe
  } = _a, props = __rest(_a, ["children", "className", "component", "isDisabled", "isAriaDisabled", "isPlainText", "isHovered", "href", "tooltip", "tooltipProps", "listItemClassName", "onClick", "ref", "additionalChild", "customChild", "tabIndex", "icon", "autoFocus", "description", "styleChildren", "ouiaId", "ouiaSafe"]);
  const ouiaProps = useOUIAProps(DropdownItem.displayName, ouiaId, ouiaSafe);
  return react.createElement(DropdownArrowContext.Consumer, null, (context2) => react.createElement(InternalDropdownItem, Object.assign({context: context2, role: "menuitem", tabIndex, className, component, isDisabled, isAriaDisabled, isPlainText, isHovered, href, tooltip: tooltip2, tooltipProps, listItemClassName, onClick, additionalChild, customChild, icon, autoFocus, styleChildren, description}, ouiaProps, props), children2));
};
DropdownItem.displayName = "DropdownItem";
var divider = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    divider: "pf-c-divider",
    modifiers: {
      hidden: "pf-m-hidden",
      hiddenOnSm: "pf-m-hidden-on-sm",
      visibleOnSm: "pf-m-visible-on-sm",
      hiddenOnMd: "pf-m-hidden-on-md",
      visibleOnMd: "pf-m-visible-on-md",
      hiddenOnLg: "pf-m-hidden-on-lg",
      visibleOnLg: "pf-m-visible-on-lg",
      hiddenOnXl: "pf-m-hidden-on-xl",
      visibleOnXl: "pf-m-visible-on-xl",
      hiddenOn_2xl: "pf-m-hidden-on-2xl",
      visibleOn_2xl: "pf-m-visible-on-2xl",
      vertical: "pf-m-vertical",
      insetNone: "pf-m-inset-none",
      insetXs: "pf-m-inset-xs",
      insetSm: "pf-m-inset-sm",
      insetMd: "pf-m-inset-md",
      insetLg: "pf-m-inset-lg",
      insetXl: "pf-m-inset-xl",
      inset_2xl: "pf-m-inset-2xl",
      inset_3xl: "pf-m-inset-3xl",
      insetNoneOnSm: "pf-m-inset-none-on-sm",
      insetXsOnSm: "pf-m-inset-xs-on-sm",
      insetSmOnSm: "pf-m-inset-sm-on-sm",
      insetMdOnSm: "pf-m-inset-md-on-sm",
      insetLgOnSm: "pf-m-inset-lg-on-sm",
      insetXlOnSm: "pf-m-inset-xl-on-sm",
      inset_2xlOnSm: "pf-m-inset-2xl-on-sm",
      inset_3xlOnSm: "pf-m-inset-3xl-on-sm",
      insetNoneOnMd: "pf-m-inset-none-on-md",
      insetXsOnMd: "pf-m-inset-xs-on-md",
      insetSmOnMd: "pf-m-inset-sm-on-md",
      insetMdOnMd: "pf-m-inset-md-on-md",
      insetLgOnMd: "pf-m-inset-lg-on-md",
      insetXlOnMd: "pf-m-inset-xl-on-md",
      inset_2xlOnMd: "pf-m-inset-2xl-on-md",
      inset_3xlOnMd: "pf-m-inset-3xl-on-md",
      insetNoneOnLg: "pf-m-inset-none-on-lg",
      insetXsOnLg: "pf-m-inset-xs-on-lg",
      insetSmOnLg: "pf-m-inset-sm-on-lg",
      insetMdOnLg: "pf-m-inset-md-on-lg",
      insetLgOnLg: "pf-m-inset-lg-on-lg",
      insetXlOnLg: "pf-m-inset-xl-on-lg",
      inset_2xlOnLg: "pf-m-inset-2xl-on-lg",
      inset_3xlOnLg: "pf-m-inset-3xl-on-lg",
      insetNoneOnXl: "pf-m-inset-none-on-xl",
      insetXsOnXl: "pf-m-inset-xs-on-xl",
      insetSmOnXl: "pf-m-inset-sm-on-xl",
      insetMdOnXl: "pf-m-inset-md-on-xl",
      insetLgOnXl: "pf-m-inset-lg-on-xl",
      insetXlOnXl: "pf-m-inset-xl-on-xl",
      inset_2xlOnXl: "pf-m-inset-2xl-on-xl",
      inset_3xlOnXl: "pf-m-inset-3xl-on-xl",
      insetNoneOn_2xl: "pf-m-inset-none-on-2xl",
      insetXsOn_2xl: "pf-m-inset-xs-on-2xl",
      insetSmOn_2xl: "pf-m-inset-sm-on-2xl",
      insetMdOn_2xl: "pf-m-inset-md-on-2xl",
      insetLgOn_2xl: "pf-m-inset-lg-on-2xl",
      insetXlOn_2xl: "pf-m-inset-xl-on-2xl",
      inset_2xlOn_2xl: "pf-m-inset-2xl-on-2xl",
      inset_3xlOn_2xl: "pf-m-inset-3xl-on-2xl"
    }
  };
});
var styles$22 = /* @__PURE__ */ getDefaultExportFromCjs(divider);
var DividerVariant;
(function(DividerVariant2) {
  DividerVariant2["hr"] = "hr";
  DividerVariant2["li"] = "li";
  DividerVariant2["div"] = "div";
})(DividerVariant || (DividerVariant = {}));
var Divider = (_a) => {
  var {className, component = DividerVariant.hr, isVertical = false, inset} = _a, props = __rest(_a, ["className", "component", "isVertical", "inset"]);
  const Component = component;
  return react.createElement(Component, Object.assign({className: css(styles$22.divider, isVertical && styles$22.modifiers.vertical, formatBreakpointMods(inset, styles$22), className)}, component !== "hr" && {role: "separator"}, props));
};
Divider.displayName = "Divider";
var DropdownSeparator = (_a) => {
  var {
    className = "",
    ref,
    ouiaId,
    ouiaSafe
  } = _a, props = __rest(_a, ["className", "ref", "ouiaId", "ouiaSafe"]);
  const ouiaProps = useOUIAProps(DropdownSeparator.displayName, ouiaId, ouiaSafe);
  return react.createElement(DropdownArrowContext.Consumer, null, (context2) => react.createElement(InternalDropdownItem, Object.assign({}, props, {context: context2, component: react.createElement(Divider, {component: DividerVariant.div}), className, role: "separator"}, ouiaProps)));
};
DropdownSeparator.displayName = "DropdownSeparator";
var Toggle = class extends react.Component {
  constructor() {
    super(...arguments);
    this.buttonRef = react.createRef();
    this.componentDidMount = () => {
      document.addEventListener("click", this.onDocClick);
      document.addEventListener("touchstart", this.onDocClick);
      document.addEventListener("keydown", this.onEscPress);
    };
    this.componentWillUnmount = () => {
      document.removeEventListener("click", this.onDocClick);
      document.removeEventListener("touchstart", this.onDocClick);
      document.removeEventListener("keydown", this.onEscPress);
    };
    this.onDocClick = (event) => {
      const {isOpen, parentRef, onToggle, getMenuRef} = this.props;
      const menuRef = getMenuRef && getMenuRef();
      const clickedOnToggle = parentRef && parentRef.current && parentRef.current.contains(event.target);
      const clickedWithinMenu = menuRef && menuRef.contains && menuRef.contains(event.target);
      if (isOpen && !(clickedOnToggle || clickedWithinMenu)) {
        onToggle(false, event);
      }
    };
    this.onEscPress = (event) => {
      const {parentRef, getMenuRef} = this.props;
      const keyCode = event.keyCode || event.which;
      const menuRef = getMenuRef && getMenuRef();
      const escFromToggle = parentRef && parentRef.current && parentRef.current.contains(event.target);
      const escFromWithinMenu = menuRef && menuRef.contains && menuRef.contains(event.target);
      if (this.props.isOpen && (keyCode === KEY_CODES.ESCAPE_KEY || event.key === "Tab") && (escFromToggle || escFromWithinMenu)) {
        this.props.onToggle(false, event);
        this.buttonRef.current.focus();
      }
    };
    this.onKeyDown = (event) => {
      if (event.key === "Tab" && !this.props.isOpen) {
        return;
      }
      if ((event.key === "Tab" || event.key === "Enter" || event.key === " ") && this.props.isOpen) {
        if (!this.props.bubbleEvent) {
          event.stopPropagation();
        }
        event.preventDefault();
        this.props.onToggle(!this.props.isOpen, event);
      } else if ((event.key === "Enter" || event.key === " ") && !this.props.isOpen) {
        if (!this.props.bubbleEvent) {
          event.stopPropagation();
        }
        event.preventDefault();
        this.props.onToggle(!this.props.isOpen, event);
        this.props.onEnter();
      }
    };
  }
  render() {
    const _a = this.props, {
      className,
      children: children2,
      isOpen,
      isDisabled,
      isPlain,
      isPrimary,
      isSplitButton,
      onToggle,
      "aria-haspopup": ariaHasPopup,
      isActive,
      bubbleEvent,
      onEnter,
      parentRef,
      getMenuRef,
      id: id3,
      type
    } = _a, props = __rest(_a, ["className", "children", "isOpen", "isDisabled", "isPlain", "isPrimary", "isSplitButton", "onToggle", "aria-haspopup", "isActive", "bubbleEvent", "onEnter", "parentRef", "getMenuRef", "id", "type"]);
    return react.createElement(DropdownContext.Consumer, null, ({toggleClass: toggleClass2}) => react.createElement("button", Object.assign({}, props, {id: id3, ref: this.buttonRef, className: css(isSplitButton ? styles$12.dropdownToggleButton : toggleClass2 || styles$12.dropdownToggle, isActive && styles$12.modifiers.active, isPlain && styles$12.modifiers.plain, isPrimary && styles$12.modifiers.primary, className), type: type || "button", onClick: (event) => onToggle(!isOpen, event), "aria-expanded": isOpen, "aria-haspopup": ariaHasPopup, onKeyDown: (event) => this.onKeyDown(event), disabled: isDisabled}), children2));
  }
};
Toggle.displayName = "Toggle";
Toggle.defaultProps = {
  className: "",
  isOpen: false,
  isActive: false,
  isDisabled: false,
  isPlain: false,
  isPrimary: false,
  isSplitButton: false,
  onToggle: () => {
  },
  onEnter: () => {
  },
  bubbleEvent: false
};
var EllipsisVIconConfig = {
  name: "EllipsisVIcon",
  height: 512,
  width: 192,
  svgPath: "M96 184c39.8 0 72 32.2 72 72s-32.2 72-72 72-72-32.2-72-72 32.2-72 72-72zM24 80c0 39.8 32.2 72 72 72s72-32.2 72-72S135.8 8 96 8 24 40.2 24 80zm0 352c0 39.8 32.2 72 72 72s72-32.2 72-72-32.2-72-72-72-72 32.2-72 72z",
  yOffset: 0,
  xOffset: 0
};
var EllipsisVIcon = createIcon(EllipsisVIconConfig);
var KebabToggle = (_a) => {
  var {
    id: id3 = "",
    children: children2 = null,
    className = "",
    isOpen = false,
    "aria-label": ariaLabel = "Actions",
    parentRef = null,
    getMenuRef = null,
    isActive = false,
    isPlain = false,
    isDisabled = false,
    bubbleEvent = false,
    onToggle = () => void 0,
    ref
  } = _a, props = __rest(_a, ["id", "children", "className", "isOpen", "aria-label", "parentRef", "getMenuRef", "isActive", "isPlain", "isDisabled", "bubbleEvent", "onToggle", "ref"]);
  return react.createElement(Toggle, Object.assign({id: id3, className, isOpen, "aria-label": ariaLabel, parentRef, getMenuRef, isActive, isPlain, isDisabled, onToggle, bubbleEvent}, props), react.createElement(EllipsisVIcon, null));
};
KebabToggle.displayName = "KebabToggle";
var StarIconConfig = {
  name: "StarIcon",
  height: 512,
  width: 576,
  svgPath: "M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z",
  yOffset: 0,
  xOffset: 0
};
var StarIcon = createIcon(StarIconConfig);
var check = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    check: "pf-c-check",
    checkBody: "pf-c-check__body",
    checkDescription: "pf-c-check__description",
    checkInput: "pf-c-check__input",
    checkLabel: "pf-c-check__label",
    modifiers: {
      standalone: "pf-m-standalone",
      disabled: "pf-m-disabled"
    }
  };
});
var checkStyles = /* @__PURE__ */ getDefaultExportFromCjs(check);
var defaultOnChange = () => {
};
var Checkbox = class extends react.Component {
  constructor(props) {
    super(props);
    this.handleChange = (event) => {
      this.props.onChange(event.currentTarget.checked, event);
    };
    this.state = {
      ouiaStateId: getDefaultOUIAId(Checkbox.displayName)
    };
  }
  render() {
    const _a = this.props, {"aria-label": ariaLabel, className, onChange, isValid, isDisabled, isChecked, label: label2, checked, defaultChecked, description, body, ouiaId, ouiaSafe} = _a, props = __rest(_a, ["aria-label", "className", "onChange", "isValid", "isDisabled", "isChecked", "label", "checked", "defaultChecked", "description", "body", "ouiaId", "ouiaSafe"]);
    if (!props.id) {
      console.error("Checkbox:", "id is required to make input accessible");
    }
    const checkedProps = {};
    if ([true, false].includes(checked) || isChecked === true) {
      checkedProps.checked = checked || isChecked;
    }
    if (onChange !== defaultOnChange) {
      checkedProps.checked = isChecked;
    }
    if ([false, true].includes(defaultChecked)) {
      checkedProps.defaultChecked = defaultChecked;
    }
    checkedProps.checked = checkedProps.checked === null ? false : checkedProps.checked;
    return react.createElement("div", {className: css(checkStyles.check, !label2 && checkStyles.modifiers.standalone, className)}, react.createElement("input", Object.assign({}, props, {className: css(checkStyles.checkInput), type: "checkbox", onChange: this.handleChange, "aria-invalid": !isValid, "aria-label": ariaLabel, disabled: isDisabled, ref: (elem) => elem && (elem.indeterminate = isChecked === null)}, checkedProps, getOUIAProps(Checkbox.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId, ouiaSafe))), label2 && react.createElement("label", {className: css(checkStyles.checkLabel, isDisabled && checkStyles.modifiers.disabled), htmlFor: props.id}, label2), description && react.createElement("span", {className: css(checkStyles.checkDescription)}, description), body && react.createElement("span", {className: css(checkStyles.checkBody)}, body));
  }
};
Checkbox.displayName = "Checkbox";
Checkbox.defaultProps = {
  className: "",
  isValid: true,
  isDisabled: false,
  isChecked: false,
  onChange: defaultOnChange,
  ouiaSafe: true
};
var AngleDownIconConfig = {
  name: "AngleDownIcon",
  height: 512,
  width: 320,
  svgPath: "M143 352.3L7 216.3c-9.4-9.4-9.4-24.6 0-33.9l22.6-22.6c9.4-9.4 24.6-9.4 33.9 0l96.4 96.4 96.4-96.4c9.4-9.4 24.6-9.4 33.9 0l22.6 22.6c9.4 9.4 9.4 24.6 0 33.9l-136 136c-9.2 9.4-24.4 9.4-33.8 0z",
  yOffset: 0,
  xOffset: 0
};
var AngleDownIcon = createIcon(AngleDownIconConfig);
var GripVerticalIconConfig = {
  name: "GripVerticalIcon",
  height: 512,
  width: 320,
  svgPath: "M96 32H32C14.33 32 0 46.33 0 64v64c0 17.67 14.33 32 32 32h64c17.67 0 32-14.33 32-32V64c0-17.67-14.33-32-32-32zm0 160H32c-17.67 0-32 14.33-32 32v64c0 17.67 14.33 32 32 32h64c17.67 0 32-14.33 32-32v-64c0-17.67-14.33-32-32-32zm0 160H32c-17.67 0-32 14.33-32 32v64c0 17.67 14.33 32 32 32h64c17.67 0 32-14.33 32-32v-64c0-17.67-14.33-32-32-32zM288 32h-64c-17.67 0-32 14.33-32 32v64c0 17.67 14.33 32 32 32h64c17.67 0 32-14.33 32-32V64c0-17.67-14.33-32-32-32zm0 160h-64c-17.67 0-32 14.33-32 32v64c0 17.67 14.33 32 32 32h64c17.67 0 32-14.33 32-32v-64c0-17.67-14.33-32-32-32zm0 160h-64c-17.67 0-32 14.33-32 32v64c0 17.67 14.33 32 32 32h64c17.67 0 32-14.33 32-32v-64c0-17.67-14.33-32-32-32z",
  yOffset: 0,
  xOffset: 0
};
var GripVerticalIcon = createIcon(GripVerticalIconConfig);
var popover = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    modifiers: {
      noPadding: "pf-m-no-padding",
      widthAuto: "pf-m-width-auto",
      top: "pf-m-top",
      topLeft: "pf-m-top-left",
      topRight: "pf-m-top-right",
      bottom: "pf-m-bottom",
      bottomLeft: "pf-m-bottom-left",
      bottomRight: "pf-m-bottom-right",
      left: "pf-m-left",
      leftTop: "pf-m-left-top",
      leftBottom: "pf-m-left-bottom",
      right: "pf-m-right",
      rightTop: "pf-m-right-top",
      rightBottom: "pf-m-right-bottom",
      danger: "pf-m-danger",
      warning: "pf-m-warning",
      success: "pf-m-success",
      default: "pf-m-default",
      info: "pf-m-info",
      icon: "pf-m-icon"
    },
    popover: "pf-c-popover",
    popoverArrow: "pf-c-popover__arrow",
    popoverBody: "pf-c-popover__body",
    popoverContent: "pf-c-popover__content",
    popoverFooter: "pf-c-popover__footer",
    popoverTitle: "pf-c-popover__title",
    popoverTitleIcon: "pf-c-popover__title-icon",
    popoverTitleText: "pf-c-popover__title-text",
    title: "pf-c-title"
  };
});
var styles$32 = /* @__PURE__ */ getDefaultExportFromCjs(popover);
var PopoverContext = react.createContext({});
var PopoverContent = (_a) => {
  var {className = null, children: children2} = _a, props = __rest(_a, ["className", "children"]);
  return react.createElement("div", Object.assign({className: css(styles$32.popoverContent, className)}, props), children2);
};
PopoverContent.displayName = "PopoverContent";
var PopoverBody = (_a) => {
  var {children: children2, id: id3} = _a, props = __rest(_a, ["children", "id"]);
  return react.createElement("div", Object.assign({className: css(styles$32.popoverBody), id: id3}, props), children2);
};
PopoverBody.displayName = "PopoverBody";
var PopoverHeader = (_a) => {
  var {children: children2, id: id3} = _a, props = __rest(_a, ["children", "id"]);
  return react.createElement(PopoverContext.Consumer, null, ({headerComponent}) => react.createElement(Title, Object.assign({headingLevel: headerComponent, size: TitleSizes.md, id: id3}, props), children2));
};
PopoverHeader.displayName = "PopoverHeader";
var PopoverFooter = (_a) => {
  var {children: children2, className = ""} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("footer", Object.assign({className: css(styles$32.popoverFooter, className)}, props), children2);
};
PopoverFooter.displayName = "PopoverFooter";
var PopoverCloseButton = (_a) => {
  var {onClose = () => void 0} = _a, props = __rest(_a, ["onClose"]);
  const [closeButtonElement, setCloseButtonElement] = react.useState(null);
  react.useEffect(() => {
    closeButtonElement && closeButtonElement.addEventListener("click", onClose, false);
    return () => {
      closeButtonElement && closeButtonElement.removeEventListener("click", onClose, false);
    };
  }, [closeButtonElement]);
  return react.createElement(FindRefWrapper, {onFoundRef: (foundRef) => setCloseButtonElement(foundRef)}, react.createElement(Button, Object.assign({variant: "plain", "aria-label": true}, props, {style: {pointerEvents: "auto"}}), react.createElement(TimesIcon, null)));
};
PopoverCloseButton.displayName = "PopoverCloseButton";
var PopoverArrow = (_a) => {
  var {className = ""} = _a, props = __rest(_a, ["className"]);
  return react.createElement("div", Object.assign({className: css(styles$32.popoverArrow, className)}, props));
};
PopoverArrow.displayName = "PopoverArrow";
var c_popover_MaxWidth = {
  name: "--pf-c-popover--MaxWidth",
  value: "none",
  var: "var(--pf-c-popover--MaxWidth)"
};
var c_popover_MinWidth = {
  name: "--pf-c-popover--MinWidth",
  value: "auto",
  var: "var(--pf-c-popover--MinWidth)"
};
var PopoverPosition;
(function(PopoverPosition2) {
  PopoverPosition2["auto"] = "auto";
  PopoverPosition2["top"] = "top";
  PopoverPosition2["bottom"] = "bottom";
  PopoverPosition2["left"] = "left";
  PopoverPosition2["right"] = "right";
  PopoverPosition2["topStart"] = "top-start";
  PopoverPosition2["topEnd"] = "top-end";
  PopoverPosition2["bottomStart"] = "bottom-start";
  PopoverPosition2["bottomEnd"] = "bottom-end";
  PopoverPosition2["leftStart"] = "left-start";
  PopoverPosition2["leftEnd"] = "left-end";
  PopoverPosition2["rightStart"] = "right-start";
  PopoverPosition2["rightEnd"] = "right-end";
})(PopoverPosition || (PopoverPosition = {}));
var Popover = (_a) => {
  var {
    children: children2,
    position: position2 = "top",
    enableFlip = true,
    className = "",
    isVisible = null,
    shouldClose = () => null,
    shouldOpen = () => null,
    "aria-label": ariaLabel = "",
    bodyContent,
    headerContent = null,
    headerComponent = "h6",
    footerContent = null,
    appendTo = () => document.body,
    hideOnOutsideClick = true,
    onHide = () => null,
    onHidden = () => null,
    onShow = () => null,
    onShown = () => null,
    onMount = () => null,
    zIndex = 9999,
    minWidth = c_popover_MinWidth && c_popover_MinWidth.value,
    maxWidth = c_popover_MaxWidth && c_popover_MaxWidth.value,
    closeBtnAriaLabel = "Close",
    showClose = true,
    distance = 25,
    flipBehavior = ["top", "right", "bottom", "left", "top", "right", "bottom"],
    animationDuration = 300,
    id: id3,
    withFocusTrap: propWithFocusTrap,
    boundary,
    tippyProps,
    reference: reference2,
    hasNoPadding = false,
    hasAutoWidth = false
  } = _a, rest = __rest(_a, ["children", "position", "enableFlip", "className", "isVisible", "shouldClose", "shouldOpen", "aria-label", "bodyContent", "headerContent", "headerComponent", "footerContent", "appendTo", "hideOnOutsideClick", "onHide", "onHidden", "onShow", "onShown", "onMount", "zIndex", "minWidth", "maxWidth", "closeBtnAriaLabel", "showClose", "distance", "flipBehavior", "animationDuration", "id", "withFocusTrap", "boundary", "tippyProps", "reference", "hasNoPadding", "hasAutoWidth"]);
  const uniqueId2 = id3 || getUniqueId();
  const triggerManually = isVisible !== null;
  const [visible, setVisible] = react.useState(false);
  const [opacity, setOpacity] = react.useState(0);
  const [focusTrapActive, setFocusTrapActive] = react.useState(Boolean(propWithFocusTrap));
  const transitionTimerRef = react.useRef(null);
  const showTimerRef = react.useRef(null);
  const hideTimerRef = react.useRef(null);
  react.useEffect(() => {
    onMount();
  }, []);
  react.useEffect(() => {
    if (triggerManually) {
      if (isVisible) {
        show2();
      } else {
        hide3();
      }
    }
  }, [isVisible, triggerManually]);
  const show2 = (withFocusTrap) => {
    onShow();
    if (transitionTimerRef.current) {
      clearTimeout(transitionTimerRef.current);
    }
    if (hideTimerRef.current) {
      clearTimeout(hideTimerRef.current);
    }
    showTimerRef.current = setTimeout(() => {
      setVisible(true);
      setOpacity(1);
      propWithFocusTrap !== false && withFocusTrap && setFocusTrapActive(true);
      onShown();
    }, 0);
  };
  const hide3 = () => {
    onHide();
    if (showTimerRef.current) {
      clearTimeout(showTimerRef.current);
    }
    hideTimerRef.current = setTimeout(() => {
      setVisible(false);
      setOpacity(0);
      setFocusTrapActive(false);
      transitionTimerRef.current = setTimeout(() => {
        onHidden();
      }, animationDuration);
    }, 0);
  };
  const positionModifiers = {
    top: styles$32.modifiers.top,
    bottom: styles$32.modifiers.bottom,
    left: styles$32.modifiers.left,
    right: styles$32.modifiers.right,
    "top-start": styles$32.modifiers.topLeft,
    "top-end": styles$32.modifiers.topRight,
    "bottom-start": styles$32.modifiers.bottomLeft,
    "bottom-end": styles$32.modifiers.bottomRight,
    "left-start": styles$32.modifiers.leftTop,
    "left-end": styles$32.modifiers.leftBottom,
    "right-start": styles$32.modifiers.rightTop,
    "right-end": styles$32.modifiers.rightBottom
  };
  const hasCustomMinWidth = minWidth !== c_popover_MinWidth.value;
  const hasCustomMaxWidth = maxWidth !== c_popover_MaxWidth.value;
  const onDocumentKeyDown = (event) => {
    if (event.keyCode === KEY_CODES.ESCAPE_KEY && visible) {
      if (triggerManually) {
        shouldClose(null, hide3, event);
      } else {
        hide3();
      }
    }
  };
  const onDocumentClick = (event, triggerElement, popperElement) => {
    if (hideOnOutsideClick && visible) {
      const isChild = popperElement && popperElement.contains(event.target);
      if (isChild) {
        return;
      }
      if (triggerManually) {
        shouldClose(null, hide3, event);
      } else {
        hide3();
      }
    }
  };
  const onTriggerEnter = (event) => {
    if (event.keyCode === KEY_CODES.ENTER) {
      if (!visible) {
        if (triggerManually) {
          shouldOpen(show2, event);
        } else {
          show2(true);
        }
      } else {
        if (triggerManually) {
          shouldClose(null, hide3, event);
        } else {
          hide3();
        }
      }
    }
  };
  const onTriggerClick = (event) => {
    if (triggerManually) {
      if (visible) {
        shouldClose(null, hide3, event);
      } else {
        shouldOpen(show2, event);
      }
    } else {
      if (visible) {
        hide3();
      } else {
        show2();
      }
    }
  };
  const onContentMouseDown = () => {
    if (focusTrapActive) {
      setFocusTrapActive(false);
    }
  };
  const closePopover = (event) => {
    event.stopPropagation();
    if (triggerManually) {
      shouldClose(null, hide3, event);
    } else {
      hide3();
    }
  };
  const content2 = react.createElement(FocusTrap, Object.assign({active: focusTrapActive, focusTrapOptions: {
    returnFocusOnDeactivate: true,
    clickOutsideDeactivates: true,
    fallbackFocus: () => {
      let node = null;
      if (document && document.activeElement) {
        node = document.activeElement;
      }
      return node;
    }
  }, preventScrollOnDeactivate: true, className: css(styles$32.popover, hasNoPadding && styles$32.modifiers.noPadding, hasAutoWidth && styles$32.modifiers.widthAuto, className), role: "dialog", "aria-modal": "true", "aria-label": headerContent ? void 0 : ariaLabel, "aria-labelledby": headerContent ? `popover-${uniqueId2}-header` : void 0, "aria-describedby": `popover-${uniqueId2}-body`, onMouseDown: onContentMouseDown, style: {
    minWidth: hasCustomMinWidth ? minWidth : null,
    maxWidth: hasCustomMaxWidth ? maxWidth : null,
    opacity,
    transition: getOpacityTransition(animationDuration)
  }}, rest), react.createElement(PopoverArrow, null), react.createElement(PopoverContent, null, showClose && react.createElement(PopoverCloseButton, {onClose: closePopover, "aria-label": closeBtnAriaLabel}), headerContent && react.createElement(PopoverHeader, {id: `popover-${uniqueId2}-header`}, typeof headerContent === "function" ? headerContent(hide3) : headerContent), react.createElement(PopoverBody, {id: `popover-${uniqueId2}-body`}, typeof bodyContent === "function" ? bodyContent(hide3) : bodyContent), footerContent && react.createElement(PopoverFooter, {id: `popover-${uniqueId2}-footer`}, typeof footerContent === "function" ? footerContent(hide3) : footerContent)));
  return react.createElement(PopoverContext.Provider, {value: {headerComponent}}, react.createElement(Popper, {trigger: children2, reference: reference2, popper: content2, popperMatchesTriggerWidth: false, appendTo, isVisible: visible, positionModifiers, distance, placement: position2, onTriggerClick, onTriggerEnter, onDocumentClick, onDocumentKeyDown, enableFlip, zIndex, flipBehavior}));
};
Popover.displayName = "Popover";
var inlineEdit = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    inlineEdit: "pf-c-inline-edit",
    inlineEditAction: "pf-c-inline-edit__action",
    inlineEditEditableText: "pf-c-inline-edit__editable-text",
    inlineEditGroup: "pf-c-inline-edit__group",
    inlineEditInput: "pf-c-inline-edit__input",
    inlineEditLabel: "pf-c-inline-edit__label",
    inlineEditValue: "pf-c-inline-edit__value",
    modifiers: {
      iconGroup: "pf-m-icon-group",
      footer: "pf-m-footer",
      column: "pf-m-column",
      valid: "pf-m-valid",
      plain: "pf-m-plain",
      actionGroup: "pf-m-action-group",
      enableEditable: "pf-m-enable-editable",
      inlineEditable: "pf-m-inline-editable",
      enable: "pf-m-enable",
      bold: "pf-m-bold"
    }
  };
});
var inlineStyles = /* @__PURE__ */ getDefaultExportFromCjs(inlineEdit);

// build/_snowpack/pkg/common/plus-icon-7ed026dd.js
var AngleRightIconConfig = {
  name: "AngleRightIcon",
  height: 512,
  width: 256,
  svgPath: "M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34z",
  yOffset: 0,
  xOffset: 0
};
var AngleRightIcon = createIcon(AngleRightIconConfig);
var CheckCircleIconConfig = {
  name: "CheckCircleIcon",
  height: 512,
  width: 512,
  svgPath: "M504 256c0 136.967-111.033 248-248 248S8 392.967 8 256 119.033 8 256 8s248 111.033 248 248zM227.314 387.314l184-184c6.248-6.248 6.248-16.379 0-22.627l-22.627-22.627c-6.248-6.249-16.379-6.249-22.628 0L216 308.118l-70.059-70.059c-6.248-6.248-16.379-6.248-22.628 0l-22.627 22.627c-6.248 6.248-6.248 16.379 0 22.627l104 104c6.249 6.249 16.379 6.249 22.628.001z",
  yOffset: 0,
  xOffset: 0
};
var CheckCircleIcon = createIcon(CheckCircleIconConfig);
var ExclamationCircleIconConfig = {
  name: "ExclamationCircleIcon",
  height: 512,
  width: 512,
  svgPath: "M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z",
  yOffset: 0,
  xOffset: 0
};
var ExclamationCircleIcon = createIcon(ExclamationCircleIconConfig);
var InfoCircleIconConfig = {
  name: "InfoCircleIcon",
  height: 512,
  width: 512,
  svgPath: "M256 8C119.043 8 8 119.083 8 256c0 136.997 111.043 248 248 248s248-111.003 248-248C504 119.083 392.957 8 256 8zm0 110c23.196 0 42 18.804 42 42s-18.804 42-42 42-42-18.804-42-42 18.804-42 42-42zm56 254c0 6.627-5.373 12-12 12h-88c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h12v-64h-12c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h64c6.627 0 12 5.373 12 12v100h12c6.627 0 12 5.373 12 12v24z",
  yOffset: 0,
  xOffset: 0
};
var InfoCircleIcon = createIcon(InfoCircleIconConfig);
var CaretDownIconConfig = {
  name: "CaretDownIcon",
  height: 512,
  width: 320,
  svgPath: "M31.3 192h257.3c17.8 0 26.7 21.5 14.1 34.1L174.1 354.8c-7.8 7.8-20.5 7.8-28.3 0L17.2 226.1C4.6 213.5 13.5 192 31.3 192z",
  yOffset: 0,
  xOffset: 0
};
var CaretDownIcon = createIcon(CaretDownIconConfig);
var SearchIconConfig = {
  name: "SearchIcon",
  height: 512,
  width: 512,
  svgPath: "M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z",
  yOffset: 0,
  xOffset: 0
};
var SearchIcon = createIcon(SearchIconConfig);
var PlusIconConfig = {
  name: "PlusIcon",
  height: 512,
  width: 448,
  svgPath: "M416 208H272V64c0-17.67-14.33-32-32-32h-32c-17.67 0-32 14.33-32 32v144H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h144v144c0 17.67 14.33 32 32 32h32c17.67 0 32-14.33 32-32V304h144c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z",
  yOffset: 0,
  xOffset: 0
};
var PlusIcon = createIcon(PlusIconConfig);

// build/_snowpack/pkg/common/data-list-0711ea37.js
var dataList = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    dataList: "pf-c-data-list",
    dataListAction: "pf-c-data-list__action",
    dataListCell: "pf-c-data-list__cell",
    dataListCheck: "pf-c-data-list__check",
    dataListExpandableContent: "pf-c-data-list__expandable-content",
    dataListExpandableContentBody: "pf-c-data-list__expandable-content-body",
    dataListItem: "pf-c-data-list__item",
    dataListItemAction: "pf-c-data-list__item-action",
    dataListItemContent: "pf-c-data-list__item-content",
    dataListItemControl: "pf-c-data-list__item-control",
    dataListItemDraggableButton: "pf-c-data-list__item-draggable-button",
    dataListItemDraggableIcon: "pf-c-data-list__item-draggable-icon",
    dataListItemRow: "pf-c-data-list__item-row",
    dataListText: "pf-c-data-list__text",
    dataListToggle: "pf-c-data-list__toggle",
    dataListToggleIcon: "pf-c-data-list__toggle-icon",
    modifiers: {
      hidden: "pf-m-hidden",
      hiddenOnSm: "pf-m-hidden-on-sm",
      visibleOnSm: "pf-m-visible-on-sm",
      hiddenOnMd: "pf-m-hidden-on-md",
      visibleOnMd: "pf-m-visible-on-md",
      hiddenOnLg: "pf-m-hidden-on-lg",
      visibleOnLg: "pf-m-visible-on-lg",
      hiddenOnXl: "pf-m-hidden-on-xl",
      visibleOnXl: "pf-m-visible-on-xl",
      hiddenOn_2xl: "pf-m-hidden-on-2xl",
      visibleOn_2xl: "pf-m-visible-on-2xl",
      icon: "pf-m-icon",
      alignRight: "pf-m-align-right",
      noFill: "pf-m-no-fill",
      flex_2: "pf-m-flex-2",
      flex_3: "pf-m-flex-3",
      flex_4: "pf-m-flex-4",
      flex_5: "pf-m-flex-5",
      gridNone: "pf-m-grid-none",
      gridSm: "pf-m-grid-sm",
      gridMd: "pf-m-grid-md",
      gridLg: "pf-m-grid-lg",
      gridXl: "pf-m-grid-xl",
      grid_2xl: "pf-m-grid-2xl",
      compact: "pf-m-compact",
      dragOver: "pf-m-drag-over",
      truncate: "pf-m-truncate",
      breakWord: "pf-m-break-word",
      nowrap: "pf-m-nowrap",
      selectable: "pf-m-selectable",
      selected: "pf-m-selected",
      ghostRow: "pf-m-ghost-row",
      expanded: "pf-m-expanded",
      disabled: "pf-m-disabled",
      noPadding: "pf-m-no-padding"
    }
  };
});
var __pika_web_default_export_for_treeshaking__2 = /* @__PURE__ */ getDefaultExportFromCjs(dataList);

// build/_snowpack/pkg/common/index-ad697a84.js
var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
function emptyFunction() {
}
function emptyFunctionWithReset() {
}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
var factoryWithThrowingShims = function() {
  function shim(props, propName, componentName, location2, propFullName, secret) {
    if (secret === ReactPropTypesSecret_1) {
      return;
    }
    var err = new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");
    err.name = "Invariant Violation";
    throw err;
  }
  shim.isRequired = shim;
  function getShim() {
    return shim;
  }
  var ReactPropTypes = {
    array: shim,
    bool: shim,
    func: shim,
    number: shim,
    object: shim,
    string: shim,
    symbol: shim,
    any: shim,
    arrayOf: getShim,
    element: shim,
    elementType: shim,
    instanceOf: getShim,
    node: shim,
    objectOf: getShim,
    oneOf: getShim,
    oneOfType: getShim,
    shape: getShim,
    exact: getShim,
    checkPropTypes: emptyFunctionWithReset,
    resetWarningCache: emptyFunction
  };
  ReactPropTypes.PropTypes = ReactPropTypes;
  return ReactPropTypes;
};
var propTypes = createCommonjsModule(function(module2) {
  {
    module2.exports = factoryWithThrowingShims();
  }
});

// build/_snowpack/pkg/common/index-9f254119.js
var getResizeObserver = (containerRefElement, handleResize) => {
  let unobserve;
  if (canUseDOM) {
    const {ResizeObserver: ResizeObserver2} = window;
    if (containerRefElement && ResizeObserver2) {
      const resizeObserver = new ResizeObserver2((entries) => {
        window.requestAnimationFrame(() => {
          if (Array.isArray(entries) && entries.length > 0) {
            handleResize();
          }
        });
      });
      resizeObserver.observe(containerRefElement);
      unobserve = () => resizeObserver.unobserve(containerRefElement);
    } else {
      window.addEventListener("resize", handleResize);
      unobserve = () => window.removeEventListener("resize", handleResize);
    }
  }
  return () => {
    if (unobserve) {
      unobserve();
    }
  };
};
var CopyIconConfig = {
  name: "CopyIcon",
  height: 512,
  width: 448,
  svgPath: "M320 448v40c0 13.255-10.745 24-24 24H24c-13.255 0-24-10.745-24-24V120c0-13.255 10.745-24 24-24h72v296c0 30.879 25.121 56 56 56h168zm0-344V0H152c-13.255 0-24 10.745-24 24v368c0 13.255 10.745 24 24 24h272c13.255 0 24-10.745 24-24V128H344c-13.2 0-24-10.8-24-24zm120.971-31.029L375.029 7.029A24 24 0 0 0 358.059 0H352v96h96v-6.059a24 24 0 0 0-7.029-16.97z",
  yOffset: 0,
  xOffset: 0
};
var CopyIcon = createIcon(CopyIconConfig);
var EmptyStateBody = (_a) => {
  var {children: children2, className = ""} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("div", Object.assign({className: css(styles$3.emptyStateBody, className)}, props), children2);
};
EmptyStateBody.displayName = "EmptyStateBody";
var EmptyStateIcon = (_a) => {
  var {className = "", icon: IconComponent, component: AnyComponent, variant = "icon"} = _a, props = __rest(_a, ["className", "icon", "component", "variant"]);
  const classNames2 = css(styles$3.emptyStateIcon, className);
  return variant === "icon" ? react.createElement(IconComponent, Object.assign({className: classNames2}, props, {"aria-hidden": "true"})) : react.createElement("div", {className: classNames2}, react.createElement(AnyComponent, null));
};
EmptyStateIcon.displayName = "EmptyStateIcon";
var EmptyStateSecondaryActions = (_a) => {
  var {children: children2 = null, className = ""} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("div", Object.assign({className: css(styles$3.emptyStateSecondary, className)}, props), children2);
};
EmptyStateSecondaryActions.displayName = "EmptyStateSecondaryActions";
var COMMON_MIME_TYPES = new Map([
  ["avi", "video/avi"],
  ["gif", "image/gif"],
  ["ico", "image/x-icon"],
  ["jpeg", "image/jpeg"],
  ["jpg", "image/jpeg"],
  ["mkv", "video/x-matroska"],
  ["mov", "video/quicktime"],
  ["mp4", "video/mp4"],
  ["pdf", "application/pdf"],
  ["png", "image/png"],
  ["zip", "application/zip"],
  ["doc", "application/msword"],
  ["docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
]);
function toFileWithPath(file, path) {
  var f2 = withMimeType(file);
  if (typeof f2.path !== "string") {
    var webkitRelativePath = file.webkitRelativePath;
    Object.defineProperty(f2, "path", {
      value: typeof path === "string" ? path : typeof webkitRelativePath === "string" && webkitRelativePath.length > 0 ? webkitRelativePath : file.name,
      writable: false,
      configurable: false,
      enumerable: true
    });
  }
  return f2;
}
function withMimeType(file) {
  var name = file.name;
  var hasExtension = name && name.lastIndexOf(".") !== -1;
  if (hasExtension && !file.type) {
    var ext = name.split(".").pop().toLowerCase();
    var type = COMMON_MIME_TYPES.get(ext);
    if (type) {
      Object.defineProperty(file, "type", {
        value: type,
        writable: false,
        configurable: false,
        enumerable: true
      });
    }
  }
  return file;
}
var FILES_TO_IGNORE = [
  ".DS_Store",
  "Thumbs.db"
];
function fromEvent(evt) {
  return __awaiter(this, void 0, void 0, function() {
    return __generator(this, function(_a) {
      return [2, isDragEvt(evt) && evt.dataTransfer ? getDataTransferFiles(evt.dataTransfer, evt.type) : getInputFiles(evt)];
    });
  });
}
function isDragEvt(value) {
  return !!value.dataTransfer;
}
function getInputFiles(evt) {
  var files = isInput3(evt.target) ? evt.target.files ? fromList(evt.target.files) : [] : [];
  return files.map(function(file) {
    return toFileWithPath(file);
  });
}
function isInput3(value) {
  return value !== null;
}
function getDataTransferFiles(dt, type) {
  return __awaiter(this, void 0, void 0, function() {
    var items, files;
    return __generator(this, function(_a) {
      switch (_a.label) {
        case 0:
          if (!dt.items)
            return [3, 2];
          items = fromList(dt.items).filter(function(item) {
            return item.kind === "file";
          });
          if (type !== "drop") {
            return [2, items];
          }
          return [4, Promise.all(items.map(toFilePromises))];
        case 1:
          files = _a.sent();
          return [2, noIgnoredFiles(flatten(files))];
        case 2:
          return [2, noIgnoredFiles(fromList(dt.files).map(function(file) {
            return toFileWithPath(file);
          }))];
      }
    });
  });
}
function noIgnoredFiles(files) {
  return files.filter(function(file) {
    return FILES_TO_IGNORE.indexOf(file.name) === -1;
  });
}
function fromList(items) {
  var files = [];
  for (var i3 = 0; i3 < items.length; i3++) {
    var file = items[i3];
    files.push(file);
  }
  return files;
}
function toFilePromises(item) {
  if (typeof item.webkitGetAsEntry !== "function") {
    return fromDataTransferItem(item);
  }
  var entry = item.webkitGetAsEntry();
  if (entry && entry.isDirectory) {
    return fromDirEntry(entry);
  }
  return fromDataTransferItem(item);
}
function flatten(items) {
  return items.reduce(function(acc, files) {
    return __spread(acc, Array.isArray(files) ? flatten(files) : [files]);
  }, []);
}
function fromDataTransferItem(item) {
  var file = item.getAsFile();
  if (!file) {
    return Promise.reject(item + " is not a File");
  }
  var fwp = toFileWithPath(file);
  return Promise.resolve(fwp);
}
function fromEntry(entry) {
  return __awaiter(this, void 0, void 0, function() {
    return __generator(this, function(_a) {
      return [2, entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry)];
    });
  });
}
function fromDirEntry(entry) {
  var reader = entry.createReader();
  return new Promise(function(resolve2, reject) {
    var entries = [];
    function readEntries() {
      var _this = this;
      reader.readEntries(function(batch2) {
        return __awaiter(_this, void 0, void 0, function() {
          var files, err_1, items;
          return __generator(this, function(_a) {
            switch (_a.label) {
              case 0:
                if (!!batch2.length)
                  return [3, 5];
                _a.label = 1;
              case 1:
                _a.trys.push([1, 3, , 4]);
                return [4, Promise.all(entries)];
              case 2:
                files = _a.sent();
                resolve2(files);
                return [3, 4];
              case 3:
                err_1 = _a.sent();
                reject(err_1);
                return [3, 4];
              case 4:
                return [3, 6];
              case 5:
                items = Promise.all(batch2.map(fromEntry));
                entries.push(items);
                readEntries();
                _a.label = 6;
              case 6:
                return [2];
            }
          });
        });
      }, function(err) {
        reject(err);
      });
    }
    readEntries();
  });
}
function fromFileEntry(entry) {
  return __awaiter(this, void 0, void 0, function() {
    return __generator(this, function(_a) {
      return [2, new Promise(function(resolve2, reject) {
        entry.file(function(file) {
          var fwp = toFileWithPath(file, entry.fullPath);
          resolve2(fwp);
        }, function(err) {
          reject(err);
        });
      })];
    });
  });
}
var dist2 = createCommonjsModule(function(module2) {
  module2.exports = function(t5) {
    function n3(e2) {
      if (r3[e2])
        return r3[e2].exports;
      var o = r3[e2] = {i: e2, l: false, exports: {}};
      return t5[e2].call(o.exports, o, o.exports, n3), o.l = true, o.exports;
    }
    var r3 = {};
    return n3.m = t5, n3.c = r3, n3.d = function(t6, r4, e2) {
      n3.o(t6, r4) || Object.defineProperty(t6, r4, {configurable: false, enumerable: true, get: e2});
    }, n3.n = function(t6) {
      var r4 = t6 && t6.__esModule ? function() {
        return t6.default;
      } : function() {
        return t6;
      };
      return n3.d(r4, "a", r4), r4;
    }, n3.o = function(t6, n4) {
      return Object.prototype.hasOwnProperty.call(t6, n4);
    }, n3.p = "", n3(n3.s = 13);
  }([function(t5, n3) {
    var r3 = t5.exports = typeof window != "undefined" && window.Math == Math ? window : typeof self != "undefined" && self.Math == Math ? self : Function("return this")();
    typeof __g == "number" && (__g = r3);
  }, function(t5, n3) {
    t5.exports = function(t6) {
      return typeof t6 == "object" ? t6 !== null : typeof t6 == "function";
    };
  }, function(t5, n3) {
    var r3 = t5.exports = {version: "2.5.0"};
    typeof __e == "number" && (__e = r3);
  }, function(t5, n3, r3) {
    t5.exports = !r3(4)(function() {
      return Object.defineProperty({}, "a", {get: function() {
        return 7;
      }}).a != 7;
    });
  }, function(t5, n3) {
    t5.exports = function(t6) {
      try {
        return !!t6();
      } catch (t7) {
        return true;
      }
    };
  }, function(t5, n3) {
    var r3 = {}.toString;
    t5.exports = function(t6) {
      return r3.call(t6).slice(8, -1);
    };
  }, function(t5, n3, r3) {
    var e2 = r3(32)("wks"), o = r3(9), i3 = r3(0).Symbol, u = typeof i3 == "function";
    (t5.exports = function(t6) {
      return e2[t6] || (e2[t6] = u && i3[t6] || (u ? i3 : o)("Symbol." + t6));
    }).store = e2;
  }, function(t5, n3, r3) {
    var e2 = r3(0), o = r3(2), i3 = r3(8), u = r3(22), c3 = r3(10), f2 = function(t6, n4, r4) {
      var a2, s2, p2, l2, v2 = t6 & f2.F, y3 = t6 & f2.G, h2 = t6 & f2.S, d2 = t6 & f2.P, x2 = t6 & f2.B, g2 = y3 ? e2 : h2 ? e2[n4] || (e2[n4] = {}) : (e2[n4] || {}).prototype, m2 = y3 ? o : o[n4] || (o[n4] = {}), b2 = m2.prototype || (m2.prototype = {});
      y3 && (r4 = n4);
      for (a2 in r4)
        s2 = !v2 && g2 && g2[a2] !== void 0, p2 = (s2 ? g2 : r4)[a2], l2 = x2 && s2 ? c3(p2, e2) : d2 && typeof p2 == "function" ? c3(Function.call, p2) : p2, g2 && u(g2, a2, p2, t6 & f2.U), m2[a2] != p2 && i3(m2, a2, l2), d2 && b2[a2] != p2 && (b2[a2] = p2);
    };
    e2.core = o, f2.F = 1, f2.G = 2, f2.S = 4, f2.P = 8, f2.B = 16, f2.W = 32, f2.U = 64, f2.R = 128, t5.exports = f2;
  }, function(t5, n3, r3) {
    var e2 = r3(16), o = r3(21);
    t5.exports = r3(3) ? function(t6, n4, r4) {
      return e2.f(t6, n4, o(1, r4));
    } : function(t6, n4, r4) {
      return t6[n4] = r4, t6;
    };
  }, function(t5, n3) {
    var r3 = 0, e2 = Math.random();
    t5.exports = function(t6) {
      return "Symbol(".concat(t6 === void 0 ? "" : t6, ")_", (++r3 + e2).toString(36));
    };
  }, function(t5, n3, r3) {
    var e2 = r3(24);
    t5.exports = function(t6, n4, r4) {
      if (e2(t6), n4 === void 0)
        return t6;
      switch (r4) {
        case 1:
          return function(r5) {
            return t6.call(n4, r5);
          };
        case 2:
          return function(r5, e3) {
            return t6.call(n4, r5, e3);
          };
        case 3:
          return function(r5, e3, o) {
            return t6.call(n4, r5, e3, o);
          };
      }
      return function() {
        return t6.apply(n4, arguments);
      };
    };
  }, function(t5, n3) {
    t5.exports = function(t6) {
      if (t6 == void 0)
        throw TypeError("Can't call method on  " + t6);
      return t6;
    };
  }, function(t5, n3, r3) {
    var e2 = r3(28), o = Math.min;
    t5.exports = function(t6) {
      return t6 > 0 ? o(e2(t6), 9007199254740991) : 0;
    };
  }, function(t5, n3, r3) {
    n3.__esModule = true, n3.default = function(t6, n4) {
      if (t6 && n4) {
        var r4 = Array.isArray(n4) ? n4 : n4.split(","), e2 = t6.name || "", o = t6.type || "", i3 = o.replace(/\/.*$/, "");
        return r4.some(function(t7) {
          var n5 = t7.trim();
          return n5.charAt(0) === "." ? e2.toLowerCase().endsWith(n5.toLowerCase()) : n5.endsWith("/*") ? i3 === n5.replace(/\/.*$/, "") : o === n5;
        });
      }
      return true;
    }, r3(14), r3(34);
  }, function(t5, n3, r3) {
    r3(15), t5.exports = r3(2).Array.some;
  }, function(t5, n3, r3) {
    var e2 = r3(7), o = r3(25)(3);
    e2(e2.P + e2.F * !r3(33)([].some, true), "Array", {some: function(t6) {
      return o(this, t6, arguments[1]);
    }});
  }, function(t5, n3, r3) {
    var e2 = r3(17), o = r3(18), i3 = r3(20), u = Object.defineProperty;
    n3.f = r3(3) ? Object.defineProperty : function(t6, n4, r4) {
      if (e2(t6), n4 = i3(n4, true), e2(r4), o)
        try {
          return u(t6, n4, r4);
        } catch (t7) {
        }
      if ("get" in r4 || "set" in r4)
        throw TypeError("Accessors not supported!");
      return "value" in r4 && (t6[n4] = r4.value), t6;
    };
  }, function(t5, n3, r3) {
    var e2 = r3(1);
    t5.exports = function(t6) {
      if (!e2(t6))
        throw TypeError(t6 + " is not an object!");
      return t6;
    };
  }, function(t5, n3, r3) {
    t5.exports = !r3(3) && !r3(4)(function() {
      return Object.defineProperty(r3(19)("div"), "a", {get: function() {
        return 7;
      }}).a != 7;
    });
  }, function(t5, n3, r3) {
    var e2 = r3(1), o = r3(0).document, i3 = e2(o) && e2(o.createElement);
    t5.exports = function(t6) {
      return i3 ? o.createElement(t6) : {};
    };
  }, function(t5, n3, r3) {
    var e2 = r3(1);
    t5.exports = function(t6, n4) {
      if (!e2(t6))
        return t6;
      var r4, o;
      if (n4 && typeof (r4 = t6.toString) == "function" && !e2(o = r4.call(t6)))
        return o;
      if (typeof (r4 = t6.valueOf) == "function" && !e2(o = r4.call(t6)))
        return o;
      if (!n4 && typeof (r4 = t6.toString) == "function" && !e2(o = r4.call(t6)))
        return o;
      throw TypeError("Can't convert object to primitive value");
    };
  }, function(t5, n3) {
    t5.exports = function(t6, n4) {
      return {enumerable: !(1 & t6), configurable: !(2 & t6), writable: !(4 & t6), value: n4};
    };
  }, function(t5, n3, r3) {
    var e2 = r3(0), o = r3(8), i3 = r3(23), u = r3(9)("src"), c3 = Function.toString, f2 = ("" + c3).split("toString");
    r3(2).inspectSource = function(t6) {
      return c3.call(t6);
    }, (t5.exports = function(t6, n4, r4, c4) {
      var a2 = typeof r4 == "function";
      a2 && (i3(r4, "name") || o(r4, "name", n4)), t6[n4] !== r4 && (a2 && (i3(r4, u) || o(r4, u, t6[n4] ? "" + t6[n4] : f2.join(String(n4)))), t6 === e2 ? t6[n4] = r4 : c4 ? t6[n4] ? t6[n4] = r4 : o(t6, n4, r4) : (delete t6[n4], o(t6, n4, r4)));
    })(Function.prototype, "toString", function() {
      return typeof this == "function" && this[u] || c3.call(this);
    });
  }, function(t5, n3) {
    var r3 = {}.hasOwnProperty;
    t5.exports = function(t6, n4) {
      return r3.call(t6, n4);
    };
  }, function(t5, n3) {
    t5.exports = function(t6) {
      if (typeof t6 != "function")
        throw TypeError(t6 + " is not a function!");
      return t6;
    };
  }, function(t5, n3, r3) {
    var e2 = r3(10), o = r3(26), i3 = r3(27), u = r3(12), c3 = r3(29);
    t5.exports = function(t6, n4) {
      var r4 = t6 == 1, f2 = t6 == 2, a2 = t6 == 3, s2 = t6 == 4, p2 = t6 == 6, l2 = t6 == 5 || p2, v2 = n4 || c3;
      return function(n5, c4, y3) {
        for (var h2, d2, x2 = i3(n5), g2 = o(x2), m2 = e2(c4, y3, 3), b2 = u(g2.length), _23 = 0, w2 = r4 ? v2(n5, b2) : f2 ? v2(n5, 0) : void 0; b2 > _23; _23++)
          if ((l2 || _23 in g2) && (h2 = g2[_23], d2 = m2(h2, _23, x2), t6)) {
            if (r4)
              w2[_23] = d2;
            else if (d2)
              switch (t6) {
                case 3:
                  return true;
                case 5:
                  return h2;
                case 6:
                  return _23;
                case 2:
                  w2.push(h2);
              }
            else if (s2)
              return false;
          }
        return p2 ? -1 : a2 || s2 ? s2 : w2;
      };
    };
  }, function(t5, n3, r3) {
    var e2 = r3(5);
    t5.exports = Object("z").propertyIsEnumerable(0) ? Object : function(t6) {
      return e2(t6) == "String" ? t6.split("") : Object(t6);
    };
  }, function(t5, n3, r3) {
    var e2 = r3(11);
    t5.exports = function(t6) {
      return Object(e2(t6));
    };
  }, function(t5, n3) {
    var r3 = Math.ceil, e2 = Math.floor;
    t5.exports = function(t6) {
      return isNaN(t6 = +t6) ? 0 : (t6 > 0 ? e2 : r3)(t6);
    };
  }, function(t5, n3, r3) {
    var e2 = r3(30);
    t5.exports = function(t6, n4) {
      return new (e2(t6))(n4);
    };
  }, function(t5, n3, r3) {
    var e2 = r3(1), o = r3(31), i3 = r3(6)("species");
    t5.exports = function(t6) {
      var n4;
      return o(t6) && (n4 = t6.constructor, typeof n4 != "function" || n4 !== Array && !o(n4.prototype) || (n4 = void 0), e2(n4) && (n4 = n4[i3]) === null && (n4 = void 0)), n4 === void 0 ? Array : n4;
    };
  }, function(t5, n3, r3) {
    var e2 = r3(5);
    t5.exports = Array.isArray || function(t6) {
      return e2(t6) == "Array";
    };
  }, function(t5, n3, r3) {
    var e2 = r3(0), o = e2["__core-js_shared__"] || (e2["__core-js_shared__"] = {});
    t5.exports = function(t6) {
      return o[t6] || (o[t6] = {});
    };
  }, function(t5, n3, r3) {
    var e2 = r3(4);
    t5.exports = function(t6, n4) {
      return !!t6 && e2(function() {
        n4 ? t6.call(null, function() {
        }, 1) : t6.call(null);
      });
    };
  }, function(t5, n3, r3) {
    r3(35), t5.exports = r3(2).String.endsWith;
  }, function(t5, n3, r3) {
    var e2 = r3(7), o = r3(12), i3 = r3(36), u = "".endsWith;
    e2(e2.P + e2.F * r3(38)("endsWith"), "String", {endsWith: function(t6) {
      var n4 = i3(this, t6, "endsWith"), r4 = arguments.length > 1 ? arguments[1] : void 0, e3 = o(n4.length), c3 = r4 === void 0 ? e3 : Math.min(o(r4), e3), f2 = String(t6);
      return u ? u.call(n4, f2, c3) : n4.slice(c3 - f2.length, c3) === f2;
    }});
  }, function(t5, n3, r3) {
    var e2 = r3(37), o = r3(11);
    t5.exports = function(t6, n4, r4) {
      if (e2(n4))
        throw TypeError("String#" + r4 + " doesn't accept regex!");
      return String(o(t6));
    };
  }, function(t5, n3, r3) {
    var e2 = r3(1), o = r3(5), i3 = r3(6)("match");
    t5.exports = function(t6) {
      var n4;
      return e2(t6) && ((n4 = t6[i3]) !== void 0 ? !!n4 : o(t6) == "RegExp");
    };
  }, function(t5, n3, r3) {
    var e2 = r3(6)("match");
    t5.exports = function(t6) {
      var n4 = /./;
      try {
        "/./"[t6](n4);
      } catch (r4) {
        try {
          return n4[e2] = false, !"/./"[t6](n4);
        } catch (t7) {
        }
      }
      return true;
    };
  }]);
});
var accepts = /* @__PURE__ */ getDefaultExportFromCjs(dist2);
var supportMultiple = typeof document !== "undefined" && document && document.createElement ? "multiple" in document.createElement("input") : true;
function fileAccepted(file, accept) {
  return file.type === "application/x-moz-file" || accepts(file, accept);
}
function fileMatchSize(file, maxSize, minSize) {
  return file.size <= maxSize && file.size >= minSize;
}
function allFilesAccepted(files, accept) {
  return files.every(function(file) {
    return fileAccepted(file, accept);
  });
}
function isPropagationStopped(evt) {
  if (typeof evt.isPropagationStopped === "function") {
    return evt.isPropagationStopped();
  } else if (typeof evt.cancelBubble !== "undefined") {
    return evt.cancelBubble;
  }
  return false;
}
function isDefaultPrevented(evt) {
  if (typeof evt.defaultPrevented !== "undefined") {
    return evt.defaultPrevented;
  } else if (typeof evt.isDefaultPrevented === "function") {
    return evt.isDefaultPrevented();
  }
  return false;
}
function isDragDataWithFiles(evt) {
  if (!evt.dataTransfer) {
    return true;
  }
  return Array.prototype.some.call(evt.dataTransfer.types, function(type) {
    return type === "Files" || type === "application/x-moz-file";
  });
}
function onDocumentDragOver(evt) {
  evt.preventDefault();
}
function isIe(userAgent2) {
  return userAgent2.indexOf("MSIE") !== -1 || userAgent2.indexOf("Trident/") !== -1;
}
function isEdge(userAgent2) {
  return userAgent2.indexOf("Edge/") !== -1;
}
function isIeOrEdge() {
  var userAgent2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : window.navigator.userAgent;
  return isIe(userAgent2) || isEdge(userAgent2);
}
function composeEventHandlers() {
  for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) {
    fns[_key] = arguments[_key];
  }
  return function(event) {
    for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      args[_key2 - 1] = arguments[_key2];
    }
    return fns.some(function(fn) {
      fn && fn.apply(void 0, [event].concat(args));
      return event.defaultPrevented;
    });
  };
}
var _extends = Object.assign || function(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3];
    for (var key in source2) {
      if (Object.prototype.hasOwnProperty.call(source2, key)) {
        target[key] = source2[key];
      }
    }
  }
  return target;
};
var _createClass = function() {
  function defineProperties(target, props) {
    for (var i3 = 0; i3 < props.length; i3++) {
      var descriptor = props[i3];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  return function(Constructor, protoProps, staticProps) {
    if (protoProps)
      defineProperties(Constructor.prototype, protoProps);
    if (staticProps)
      defineProperties(Constructor, staticProps);
    return Constructor;
  };
}();
function _defineProperty2(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {value, enumerable: true, configurable: true, writable: true});
  } else {
    obj[key] = value;
  }
  return obj;
}
function _objectWithoutProperties(obj, keys2) {
  var target = {};
  for (var i3 in obj) {
    if (keys2.indexOf(i3) >= 0)
      continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i3))
      continue;
    target[i3] = obj[i3];
  }
  return target;
}
function _toConsumableArray(arr) {
  if (Array.isArray(arr)) {
    for (var i3 = 0, arr2 = Array(arr.length); i3 < arr.length; i3++) {
      arr2[i3] = arr[i3];
    }
    return arr2;
  } else {
    return Array.from(arr);
  }
}
function _classCallCheck(instance2, Constructor) {
  if (!(instance2 instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _possibleConstructorReturn(self2, call) {
  if (!self2) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return call && (typeof call === "object" || typeof call === "function") ? call : self2;
}
function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, {constructor: {value: subClass, enumerable: false, writable: true, configurable: true}});
  if (superClass)
    Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Dropzone = function(_React$Component) {
  _inherits(Dropzone2, _React$Component);
  function Dropzone2() {
    var _ref;
    var _temp, _this, _ret;
    _classCallCheck(this, Dropzone2);
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Dropzone2.__proto__ || Object.getPrototypeOf(Dropzone2)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      draggedFiles: [],
      acceptedFiles: [],
      rejectedFiles: []
    }, _this.isFileDialogActive = false, _this.onDocumentDrop = function(evt) {
      if (_this.node && _this.node.contains(evt.target)) {
        return;
      }
      evt.preventDefault();
      _this.dragTargets = [];
    }, _this.onDragStart = function(evt) {
      evt.persist();
      if (_this.props.onDragStart && isDragDataWithFiles(evt)) {
        _this.props.onDragStart.call(_this, evt);
      }
    }, _this.onDragEnter = function(evt) {
      evt.preventDefault();
      if (_this.dragTargets.indexOf(evt.target) === -1) {
        _this.dragTargets.push(evt.target);
      }
      evt.persist();
      if (isDragDataWithFiles(evt)) {
        Promise.resolve(_this.props.getDataTransferItems(evt)).then(function(draggedFiles) {
          if (isPropagationStopped(evt)) {
            return;
          }
          _this.setState({
            draggedFiles,
            isDragActive: true
          });
        });
        if (_this.props.onDragEnter) {
          _this.props.onDragEnter.call(_this, evt);
        }
      }
    }, _this.onDragOver = function(evt) {
      evt.preventDefault();
      evt.persist();
      if (evt.dataTransfer) {
        evt.dataTransfer.dropEffect = "copy";
      }
      if (_this.props.onDragOver && isDragDataWithFiles(evt)) {
        _this.props.onDragOver.call(_this, evt);
      }
      return false;
    }, _this.onDragLeave = function(evt) {
      evt.preventDefault();
      evt.persist();
      _this.dragTargets = _this.dragTargets.filter(function(el) {
        return el !== evt.target && _this.node.contains(el);
      });
      if (_this.dragTargets.length > 0) {
        return;
      }
      _this.setState({
        isDragActive: false,
        draggedFiles: []
      });
      if (_this.props.onDragLeave && isDragDataWithFiles(evt)) {
        _this.props.onDragLeave.call(_this, evt);
      }
    }, _this.onDrop = function(evt) {
      var _this$props = _this.props, onDrop = _this$props.onDrop, onDropAccepted = _this$props.onDropAccepted, onDropRejected = _this$props.onDropRejected, multiple = _this$props.multiple, accept = _this$props.accept, getDataTransferItems = _this$props.getDataTransferItems;
      evt.preventDefault();
      evt.persist();
      _this.dragTargets = [];
      _this.isFileDialogActive = false;
      _this.draggedFiles = null;
      _this.setState({
        isDragActive: false,
        draggedFiles: []
      });
      if (isDragDataWithFiles(evt)) {
        Promise.resolve(getDataTransferItems(evt)).then(function(fileList) {
          var acceptedFiles = [];
          var rejectedFiles = [];
          if (isPropagationStopped(evt)) {
            return;
          }
          fileList.forEach(function(file) {
            if (fileAccepted(file, accept) && fileMatchSize(file, _this.props.maxSize, _this.props.minSize)) {
              acceptedFiles.push(file);
            } else {
              rejectedFiles.push(file);
            }
          });
          if (!multiple && acceptedFiles.length > 1) {
            rejectedFiles.push.apply(rejectedFiles, _toConsumableArray(acceptedFiles.splice(0)));
          }
          _this.setState({acceptedFiles, rejectedFiles}, function() {
            if (onDrop) {
              onDrop.call(_this, acceptedFiles, rejectedFiles, evt);
            }
            if (rejectedFiles.length > 0 && onDropRejected) {
              onDropRejected.call(_this, rejectedFiles, evt);
            }
            if (acceptedFiles.length > 0 && onDropAccepted) {
              onDropAccepted.call(_this, acceptedFiles, evt);
            }
          });
        });
      }
    }, _this.onClick = function(evt) {
      var onClick = _this.props.onClick;
      if (onClick) {
        onClick.call(_this, evt);
      }
      if (!isDefaultPrevented(evt)) {
        evt.stopPropagation();
        if (isIeOrEdge()) {
          setTimeout(_this.open, 0);
        } else {
          _this.open();
        }
      }
    }, _this.onInputElementClick = function(evt) {
      evt.stopPropagation();
    }, _this.onFileDialogCancel = function() {
      var onFileDialogCancel = _this.props.onFileDialogCancel;
      if (_this.isFileDialogActive) {
        setTimeout(function() {
          if (_this.input != null) {
            var files = _this.input.files;
            if (!files.length) {
              _this.isFileDialogActive = false;
              if (typeof onFileDialogCancel === "function") {
                onFileDialogCancel();
              }
            }
          }
        }, 300);
      }
    }, _this.onFocus = function(evt) {
      var onFocus = _this.props.onFocus;
      if (onFocus) {
        onFocus.call(_this, evt);
      }
      if (!isDefaultPrevented(evt)) {
        _this.setState({isFocused: true});
      }
    }, _this.onBlur = function(evt) {
      var onBlur = _this.props.onBlur;
      if (onBlur) {
        onBlur.call(_this, evt);
      }
      if (!isDefaultPrevented(evt)) {
        _this.setState({isFocused: false});
      }
    }, _this.onKeyDown = function(evt) {
      var onKeyDown = _this.props.onKeyDown;
      if (!_this.node.isEqualNode(evt.target)) {
        return;
      }
      if (onKeyDown) {
        onKeyDown.call(_this, evt);
      }
      if (!isDefaultPrevented(evt) && (evt.keyCode === 32 || evt.keyCode === 13)) {
        evt.preventDefault();
        _this.open();
      }
    }, _this.composeHandler = function(handler) {
      if (_this.props.disabled) {
        return null;
      }
      return handler;
    }, _this.getRootProps = function() {
      var _extends22;
      var _ref2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      var _ref2$refKey = _ref2.refKey, refKey = _ref2$refKey === void 0 ? "ref" : _ref2$refKey, onKeyDown = _ref2.onKeyDown, onFocus = _ref2.onFocus, onBlur = _ref2.onBlur, onClick = _ref2.onClick, onDragStart = _ref2.onDragStart, onDragEnter = _ref2.onDragEnter, onDragOver = _ref2.onDragOver, onDragLeave = _ref2.onDragLeave, onDrop = _ref2.onDrop, rest = _objectWithoutProperties(_ref2, ["refKey", "onKeyDown", "onFocus", "onBlur", "onClick", "onDragStart", "onDragEnter", "onDragOver", "onDragLeave", "onDrop"]);
      return _extends((_extends22 = {
        onKeyDown: _this.composeHandler(onKeyDown ? composeEventHandlers(onKeyDown, _this.onKeyDown) : _this.onKeyDown),
        onFocus: _this.composeHandler(onFocus ? composeEventHandlers(onFocus, _this.onFocus) : _this.onFocus),
        onBlur: _this.composeHandler(onBlur ? composeEventHandlers(onBlur, _this.onBlur) : _this.onBlur),
        onClick: _this.composeHandler(onClick ? composeEventHandlers(onClick, _this.onClick) : _this.onClick),
        onDragStart: _this.composeHandler(onDragStart ? composeEventHandlers(onDragStart, _this.onDragStart) : _this.onDragStart),
        onDragEnter: _this.composeHandler(onDragEnter ? composeEventHandlers(onDragEnter, _this.onDragEnter) : _this.onDragEnter),
        onDragOver: _this.composeHandler(onDragOver ? composeEventHandlers(onDragOver, _this.onDragOver) : _this.onDragOver),
        onDragLeave: _this.composeHandler(onDragLeave ? composeEventHandlers(onDragLeave, _this.onDragLeave) : _this.onDragLeave),
        onDrop: _this.composeHandler(onDrop ? composeEventHandlers(onDrop, _this.onDrop) : _this.onDrop)
      }, _defineProperty2(_extends22, refKey, _this.setNodeRef), _defineProperty2(_extends22, "tabIndex", _this.props.disabled ? -1 : 0), _extends22), rest);
    }, _this.getInputProps = function() {
      var _ref3 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      var _ref3$refKey = _ref3.refKey, refKey = _ref3$refKey === void 0 ? "ref" : _ref3$refKey, onChange = _ref3.onChange, onClick = _ref3.onClick, rest = _objectWithoutProperties(_ref3, ["refKey", "onChange", "onClick"]);
      var _this$props2 = _this.props, accept = _this$props2.accept, multiple = _this$props2.multiple, name = _this$props2.name;
      var inputProps = _defineProperty2({
        accept,
        type: "file",
        style: {display: "none"},
        multiple: supportMultiple && multiple,
        onChange: composeEventHandlers(onChange, _this.onDrop),
        onClick: composeEventHandlers(onClick, _this.onInputElementClick),
        autoComplete: "off",
        tabIndex: -1
      }, refKey, _this.setInputRef);
      if (name && name.length) {
        inputProps.name = name;
      }
      return _extends({}, inputProps, rest);
    }, _this.setNodeRef = function(node) {
      _this.node = node;
    }, _this.setInputRef = function(input) {
      _this.input = input;
    }, _this.open = function() {
      _this.isFileDialogActive = true;
      if (_this.input) {
        _this.input.value = null;
        _this.input.click();
      }
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }
  _createClass(Dropzone2, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var preventDropOnDocument = this.props.preventDropOnDocument;
      this.dragTargets = [];
      if (preventDropOnDocument) {
        document.addEventListener("dragover", onDocumentDragOver, false);
        document.addEventListener("drop", this.onDocumentDrop, false);
      }
      window.addEventListener("focus", this.onFileDialogCancel, false);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var preventDropOnDocument = this.props.preventDropOnDocument;
      if (preventDropOnDocument) {
        document.removeEventListener("dragover", onDocumentDragOver);
        document.removeEventListener("drop", this.onDocumentDrop);
      }
      window.removeEventListener("focus", this.onFileDialogCancel, false);
    }
  }, {
    key: "render",
    value: function render4() {
      var _props = this.props, children2 = _props.children, multiple = _props.multiple, disabled = _props.disabled;
      var _state = this.state, isDragActive = _state.isDragActive, isFocused = _state.isFocused, draggedFiles = _state.draggedFiles, acceptedFiles = _state.acceptedFiles, rejectedFiles = _state.rejectedFiles;
      var filesCount = draggedFiles.length;
      var isMultipleAllowed = multiple || filesCount <= 1;
      var isDragAccept = filesCount > 0 && allFilesAccepted(draggedFiles, this.props.accept);
      var isDragReject = filesCount > 0 && (!isDragAccept || !isMultipleAllowed);
      return children2({
        isDragActive,
        isDragAccept,
        isDragReject,
        draggedFiles,
        acceptedFiles,
        rejectedFiles,
        isFocused: isFocused && !disabled,
        getRootProps: this.getRootProps,
        getInputProps: this.getInputProps,
        open: this.open
      });
    }
  }]);
  return Dropzone2;
}(react.Component);
Dropzone.propTypes = {
  accept: propTypes.oneOfType([propTypes.string, propTypes.arrayOf(propTypes.string)]),
  children: propTypes.func,
  disabled: propTypes.bool,
  preventDropOnDocument: propTypes.bool,
  multiple: propTypes.bool,
  name: propTypes.string,
  maxSize: propTypes.number,
  minSize: propTypes.number,
  getDataTransferItems: propTypes.func,
  onClick: propTypes.func,
  onFocus: propTypes.func,
  onBlur: propTypes.func,
  onKeyDown: propTypes.func,
  onDrop: propTypes.func,
  onDropAccepted: propTypes.func,
  onDropRejected: propTypes.func,
  onDragStart: propTypes.func,
  onDragEnter: propTypes.func,
  onDragOver: propTypes.func,
  onDragLeave: propTypes.func,
  onFileDialogCancel: propTypes.func
};
Dropzone.defaultProps = {
  preventDropOnDocument: true,
  disabled: false,
  multiple: true,
  maxSize: Infinity,
  minSize: 0,
  getDataTransferItems: fromEvent
};

// build/_snowpack/pkg/@patternfly/react-core.js
var backdrop = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    backdrop: "pf-c-backdrop",
    backdropOpen: "pf-c-backdrop__open"
  };
});
var styles3 = /* @__PURE__ */ getDefaultExportFromCjs(backdrop);
var currentId2 = 0;
var GenerateId = class extends react.Component {
  constructor() {
    super(...arguments);
    this.id = `${this.props.prefix}${currentId2++}`;
  }
  render() {
    return this.props.children(this.id);
  }
};
GenerateId.displayName = "GenerateId";
GenerateId.defaultProps = {
  prefix: "pf-random-id-"
};
var ASTERISK = "*";
var content = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    content: "pf-c-content",
    modifiers: {
      visited: "pf-m-visited",
      overpassFont: "pf-m-overpass-font"
    }
  };
});
var styles$13 = /* @__PURE__ */ getDefaultExportFromCjs(content);
var Backdrop = (_a) => {
  var {children: children2 = null, className = ""} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("div", Object.assign({}, props, {className: css(styles3.backdrop, className)}), children2);
};
Backdrop.displayName = "Backdrop";
var alert2 = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    alert: "pf-c-alert",
    alertAction: "pf-c-alert__action",
    alertActionGroup: "pf-c-alert__action-group",
    alertDescription: "pf-c-alert__description",
    alertIcon: "pf-c-alert__icon",
    alertTitle: "pf-c-alert__title",
    alertToggle: "pf-c-alert__toggle",
    alertToggleIcon: "pf-c-alert__toggle-icon",
    button: "pf-c-button",
    modifiers: {
      success: "pf-m-success",
      danger: "pf-m-danger",
      warning: "pf-m-warning",
      info: "pf-m-info",
      inline: "pf-m-inline",
      plain: "pf-m-plain",
      expandable: "pf-m-expandable",
      expanded: "pf-m-expanded",
      truncate: "pf-m-truncate",
      overpassFont: "pf-m-overpass-font"
    }
  };
});
var styles$23 = /* @__PURE__ */ getDefaultExportFromCjs(alert2);
var accessibility = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    hidden: "pf-u-hidden",
    hiddenOnLg: "pf-u-hidden-on-lg",
    hiddenOnMd: "pf-u-hidden-on-md",
    hiddenOnSm: "pf-u-hidden-on-sm",
    hiddenOnXl: "pf-u-hidden-on-xl",
    hiddenOn_2xl: "pf-u-hidden-on-2xl",
    screenReader: "pf-u-screen-reader",
    screenReaderOnLg: "pf-u-screen-reader-on-lg",
    screenReaderOnMd: "pf-u-screen-reader-on-md",
    screenReaderOnSm: "pf-u-screen-reader-on-sm",
    screenReaderOnXl: "pf-u-screen-reader-on-xl",
    screenReaderOn_2xl: "pf-u-screen-reader-on-2xl",
    visible: "pf-u-visible",
    visibleOnLg: "pf-u-visible-on-lg",
    visibleOnMd: "pf-u-visible-on-md",
    visibleOnSm: "pf-u-visible-on-sm",
    visibleOnXl: "pf-u-visible-on-xl",
    visibleOn_2xl: "pf-u-visible-on-2xl"
  };
});
var a11yStyles = /* @__PURE__ */ getDefaultExportFromCjs(accessibility);
var ExclamationTriangleIconConfig = {
  name: "ExclamationTriangleIcon",
  height: 512,
  width: 576,
  svgPath: "M569.517 440.013C587.975 472.007 564.806 512 527.94 512H48.054c-36.937 0-59.999-40.055-41.577-71.987L246.423 23.985c18.467-32.009 64.72-31.951 83.154 0l239.94 416.028zM288 354c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z",
  yOffset: 0,
  xOffset: 0
};
var ExclamationTriangleIcon = createIcon(ExclamationTriangleIconConfig);
var BellIconConfig = {
  name: "BellIcon",
  height: 1024,
  width: 896,
  svgPath: "M448,0 C465.333333,0 480.333333,6.33333333 493,19 C505.666667,31.6666667 512,46.6666667 512,64 L512,106 L514.23,106.45 C587.89,121.39 648.48,157.24 696,214 C744,271.333333 768,338.666667 768,416 C768,500 780,568.666667 804,622 C818.666667,652.666667 841.333333,684 872,716 C873.773676,718.829136 875.780658,721.505113 878,724 C890,737.333333 896,752.333333 896,769 C896,785.666667 890,800.333333 878,813 C866,825.666667 850.666667,832 832,832 L63.3,832 C44.9533333,831.84 29.8533333,825.506667 18,813 C6,800.333333 0,785.666667 0,769 C0,752.333333 6,737.333333 18,724 L24,716 L25.06,714.9 C55.1933333,683.28 77.5066667,652.313333 92,622 C116,568.666667 128,500 128,416 C128,338.666667 152,271.333333 200,214 C248,156.666667 309.333333,120.666667 384,106 L384,63.31 C384.166667,46.27 390.5,31.5 403,19 C415.666667,6.33333333 430.666667,0 448,0 Z M576,896 L576,897.08 C575.74,932.6 563.073333,962.573333 538,987 C512.666667,1011.66667 482.666667,1024 448,1024 C413.333333,1024 383.333333,1011.66667 358,987 C332.666667,962.333333 320,932 320,896 L576,896 Z",
  yOffset: 0,
  xOffset: 0
};
var BellIcon = createIcon(BellIconConfig);
var variantIcons = {
  success: CheckCircleIcon,
  danger: ExclamationCircleIcon,
  warning: ExclamationTriangleIcon,
  info: InfoCircleIcon,
  default: BellIcon
};
var AlertIcon = (_a) => {
  var {variant, customIcon, className = ""} = _a, props = __rest(_a, ["variant", "customIcon", "className"]);
  const Icon = variantIcons[variant];
  return react.createElement("div", Object.assign({}, props, {className: css(styles$23.alertIcon, className)}), customIcon || react.createElement(Icon, null));
};
var AlertContext = react.createContext(null);
var c_alert__title_max_lines = {
  name: "--pf-c-alert__title--max-lines",
  value: "1",
  var: "var(--pf-c-alert__title--max-lines)"
};
var AlertToggleExpandButton = (_a) => {
  var {"aria-label": ariaLabel, variantLabel, onToggleExpand, isExpanded} = _a, props = __rest(_a, ["aria-label", "variantLabel", "onToggleExpand", "isExpanded"]);
  const {title: title3, variantLabel: alertVariantLabel} = react.useContext(AlertContext);
  return react.createElement(Button, Object.assign({variant: ButtonVariant.plain, onClick: onToggleExpand, "aria-expanded": isExpanded, "aria-label": ariaLabel === "" ? `Toggle ${variantLabel || alertVariantLabel} alert: ${title3}` : ariaLabel}, props), react.createElement("span", {className: css(styles$23.alertToggleIcon)}, react.createElement(AngleRightIcon, {"aria-hidden": "true"})));
};
AlertToggleExpandButton.displayName = "AlertToggleExpandButton";
var AlertVariant;
(function(AlertVariant2) {
  AlertVariant2["success"] = "success";
  AlertVariant2["danger"] = "danger";
  AlertVariant2["warning"] = "warning";
  AlertVariant2["info"] = "info";
  AlertVariant2["default"] = "default";
})(AlertVariant || (AlertVariant = {}));
var Alert = (_a) => {
  var {variant = AlertVariant.default, isInline = false, isPlain = false, isLiveRegion = false, variantLabel = `${capitalize2(variant)} alert:`, "aria-label": ariaLabel = `${capitalize2(variant)} Alert`, actionClose, actionLinks, title: title3, children: children2 = "", className = "", ouiaId, ouiaSafe = true, timeout: timeout3 = false, timeoutAnimation = 3e3, onTimeout = () => {
  }, truncateTitle = 0, tooltipPosition, customIcon, isExpandable = false, toggleAriaLabel = `${capitalize2(variant)} alert details`, onMouseEnter = () => {
  }, onMouseLeave = () => {
  }} = _a, props = __rest(_a, ["variant", "isInline", "isPlain", "isLiveRegion", "variantLabel", "aria-label", "actionClose", "actionLinks", "title", "children", "className", "ouiaId", "ouiaSafe", "timeout", "timeoutAnimation", "onTimeout", "truncateTitle", "tooltipPosition", "customIcon", "isExpandable", "toggleAriaLabel", "onMouseEnter", "onMouseLeave"]);
  const ouiaProps = useOUIAProps(Alert.displayName, ouiaId, ouiaSafe, variant);
  const getHeadingContent = react.createElement(react.Fragment, null, react.createElement("span", {className: css(a11yStyles.screenReader)}, variantLabel), title3);
  const titleRef = react.useRef(null);
  const divRef = react.useRef();
  const [isTooltipVisible, setIsTooltipVisible] = react.useState(false);
  react.useEffect(() => {
    if (!titleRef.current || !truncateTitle) {
      return;
    }
    titleRef.current.style.setProperty(c_alert__title_max_lines.name, truncateTitle.toString());
    const showTooltip = titleRef.current && titleRef.current.offsetHeight < titleRef.current.scrollHeight;
    if (isTooltipVisible !== showTooltip) {
      setIsTooltipVisible(showTooltip);
    }
  }, [titleRef, truncateTitle, isTooltipVisible]);
  const [timedOut, setTimedOut] = react.useState(false);
  const [timedOutAnimation, setTimedOutAnimation] = react.useState(true);
  const [isMouseOver, setIsMouseOver] = react.useState();
  const [containsFocus, setContainsFocus] = react.useState();
  const dismissed = timedOut && timedOutAnimation && !isMouseOver && !containsFocus;
  react.useEffect(() => {
    timeout3 = timeout3 === true ? 8e3 : Number(timeout3);
    if (timeout3 > 0) {
      const timer2 = setTimeout(() => setTimedOut(true), timeout3);
      return () => clearTimeout(timer2);
    }
  }, []);
  react.useEffect(() => {
    const onDocumentFocus = () => {
      if (divRef.current) {
        if (divRef.current.contains(document.activeElement)) {
          setContainsFocus(true);
          setTimedOutAnimation(false);
        } else if (containsFocus) {
          setContainsFocus(false);
        }
      }
    };
    document.addEventListener("focus", onDocumentFocus, true);
    return () => document.removeEventListener("focus", onDocumentFocus, true);
  }, [containsFocus]);
  react.useEffect(() => {
    if (containsFocus === false || isMouseOver === false) {
      const timer2 = setTimeout(() => setTimedOutAnimation(true), timeoutAnimation);
      return () => clearTimeout(timer2);
    }
  }, [containsFocus, isMouseOver]);
  react.useEffect(() => {
    dismissed && onTimeout();
  }, [dismissed]);
  const [isExpanded, setIsExpanded] = react.useState(false);
  const onToggleExpand = () => {
    setIsExpanded(!isExpanded);
  };
  const myOnMouseEnter = (ev) => {
    setIsMouseOver(true);
    setTimedOutAnimation(false);
    onMouseEnter(ev);
  };
  const myOnMouseLeave = (ev) => {
    setIsMouseOver(false);
    onMouseLeave(ev);
  };
  if (dismissed) {
    return null;
  }
  const Title2 = react.createElement("h4", Object.assign({}, isTooltipVisible && {tabIndex: 0}, {ref: titleRef, className: css(styles$23.alertTitle, truncateTitle && styles$23.modifiers.truncate)}), getHeadingContent);
  return react.createElement("div", Object.assign({ref: divRef, className: css(styles$23.alert, isInline && styles$23.modifiers.inline, isPlain && styles$23.modifiers.plain, isExpandable && styles$23.modifiers.expandable, isExpanded && styles$23.modifiers.expanded, styles$23.modifiers[variant], className), "aria-label": ariaLabel}, ouiaProps, isLiveRegion && {
    "aria-live": "polite",
    "aria-atomic": "false"
  }, {onMouseEnter: myOnMouseEnter, onMouseLeave: myOnMouseLeave}, props), isExpandable && react.createElement(AlertContext.Provider, {value: {title: title3, variantLabel}}, react.createElement("div", {className: css(styles$23.alertToggle)}, react.createElement(AlertToggleExpandButton, {isExpanded, onToggleExpand, "aria-label": toggleAriaLabel}))), react.createElement(AlertIcon, {variant, customIcon}), isTooltipVisible ? react.createElement(Tooltip, {content: getHeadingContent, position: tooltipPosition}, Title2) : Title2, actionClose && react.createElement(AlertContext.Provider, {value: {title: title3, variantLabel}}, react.createElement("div", {className: css(styles$23.alertAction)}, actionClose)), children2 && (!isExpandable || isExpandable && isExpanded) && react.createElement("div", {className: css(styles$23.alertDescription)}, children2), actionLinks && react.createElement("div", {className: css(styles$23.alertActionGroup)}, actionLinks));
};
Alert.displayName = "Alert";
var AlertActionCloseButton = (_a) => {
  var {
    className = "",
    onClose = () => void 0,
    "aria-label": ariaLabel = "",
    variantLabel
  } = _a, props = __rest(_a, ["className", "onClose", "aria-label", "variantLabel"]);
  return react.createElement(AlertContext.Consumer, null, ({title: title3, variantLabel: alertVariantLabel}) => react.createElement(Button, Object.assign({variant: ButtonVariant.plain, onClick: onClose, "aria-label": ariaLabel === "" ? `Close ${variantLabel || alertVariantLabel} alert: ${title3}` : ariaLabel}, props), react.createElement(TimesIcon, null)));
};
AlertActionCloseButton.displayName = "AlertActionCloseButton";
var AlertActionLink = (_a) => {
  var {className = "", children: children2} = _a, props = __rest(_a, ["className", "children"]);
  return react.createElement(Button, Object.assign({variant: ButtonVariant.link, isInline: true, className}, props), children2);
};
AlertActionLink.displayName = "AlertActionLink";
var alertGroup = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    alertGroup: "pf-c-alert-group",
    modifiers: {
      toast: "pf-m-toast"
    }
  };
});
var styles$33 = /* @__PURE__ */ getDefaultExportFromCjs(alertGroup);
var AlertGroupInline = (_a) => {
  var {className, children: children2, isToast, isLiveRegion} = _a, rest = __rest(_a, ["className", "children", "isToast", "isLiveRegion"]);
  return react.createElement("ul", Object.assign({"aria-live": isLiveRegion ? "polite" : null, "aria-atomic": isLiveRegion ? false : null, className: css(styles$33.alertGroup, className, isToast ? styles$33.modifiers.toast : "")}, rest), react.Children.toArray(children2).map((Alert2, index3) => react.createElement("li", {key: index3}, Alert2)));
};
AlertGroupInline.displayName = "AlertGroupInline";
var AlertGroup = class extends react.Component {
  constructor() {
    super(...arguments);
    this.state = {
      container: void 0
    };
  }
  componentDidMount() {
    const container = document.createElement("div");
    const target = this.getTargetElement();
    this.setState({container});
    target.appendChild(container);
  }
  componentWillUnmount() {
    const target = this.getTargetElement();
    if (this.state.container) {
      target.removeChild(this.state.container);
    }
  }
  getTargetElement() {
    const appendTo = this.props.appendTo;
    if (typeof appendTo === "function") {
      return appendTo();
    }
    return appendTo || document.body;
  }
  render() {
    const _a = this.props, {className, children: children2, isToast, isLiveRegion} = _a, props = __rest(_a, ["className", "children", "isToast", "isLiveRegion"]);
    const alertGroup2 = react.createElement(AlertGroupInline, Object.assign({className, isToast, isLiveRegion}, props), children2);
    if (!this.props.isToast) {
      return alertGroup2;
    }
    const container = this.state.container;
    if (!canUseDOM || !container) {
      return null;
    }
    return reactDom.createPortal(alertGroup2, container);
  }
};
AlertGroup.displayName = "AlertGroup";
var formControl = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    formControl: "pf-c-form-control",
    modifiers: {
      success: "pf-m-success",
      expanded: "pf-m-expanded",
      icon: "pf-m-icon",
      warning: "pf-m-warning",
      search: "pf-m-search",
      calendar: "pf-m-calendar",
      clock: "pf-m-clock",
      placeholder: "pf-m-placeholder",
      resizeVertical: "pf-m-resize-vertical",
      resizeHorizontal: "pf-m-resize-horizontal"
    }
  };
});
var formStyles = /* @__PURE__ */ getDefaultExportFromCjs(formControl);
var DropdownGroup = (_a) => {
  var {children: children2 = null, className = "", label: label2 = ""} = _a, props = __rest(_a, ["children", "className", "label"]);
  return react.createElement(DropdownContext.Consumer, null, ({sectionClass, sectionTitleClass, sectionComponent}) => {
    const SectionComponent = sectionComponent;
    return react.createElement(SectionComponent, Object.assign({className: css(sectionClass, className)}, props), label2 && react.createElement("h1", {className: css(sectionTitleClass), "aria-hidden": true}, label2), react.createElement("ul", {role: "none"}, children2));
  });
};
DropdownGroup.displayName = "DropdownGroup";
var badge = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    badge: "pf-c-badge",
    modifiers: {
      read: "pf-m-read",
      unread: "pf-m-unread"
    }
  };
});
var badgeStyles = /* @__PURE__ */ getDefaultExportFromCjs(badge);
var Badge = (_a) => {
  var {isRead = false, className = "", children: children2 = ""} = _a, props = __rest(_a, ["isRead", "className", "children"]);
  return react.createElement("span", Object.assign({}, props, {className: css(badgeStyles.badge, isRead ? badgeStyles.modifiers.read : badgeStyles.modifiers.unread, className)}), children2);
};
Badge.displayName = "Badge";
var DropdownToggle = (_a) => {
  var {
    id: id3 = "",
    children: children2 = null,
    className = "",
    isOpen = false,
    parentRef = null,
    getMenuRef = null,
    isDisabled = false,
    isPlain = false,
    isPrimary = false,
    isActive = false,
    onToggle = (_isOpen) => void 0,
    icon = null,
    toggleIndicator: ToggleIndicator = CaretDownIcon,
    splitButtonItems,
    splitButtonVariant = "checkbox",
    "aria-haspopup": ariaHasPopup,
    ouiaId,
    ouiaSafe,
    ref
  } = _a, props = __rest(_a, ["id", "children", "className", "isOpen", "parentRef", "getMenuRef", "isDisabled", "isPlain", "isPrimary", "isActive", "onToggle", "icon", "toggleIndicator", "splitButtonItems", "splitButtonVariant", "aria-haspopup", "ouiaId", "ouiaSafe", "ref"]);
  const ouiaProps = useOUIAProps(DropdownToggle.displayName, ouiaId, ouiaSafe);
  const toggle = react.createElement(DropdownContext.Consumer, null, ({toggleTextClass, toggleIndicatorClass, toggleIconClass}) => react.createElement(Toggle, Object.assign({}, props, {id: id3, className, isOpen, parentRef, getMenuRef, isActive, isDisabled, isPlain, isPrimary, onToggle, "aria-haspopup": ariaHasPopup}, ouiaProps, splitButtonItems && {isSplitButton: true, "aria-label": props["aria-label"] || "Select"}), icon && react.createElement("span", {className: css(toggleIconClass)}, icon), children2 && react.createElement("span", {className: ToggleIndicator && css(toggleTextClass)}, children2), ToggleIndicator && react.createElement("span", {className: css(!splitButtonItems && toggleIndicatorClass)}, react.createElement(ToggleIndicator, null))));
  if (splitButtonItems) {
    return react.createElement("div", {className: css(styles$12.dropdownToggle, styles$12.modifiers.splitButton, splitButtonVariant === "action" && styles$12.modifiers.action, isDisabled && styles$12.modifiers.disabled)}, splitButtonItems, toggle);
  }
  return toggle;
};
DropdownToggle.displayName = "DropdownToggle";
var ApplicationLauncherSeparator = (_a) => {
  var props = __rest(_a, ["children"]);
  return react.createElement(DropdownSeparator, Object.assign({}, props));
};
ApplicationLauncherSeparator.displayName = "ApplicationLauncherSeparator";
var createRenderableFavorites = (items, isGrouped, favorites, isEnterTriggersArrowDown) => {
  if (isGrouped) {
    const favoriteItems = [];
    items.forEach((group) => {
      if (favorites.length > 0) {
        return group.props.children && group.props.children.filter((item) => favorites.includes(item.props.id)).map((item) => {
          if (isEnterTriggersArrowDown) {
            return favoriteItems.push(react.cloneElement(item, {
              isFavorite: true,
              enterTriggersArrowDown: isEnterTriggersArrowDown,
              id: `favorite-${item.props.id}`
            }));
          } else {
            return favoriteItems.push(react.cloneElement(item, {isFavorite: true, id: `favorite-${item.props.id}`}));
          }
        });
      }
    });
    return favoriteItems;
  }
  return items.filter((item) => favorites.includes(item.props.id)).map((item) => react.cloneElement(item, {isFavorite: true, enterTriggersArrowDown: isEnterTriggersArrowDown}));
};
var extendItemsWithFavorite = (items, isGrouped, favorites) => {
  if (isGrouped) {
    return items.map((group) => react.cloneElement(group, {
      children: react.Children.map(group.props.children, (item) => {
        if (item.type === ApplicationLauncherSeparator || item.type === Divider) {
          return item;
        }
        return react.cloneElement(item, {
          isFavorite: favorites.some((favoriteId) => favoriteId === item.props.id || `favorite-${favoriteId}` === item.props.id)
        });
      })
    }));
  }
  return items.map((item) => react.cloneElement(item, {
    isFavorite: favorites.some((favoriteId) => favoriteId === item.props.id)
  }));
};
var avatar = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    avatar: "pf-c-avatar",
    modifiers: {
      light: "pf-m-light",
      dark: "pf-m-dark"
    }
  };
});
var styles$4 = /* @__PURE__ */ getDefaultExportFromCjs(avatar);
var Avatar = (_a) => {
  var {className = "", src = "", alt, border} = _a, props = __rest(_a, ["className", "src", "alt", "border"]);
  return react.createElement("img", Object.assign({src, alt, className: css(styles$4.avatar, border === "light" && styles$4.modifiers.light, border === "dark" && styles$4.modifiers.dark, className)}, props));
};
Avatar.displayName = "Avatar";
var Brand = (_a) => {
  var {className = "", src = "", alt} = _a, props = __rest(_a, ["className", "src", "alt"]);
  return react.createElement("img", Object.assign({}, props, {className: css("pf-c-brand", className), src, alt}));
};
Brand.displayName = "Brand";
var breadcrumb = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    breadcrumb: "pf-c-breadcrumb",
    breadcrumbDropdown: "pf-c-breadcrumb__dropdown",
    breadcrumbHeading: "pf-c-breadcrumb__heading",
    breadcrumbItem: "pf-c-breadcrumb__item",
    breadcrumbItemDivider: "pf-c-breadcrumb__item-divider",
    breadcrumbLink: "pf-c-breadcrumb__link",
    breadcrumbList: "pf-c-breadcrumb__list",
    dropdownToggle: "pf-c-dropdown__toggle",
    modifiers: {
      current: "pf-m-current",
      overpassFont: "pf-m-overpass-font"
    }
  };
});
var styles$5 = /* @__PURE__ */ getDefaultExportFromCjs(breadcrumb);
var Breadcrumb = (_a) => {
  var {children: children2 = null, className = "", "aria-label": ariaLabel = "Breadcrumb", ouiaId, ouiaSafe = true} = _a, props = __rest(_a, ["children", "className", "aria-label", "ouiaId", "ouiaSafe"]);
  const ouiaProps = useOUIAProps(Breadcrumb.displayName, ouiaId, ouiaSafe);
  return react.createElement("nav", Object.assign({}, props, {"aria-label": ariaLabel, className: css(styles$5.breadcrumb, className)}, ouiaProps), react.createElement("ol", {className: styles$5.breadcrumbList}, react.Children.map(children2, (child, index3) => {
    const showDivider = index3 > 0;
    if (react.isValidElement(child)) {
      return react.cloneElement(child, {showDivider});
    }
    return child;
  })));
};
Breadcrumb.displayName = "Breadcrumb";
var BreadcrumbItem = (_a) => {
  var {children: children2 = null, className: classNameProp = "", to = void 0, isActive = false, isDropdown = false, showDivider, target = void 0, component = "a", render: render4 = void 0} = _a, props = __rest(_a, ["children", "className", "to", "isActive", "isDropdown", "showDivider", "target", "component", "render"]);
  const Component = component;
  const ariaCurrent = isActive ? "page" : void 0;
  const className = css(styles$5.breadcrumbLink, isActive && styles$5.modifiers.current);
  return react.createElement("li", Object.assign({}, props, {className: css(styles$5.breadcrumbItem, classNameProp)}), showDivider && react.createElement("span", {className: styles$5.breadcrumbItemDivider}, react.createElement(AngleRightIcon, null)), component === "button" && react.createElement("button", {className, "aria-current": ariaCurrent, type: "button"}, children2), isDropdown && react.createElement("span", {className: css(styles$5.breadcrumbDropdown)}, children2), render4 && render4({className, ariaCurrent}), to && !render4 && react.createElement(Component, {href: to, target, className, "aria-current": ariaCurrent}, children2), !to && component !== "button" && !isDropdown && children2);
};
BreadcrumbItem.displayName = "BreadcrumbItem";
var TextInputTypes;
(function(TextInputTypes2) {
  TextInputTypes2["text"] = "text";
  TextInputTypes2["date"] = "date";
  TextInputTypes2["datetimeLocal"] = "datetime-local";
  TextInputTypes2["email"] = "email";
  TextInputTypes2["month"] = "month";
  TextInputTypes2["number"] = "number";
  TextInputTypes2["password"] = "password";
  TextInputTypes2["search"] = "search";
  TextInputTypes2["tel"] = "tel";
  TextInputTypes2["time"] = "time";
  TextInputTypes2["url"] = "url";
})(TextInputTypes || (TextInputTypes = {}));
var TextInputBase = class extends react.Component {
  constructor(props) {
    super(props);
    this.inputRef = react.createRef();
    this.observer = () => {
    };
    this.handleChange = (event) => {
      if (this.props.onChange) {
        this.props.onChange(event.currentTarget.value, event);
      }
    };
    this.handleResize = () => {
      const inputRef = this.props.innerRef || this.inputRef;
      if (inputRef && inputRef.current) {
        trimLeft(inputRef.current, String(this.props.value));
      }
    };
    this.restoreText = () => {
      const inputRef = this.props.innerRef || this.inputRef;
      inputRef.current.value = String(this.props.value);
      inputRef.current.scrollLeft = inputRef.current.scrollWidth;
    };
    this.onFocus = (event) => {
      const {isLeftTruncated, onFocus} = this.props;
      if (isLeftTruncated) {
        this.restoreText();
      }
      onFocus && onFocus(event);
    };
    this.onBlur = (event) => {
      const {isLeftTruncated, onBlur} = this.props;
      if (isLeftTruncated) {
        this.handleResize();
      }
      onBlur && onBlur(event);
    };
    if (!props.id && !props["aria-label"] && !props["aria-labelledby"]) {
      console.error("Text input:", "Text input requires either an id or aria-label to be specified");
    }
    this.state = {
      ouiaStateId: getDefaultOUIAId(TextInputBase.displayName)
    };
  }
  componentDidMount() {
    if (this.props.isLeftTruncated) {
      const inputRef = this.props.innerRef || this.inputRef;
      this.observer = getResizeObserver(inputRef.current, this.handleResize);
      this.handleResize();
    }
  }
  componentWillUnmount() {
    if (this.props.isLeftTruncated) {
      this.observer();
    }
  }
  render() {
    const _a = this.props, {
      innerRef,
      className,
      type,
      value,
      validated,
      onChange,
      onFocus,
      onBlur,
      isLeftTruncated,
      isReadOnly,
      isRequired,
      isDisabled,
      iconVariant,
      customIconUrl,
      customIconDimensions,
      ouiaId,
      ouiaSafe
    } = _a, props = __rest(_a, ["innerRef", "className", "type", "value", "validated", "onChange", "onFocus", "onBlur", "isLeftTruncated", "isReadOnly", "isRequired", "isDisabled", "iconVariant", "customIconUrl", "customIconDimensions", "ouiaId", "ouiaSafe"]);
    const customIconStyle = {};
    if (customIconUrl) {
      customIconStyle.backgroundImage = `url('${customIconUrl}')`;
    }
    if (customIconDimensions) {
      customIconStyle.backgroundSize = customIconDimensions;
    }
    return react.createElement("input", Object.assign({}, props, {onFocus: this.onFocus, onBlur: this.onBlur, className: css(formStyles.formControl, validated === ValidatedOptions.success && formStyles.modifiers.success, validated === ValidatedOptions.warning && formStyles.modifiers.warning, (iconVariant && iconVariant !== "search" || customIconUrl) && formStyles.modifiers.icon, iconVariant && formStyles.modifiers[iconVariant], className), onChange: this.handleChange, type, value, "aria-invalid": props["aria-invalid"] ? props["aria-invalid"] : validated === ValidatedOptions.error, required: isRequired, disabled: isDisabled, readOnly: isReadOnly, ref: innerRef || this.inputRef}, (customIconUrl || customIconDimensions) && {style: customIconStyle}, getOUIAProps(TextInput.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId, ouiaSafe)));
  }
};
TextInputBase.displayName = "TextInputBase";
TextInputBase.defaultProps = {
  "aria-label": null,
  className: "",
  isRequired: false,
  validated: "default",
  isDisabled: false,
  isReadOnly: false,
  type: TextInputTypes.text,
  isLeftTruncated: false,
  onChange: () => void 0,
  ouiaSafe: true
};
var TextInput = react.forwardRef((props, ref) => react.createElement(TextInputBase, Object.assign({}, props, {innerRef: ref})));
TextInput.displayName = "TextInput";
var select = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    check: "pf-c-check",
    checkLabel: "pf-c-check__label",
    chipGroup: "pf-c-chip-group",
    divider: "pf-c-divider",
    formControl: "pf-c-form-control",
    modifiers: {
      invalid: "pf-m-invalid",
      success: "pf-m-success",
      warning: "pf-m-warning",
      disabled: "pf-m-disabled",
      active: "pf-m-active",
      expanded: "pf-m-expanded",
      plain: "pf-m-plain",
      typeahead: "pf-m-typeahead",
      placeholder: "pf-m-placeholder",
      top: "pf-m-top",
      alignRight: "pf-m-align-right",
      favorite: "pf-m-favorite",
      favoriteAction: "pf-m-favorite-action",
      focus: "pf-m-focus",
      link: "pf-m-link",
      action: "pf-m-action",
      selected: "pf-m-selected",
      description: "pf-m-description",
      load: "pf-m-load",
      loading: "pf-m-loading"
    },
    select: "pf-c-select",
    selectListItem: "pf-c-select__list-item",
    selectMenu: "pf-c-select__menu",
    selectMenuFieldset: "pf-c-select__menu-fieldset",
    selectMenuFooter: "pf-c-select__menu-footer",
    selectMenuGroup: "pf-c-select__menu-group",
    selectMenuGroupTitle: "pf-c-select__menu-group-title",
    selectMenuItem: "pf-c-select__menu-item",
    selectMenuItemActionIcon: "pf-c-select__menu-item-action-icon",
    selectMenuItemCount: "pf-c-select__menu-item-count",
    selectMenuItemDescription: "pf-c-select__menu-item-description",
    selectMenuItemIcon: "pf-c-select__menu-item-icon",
    selectMenuItemMain: "pf-c-select__menu-item-main",
    selectMenuItemMatch: "pf-c-select__menu-item--match",
    selectMenuItemRow: "pf-c-select__menu-item-row",
    selectMenuItemText: "pf-c-select__menu-item-text",
    selectMenuSearch: "pf-c-select__menu-search",
    selectMenuWrapper: "pf-c-select__menu-wrapper",
    selectToggle: "pf-c-select__toggle",
    selectToggleArrow: "pf-c-select__toggle-arrow",
    selectToggleBadge: "pf-c-select__toggle-badge",
    selectToggleButton: "pf-c-select__toggle-button",
    selectToggleClear: "pf-c-select__toggle-clear",
    selectToggleIcon: "pf-c-select__toggle-icon",
    selectToggleStatusIcon: "pf-c-select__toggle-status-icon",
    selectToggleText: "pf-c-select__toggle-text",
    selectToggleTypeahead: "pf-c-select__toggle-typeahead",
    selectToggleWrapper: "pf-c-select__toggle-wrapper"
  };
});
var styles$6 = /* @__PURE__ */ getDefaultExportFromCjs(select);
var TimesCircleIconConfig = {
  name: "TimesCircleIcon",
  height: 512,
  width: 512,
  svgPath: "M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm121.6 313.1c4.7 4.7 4.7 12.3 0 17L338 377.6c-4.7 4.7-12.3 4.7-17 0L256 312l-65.1 65.6c-4.7 4.7-12.3 4.7-17 0L134.4 338c-4.7-4.7-4.7-12.3 0-17l65.6-65-65.6-65.1c-4.7-4.7-4.7-12.3 0-17l39.6-39.6c4.7-4.7 12.3-4.7 17 0l65 65.7 65.1-65.6c4.7-4.7 12.3-4.7 17 0l39.6 39.6c4.7 4.7 4.7 12.3 0 17L312 256l65.6 65.1z",
  yOffset: 0,
  xOffset: 0
};
var TimesCircleIcon = createIcon(TimesCircleIconConfig);
var form = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    form: "pf-c-form",
    formActions: "pf-c-form__actions",
    formFieldGroup: "pf-c-form__field-group",
    formFieldGroupBody: "pf-c-form__field-group-body",
    formFieldGroupHeader: "pf-c-form__field-group-header",
    formFieldGroupHeaderActions: "pf-c-form__field-group-header-actions",
    formFieldGroupHeaderDescription: "pf-c-form__field-group-header-description",
    formFieldGroupHeaderMain: "pf-c-form__field-group-header-main",
    formFieldGroupHeaderTitle: "pf-c-form__field-group-header-title",
    formFieldGroupHeaderTitleText: "pf-c-form__field-group-header-title-text",
    formFieldGroupToggle: "pf-c-form__field-group-toggle",
    formFieldGroupToggleButton: "pf-c-form__field-group-toggle-button",
    formFieldGroupToggleIcon: "pf-c-form__field-group-toggle-icon",
    formFieldset: "pf-c-form__fieldset",
    formGroup: "pf-c-form__group",
    formGroupControl: "pf-c-form__group-control",
    formGroupLabel: "pf-c-form__group-label",
    formGroupLabelHelp: "pf-c-form__group-label-help",
    formGroupLabelInfo: "pf-c-form__group-label-info",
    formGroupLabelMain: "pf-c-form__group-label-main",
    formHelperText: "pf-c-form__helper-text",
    formHelperTextIcon: "pf-c-form__helper-text-icon",
    formLabel: "pf-c-form__label",
    formLabelRequired: "pf-c-form__label-required",
    formLabelText: "pf-c-form__label-text",
    formSection: "pf-c-form__section",
    formSectionTitle: "pf-c-form__section-title",
    modifiers: {
      horizontal: "pf-m-horizontal",
      alignRight: "pf-m-align-right",
      noPaddingTop: "pf-m-no-padding-top",
      limitWidth: "pf-m-limit-width",
      action: "pf-m-action",
      info: "pf-m-info",
      disabled: "pf-m-disabled",
      inline: "pf-m-inline",
      stack: "pf-m-stack",
      error: "pf-m-error",
      success: "pf-m-success",
      warning: "pf-m-warning",
      inactive: "pf-m-inactive",
      hidden: "pf-m-hidden",
      expanded: "pf-m-expanded"
    }
  };
});
var formStyles$1 = /* @__PURE__ */ getDefaultExportFromCjs(form);
var SelectContext = react.createContext(null);
var SelectProvider = SelectContext.Provider;
var SelectConsumer = SelectContext.Consumer;
var SelectVariant;
(function(SelectVariant2) {
  SelectVariant2["single"] = "single";
  SelectVariant2["checkbox"] = "checkbox";
  SelectVariant2["typeahead"] = "typeahead";
  SelectVariant2["typeaheadMulti"] = "typeaheadmulti";
})(SelectVariant || (SelectVariant = {}));
var SelectPosition;
(function(SelectPosition2) {
  SelectPosition2["right"] = "right";
  SelectPosition2["left"] = "left";
})(SelectPosition || (SelectPosition = {}));
var SelectDirection;
(function(SelectDirection2) {
  SelectDirection2["up"] = "up";
  SelectDirection2["down"] = "down";
})(SelectDirection || (SelectDirection = {}));
var KeyTypes = {
  Tab: "Tab",
  Space: " ",
  Escape: "Escape",
  Enter: "Enter",
  ArrowUp: "ArrowUp",
  ArrowDown: "ArrowDown",
  ArrowLeft: "ArrowLeft",
  ArrowRight: "ArrowRight"
};
var SelectOption = class extends react.Component {
  constructor() {
    super(...arguments);
    this.ref = react.createRef();
    this.liRef = react.createRef();
    this.favoriteRef = react.createRef();
    this.onKeyDown = (event, innerIndex, onEnter, isCheckbox) => {
      const {index: index3, keyHandler: keyHandler2, isLastOptionBeforeFooter} = this.props;
      let isLastItemBeforeFooter = false;
      if (isLastOptionBeforeFooter !== void 0) {
        isLastItemBeforeFooter = isLastOptionBeforeFooter(index3);
      }
      if (event.key === KeyTypes.Tab) {
        if (isCheckbox && !isLastItemBeforeFooter) {
          if (event.shiftKey) {
            keyHandler2(index3, innerIndex, "up");
          } else {
            keyHandler2(index3, innerIndex, "down");
          }
          event.stopPropagation();
        } else {
          keyHandler2(index3, innerIndex, "tab");
        }
      }
      event.preventDefault();
      if (event.key === KeyTypes.ArrowUp) {
        keyHandler2(index3, innerIndex, "up");
      } else if (event.key === KeyTypes.ArrowDown) {
        keyHandler2(index3, innerIndex, "down");
      } else if (event.key === KeyTypes.ArrowLeft) {
        keyHandler2(index3, innerIndex, "left");
      } else if (event.key === KeyTypes.ArrowRight) {
        keyHandler2(index3, innerIndex, "right");
      } else if (event.key === KeyTypes.Enter) {
        if (onEnter !== void 0) {
          onEnter();
        } else {
          this.ref.current.click();
        }
      }
    };
  }
  componentDidMount() {
    this.props.sendRef(this.props.isDisabled ? null : this.ref.current, this.props.isDisabled ? null : this.favoriteRef.current, this.props.isDisabled ? null : this.liRef.current, this.props.index);
  }
  componentDidUpdate() {
    this.props.sendRef(this.props.isDisabled ? null : this.ref.current, this.props.isDisabled ? null : this.favoriteRef.current, this.props.isDisabled ? null : this.liRef.current, this.props.index);
  }
  render() {
    const _a = this.props, {
      children: children2,
      className,
      id: id3,
      description,
      itemCount,
      value,
      onClick,
      isDisabled,
      isPlaceholder,
      isNoResultsOption,
      isSelected,
      isChecked,
      isFocused,
      sendRef,
      keyHandler: keyHandler2,
      index: index3,
      component,
      inputId,
      isFavorite,
      ariaIsFavoriteLabel = "starred",
      ariaIsNotFavoriteLabel = "not starred",
      isLoad,
      isLoading,
      setViewMoreNextIndex,
      isLastOptionBeforeFooter
    } = _a, props = __rest(_a, ["children", "className", "id", "description", "itemCount", "value", "onClick", "isDisabled", "isPlaceholder", "isNoResultsOption", "isSelected", "isChecked", "isFocused", "sendRef", "keyHandler", "index", "component", "inputId", "isFavorite", "ariaIsFavoriteLabel", "ariaIsNotFavoriteLabel", "isLoad", "isLoading", "setViewMoreNextIndex", "isLastOptionBeforeFooter"]);
    const Component = component;
    if (!id3 && isFavorite !== null) {
      console.error("Please provide an id to use the favorites feature.");
    }
    const generatedId = id3 || getUniqueId("select-option");
    const favoriteButton = (onFavorite) => react.createElement("button", {className: css(styles$6.selectMenuItem, styles$6.modifiers.action, styles$6.modifiers.favoriteAction), "aria-label": isFavorite ? ariaIsFavoriteLabel : ariaIsNotFavoriteLabel, onClick: () => {
      onFavorite(generatedId.replace("favorite-", ""), isFavorite);
    }, onKeyDown: (event) => {
      this.onKeyDown(event, 1, () => onFavorite(generatedId.replace("favorite-", "")));
    }, ref: this.favoriteRef}, react.createElement("span", {className: css(styles$6.selectMenuItemActionIcon)}, react.createElement(StarIcon, null)));
    const itemDisplay = itemCount ? react.createElement("span", {className: css(styles$6.selectMenuItemRow)}, react.createElement("span", {className: css(styles$6.selectMenuItemText)}, children2 || value && value.toString && value.toString()), react.createElement("span", {className: css(styles$6.selectMenuItemCount)}, itemCount)) : children2 || value.toString();
    const onViewMoreClick = (event) => {
      setViewMoreNextIndex();
      onClick(event);
    };
    return react.createElement(SelectConsumer, null, ({onSelect, onClose, variant, inputIdPrefix, onFavorite}) => react.createElement(react.Fragment, null, variant !== SelectVariant.checkbox && react.createElement("li", {id: generatedId, role: "presentation", className: css(isLoading && styles$6.selectListItem, !isLoad && !isLoading && styles$6.selectMenuWrapper, isFavorite && styles$6.modifiers.favorite, isFocused && styles$6.modifiers.focus, isLoading && styles$6.modifiers.loading), ref: this.liRef}, isLoading && children2, !isLoading && react.createElement(react.Fragment, null, react.createElement(Component, Object.assign({}, props, {className: css(styles$6.selectMenuItem, isLoad && styles$6.modifiers.load, isSelected && styles$6.modifiers.selected, isDisabled && styles$6.modifiers.disabled, description && styles$6.modifiers.description, isFavorite !== null && styles$6.modifiers.link, className), onClick: (event) => {
      if (isLoad) {
        onViewMoreClick(event);
        event.stopPropagation();
      } else if (!isDisabled && !isLoading) {
        onClick(event);
        onSelect(event, value, isPlaceholder);
        onClose();
      }
    }, role: "option", "aria-selected": isSelected || null, ref: this.ref, onKeyDown: (event) => {
      this.onKeyDown(event, 0);
    }, type: "button"}), description && react.createElement(react.Fragment, null, react.createElement("span", {className: css(styles$6.selectMenuItemMain)}, itemDisplay, isSelected && react.createElement("span", {className: css(styles$6.selectMenuItemIcon)}, react.createElement(CheckIcon, {"aria-hidden": true}))), react.createElement("span", {className: css(styles$6.selectMenuItemDescription)}, description)), !description && react.createElement(react.Fragment, null, itemDisplay, isSelected && react.createElement("span", {className: css(styles$6.selectMenuItemIcon)}, react.createElement(CheckIcon, {"aria-hidden": true})))), isFavorite !== null && id3 && favoriteButton(onFavorite))), variant === SelectVariant.checkbox && isLoad && react.createElement("button", {className: css(styles$6.selectMenuItem, styles$6.modifiers.load, isFocused && styles$6.modifiers.focus, className), onKeyDown: (event) => {
      this.onKeyDown(event, 0, void 0, true);
    }, onClick: (event) => {
      onViewMoreClick(event);
      event.stopPropagation();
    }, ref: this.ref}, children2 || value && value.toString && value.toString()), variant === SelectVariant.checkbox && isLoading && react.createElement("div", {className: css(styles$6.selectListItem, isLoading && styles$6.modifiers.loading, className)}, children2), variant === SelectVariant.checkbox && !isNoResultsOption && !isLoading && !isLoad && react.createElement("label", Object.assign({}, props, {className: css(checkStyles.check, styles$6.selectMenuItem, isDisabled && styles$6.modifiers.disabled, description && styles$6.modifiers.description, className), onKeyDown: (event) => {
      this.onKeyDown(event, 0, void 0, true);
    }}), react.createElement("input", {id: inputId || `${inputIdPrefix}-${value.toString()}`, className: css(checkStyles.checkInput), type: "checkbox", onChange: (event) => {
      if (!isDisabled) {
        onClick(event);
        onSelect(event, value);
      }
    }, ref: this.ref, checked: isChecked || false, disabled: isDisabled}), react.createElement("span", {className: css(checkStyles.checkLabel, isDisabled && styles$6.modifiers.disabled)}, itemDisplay), description && react.createElement("div", {className: css(checkStyles.checkDescription)}, description)), variant === SelectVariant.checkbox && isNoResultsOption && !isLoading && !isLoad && react.createElement("div", null, react.createElement(Component, Object.assign({}, props, {className: css(styles$6.selectMenuItem, isSelected && styles$6.modifiers.selected, isDisabled && styles$6.modifiers.disabled, className), role: "option", "aria-selected": isSelected || null, ref: this.ref, onKeyDown: (event) => {
      this.onKeyDown(event, 0, void 0, true);
    }, type: "button"}), itemDisplay))));
  }
};
SelectOption.displayName = "SelectOption";
SelectOption.defaultProps = {
  className: "",
  value: "",
  index: 0,
  isDisabled: false,
  isPlaceholder: false,
  isSelected: false,
  isChecked: false,
  isNoResultsOption: false,
  component: "button",
  onClick: () => {
  },
  sendRef: () => {
  },
  keyHandler: () => {
  },
  inputId: "",
  isFavorite: null,
  isLoad: false,
  isLoading: false,
  setViewMoreNextIndex: () => {
  },
  isLastOptionBeforeFooter: () => false
};
var SelectGroup = (_a) => {
  var {children: children2 = [], className = "", label: label2 = "", titleId = ""} = _a, props = __rest(_a, ["children", "className", "label", "titleId"]);
  return react.createElement(SelectConsumer, null, ({variant}) => react.createElement("div", Object.assign({}, props, {className: css(styles$6.selectMenuGroup, className)}), react.createElement("div", {className: css(styles$6.selectMenuGroupTitle), id: titleId, "aria-hidden": true}, label2), variant === SelectVariant.checkbox ? children2 : react.createElement("ul", {role: "listbox"}, children2)));
};
SelectGroup.displayName = "SelectGroup";
var SelectMenuWithRef = class extends react.Component {
  extendChildren(randomId) {
    const {children: children2, hasInlineFilter, isGrouped} = this.props;
    const childrenArray = children2;
    let index3 = hasInlineFilter ? 1 : 0;
    if (isGrouped) {
      return react.Children.map(childrenArray, (group) => {
        if (group.type === SelectGroup) {
          return react.cloneElement(group, {
            titleId: group.props.label && group.props.label.replace(/\W/g, "-"),
            children: react.Children.map(group.props.children, (option) => this.cloneOption(option, index3++, randomId))
          });
        } else {
          return this.cloneOption(group, index3++, randomId);
        }
      });
    }
    return react.Children.map(childrenArray, (child) => this.cloneOption(child, index3++, randomId));
  }
  cloneOption(child, index3, randomId) {
    const {selected, sendRef, keyHandler: keyHandler2} = this.props;
    const isSelected = this.checkForValue(child.props.value, selected);
    if (child.type === Divider) {
      return child;
    }
    return react.cloneElement(child, {
      inputId: `${randomId}-${index3}`,
      isSelected,
      sendRef,
      keyHandler: keyHandler2,
      index: index3
    });
  }
  checkForValue(valueToCheck, options) {
    if (!options || !valueToCheck) {
      return false;
    }
    const isSelectOptionObject = typeof valueToCheck !== "string" && valueToCheck.toString && valueToCheck.compareTo;
    if (Array.isArray(options)) {
      if (isSelectOptionObject) {
        return options.some((option) => option.compareTo(valueToCheck));
      } else {
        return options.includes(valueToCheck);
      }
    } else {
      if (isSelectOptionObject) {
        return options.compareTo(valueToCheck);
      } else {
        return options === valueToCheck;
      }
    }
  }
  extendCheckboxChildren(children2) {
    const {isGrouped, checked, sendRef, keyHandler: keyHandler2, hasInlineFilter, isLastOptionBeforeFooter} = this.props;
    let index3 = hasInlineFilter ? 1 : 0;
    if (isGrouped) {
      return react.Children.map(children2, (group) => {
        if (group.type === SelectOption || group.type === Divider) {
          return group;
        }
        return react.cloneElement(group, {
          titleId: group.props.label && group.props.label.replace(/\W/g, "-"),
          children: group.props.children ? react.createElement("fieldset", {"aria-labelledby": group.props.label && group.props.label.replace(/\W/g, "-"), className: css(styles$6.selectMenuFieldset)}, react.Children.map(group.props.children, (option) => option.type === Divider ? option : react.cloneElement(option, {
            isChecked: this.checkForValue(option.props.value, checked),
            sendRef,
            keyHandler: keyHandler2,
            index: index3++
          }))) : null
        });
      });
    }
    return react.Children.map(children2, (child) => child.type === Divider ? child : react.cloneElement(child, {
      isChecked: this.checkForValue(child.props.value, checked),
      sendRef,
      keyHandler: keyHandler2,
      index: index3++,
      isLastOptionBeforeFooter
    }));
  }
  renderSelectMenu({variant, inputIdPrefix}) {
    const _a = this.props, {children: children2, isCustomContent, className, isExpanded, openedOnEnter, selected, checked, isGrouped, position: position2, sendRef, keyHandler: keyHandler2, maxHeight, noResultsFoundText, createText, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, hasInlineFilter, innerRef, footer, footerRef, isLastOptionBeforeFooter} = _a, props = __rest(_a, ["children", "isCustomContent", "className", "isExpanded", "openedOnEnter", "selected", "checked", "isGrouped", "position", "sendRef", "keyHandler", "maxHeight", "noResultsFoundText", "createText", "aria-label", "aria-labelledby", "hasInlineFilter", "innerRef", "footer", "footerRef", "isLastOptionBeforeFooter"]);
    let Component = "div";
    const variantProps = Object.assign({ref: innerRef, className: css(!footer ? styles$6.selectMenu : "pf-c-select__menu-list", position2 === SelectPosition.right && styles$6.modifiers.alignRight, className)}, maxHeight && {style: {maxHeight, overflow: "auto"}});
    const extendedChildren = () => variant === SelectVariant.checkbox ? this.extendCheckboxChildren(children2) : this.extendChildren(inputIdPrefix);
    if (isCustomContent) {
      variantProps.children = children2;
    } else if (hasInlineFilter) {
      if (react.Children.count(children2) === 0) {
        variantProps.children = react.createElement("fieldset", {className: css(styles$6.selectMenuFieldset)});
      } else {
        variantProps.children = react.createElement("fieldset", {"aria-label": ariaLabel, "aria-labelledby": !ariaLabel && ariaLabelledBy || null, className: css(formStyles$1.formFieldset)}, children2.shift(), extendedChildren());
      }
    } else {
      variantProps.children = extendedChildren();
      if (!isGrouped) {
        Component = "ul";
        variantProps.role = "listbox";
        variantProps["aria-label"] = ariaLabel;
        variantProps["aria-labelledby"] = !ariaLabel && ariaLabelledBy || null;
      }
    }
    return react.createElement(react.Fragment, null, react.createElement(Component, Object.assign({}, variantProps, props)), footer && react.createElement("div", {className: css(styles$6.selectMenuFooter), ref: footerRef}, footer));
  }
  render() {
    return react.createElement(SelectConsumer, null, (context2) => this.renderSelectMenu(context2));
  }
};
SelectMenuWithRef.displayName = "SelectMenu";
SelectMenuWithRef.defaultProps = {
  className: "",
  isExpanded: false,
  isGrouped: false,
  openedOnEnter: false,
  selected: "",
  maxHeight: "",
  position: SelectPosition.left,
  sendRef: () => {
  },
  keyHandler: () => {
  },
  isCustomContent: false,
  hasInlineFilter: false,
  isLastOptionBeforeFooter: () => {
  }
};
var SelectMenu = react.forwardRef((props, ref) => react.createElement(SelectMenuWithRef, Object.assign({innerRef: ref}, props), props.children));
var SelectToggle = class extends react.Component {
  constructor(props) {
    super(props);
    this.onDocClick = (event) => {
      const {parentRef, menuRef, isOpen, onToggle, onClose} = this.props;
      const clickedOnToggle = parentRef && parentRef.current && parentRef.current.contains(event.target);
      const clickedWithinMenu = menuRef && menuRef.current && menuRef.current.contains && menuRef.current.contains(event.target);
      if (isOpen && !(clickedOnToggle || clickedWithinMenu)) {
        onToggle(false);
        onClose();
      }
    };
    this.findTabbableFooterElements = () => {
      const tabbable3 = this.props.footerRef.current.querySelectorAll("input, button, select, textarea, a[href]");
      const list3 = Array.prototype.filter.call(tabbable3, function(item) {
        return item.tabIndex >= "0";
      });
      return list3;
    };
    this.handleGlobalKeys = (event) => {
      const {parentRef, menuRef, hasFooter, isOpen, variant: variant2, onToggle, onClose} = this.props;
      const escFromToggle = parentRef && parentRef.current && parentRef.current.contains(event.target);
      const escFromWithinMenu = menuRef && menuRef.current && menuRef.current.contains && menuRef.current.contains(event.target);
      if (isOpen && event.key === KeyTypes.Tab && (variant2 === SelectVariant.typeahead || variant2 === SelectVariant.typeaheadMulti)) {
        this.props.handleTypeaheadKeys("tab");
        event.preventDefault();
        return;
      }
      if (isOpen && event.key === KeyTypes.Tab && hasFooter) {
        const tabbableItems = this.findTabbableFooterElements();
        if (tabbableItems.length <= 0) {
          onToggle(false);
          onClose();
          this.toggle.current.focus();
          return;
        } else {
          const currentElementIndex = tabbableItems.findIndex((item) => item === document.activeElement);
          if (currentElementIndex === -1) {
            tabbableItems[0].focus();
            return;
          }
          if (event.shiftKey) {
            return;
          }
          if (currentElementIndex + 1 < tabbableItems.length) {
            tabbableItems[currentElementIndex + 1].focus();
          } else {
            onToggle(false);
            onClose();
            this.toggle.current.focus();
          }
          event.preventDefault();
          return;
        }
      }
      if (isOpen && (event.key === KeyTypes.Escape || event.key === KeyTypes.Tab) && (escFromToggle || escFromWithinMenu)) {
        onToggle(false);
        onClose();
        this.toggle.current.focus();
      }
    };
    this.onKeyDown = (event) => {
      const {isOpen, onToggle, variant: variant2, onClose, onEnter, handleTypeaheadKeys} = this.props;
      if (variant2 === SelectVariant.typeahead || variant2 === SelectVariant.typeaheadMulti) {
        if (event.key === KeyTypes.ArrowDown || event.key === KeyTypes.ArrowUp) {
          handleTypeaheadKeys(event.key === KeyTypes.ArrowDown && "down" || event.key === KeyTypes.ArrowUp && "up");
          event.preventDefault();
        } else if (event.key === KeyTypes.Enter) {
          if (isOpen) {
            handleTypeaheadKeys("enter");
          } else {
            onToggle(!isOpen);
          }
        }
      }
      if (variant2 === SelectVariant.typeahead || variant2 === SelectVariant.typeaheadMulti || event.key === KeyTypes.Tab && !isOpen || event.key !== KeyTypes.Enter && event.key !== KeyTypes.Space) {
        return;
      }
      event.preventDefault();
      if ((event.key === KeyTypes.Tab || event.key === KeyTypes.Enter || event.key === KeyTypes.Space) && isOpen) {
        onToggle(!isOpen);
        onClose();
        this.toggle.current.focus();
      } else if ((event.key === KeyTypes.Enter || event.key === KeyTypes.Space) && !isOpen) {
        onToggle(!isOpen);
        onEnter();
      }
    };
    const {variant} = props;
    const isTypeahead = variant === SelectVariant.typeahead || variant === SelectVariant.typeaheadMulti;
    this.toggle = isTypeahead ? react.createRef() : react.createRef();
  }
  componentDidMount() {
    document.addEventListener("click", this.onDocClick);
    document.addEventListener("touchstart", this.onDocClick);
    document.addEventListener("keydown", this.handleGlobalKeys);
  }
  componentWillUnmount() {
    document.removeEventListener("click", this.onDocClick);
    document.removeEventListener("touchstart", this.onDocClick);
    document.removeEventListener("keydown", this.handleGlobalKeys);
  }
  render() {
    const _a = this.props, {className, children: children2, isOpen, isActive, isPlain, isDisabled, hasPlaceholderStyle, variant, onToggle, onEnter, onClose, onClickTypeaheadToggleButton, handleTypeaheadKeys, parentRef, menuRef, id: id3, type, hasClearButton, "aria-labelledby": ariaLabelledBy, "aria-label": ariaLabel, hasFooter, footerRef} = _a, props = __rest(_a, ["className", "children", "isOpen", "isActive", "isPlain", "isDisabled", "hasPlaceholderStyle", "variant", "onToggle", "onEnter", "onClose", "onClickTypeaheadToggleButton", "handleTypeaheadKeys", "parentRef", "menuRef", "id", "type", "hasClearButton", "aria-labelledby", "aria-label", "hasFooter", "footerRef"]);
    const isTypeahead = variant === SelectVariant.typeahead || variant === SelectVariant.typeaheadMulti || hasClearButton;
    const toggleProps = {
      id: id3,
      "aria-labelledby": ariaLabelledBy,
      "aria-expanded": isOpen,
      "aria-haspopup": variant !== SelectVariant.checkbox && "listbox" || null
    };
    return react.createElement(react.Fragment, null, !isTypeahead && react.createElement("button", Object.assign({}, props, toggleProps, {
      ref: this.toggle,
      type,
      className: css(styles$6.selectToggle, hasPlaceholderStyle && styles$6.modifiers.placeholder, isDisabled && styles$6.modifiers.disabled, isPlain && styles$6.modifiers.plain, isActive && styles$6.modifiers.active, className),
      "aria-label": ariaLabel,
      onClick: (_event) => {
        onToggle(!isOpen);
        if (isOpen) {
          onClose();
        }
      },
      onKeyDown: this.onKeyDown,
      disabled: isDisabled
    }), children2, react.createElement("span", {className: css(styles$6.selectToggleArrow)}, react.createElement(CaretDownIcon, null))), isTypeahead && react.createElement("div", Object.assign({}, props, {
      ref: this.toggle,
      className: css(styles$6.selectToggle, hasPlaceholderStyle && styles$6.modifiers.placeholder, isDisabled && styles$6.modifiers.disabled, isPlain && styles$6.modifiers.plain, isTypeahead && styles$6.modifiers.typeahead, className),
      onClick: (_event) => {
        if (!isDisabled) {
          onToggle(!isOpen);
        }
      },
      onKeyDown: this.onKeyDown
    }), children2, react.createElement("button", Object.assign({}, toggleProps, {type, className: css(buttonStyles.button, styles$6.selectToggleButton, styles$6.modifiers.plain), "aria-label": ariaLabel, onClick: (_event) => {
      onToggle(!isOpen);
      if (isOpen) {
        onClose();
      }
      onClickTypeaheadToggleButton();
    }}, (variant === SelectVariant.typeahead || variant === SelectVariant.typeaheadMulti) && {
      tabIndex: -1
    }, {disabled: isDisabled}), react.createElement(CaretDownIcon, {className: css(styles$6.selectToggleArrow)}))));
  }
};
SelectToggle.displayName = "SelectToggle";
SelectToggle.defaultProps = {
  className: "",
  isOpen: false,
  isActive: false,
  isPlain: false,
  isDisabled: false,
  hasPlaceholderStyle: false,
  hasClearButton: false,
  hasFooter: false,
  variant: "single",
  "aria-labelledby": "",
  "aria-label": "",
  type: "button",
  onToggle: () => {
  },
  onEnter: () => {
  },
  onClose: () => {
  },
  onClickTypeaheadToggleButton: () => {
  }
};
var chipGroup = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    chipGroup: "pf-c-chip-group",
    chipGroupClose: "pf-c-chip-group__close",
    chipGroupLabel: "pf-c-chip-group__label",
    chipGroupList: "pf-c-chip-group__list",
    chipGroupListItem: "pf-c-chip-group__list-item",
    chipGroupMain: "pf-c-chip-group__main",
    modifiers: {
      category: "pf-m-category"
    }
  };
});
var styles$7 = /* @__PURE__ */ getDefaultExportFromCjs(chipGroup);
var chip = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    badge: "pf-c-badge",
    button: "pf-c-button",
    chip: "pf-c-chip",
    chipIcon: "pf-c-chip__icon",
    chipText: "pf-c-chip__text",
    modifiers: {
      overflow: "pf-m-overflow",
      draggable: "pf-m-draggable"
    }
  };
});
var styles$8 = /* @__PURE__ */ getDefaultExportFromCjs(chip);
var Chip = class extends react.Component {
  constructor(props) {
    super(props);
    this.span = react.createRef();
    this.renderOverflowChip = () => {
      const {children: children2, className, onClick, ouiaId} = this.props;
      const Component = this.props.component;
      return react.createElement(Component, Object.assign({onClick, className: css(styles$8.chip, styles$8.modifiers.overflow, className)}, this.props.component === "button" ? {type: "button"} : {}, getOUIAProps("OverflowChip", ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId)), react.createElement("span", {className: css(styles$8.chipText)}, children2));
    };
    this.renderChip = (randomId) => {
      const {children: children2, tooltipPosition} = this.props;
      if (this.state.isTooltipVisible) {
        return react.createElement(Tooltip, {position: tooltipPosition, content: children2}, this.renderInnerChip(randomId));
      }
      return this.renderInnerChip(randomId);
    };
    this.state = {
      isTooltipVisible: false,
      ouiaStateId: getDefaultOUIAId(Chip.displayName)
    };
  }
  componentDidMount() {
    this.setState({
      isTooltipVisible: Boolean(this.span.current && this.span.current.offsetWidth < this.span.current.scrollWidth)
    });
  }
  renderInnerChip(id3) {
    const {children: children2, className, onClick, closeBtnAriaLabel, isReadOnly, component, ouiaId} = this.props;
    const Component = component;
    return react.createElement(Component, Object.assign({className: css(styles$8.chip, className)}, this.state.isTooltipVisible && {tabIndex: 0}, getOUIAProps(Chip.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId)), react.createElement("span", {ref: this.span, className: css(styles$8.chipText), id: id3}, children2), !isReadOnly && react.createElement(Button, {onClick, variant: "plain", "aria-label": closeBtnAriaLabel, id: `remove_${id3}`, "aria-labelledby": `remove_${id3} ${id3}`, ouiaId: ouiaId || closeBtnAriaLabel}, react.createElement(TimesIcon, {"aria-hidden": "true"})));
  }
  render() {
    const {isOverflowChip} = this.props;
    return react.createElement(GenerateId, null, (randomId) => isOverflowChip ? this.renderOverflowChip() : this.renderChip(this.props.id || randomId));
  }
};
Chip.displayName = "Chip";
Chip.defaultProps = {
  closeBtnAriaLabel: "close",
  className: "",
  isOverflowChip: false,
  isReadOnly: false,
  tooltipPosition: "top",
  onClick: (_e) => void 0,
  component: "div"
};
var ChipGroup = class extends react.Component {
  constructor(props) {
    super(props);
    this.headingRef = react.createRef();
    this.toggleCollapse = () => {
      this.setState((prevState) => ({
        isOpen: !prevState.isOpen,
        isTooltipVisible: Boolean(this.headingRef.current && this.headingRef.current.offsetWidth < this.headingRef.current.scrollWidth)
      }));
    };
    this.state = {
      isOpen: this.props.defaultIsOpen,
      isTooltipVisible: false
    };
  }
  componentDidMount() {
    this.setState({
      isTooltipVisible: Boolean(this.headingRef.current && this.headingRef.current.offsetWidth < this.headingRef.current.scrollWidth)
    });
  }
  renderLabel(id3) {
    const {categoryName, tooltipPosition} = this.props;
    const {isTooltipVisible} = this.state;
    return isTooltipVisible ? react.createElement(Tooltip, {position: tooltipPosition, content: categoryName}, react.createElement("span", {tabIndex: 0, ref: this.headingRef, className: css(styles$7.chipGroupLabel), id: id3, "aria-label": categoryName}, react.createElement("span", {"aria-hidden": "true"}, categoryName))) : react.createElement("span", {ref: this.headingRef, className: css(styles$7.chipGroupLabel), "aria-hidden": "true", id: id3}, categoryName);
  }
  render() {
    const _a = this.props, {
      categoryName,
      children: children2,
      className,
      isClosable,
      closeBtnAriaLabel,
      "aria-label": ariaLabel,
      onClick,
      onOverflowChipClick,
      numChips,
      expandedText,
      collapsedText,
      ouiaId,
      defaultIsOpen,
      tooltipPosition
    } = _a, rest = __rest(_a, ["categoryName", "children", "className", "isClosable", "closeBtnAriaLabel", "aria-label", "onClick", "onOverflowChipClick", "numChips", "expandedText", "collapsedText", "ouiaId", "defaultIsOpen", "tooltipPosition"]);
    const {isOpen} = this.state;
    const numChildren = react.Children.count(children2);
    const collapsedTextResult = fillTemplate(collapsedText, {
      remaining: react.Children.count(children2) - numChips
    });
    const renderChipGroup = (id3) => {
      const chipArray = !isOpen ? react.Children.toArray(children2).slice(0, numChips) : react.Children.toArray(children2);
      return react.createElement("div", Object.assign({className: css(styles$7.chipGroup, className, categoryName && styles$7.modifiers.category)}, getOUIAProps(ChipGroup.displayName, ouiaId)), react.createElement("div", {className: css(styles$7.chipGroupMain)}, categoryName && this.renderLabel(id3), react.createElement("ul", Object.assign({className: css(styles$7.chipGroupList)}, categoryName && {"aria-labelledby": id3}, !categoryName && {"aria-label": ariaLabel}, {role: "list"}, rest), chipArray.map((child, i3) => react.createElement("li", {className: css(styles$7.chipGroupListItem), key: i3}, child)), numChildren > numChips && react.createElement("li", {className: css(styles$7.chipGroupListItem)}, react.createElement(Chip, {isOverflowChip: true, onClick: (event) => {
        this.toggleCollapse();
        onOverflowChipClick(event);
      }, component: "button"}, isOpen ? expandedText : collapsedTextResult)))), isClosable && react.createElement("div", {className: css(styles$7.chipGroupClose)}, react.createElement(Button, {variant: "plain", "aria-label": closeBtnAriaLabel, onClick, id: `remove_group_${id3}`, "aria-labelledby": `remove_group_${id3} ${id3}`, ouiaId: ouiaId || closeBtnAriaLabel}, react.createElement(TimesCircleIcon, {"aria-hidden": "true"}))));
    };
    return numChildren === 0 ? null : react.createElement(GenerateId, null, (randomId) => renderChipGroup(this.props.id || randomId));
  }
};
ChipGroup.displayName = "ChipGroup";
ChipGroup.defaultProps = {
  expandedText: "Show Less",
  collapsedText: "${remaining} more",
  categoryName: "",
  defaultIsOpen: false,
  numChips: 3,
  isClosable: false,
  onClick: (_e) => void 0,
  onOverflowChipClick: (_e) => void 0,
  closeBtnAriaLabel: "Close chip group",
  tooltipPosition: "top",
  "aria-label": "Chip group category"
};
var currentId$1 = 0;
var Select = class extends react.Component {
  constructor() {
    super(...arguments);
    this.parentRef = react.createRef();
    this.menuComponentRef = react.createRef();
    this.filterRef = react.createRef();
    this.clearRef = react.createRef();
    this.inputRef = react.createRef();
    this.refCollection = [[]];
    this.optionContainerRefCollection = [];
    this.footerRef = react.createRef();
    this.state = {
      focusFirstOption: false,
      typeaheadInputValue: null,
      typeaheadFilteredChildren: react.Children.toArray(this.props.children),
      favoritesGroup: [],
      typeaheadCurrIndex: -1,
      typeaheadStoredIndex: -1,
      creatableValue: "",
      tabbedIntoFavoritesMenu: false,
      ouiaStateId: getDefaultOUIAId(Select.displayName, this.props.variant),
      viewMoreNextIndex: -1
    };
    this.getTypeaheadActiveChild = (typeaheadCurrIndex) => this.refCollection[typeaheadCurrIndex] ? this.refCollection[typeaheadCurrIndex][0] : null;
    this.componentDidUpdate = (prevProps, prevState) => {
      if (this.props.hasInlineFilter) {
        this.refCollection[0][0] = this.filterRef.current;
      }
      if (!prevState.focusFirstOption && this.state.focusFirstOption && !this.props.customContent) {
        const firstRef = this.refCollection.find((ref) => ref !== null);
        if (firstRef && firstRef[0]) {
          firstRef[0].focus();
        }
      }
      if (this.state.viewMoreNextIndex !== -1 && this.refCollection.length > this.state.viewMoreNextIndex && this.props.loadingVariant !== "spinner") {
        this.refCollection[this.state.viewMoreNextIndex][0].focus();
      }
      if (prevProps.children.length !== this.props.children.length || prevProps.children.some((child, index3) => {
        if (child.props && this.props.children[index3].props) {
          return child.props.value !== this.props.children[index3].props.value;
        } else {
          return child !== this.props.children[index3];
        }
      })) {
        this.updateTypeAheadFilteredChildren(prevState.typeaheadInputValue || "", null);
      }
      if (this.props.onFavorite && (this.props.favorites.length !== prevProps.favorites.length || this.state.typeaheadFilteredChildren !== prevState.typeaheadFilteredChildren)) {
        const tempRenderableChildren = this.props.variant === "typeahead" || this.props.variant === "typeaheadmulti" ? this.state.typeaheadFilteredChildren : this.props.children;
        const renderableFavorites = createRenderableFavorites(tempRenderableChildren, this.props.isGrouped, this.props.favorites);
        const favoritesGroup = renderableFavorites.length ? [
          react.createElement(SelectGroup, {key: "favorites", label: this.props.favoritesLabel}, renderableFavorites),
          react.createElement(Divider, {key: "favorites-group-divider"})
        ] : [];
        this.setState({favoritesGroup});
      }
    };
    this.onEnter = () => {
      this.setState({focusFirstOption: true});
    };
    this.onToggle = (isExpanded) => {
      const {isInputValuePersisted, onSelect, onToggle, hasInlineFilter} = this.props;
      if (!isExpanded && isInputValuePersisted && onSelect) {
        onSelect(void 0, this.inputRef.current ? this.inputRef.current.value : "");
      }
      if (isExpanded && hasInlineFilter) {
        this.setState({
          focusFirstOption: true
        });
      }
      onToggle(isExpanded);
    };
    this.onClose = () => {
      this.setState({
        focusFirstOption: false,
        typeaheadInputValue: null,
        typeaheadFilteredChildren: react.Children.toArray(this.props.children),
        typeaheadCurrIndex: -1,
        tabbedIntoFavoritesMenu: false
      });
    };
    this.onChange = (e2) => {
      if (e2.target.value.toString() !== "" && !this.props.isOpen) {
        this.onToggle(true);
      }
      if (this.props.onTypeaheadInputChanged) {
        this.props.onTypeaheadInputChanged(e2.target.value.toString());
      }
      this.setState({
        typeaheadCurrIndex: -1,
        typeaheadInputValue: e2.target.value,
        creatableValue: e2.target.value
      });
      this.updateTypeAheadFilteredChildren(e2.target.value.toString(), e2);
      this.refCollection = [[]];
    };
    this.updateTypeAheadFilteredChildren = (typeaheadInputValue, e2) => {
      let typeaheadFilteredChildren;
      const {onFilter, isCreatable, onCreateOption, createText, noResultsFoundText, children: children2, isGrouped, isCreateSelectOptionObject} = this.props;
      if (onFilter) {
        typeaheadFilteredChildren = onFilter(e2, e2 ? e2.target.value : typeaheadInputValue) || children2;
      } else {
        let input;
        try {
          input = new RegExp(typeaheadInputValue.toString(), "i");
        } catch (err) {
          input = new RegExp(typeaheadInputValue.toString().replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
        }
        const childrenArray = react.Children.toArray(children2);
        if (isGrouped) {
          const childFilter = (child) => child.props.value && child.props.value.toString && this.getDisplay(child.props.value.toString(), "text").search(input) === 0;
          typeaheadFilteredChildren = typeaheadInputValue.toString() !== "" ? react.Children.map(children2, (group) => {
            if (group.type === SelectGroup) {
              const filteredGroupChildren = react.Children.toArray(group.props.children).filter(childFilter);
              if (filteredGroupChildren.length > 0) {
                return react.cloneElement(group, {
                  titleId: group.props.label && group.props.label.replace(/\W/g, "-"),
                  children: filteredGroupChildren
                });
              }
            } else {
              return react.Children.toArray(group).filter(childFilter);
            }
          }) : childrenArray;
        } else {
          typeaheadFilteredChildren = typeaheadInputValue.toString() !== "" ? childrenArray.filter((child) => {
            const valueToCheck = child.props.value;
            if (!valueToCheck) {
              return true;
            }
            const isSelectOptionObject = typeof valueToCheck !== "string" && valueToCheck.toString && valueToCheck.compareTo;
            if (isSelectOptionObject) {
              return valueToCheck.compareTo(typeaheadInputValue);
            } else {
              return this.getDisplay(child.props.value.toString(), "text").search(input) === 0;
            }
          }) : childrenArray;
        }
      }
      if (!typeaheadFilteredChildren) {
        typeaheadFilteredChildren = [];
      }
      if (typeaheadFilteredChildren.length === 0) {
        !isCreatable && typeaheadFilteredChildren.push(react.createElement(SelectOption, {isDisabled: true, key: "no-results", value: noResultsFoundText, isNoResultsOption: true}));
      }
      if (isCreatable && typeaheadInputValue !== "") {
        const newValue = typeaheadInputValue;
        if (!typeaheadFilteredChildren.find((i3) => i3.props.value && i3.props.value.toString().toLowerCase() === newValue.toString().toLowerCase())) {
          const newOptionValue = isCreateSelectOptionObject ? {
            toString: () => newValue,
            compareTo: (value) => this.toString().toLowerCase().includes(value.toString().toLowerCase())
          } : newValue;
          typeaheadFilteredChildren.push(react.createElement(SelectOption, {key: `create ${newValue}`, value: newOptionValue, onClick: () => onCreateOption && onCreateOption(newValue)}, createText, ' "', newValue, '"'));
        }
      }
      this.setState({
        typeaheadFilteredChildren
      });
    };
    this.onClick = (_e) => {
      if (!this.props.isOpen) {
        this.onToggle(true);
      }
    };
    this.clearSelection = (_e) => {
      this.setState({
        typeaheadInputValue: null,
        typeaheadFilteredChildren: react.Children.toArray(this.props.children),
        typeaheadCurrIndex: -1
      });
    };
    this.sendRef = (optionRef, favoriteRef, optionContainerRef, index3) => {
      this.refCollection[index3] = [optionRef, favoriteRef];
      this.optionContainerRefCollection[index3] = optionContainerRef;
    };
    this.handleMenuKeys = (index3, innerIndex, position2) => {
      keyHandler(index3, innerIndex, position2, this.refCollection, this.refCollection);
      if (this.props.variant === SelectVariant.typeahead || this.props.variant === SelectVariant.typeaheadMulti) {
        if (position2 !== "tab") {
          this.handleTypeaheadKeys(position2);
        }
      }
    };
    this.moveFocus = (nextIndex, updateCurrentIndex = true) => {
      const {isCreatable, createText} = this.props;
      const hasDescriptionElm = Boolean(this.refCollection[nextIndex][0] && this.refCollection[nextIndex][0].classList.contains("pf-m-description"));
      const optionTextElm = hasDescriptionElm ? this.refCollection[nextIndex][0].firstElementChild : this.refCollection[nextIndex][0];
      let typeaheadInputValue = "";
      if (isCreatable && optionTextElm.innerText.includes(createText)) {
        typeaheadInputValue = this.state.creatableValue;
      } else if (optionTextElm) {
        typeaheadInputValue = optionTextElm.innerText;
      }
      this.setState((prevState) => ({
        typeaheadCurrIndex: updateCurrentIndex ? nextIndex : prevState.typeaheadCurrIndex,
        typeaheadStoredIndex: nextIndex,
        typeaheadInputValue
      }));
    };
    this.handleTypeaheadKeys = (position2) => {
      const {isOpen, onFavorite} = this.props;
      const {typeaheadCurrIndex, tabbedIntoFavoritesMenu, typeaheadStoredIndex} = this.state;
      const typeaheadActiveChild = this.getTypeaheadActiveChild(typeaheadCurrIndex);
      if (isOpen) {
        if (position2 === "enter") {
          if (typeaheadActiveChild || this.refCollection[0] && this.refCollection[0][0]) {
            this.setState({
              typeaheadInputValue: typeaheadActiveChild && typeaheadActiveChild.innerText || this.refCollection[0][0].innerText
            });
            if (typeaheadActiveChild) {
              typeaheadActiveChild.click();
            } else {
              this.refCollection[0][0].click();
            }
          }
        } else if (position2 === "tab") {
          if (onFavorite) {
            if (this.inputRef.current === document.activeElement) {
              let indexForFocus = 0;
              if (typeaheadCurrIndex !== -1) {
                indexForFocus = typeaheadCurrIndex;
              } else if (typeaheadStoredIndex !== -1) {
                indexForFocus = typeaheadStoredIndex;
              }
              if (this.refCollection[indexForFocus] !== null && this.refCollection[indexForFocus][0] !== null) {
                this.refCollection[indexForFocus][0].focus();
              } else {
                this.clearRef.current.focus();
              }
              this.setState({
                tabbedIntoFavoritesMenu: true,
                typeaheadCurrIndex: -1
              });
            } else {
              this.inputRef.current.focus();
              this.setState({tabbedIntoFavoritesMenu: false});
            }
          } else {
            this.onToggle(false);
          }
        } else if (!tabbedIntoFavoritesMenu) {
          if (this.refCollection[0][0] === null) {
            return;
          }
          let nextIndex;
          if (typeaheadCurrIndex === -1 && position2 === "down") {
            nextIndex = 0;
          } else if (typeaheadCurrIndex === -1 && position2 === "up") {
            nextIndex = this.refCollection.length - 1;
          } else if (position2 !== "left" && position2 !== "right") {
            nextIndex = getNextIndex(typeaheadCurrIndex, position2, this.refCollection);
          } else {
            nextIndex = typeaheadCurrIndex;
          }
          if (this.refCollection[nextIndex] === null) {
            return;
          }
          this.moveFocus(nextIndex);
        } else {
          const nextIndex = this.refCollection.findIndex((ref) => ref !== void 0 && (ref[0] === document.activeElement || ref[1] === document.activeElement));
          this.moveFocus(nextIndex);
        }
      }
    };
    this.onClickTypeaheadToggleButton = () => {
      if (this.inputRef && this.inputRef.current) {
        this.inputRef.current.focus();
      }
    };
    this.getDisplay = (value, type = "node") => {
      if (!value) {
        return;
      }
      const item = this.props.isGrouped ? react.Children.toArray(this.props.children).reduce((acc, curr) => [...acc, ...react.Children.toArray(curr.props.children)], []).find((child) => child.props.value.toString() === value.toString()) : react.Children.toArray(this.props.children).find((child) => child.props.value && child.props.value.toString() === value.toString());
      if (item) {
        if (item && item.props.children) {
          if (type === "node") {
            return item.props.children;
          }
          return this.findText(item);
        }
        return item.props.value.toString();
      }
      return value.toString();
    };
    this.findText = (item) => {
      if (typeof item === "string") {
        return item;
      } else if (!react.isValidElement(item)) {
        return "";
      } else {
        const multi = [];
        react.Children.toArray(item.props.children).forEach((child) => multi.push(this.findText(child)));
        return multi.join("");
      }
    };
    this.generateSelectedBadge = () => {
      const {customBadgeText, selections} = this.props;
      if (customBadgeText !== null) {
        return customBadgeText;
      }
      if (Array.isArray(selections) && selections.length > 0) {
        return selections.length;
      }
      return null;
    };
    this.setVieMoreNextIndex = () => {
      this.setState({viewMoreNextIndex: this.refCollection.length - 1});
    };
    this.isLastOptionBeforeFooter = (index3) => this.props.footer && index3 === this.refCollection.length - 1 ? true : false;
  }
  extendTypeaheadChildren(typeaheadCurrIndex, favoritesGroup) {
    const {isGrouped, onFavorite} = this.props;
    const typeaheadChildren = favoritesGroup ? favoritesGroup.concat(this.state.typeaheadFilteredChildren) : this.state.typeaheadFilteredChildren;
    const activeElement = this.optionContainerRefCollection[typeaheadCurrIndex];
    let typeaheadActiveChild = this.getTypeaheadActiveChild(typeaheadCurrIndex);
    if (typeaheadActiveChild && typeaheadActiveChild.classList.contains("pf-m-description")) {
      typeaheadActiveChild = typeaheadActiveChild.firstElementChild;
    }
    this.refCollection = [[]];
    this.optionContainerRefCollection = [];
    if (isGrouped) {
      return react.Children.map(typeaheadChildren, (group) => {
        if (group.type === Divider) {
          return group;
        } else if (group.type === SelectGroup && onFavorite) {
          return react.cloneElement(group, {
            titleId: group.props.label && group.props.label.replace(/\W/g, "-"),
            children: react.Children.map(group.props.children, (child) => child.type === Divider ? child : react.cloneElement(child, {
              isFocused: activeElement && (activeElement.id === child.props.id || this.props.isCreatable && typeaheadActiveChild.innerText === `{createText} "${group.props.value}"`)
            }))
          });
        } else if (group.type === SelectGroup) {
          return react.cloneElement(group, {
            titleId: group.props.label && group.props.label.replace(/\W/g, "-"),
            children: react.Children.map(group.props.children, (child) => child.type === Divider ? child : react.cloneElement(child, {
              isFocused: typeaheadActiveChild && (typeaheadActiveChild.innerText === child.props.value.toString() || this.props.isCreatable && typeaheadActiveChild.innerText === `{createText} "${child.props.value}"`)
            }))
          });
        } else {
          return react.cloneElement(group, {
            isFocused: typeaheadActiveChild && (typeaheadActiveChild.innerText === group.props.value.toString() || this.props.isCreatable && typeaheadActiveChild.innerText === `{createText} "${group.props.value}"`)
          });
        }
      });
    }
    return typeaheadChildren.map((child) => {
      const childElement = child;
      return childElement.type.displayName === "Divider" ? child : react.cloneElement(child, {
        isFocused: typeaheadActiveChild && (typeaheadActiveChild.innerText === child.props.value.toString() || this.props.isCreatable && typeaheadActiveChild.innerText === `{createText} "${child.props.value}"`)
      });
    });
  }
  render() {
    const _a = this.props, {
      children: children2,
      chipGroupProps,
      chipGroupComponent,
      className,
      customContent,
      variant,
      direction,
      onSelect,
      onClear,
      toggleId: toggleId2,
      isOpen,
      isGrouped,
      isPlain,
      isDisabled,
      hasPlaceholderStyle,
      validated,
      selections: selectionsProp,
      typeAheadAriaLabel,
      clearSelectionsAriaLabel,
      toggleAriaLabel,
      removeSelectionAriaLabel,
      "aria-label": ariaLabel,
      "aria-labelledby": ariaLabelledBy,
      "aria-describedby": ariaDescribedby,
      "aria-invalid": ariaInvalid,
      placeholderText,
      width: width2,
      maxHeight,
      toggleIcon,
      ouiaId,
      ouiaSafe,
      hasInlineFilter,
      isCheckboxSelectionBadgeHidden,
      inlineFilterPlaceholderText,
      onFilter,
      onTypeaheadInputChanged,
      onCreateOption,
      isCreatable,
      onToggle,
      createText,
      noResultsFoundText,
      customBadgeText,
      inputIdPrefix,
      isInputValuePersisted,
      menuAppendTo,
      favorites,
      onFavorite,
      favoritesLabel,
      footer,
      loadingVariant,
      isCreateSelectOptionObject
    } = _a, props = __rest(_a, ["children", "chipGroupProps", "chipGroupComponent", "className", "customContent", "variant", "direction", "onSelect", "onClear", "toggleId", "isOpen", "isGrouped", "isPlain", "isDisabled", "hasPlaceholderStyle", "validated", "selections", "typeAheadAriaLabel", "clearSelectionsAriaLabel", "toggleAriaLabel", "removeSelectionAriaLabel", "aria-label", "aria-labelledby", "aria-describedby", "aria-invalid", "placeholderText", "width", "maxHeight", "toggleIcon", "ouiaId", "ouiaSafe", "hasInlineFilter", "isCheckboxSelectionBadgeHidden", "inlineFilterPlaceholderText", "onFilter", "onTypeaheadInputChanged", "onCreateOption", "isCreatable", "onToggle", "createText", "noResultsFoundText", "customBadgeText", "inputIdPrefix", "isInputValuePersisted", "menuAppendTo", "favorites", "onFavorite", "favoritesLabel", "footer", "loadingVariant", "isCreateSelectOptionObject"]);
    const {focusFirstOption: openedOnEnter, typeaheadCurrIndex, typeaheadInputValue, typeaheadFilteredChildren, favoritesGroup} = this.state;
    const selectToggleId = toggleId2 || `pf-select-toggle-id-${currentId$1++}`;
    const selections = Array.isArray(selectionsProp) ? selectionsProp : [selectionsProp];
    const selectedOption = react.Children.toArray(children2).find((option) => option.props.value === selections[0]);
    const isSelectedPlaceholder = selectedOption && selectedOption.props.isPlaceholder;
    const hasAnySelections = Boolean(selections[0] && selections[0] !== "");
    const typeaheadActiveChild = this.getTypeaheadActiveChild(typeaheadCurrIndex);
    let childPlaceholderText = null;
    let renderableItems = [];
    if (onFavorite) {
      let tempExtendedChildren = children2;
      if (variant === "typeahead" || variant === "typeaheadmulti") {
        tempExtendedChildren = this.extendTypeaheadChildren(typeaheadCurrIndex, favoritesGroup);
      } else if (onFavorite) {
        tempExtendedChildren = favoritesGroup.concat(children2);
      }
      renderableItems = extendItemsWithFavorite(tempExtendedChildren, isGrouped, favorites);
    } else {
      renderableItems = children2;
    }
    if (!customContent) {
      if (!hasAnySelections && !placeholderText) {
        const childPlaceholder = react.Children.toArray(children2).filter((child) => child.props.isPlaceholder === true);
        childPlaceholderText = childPlaceholder[0] && this.getDisplay(childPlaceholder[0].props.value, "node") || children2[0] && this.getDisplay(children2[0].props.value, "node");
      }
    }
    if (isOpen) {
      if (renderableItems.find((item) => {
        var _a2;
        return ((_a2 = item) === null || _a2 === void 0 ? void 0 : _a2.key) === "loading";
      }) === void 0) {
        if (loadingVariant === "spinner") {
          renderableItems.push(react.createElement(SelectOption, {isLoading: true, key: "loading", value: "loading"}, react.createElement(Spinner, {size: "lg"})));
        } else if (loadingVariant === null || loadingVariant === void 0 ? void 0 : loadingVariant.text) {
          renderableItems.push(react.createElement(SelectOption, {isLoad: true, key: "loading", value: loadingVariant.text, setViewMoreNextIndex: this.setVieMoreNextIndex, onClick: loadingVariant === null || loadingVariant === void 0 ? void 0 : loadingVariant.onClick}));
        }
      }
    }
    const hasOnClear = onClear !== Select.defaultProps.onClear;
    const clearBtn = react.createElement("button", {className: css(buttonStyles.button, buttonStyles.modifiers.plain, styles$6.selectToggleClear), onClick: (e2) => {
      this.clearSelection(e2);
      onClear(e2);
    }, "aria-label": clearSelectionsAriaLabel, type: "button", disabled: isDisabled, ref: this.clearRef, onKeyDown: (event) => {
      if (event.key === KeyTypes.Enter) {
        this.clearRef.current.click();
      }
    }}, react.createElement(TimesCircleIcon, {"aria-hidden": true}));
    let selectedChips = null;
    if (variant === SelectVariant.typeaheadMulti) {
      selectedChips = chipGroupComponent ? chipGroupComponent : react.createElement(ChipGroup, Object.assign({}, chipGroupProps), selections && selections.map((item) => react.createElement(Chip, {key: item, onClick: (e2) => onSelect(e2, item), closeBtnAriaLabel: removeSelectionAriaLabel}, this.getDisplay(item, "node"))));
    }
    if (hasInlineFilter) {
      const filterBox = react.createElement(react.Fragment, null, react.createElement("div", {key: "inline-filter", className: css(styles$6.selectMenuSearch)}, react.createElement("input", {key: "inline-filter-input", type: "search", className: css(formStyles.formControl, formStyles.modifiers.search), onChange: this.onChange, placeholder: inlineFilterPlaceholderText, onKeyDown: (event) => {
        if (event.key === KeyTypes.ArrowUp) {
          this.handleMenuKeys(0, 0, "up");
          event.preventDefault();
        } else if (event.key === KeyTypes.ArrowDown) {
          this.handleMenuKeys(0, 0, "down");
          event.preventDefault();
        } else if (event.key === KeyTypes.ArrowLeft) {
          this.handleMenuKeys(0, 0, "left");
          event.preventDefault();
        } else if (event.key === KeyTypes.ArrowRight) {
          this.handleMenuKeys(0, 0, "right");
          event.preventDefault();
        } else if (event.key === KeyTypes.Tab && variant === SelectVariant.checkbox) {
          if (event.shiftKey) {
            this.handleMenuKeys(0, 0, "up");
          } else {
            this.handleMenuKeys(0, 0, "down");
          }
          event.stopPropagation();
          event.preventDefault();
        }
      }, ref: this.filterRef, autoComplete: "off"})), react.createElement(Divider, {key: "inline-filter-divider"}));
      renderableItems = [filterBox, ...typeaheadFilteredChildren].map((option, index3) => react.cloneElement(option, {key: index3}));
    }
    let variantProps;
    let variantChildren;
    if (customContent) {
      variantProps = {
        selected: selections,
        openedOnEnter,
        isCustomContent: true
      };
      variantChildren = customContent;
    } else {
      switch (variant) {
        case "single":
          variantProps = {
            selected: selections[0],
            hasInlineFilter,
            openedOnEnter
          };
          variantChildren = renderableItems;
          break;
        case "checkbox":
          variantProps = {
            checked: selections,
            isGrouped,
            hasInlineFilter,
            openedOnEnter
          };
          variantChildren = renderableItems;
          break;
        case "typeahead":
          variantProps = {
            selected: selections[0],
            openedOnEnter
          };
          variantChildren = onFavorite ? renderableItems : this.extendTypeaheadChildren(typeaheadCurrIndex);
          if (variantChildren.length === 0) {
            variantChildren.push(react.createElement(SelectOption, {isDisabled: true, key: 0, value: noResultsFoundText, isNoResultsOption: true}));
          }
          break;
        case "typeaheadmulti":
          variantProps = {
            selected: selections,
            openedOnEnter
          };
          variantChildren = onFavorite ? renderableItems : this.extendTypeaheadChildren(typeaheadCurrIndex);
          if (variantChildren.length === 0) {
            variantChildren.push(react.createElement(SelectOption, {isDisabled: true, key: 0, value: noResultsFoundText, isNoResultsOption: true}));
          }
          break;
      }
    }
    const innerMenu = react.createElement(SelectMenu, Object.assign({}, props, {isGrouped, selected: selections}, variantProps, {openedOnEnter, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, sendRef: this.sendRef, keyHandler: this.handleMenuKeys, maxHeight, ref: this.menuComponentRef, footer, footerRef: this.footerRef, isLastOptionBeforeFooter: this.isLastOptionBeforeFooter}), variantChildren);
    const menuContainer = footer ? react.createElement("div", {className: css(styles$6.selectMenu)}, " ", innerMenu, " ") : innerMenu;
    const popperContainer = react.createElement("div", Object.assign({className: css(styles$6.select, isOpen && styles$6.modifiers.expanded, validated === ValidatedOptions.success && styles$6.modifiers.success, validated === ValidatedOptions.warning && styles$6.modifiers.warning, validated === ValidatedOptions.error && styles$6.modifiers.invalid, direction === SelectDirection.up && styles$6.modifiers.top, className)}, width2 && {style: {width: width2}}, validated !== ValidatedOptions.default && {"aria-describedby": ariaDescribedby}, validated !== ValidatedOptions.default && {"aria-invalid": ariaInvalid}), isOpen && menuContainer);
    const mainContainer = react.createElement("div", Object.assign({className: css(styles$6.select, isOpen && styles$6.modifiers.expanded, validated === ValidatedOptions.success && styles$6.modifiers.success, validated === ValidatedOptions.warning && styles$6.modifiers.warning, validated === ValidatedOptions.error && styles$6.modifiers.invalid, direction === SelectDirection.up && styles$6.modifiers.top, className), ref: this.parentRef}, getOUIAProps(Select.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId, ouiaSafe), width2 && {style: {width: width2}}, validated !== ValidatedOptions.default && {"aria-describedby": ariaDescribedby}, validated !== ValidatedOptions.default && {"aria-invalid": ariaInvalid}), react.createElement(SelectToggle, Object.assign({id: selectToggleId, parentRef: this.parentRef, menuRef: this.menuComponentRef}, footer && {footerRef: this.footerRef}, {isOpen, isPlain, hasPlaceholderStyle: hasPlaceholderStyle && (!selections.length || selections[0] === null || isSelectedPlaceholder), onToggle: this.onToggle, onEnter: this.onEnter, onClose: this.onClose, variant, "aria-labelledby": `${ariaLabelledBy || ""} ${selectToggleId}`, "aria-label": toggleAriaLabel, handleTypeaheadKeys: this.handleTypeaheadKeys, isDisabled, hasClearButton: hasOnClear, hasFooter: footer !== void 0, onClickTypeaheadToggleButton: this.onClickTypeaheadToggleButton}), customContent && react.createElement("div", {className: css(styles$6.selectToggleWrapper)}, toggleIcon && react.createElement("span", {className: css(styles$6.selectToggleIcon)}, toggleIcon), react.createElement("span", {className: css(styles$6.selectToggleText)}, placeholderText)), variant === SelectVariant.single && !customContent && react.createElement(react.Fragment, null, react.createElement("div", {className: css(styles$6.selectToggleWrapper)}, toggleIcon && react.createElement("span", {className: css(styles$6.selectToggleIcon)}, toggleIcon), react.createElement("span", {className: css(styles$6.selectToggleText)}, this.getDisplay(selections[0], "node") || placeholderText || childPlaceholderText)), hasOnClear && hasAnySelections && clearBtn), variant === SelectVariant.checkbox && !customContent && react.createElement(react.Fragment, null, react.createElement("div", {className: css(styles$6.selectToggleWrapper)}, toggleIcon && react.createElement("span", {className: css(styles$6.selectToggleIcon)}, toggleIcon), react.createElement("span", {className: css(styles$6.selectToggleText)}, placeholderText), !isCheckboxSelectionBadgeHidden && hasAnySelections && react.createElement("div", {className: css(styles$6.selectToggleBadge)}, react.createElement("span", {className: css(badgeStyles.badge, badgeStyles.modifiers.read)}, this.generateSelectedBadge()))), hasOnClear && hasAnySelections && clearBtn), variant === SelectVariant.typeahead && !customContent && react.createElement(react.Fragment, null, react.createElement("div", {className: css(styles$6.selectToggleWrapper)}, toggleIcon && react.createElement("span", {className: css(styles$6.selectToggleIcon)}, toggleIcon), react.createElement("input", {className: css(formStyles.formControl, styles$6.selectToggleTypeahead), "aria-activedescendant": typeaheadActiveChild && typeaheadActiveChild.id, id: `${selectToggleId}-select-typeahead`, "aria-label": typeAheadAriaLabel, placeholder: placeholderText, value: typeaheadInputValue !== null ? typeaheadInputValue : this.getDisplay(selections[0], "text") || "", type: "text", onClick: this.onClick, onChange: this.onChange, autoComplete: "off", disabled: isDisabled, ref: this.inputRef})), hasOnClear && (selections[0] || typeaheadInputValue) && clearBtn), variant === SelectVariant.typeaheadMulti && !customContent && react.createElement(react.Fragment, null, react.createElement("div", {className: css(styles$6.selectToggleWrapper)}, toggleIcon && react.createElement("span", {className: css(styles$6.selectToggleIcon)}, toggleIcon), selections && Array.isArray(selections) && selections.length > 0 && selectedChips, react.createElement("input", {className: css(formStyles.formControl, styles$6.selectToggleTypeahead), "aria-activedescendant": typeaheadActiveChild && typeaheadActiveChild.id, id: `${selectToggleId}-select-multi-typeahead-typeahead`, "aria-label": typeAheadAriaLabel, "aria-invalid": validated === ValidatedOptions.error, placeholder: placeholderText, value: typeaheadInputValue !== null ? typeaheadInputValue : "", type: "text", onChange: this.onChange, onClick: this.onClick, autoComplete: "off", disabled: isDisabled, ref: this.inputRef})), hasOnClear && (selections && selections.length > 0 || typeaheadInputValue) && clearBtn), validated === ValidatedOptions.success && react.createElement("span", {className: css(styles$6.selectToggleStatusIcon)}, react.createElement(CheckCircleIcon, {"aria-hidden": "true"})), validated === ValidatedOptions.error && react.createElement("span", {className: css(styles$6.selectToggleStatusIcon)}, react.createElement(ExclamationCircleIcon, {"aria-hidden": "true"})), validated === ValidatedOptions.warning && react.createElement("span", {className: css(styles$6.selectToggleStatusIcon)}, react.createElement(ExclamationTriangleIcon, {"aria-hidden": "true"}))), isOpen && menuAppendTo === "inline" && menuContainer);
    const getParentElement = () => {
      if (this.parentRef && this.parentRef.current) {
        return this.parentRef.current.parentElement;
      }
      return null;
    };
    return react.createElement(GenerateId, null, (randomId) => react.createElement(SelectContext.Provider, {value: {onSelect, onFavorite, onClose: this.onClose, variant, inputIdPrefix: inputIdPrefix || randomId}}, menuAppendTo === "inline" ? mainContainer : react.createElement(Popper, {trigger: mainContainer, popper: popperContainer, direction, appendTo: menuAppendTo === "parent" ? getParentElement() : menuAppendTo, isVisible: isOpen})));
  }
};
Select.displayName = "Select";
Select.defaultProps = {
  children: [],
  className: "",
  position: SelectPosition.left,
  direction: SelectDirection.down,
  toggleId: null,
  isOpen: false,
  isGrouped: false,
  isPlain: false,
  isDisabled: false,
  hasPlaceholderStyle: false,
  isCreatable: false,
  validated: "default",
  "aria-label": "",
  "aria-labelledby": "",
  "aria-describedby": "",
  "aria-invalid": false,
  typeAheadAriaLabel: "",
  clearSelectionsAriaLabel: "Clear all",
  toggleAriaLabel: "Options menu",
  removeSelectionAriaLabel: "Remove",
  selections: [],
  createText: "Create",
  placeholderText: "",
  noResultsFoundText: "No results found",
  variant: SelectVariant.single,
  width: "",
  onClear: () => void 0,
  onCreateOption: () => void 0,
  toggleIcon: null,
  onFilter: null,
  onTypeaheadInputChanged: null,
  customContent: null,
  hasInlineFilter: false,
  inlineFilterPlaceholderText: null,
  customBadgeText: null,
  inputIdPrefix: "",
  menuAppendTo: "inline",
  favorites: [],
  favoritesLabel: "Favorites",
  ouiaSafe: true,
  chipGroupComponent: null,
  isInputValuePersisted: false,
  isCreateSelectOptionObject: false
};
var card = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    card: "pf-c-card",
    cardActions: "pf-c-card__actions",
    cardBody: "pf-c-card__body",
    cardExpandableContent: "pf-c-card__expandable-content",
    cardFooter: "pf-c-card__footer",
    cardHeader: "pf-c-card__header",
    cardHeaderToggle: "pf-c-card__header-toggle",
    cardHeaderToggleIcon: "pf-c-card__header-toggle-icon",
    cardTitle: "pf-c-card__title",
    divider: "pf-c-divider",
    modifiers: {
      hoverable: "pf-m-hoverable",
      selectable: "pf-m-selectable",
      selected: "pf-m-selected",
      hoverableRaised: "pf-m-hoverable-raised",
      selectableRaised: "pf-m-selectable-raised",
      nonSelectableRaised: "pf-m-non-selectable-raised",
      selectedRaised: "pf-m-selected-raised",
      compact: "pf-m-compact",
      displayLg: "pf-m-display-lg",
      flat: "pf-m-flat",
      plain: "pf-m-plain",
      rounded: "pf-m-rounded",
      expanded: "pf-m-expanded",
      fullHeight: "pf-m-full-height",
      toggleRight: "pf-m-toggle-right",
      noOffset: "pf-m-no-offset",
      noFill: "pf-m-no-fill",
      overpassFont: "pf-m-overpass-font"
    }
  };
});
var styles$9 = /* @__PURE__ */ getDefaultExportFromCjs(card);
var CardContext = react.createContext({
  cardId: "",
  isExpanded: false
});
var Card = (_a) => {
  var {children: children2 = null, id: id3 = "", className = "", component = "article", isHoverable = false, isHoverableRaised = false, isCompact = false, isSelectable = false, isSelected = false, isSelectableRaised = false, isSelectedRaised = false, isFlat = false, isExpanded = false, isRounded = false, isLarge = false, isFullHeight = false, isPlain = false, ouiaId, ouiaSafe = true} = _a, props = __rest(_a, ["children", "id", "className", "component", "isHoverable", "isHoverableRaised", "isCompact", "isSelectable", "isSelected", "isSelectableRaised", "isSelectedRaised", "isFlat", "isExpanded", "isRounded", "isLarge", "isFullHeight", "isPlain", "ouiaId", "ouiaSafe"]);
  const Component = component;
  const ouiaProps = useOUIAProps(Card.displayName, ouiaId, ouiaSafe);
  if (isCompact && isLarge) {
    console.warn("Card: Cannot use isCompact with isLarge. Defaulting to isCompact");
    isLarge = false;
  }
  return react.createElement(CardContext.Provider, {value: {
    cardId: id3,
    isExpanded
  }}, react.createElement(Component, Object.assign({id: id3, className: css(styles$9.card, isHoverable && styles$9.modifiers.hoverable, isHoverableRaised && styles$9.modifiers.hoverableRaised, isCompact && styles$9.modifiers.compact, isSelectable && !isSelectableRaised && styles$9.modifiers.selectable, isSelected && !isSelectedRaised && isSelectable && styles$9.modifiers.selected, isSelectableRaised && styles$9.modifiers.selectableRaised, isSelectedRaised && isSelectableRaised && styles$9.modifiers.selectedRaised, isExpanded && styles$9.modifiers.expanded, isFlat && styles$9.modifiers.flat, isRounded && styles$9.modifiers.rounded, isLarge && styles$9.modifiers.displayLg, isFullHeight && styles$9.modifiers.fullHeight, isPlain && styles$9.modifiers.plain, className), tabIndex: isSelectableRaised || isSelectable ? "0" : void 0}, props, ouiaProps), children2));
};
Card.displayName = "Card";
var CardActions = (_a) => {
  var {children: children2 = null, className = "", hasNoOffset = false} = _a, props = __rest(_a, ["children", "className", "hasNoOffset"]);
  return react.createElement("div", Object.assign({className: css(styles$9.cardActions, hasNoOffset && styles$9.modifiers.noOffset, className)}, props), children2);
};
CardActions.displayName = "CardActions";
var CardBody = (_a) => {
  var {children: children2 = null, className = "", component = "div", isFilled = true} = _a, props = __rest(_a, ["children", "className", "component", "isFilled"]);
  const Component = component;
  return react.createElement(Component, Object.assign({className: css(styles$9.cardBody, !isFilled && styles$9.modifiers.noFill, className)}, props), children2);
};
CardBody.displayName = "CardBody";
var CardFooter = (_a) => {
  var {children: children2 = null, className = "", component = "div"} = _a, props = __rest(_a, ["children", "className", "component"]);
  const Component = component;
  return react.createElement(Component, Object.assign({className: css(styles$9.cardFooter, className)}, props), children2);
};
CardFooter.displayName = "CardFooter";
var CardTitle = (_a) => {
  var {children: children2 = null, className = "", component = "div"} = _a, props = __rest(_a, ["children", "className", "component"]);
  const Component = component;
  return react.createElement(Component, Object.assign({className: css(styles$9.cardTitle, className)}, props), children2);
};
CardTitle.displayName = "CardTitle";
var CardHeader = (_a) => {
  var {children: children2 = null, className = "", id: id3, onExpand, toggleButtonProps, isToggleRightAligned} = _a, props = __rest(_a, ["children", "className", "id", "onExpand", "toggleButtonProps", "isToggleRightAligned"]);
  return react.createElement(CardContext.Consumer, null, ({cardId}) => {
    const cardHeaderToggle = react.createElement("div", {className: css(styles$9.cardHeaderToggle)}, react.createElement(Button, Object.assign({variant: "plain", type: "button", onClick: (evt) => {
      onExpand(evt, cardId);
    }}, toggleButtonProps), react.createElement("span", {className: css(styles$9.cardHeaderToggleIcon)}, react.createElement(AngleRightIcon, {"aria-hidden": "true"}))));
    return react.createElement("div", Object.assign({className: css(styles$9.cardHeader, isToggleRightAligned && styles$9.modifiers.toggleRight, className), id: id3}, props), onExpand && !isToggleRightAligned && cardHeaderToggle, children2, onExpand && isToggleRightAligned && cardHeaderToggle);
  });
};
CardHeader.displayName = "CardHeader";
var clipboardCopy = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    clipboardCopy: "pf-c-clipboard-copy",
    clipboardCopyActions: "pf-c-clipboard-copy__actions",
    clipboardCopyActionsItem: "pf-c-clipboard-copy__actions-item",
    clipboardCopyExpandableContent: "pf-c-clipboard-copy__expandable-content",
    clipboardCopyGroup: "pf-c-clipboard-copy__group",
    clipboardCopyText: "pf-c-clipboard-copy__text",
    clipboardCopyToggleIcon: "pf-c-clipboard-copy__toggle-icon",
    modifiers: {
      expanded: "pf-m-expanded",
      inline: "pf-m-inline",
      block: "pf-m-block",
      code: "pf-m-code"
    }
  };
});
var styles$a = /* @__PURE__ */ getDefaultExportFromCjs(clipboardCopy);
var ClipboardCopyButton = (_a) => {
  var {onClick, exitDelay = 0, entryDelay = 300, maxWidth = "100px", position: position2 = "top", "aria-label": ariaLabel = "Copyable input", id: id3, textId, children: children2, variant = "control"} = _a, props = __rest(_a, ["onClick", "exitDelay", "entryDelay", "maxWidth", "position", "aria-label", "id", "textId", "children", "variant"]);
  return react.createElement(Tooltip, {trigger: "mouseenter focus click", exitDelay, entryDelay, maxWidth, position: position2, content: react.createElement("div", null, children2)}, react.createElement(Button, Object.assign({type: "button", variant, onClick, "aria-label": ariaLabel, id: id3, "aria-labelledby": `${id3} ${textId}`}, props), react.createElement(CopyIcon, null)));
};
ClipboardCopyButton.displayName = "ClipboardCopyButton";
var ClipboardCopyToggle = (_a) => {
  var {onClick, id: id3, textId, contentId, isExpanded = false} = _a, props = __rest(_a, ["onClick", "id", "textId", "contentId", "isExpanded"]);
  return react.createElement(Button, Object.assign({type: "button", variant: "control", onClick, id: id3, "aria-labelledby": `${id3} ${textId}`, "aria-controls": `${id3} ${contentId}`, "aria-expanded": isExpanded}, props), isExpanded ? react.createElement(AngleDownIcon, {"aria-hidden": "true"}) : react.createElement(AngleRightIcon, {"aria-hidden": "true"}));
};
ClipboardCopyToggle.displayName = "ClipboardCopyToggle";
var ClipboardCopyExpanded = class extends react.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const _a = this.props, {className, children: children2, onChange, isReadOnly, isCode} = _a, props = __rest(_a, ["className", "children", "onChange", "isReadOnly", "isCode"]);
    return react.createElement("div", Object.assign({suppressContentEditableWarning: true, className: css(styles$a.clipboardCopyExpandableContent, className), onInput: (e2) => onChange(e2.target.innerText, e2), contentEditable: !isReadOnly}, props), isCode ? react.createElement("pre", null, children2) : children2);
  }
};
ClipboardCopyExpanded.displayName = "ClipboardCopyExpanded";
ClipboardCopyExpanded.defaultProps = {
  onChange: () => void 0,
  className: "",
  isReadOnly: false,
  isCode: false
};
var clipboardCopyFunc = (event, text) => {
  const clipboard = event.currentTarget.parentElement;
  const el = document.createElement("textarea");
  el.value = text.toString();
  clipboard.appendChild(el);
  el.select();
  document.execCommand("copy");
  clipboard.removeChild(el);
};
var ClipboardCopyVariant;
(function(ClipboardCopyVariant2) {
  ClipboardCopyVariant2["inline"] = "inline";
  ClipboardCopyVariant2["expansion"] = "expansion";
  ClipboardCopyVariant2["inlineCompact"] = "inline-compact";
})(ClipboardCopyVariant || (ClipboardCopyVariant = {}));
var ClipboardCopy = class extends react.Component {
  constructor(props) {
    super(props);
    this.timer = null;
    this.componentDidUpdate = (prevProps, prevState) => {
      if (prevProps.children !== this.props.children) {
        this.updateText(this.props.children);
      }
    };
    this.expandContent = (_event) => {
      this.setState((prevState) => ({
        expanded: !prevState.expanded
      }));
    };
    this.updateText = (text) => {
      this.setState({text});
      this.props.onChange(text);
    };
    this.render = () => {
      const _a = this.props, {
        isExpanded,
        onChange,
        isReadOnly,
        isCode,
        isBlock,
        exitDelay,
        maxWidth,
        entryDelay,
        switchDelay,
        onCopy,
        hoverTip,
        clickTip,
        textAriaLabel,
        toggleAriaLabel,
        variant,
        position: position2,
        className,
        additionalActions
      } = _a, divProps = __rest(_a, ["isExpanded", "onChange", "isReadOnly", "isCode", "isBlock", "exitDelay", "maxWidth", "entryDelay", "switchDelay", "onCopy", "hoverTip", "clickTip", "textAriaLabel", "toggleAriaLabel", "variant", "position", "className", "additionalActions"]);
      const textIdPrefix = "text-input-";
      const toggleIdPrefix = "toggle-";
      const contentIdPrefix = "content-";
      return react.createElement("div", Object.assign({className: css(styles$a.clipboardCopy, variant === "inline-compact" && styles$a.modifiers.inline, isBlock && styles$a.modifiers.block, this.state.expanded && styles$a.modifiers.expanded, className)}, divProps), variant === "inline-compact" && react.createElement(GenerateId, {prefix: ""}, (id3) => react.createElement(react.Fragment, null, !isCode && react.createElement("span", {className: css(styles$a.clipboardCopyText), id: `${textIdPrefix}${id3}`}, this.state.text), isCode && react.createElement("code", {className: css(styles$a.clipboardCopyText, styles$a.modifiers.code), id: `${textIdPrefix}${id3}`}, this.state.text), react.createElement("span", {className: css(styles$a.clipboardCopyActions)}, react.createElement("span", {className: css(styles$a.clipboardCopyActionsItem)}, react.createElement(ClipboardCopyButton, {variant: "plain", exitDelay, entryDelay, maxWidth, position: position2, id: `copy-button-${id3}`, textId: `text-input-${id3}`, "aria-label": hoverTip, onClick: (event) => {
        if (this.timer) {
          window.clearTimeout(this.timer);
          this.setState({copied: false});
        }
        onCopy(event, this.state.text);
        this.setState({copied: true}, () => {
          this.timer = window.setTimeout(() => {
            this.setState({copied: false});
            this.timer = null;
          }, switchDelay);
        });
      }}, this.state.copied ? clickTip : hoverTip)), additionalActions && additionalActions))), variant !== "inline-compact" && react.createElement(GenerateId, {prefix: ""}, (id3) => react.createElement(react.Fragment, null, react.createElement("div", {className: css(styles$a.clipboardCopyGroup)}, variant === "expansion" && react.createElement(ClipboardCopyToggle, {isExpanded: this.state.expanded, onClick: this.expandContent, id: `${toggleIdPrefix}${id3}`, textId: `${textIdPrefix}${id3}`, contentId: `${contentIdPrefix}${id3}`, "aria-label": toggleAriaLabel}), react.createElement(TextInput, {isReadOnly: isReadOnly || this.state.expanded, onChange: this.updateText, value: this.state.text, id: `text-input-${id3}`, "aria-label": textAriaLabel}), react.createElement(ClipboardCopyButton, {exitDelay, entryDelay, maxWidth, position: position2, id: `copy-button-${id3}`, textId: `text-input-${id3}`, "aria-label": hoverTip, onClick: (event) => {
        if (this.timer) {
          window.clearTimeout(this.timer);
          this.setState({copied: false});
        }
        onCopy(event, this.state.text);
        this.setState({copied: true}, () => {
          this.timer = window.setTimeout(() => {
            this.setState({copied: false});
            this.timer = null;
          }, switchDelay);
        });
      }}, this.state.copied ? clickTip : hoverTip)), this.state.expanded && react.createElement(ClipboardCopyExpanded, {isReadOnly, isCode, id: `content-${id3}`, onChange: this.updateText}, this.state.text))));
    };
    this.state = {
      text: this.props.children,
      expanded: this.props.isExpanded,
      copied: false
    };
  }
};
ClipboardCopy.displayName = "ClipboardCopy";
ClipboardCopy.defaultProps = {
  hoverTip: "Copy to clipboard",
  clickTip: "Successfully copied to clipboard!",
  isReadOnly: false,
  isExpanded: false,
  isCode: false,
  variant: "inline",
  position: TooltipPosition.top,
  maxWidth: "150px",
  exitDelay: 1600,
  entryDelay: 300,
  switchDelay: 2e3,
  onCopy: clipboardCopyFunc,
  onChange: () => void 0,
  textAriaLabel: "Copyable input",
  toggleAriaLabel: "Show content",
  additionalActions: null
};
var contextSelector = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    contextSelector: "pf-c-context-selector",
    contextSelectorMenu: "pf-c-context-selector__menu",
    contextSelectorMenuFooter: "pf-c-context-selector__menu-footer",
    contextSelectorMenuList: "pf-c-context-selector__menu-list",
    contextSelectorMenuListItem: "pf-c-context-selector__menu-list-item",
    contextSelectorMenuSearch: "pf-c-context-selector__menu-search",
    contextSelectorToggle: "pf-c-context-selector__toggle",
    contextSelectorToggleIcon: "pf-c-context-selector__toggle-icon",
    contextSelectorToggleText: "pf-c-context-selector__toggle-text",
    modifiers: {
      fullHeight: "pf-m-full-height",
      large: "pf-m-large",
      pageInsets: "pf-m-page-insets",
      active: "pf-m-active",
      expanded: "pf-m-expanded",
      plain: "pf-m-plain",
      text: "pf-m-text",
      disabled: "pf-m-disabled"
    }
  };
});
var styles$b = /* @__PURE__ */ getDefaultExportFromCjs(contextSelector);
var ContextSelectorToggle = class extends react.Component {
  constructor() {
    super(...arguments);
    this.toggle = react.createRef();
    this.componentDidMount = () => {
      document.addEventListener("mousedown", this.onDocClick);
      document.addEventListener("touchstart", this.onDocClick);
      document.addEventListener("keydown", this.onEscPress);
    };
    this.componentWillUnmount = () => {
      document.removeEventListener("mousedown", this.onDocClick);
      document.removeEventListener("touchstart", this.onDocClick);
      document.removeEventListener("keydown", this.onEscPress);
    };
    this.onDocClick = (event) => {
      const {isOpen, parentRef, onToggle} = this.props;
      if (isOpen && parentRef && !parentRef.contains(event.target)) {
        onToggle(null, false);
        this.toggle.current.focus();
      }
    };
    this.onEscPress = (event) => {
      const {isOpen, parentRef, onToggle} = this.props;
      const keyCode = event.keyCode || event.which;
      if (isOpen && keyCode === KEY_CODES.ESCAPE_KEY && parentRef && parentRef.contains(event.target)) {
        onToggle(null, false);
        this.toggle.current.focus();
      }
    };
    this.onKeyDown = (event) => {
      const {isOpen, onToggle, onEnter} = this.props;
      if (event.keyCode === KEY_CODES.TAB && !isOpen || event.key !== KEY_CODES.ENTER) {
        return;
      }
      event.preventDefault();
      if ((event.keyCode === KEY_CODES.TAB || event.keyCode === KEY_CODES.ENTER || event.key !== KEY_CODES.SPACE) && isOpen) {
        onToggle(null, !isOpen);
      } else if ((event.keyCode === KEY_CODES.ENTER || event.key === " ") && !isOpen) {
        onToggle(null, !isOpen);
        onEnter();
      }
    };
  }
  render() {
    const _a = this.props, {
      className,
      toggleText,
      isOpen,
      onToggle,
      id: id3,
      isPlain,
      isText,
      isActive,
      onEnter,
      parentRef
    } = _a, props = __rest(_a, ["className", "toggleText", "isOpen", "onToggle", "id", "isPlain", "isText", "isActive", "onEnter", "parentRef"]);
    return react.createElement("button", Object.assign({}, props, {id: id3, ref: this.toggle, className: css(styles$b.contextSelectorToggle, isActive && styles$b.modifiers.active, isPlain && styles$b.modifiers.plain, isText && styles$b.modifiers.text, className), type: "button", onClick: (event) => onToggle(event, !isOpen), "aria-expanded": isOpen, onKeyDown: this.onKeyDown}), react.createElement("span", {className: css(styles$b.contextSelectorToggleText)}, toggleText), react.createElement("span", {className: css(styles$b.contextSelectorToggleIcon)}, react.createElement(CaretDownIcon, {"aria-hidden": true})));
  }
};
ContextSelectorToggle.displayName = "ContextSelectorToggle";
ContextSelectorToggle.defaultProps = {
  className: "",
  toggleText: "",
  isOpen: false,
  onEnter: () => void 0,
  parentRef: null,
  isActive: false,
  onToggle: (event, value) => void 0
};
var ContextSelectorMenuList = class extends react.Component {
  constructor() {
    super(...arguments);
    this.refsCollection = [];
    this.sendRef = (index3, ref) => {
      this.refsCollection[index3] = ref;
    };
    this.render = () => {
      const _a = this.props, {className, isOpen, children: children2} = _a, props = __rest(_a, ["className", "isOpen", "children"]);
      return react.createElement("ul", Object.assign({className: css(styles$b.contextSelectorMenuList, className), hidden: !isOpen, role: "menu"}, props), this.extendChildren());
    };
  }
  extendChildren() {
    return react.Children.map(this.props.children, (child, index3) => react.cloneElement(child, {
      sendRef: this.sendRef,
      index: index3
    }));
  }
};
ContextSelectorMenuList.displayName = "ContextSelectorMenuList";
ContextSelectorMenuList.defaultProps = {
  children: null,
  className: "",
  isOpen: true
};
var ContextSelectorContext = react.createContext({
  onSelect: (event, value) => void 0
});
var inputGroup = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    formControl: "pf-c-form-control",
    inputGroup: "pf-c-input-group",
    inputGroupText: "pf-c-input-group__text",
    modifiers: {
      plain: "pf-m-plain"
    }
  };
});
var styles$c = /* @__PURE__ */ getDefaultExportFromCjs(inputGroup);
var FormSelect = class extends react.Component {
  constructor(props) {
    super(props);
    this.handleChange = (event) => {
      this.props.onChange(event.currentTarget.value, event);
    };
    if (!props.id && !props["aria-label"]) {
      console.error("FormSelect requires either an id or aria-label to be specified");
    }
    this.state = {
      ouiaStateId: getDefaultOUIAId(FormSelect.displayName, props.validated)
    };
  }
  render() {
    const _a = this.props, {children: children2, className, value, validated, isDisabled, isRequired, ouiaId, ouiaSafe} = _a, props = __rest(_a, ["children", "className", "value", "validated", "isDisabled", "isRequired", "ouiaId", "ouiaSafe"]);
    const selectedOption = react.Children.toArray(children2).find((option) => option.props.value === value);
    const isSelectedPlaceholder = selectedOption && selectedOption.props.isPlaceholder;
    return react.createElement("select", Object.assign({}, props, {className: css(formStyles.formControl, className, validated === ValidatedOptions.success && formStyles.modifiers.success, validated === ValidatedOptions.warning && formStyles.modifiers.warning, isSelectedPlaceholder && formStyles.modifiers.placeholder), "aria-invalid": validated === ValidatedOptions.error}, getOUIAProps(FormSelect.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId, ouiaSafe), {onChange: this.handleChange, disabled: isDisabled, required: isRequired, value}), children2);
  }
};
FormSelect.displayName = "FormSelect";
FormSelect.defaultProps = {
  className: "",
  value: "",
  validated: "default",
  isDisabled: false,
  isRequired: false,
  onBlur: () => void 0,
  onFocus: () => void 0,
  onChange: () => void 0,
  ouiaSafe: true
};
var c_form_control_textarea_Height = {
  name: "--pf-c-form-control--textarea--Height",
  value: "auto",
  var: "var(--pf-c-form-control--textarea--Height)"
};
var TextAreResizeOrientation;
(function(TextAreResizeOrientation2) {
  TextAreResizeOrientation2["horizontal"] = "horizontal";
  TextAreResizeOrientation2["vertical"] = "vertical";
  TextAreResizeOrientation2["both"] = "both";
})(TextAreResizeOrientation || (TextAreResizeOrientation = {}));
var TextAreaBase = class extends react.Component {
  constructor(props) {
    super(props);
    this.handleChange = (event) => {
      const field = event.currentTarget;
      if (this.props.autoResize && canUseDOM) {
        field.style.setProperty(c_form_control_textarea_Height.name, "inherit");
        const computed = window.getComputedStyle(field);
        const height = parseInt(computed.getPropertyValue("border-top-width")) + parseInt(computed.getPropertyValue("padding-top")) + field.scrollHeight + parseInt(computed.getPropertyValue("padding-bottom")) + parseInt(computed.getPropertyValue("border-bottom-width"));
        field.style.setProperty(c_form_control_textarea_Height.name, `${height}px`);
      }
      if (this.props.onChange) {
        this.props.onChange(field.value, event);
      }
    };
    if (!props.id && !props["aria-label"]) {
      console.error("TextArea: TextArea requires either an id or aria-label to be specified");
    }
  }
  render() {
    const _a = this.props, {
      className,
      value,
      validated,
      isRequired,
      isDisabled,
      isReadOnly,
      resizeOrientation,
      innerRef,
      readOnly,
      disabled,
      autoResize,
      onChange
    } = _a, props = __rest(_a, ["className", "value", "validated", "isRequired", "isDisabled", "isReadOnly", "resizeOrientation", "innerRef", "readOnly", "disabled", "autoResize", "onChange"]);
    const orientation = `resize${capitalize2(resizeOrientation)}`;
    return react.createElement("textarea", Object.assign({className: css(formStyles.formControl, className, resizeOrientation !== TextAreResizeOrientation.both && formStyles.modifiers[orientation], validated === ValidatedOptions.success && formStyles.modifiers.success, validated === ValidatedOptions.warning && formStyles.modifiers.warning), onChange: this.handleChange}, typeof this.props.defaultValue !== "string" && {value}, {"aria-invalid": validated === ValidatedOptions.error, required: isRequired, disabled: isDisabled || disabled, readOnly: isReadOnly || readOnly, ref: innerRef}, props));
  }
};
TextAreaBase.displayName = "TextArea";
TextAreaBase.defaultProps = {
  innerRef: react.createRef(),
  className: "",
  isRequired: false,
  isDisabled: false,
  validated: "default",
  resizeOrientation: "both",
  "aria-label": null
};
var TextArea = react.forwardRef((props, ref) => react.createElement(TextAreaBase, Object.assign({}, props, {innerRef: ref})));
TextArea.displayName = "TextArea";
var InputGroup = (_a) => {
  var {className = "", children: children2} = _a, props = __rest(_a, ["className", "children"]);
  const formCtrls = [FormSelect, TextArea, TextInput].map((comp) => comp.displayName);
  const idItem = react.Children.toArray(children2).find((child) => !formCtrls.includes(child.type.displayName) && child.props.id);
  return react.createElement("div", Object.assign({className: css(styles$c.inputGroup, className)}, props), idItem ? react.Children.map(children2, (child) => formCtrls.includes(child.type.displayName) ? react.cloneElement(child, {"aria-describedby": idItem.props.id}) : child) : children2);
};
InputGroup.displayName = "InputGroup";
var currentId$2 = 0;
var newId = currentId$2++;
var ContextSelector = class extends react.Component {
  constructor(props) {
    super(props);
    this.parentRef = react.createRef();
    this.onEnterPressed = (event) => {
      if (event.charCode === KEY_CODES.ENTER) {
        this.props.onSearchButtonClick();
      }
    };
    this.state = {
      ouiaStateId: getDefaultOUIAId(ContextSelector.displayName)
    };
  }
  render() {
    const toggleId2 = `pf-context-selector-toggle-id-${newId}`;
    const screenReaderLabelId = `pf-context-selector-label-id-${newId}`;
    const searchButtonId = `pf-context-selector-search-button-id-${newId}`;
    const _a = this.props, {children: children2, className, isOpen, isFullHeight, onToggle, onSelect, screenReaderLabel, toggleText, searchButtonAriaLabel, searchInputValue, onSearchInputChange, searchInputPlaceholder, onSearchButtonClick, menuAppendTo, ouiaId, ouiaSafe, isPlain, isText, footer} = _a, props = __rest(_a, ["children", "className", "isOpen", "isFullHeight", "onToggle", "onSelect", "screenReaderLabel", "toggleText", "searchButtonAriaLabel", "searchInputValue", "onSearchInputChange", "searchInputPlaceholder", "onSearchButtonClick", "menuAppendTo", "ouiaId", "ouiaSafe", "isPlain", "isText", "footer"]);
    const menuContainer = react.createElement("div", {className: css(styles$b.contextSelectorMenu)}, isOpen && react.createElement(FocusTrap, {focusTrapOptions: {clickOutsideDeactivates: true}}, react.createElement("div", {className: css(styles$b.contextSelectorMenuSearch)}, react.createElement(InputGroup, null, react.createElement(TextInput, {value: searchInputValue, type: "search", placeholder: searchInputPlaceholder, onChange: onSearchInputChange, onKeyPress: this.onEnterPressed, "aria-labelledby": searchButtonId}), react.createElement(Button, {variant: ButtonVariant.control, "aria-label": searchButtonAriaLabel, id: searchButtonId, onClick: onSearchButtonClick}, react.createElement(SearchIcon, {"aria-hidden": "true"})))), react.createElement(ContextSelectorContext.Provider, {value: {onSelect}}, react.createElement(ContextSelectorMenuList, {isOpen}, children2)), footer));
    const popperContainer = react.createElement("div", Object.assign({className: css(styles$b.contextSelector, isOpen && styles$b.modifiers.expanded, className), ref: this.parentRef}, props), isOpen && menuContainer);
    const mainContainer = react.createElement("div", Object.assign({className: css(styles$b.contextSelector, isOpen && styles$b.modifiers.expanded, isFullHeight && styles$b.modifiers.fullHeight, className), ref: this.parentRef}, getOUIAProps(ContextSelector.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId, ouiaSafe), props), screenReaderLabel && react.createElement("span", {id: screenReaderLabelId, hidden: true}, screenReaderLabel), react.createElement(ContextSelectorToggle, {onToggle, isOpen, toggleText, id: toggleId2, parentRef: this.parentRef.current, "aria-labelledby": `${screenReaderLabelId} ${toggleId2}`, isPlain, isText}), isOpen && menuAppendTo === "inline" && menuContainer);
    const getParentElement = () => {
      if (this.parentRef && this.parentRef.current) {
        return this.parentRef.current.parentElement;
      }
      return null;
    };
    return menuAppendTo === "inline" ? mainContainer : react.createElement(Popper, {trigger: mainContainer, popper: popperContainer, appendTo: menuAppendTo === "parent" ? getParentElement() : menuAppendTo, isVisible: isOpen});
  }
};
ContextSelector.displayName = "ContextSelector";
ContextSelector.defaultProps = {
  children: null,
  className: "",
  isOpen: false,
  onToggle: () => void 0,
  onSelect: () => void 0,
  screenReaderLabel: "",
  toggleText: "",
  searchButtonAriaLabel: "Search menu items",
  searchInputValue: "",
  onSearchInputChange: () => void 0,
  searchInputPlaceholder: "Search",
  onSearchButtonClick: () => void 0,
  menuAppendTo: "inline",
  ouiaSafe: true,
  footer: null,
  isPlain: false,
  isText: false
};
var ContextSelectorItem = class extends react.Component {
  constructor() {
    super(...arguments);
    this.ref = react.createRef();
  }
  componentDidMount() {
    this.props.sendRef(this.props.index, this.ref.current);
  }
  render() {
    const _a = this.props, {className, children: children2, onClick, isDisabled, index: index3, sendRef, href} = _a, props = __rest(_a, ["className", "children", "onClick", "isDisabled", "index", "sendRef", "href"]);
    const Component = href ? "a" : "button";
    const isDisabledLink = href && isDisabled;
    return react.createElement(ContextSelectorContext.Consumer, null, ({onSelect}) => react.createElement("li", {role: "none"}, react.createElement(Component, Object.assign({className: css(styles$b.contextSelectorMenuListItem, isDisabledLink && styles$b.modifiers.disabled, className), ref: this.ref, onClick: (event) => {
      if (!isDisabled) {
        onClick(event);
        onSelect(event, children2);
      }
    }, disabled: isDisabled && !href, href}, isDisabledLink && {"aria-disabled": true, tabIndex: -1}, props), children2)));
  }
};
ContextSelectorItem.displayName = "ContextSelectorItem";
ContextSelectorItem.defaultProps = {
  children: null,
  className: "",
  isDisabled: false,
  onClick: () => void 0,
  index: void 0,
  sendRef: () => {
  },
  href: null
};
var dataListGrid = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    dataList: "pf-c-data-list",
    dataListCell: "pf-c-data-list__cell",
    dataListExpandableContent: "pf-c-data-list__expandable-content",
    dataListItemContent: "pf-c-data-list__item-content",
    modifiers: {
      icon: "pf-m-icon",
      alignRight: "pf-m-align-right",
      noFill: "pf-m-no-fill",
      flex_2: "pf-m-flex-2",
      flex_3: "pf-m-flex-3",
      flex_4: "pf-m-flex-4",
      flex_5: "pf-m-flex-5",
      gridNone: "pf-m-grid-none",
      gridSm: "pf-m-grid-sm",
      gridMd: "pf-m-grid-md",
      gridLg: "pf-m-grid-lg",
      gridXl: "pf-m-grid-xl",
      grid_2xl: "pf-m-grid-2xl"
    }
  };
});
var stylesGrid = /* @__PURE__ */ getDefaultExportFromCjs(dataListGrid);
var gridBreakpointClasses = {
  none: stylesGrid.modifiers.gridNone,
  always: "pf-m-grid",
  sm: stylesGrid.modifiers.gridSm,
  md: stylesGrid.modifiers.gridMd,
  lg: stylesGrid.modifiers.gridLg,
  xl: stylesGrid.modifiers.gridXl,
  "2xl": stylesGrid.modifiers.grid_2xl
};
var DataListWrapModifier;
(function(DataListWrapModifier2) {
  DataListWrapModifier2["nowrap"] = "nowrap";
  DataListWrapModifier2["truncate"] = "truncate";
  DataListWrapModifier2["breakWord"] = "breakWord";
})(DataListWrapModifier || (DataListWrapModifier = {}));
var DataListContext = react.createContext({
  isSelectable: false
});
var moveItem = (arr, i1, toIndex) => {
  const fromIndex = arr.indexOf(i1);
  if (fromIndex === toIndex) {
    return arr;
  }
  const temp = arr.splice(fromIndex, 1);
  arr.splice(toIndex, 0, temp[0]);
  return arr;
};
var DataList = class extends react.Component {
  constructor(props) {
    super(props);
    this.dragFinished = false;
    this.html5DragDrop = false;
    this.arrayCopy = react.Children.toArray(this.props.children);
    this.ref = react.createRef();
    this.state = {
      tempItemOrder: [],
      draggedItemId: null,
      draggingToItemIndex: null,
      dragging: false
    };
    this.getIndex = (id3) => Array.from(this.ref.current.children).findIndex((item) => item.id === id3);
    this.move = (itemOrder) => {
      const ulNode = this.ref.current;
      const nodes = Array.from(ulNode.children);
      if (nodes.map((node) => node.id).every((id3, i3) => id3 === itemOrder[i3])) {
        return;
      }
      while (ulNode.firstChild) {
        ulNode.removeChild(ulNode.lastChild);
      }
      itemOrder.forEach((id3) => {
        ulNode.appendChild(nodes.find((n3) => n3.id === id3));
      });
    };
    this.dragStart0 = (el) => {
      const {onDragStart} = this.props;
      const draggedItemId = el.id;
      el.classList.add(__pika_web_default_export_for_treeshaking__2.modifiers.ghostRow);
      el.setAttribute("aria-pressed", "true");
      this.setState({
        draggedItemId,
        dragging: true
      });
      onDragStart && onDragStart(draggedItemId);
    };
    this.dragStart = (evt) => {
      evt.dataTransfer.effectAllowed = "move";
      evt.dataTransfer.setData("text/plain", evt.currentTarget.id);
      this.dragStart0(evt.currentTarget);
    };
    this.onDragCancel = () => {
      this.move(this.props.itemOrder);
      Array.from(this.ref.current.children).forEach((el) => {
        el.classList.remove(__pika_web_default_export_for_treeshaking__2.modifiers.ghostRow);
        el.classList.remove(__pika_web_default_export_for_treeshaking__2.modifiers.dragOver);
        el.setAttribute("aria-pressed", "false");
      });
      this.setState({
        draggedItemId: null,
        draggingToItemIndex: null,
        dragging: false
      });
      if (this.props.onDragCancel) {
        this.props.onDragCancel();
      }
    };
    this.dragLeave = (evt) => {
      if (!this.isValidDrop(evt)) {
        this.move(this.props.itemOrder);
        this.setState({
          draggingToItemIndex: null
        });
      }
    };
    this.dragEnd0 = (el) => {
      el.classList.remove(__pika_web_default_export_for_treeshaking__2.modifiers.ghostRow);
      el.classList.remove(__pika_web_default_export_for_treeshaking__2.modifiers.dragOver);
      el.setAttribute("aria-pressed", "false");
      this.setState({
        draggedItemId: null,
        draggingToItemIndex: null,
        dragging: false
      });
    };
    this.dragEnd = (evt) => {
      this.dragEnd0(evt.target);
    };
    this.isValidDrop = (evt) => {
      const ulRect = this.ref.current.getBoundingClientRect();
      return evt.clientX > ulRect.x && evt.clientX < ulRect.x + ulRect.width && evt.clientY > ulRect.y && evt.clientY < ulRect.y + ulRect.height;
    };
    this.drop = (evt) => {
      if (this.isValidDrop(evt)) {
        this.props.onDragFinish(this.state.tempItemOrder);
      } else {
        this.onDragCancel();
      }
    };
    this.dragOver0 = (id3) => {
      const draggingToItemIndex = Array.from(this.ref.current.children).findIndex((item) => item.id === id3);
      if (draggingToItemIndex !== this.state.draggingToItemIndex) {
        const tempItemOrder = moveItem([...this.props.itemOrder], this.state.draggedItemId, draggingToItemIndex);
        this.move(tempItemOrder);
        this.setState({
          draggingToItemIndex,
          tempItemOrder
        });
      }
    };
    this.dragOver = (evt) => {
      evt.preventDefault();
      const curListItem = evt.target.closest("li");
      if (!curListItem || !this.ref.current.contains(curListItem) || curListItem.id === this.state.draggedItemId) {
        return null;
      } else {
        this.dragOver0(curListItem.id);
      }
    };
    this.handleDragButtonKeys = (evt) => {
      const {dragging} = this.state;
      if (![" ", "Escape", "Enter", "ArrowUp", "ArrowDown"].includes(evt.key) || !this.html5DragDrop) {
        if (dragging) {
          evt.preventDefault();
        }
        return;
      }
      evt.preventDefault();
      const dragItem = evt.target.closest("li");
      if (evt.key === " " || evt.key === "Enter" && !dragging) {
        this.dragStart0(dragItem);
      } else if (dragging) {
        if (evt.key === "Escape" || evt.key === "Enter") {
          this.setState({
            dragging: false
          });
          this.dragFinished = true;
          if (evt.key === "Enter") {
            this.dragEnd0(dragItem);
            this.props.onDragFinish(this.state.tempItemOrder);
          } else {
            this.onDragCancel();
          }
        } else if (evt.key === "ArrowUp") {
          const nextSelection = dragItem.previousSibling;
          if (nextSelection) {
            this.dragOver0(nextSelection.id);
            dragItem.querySelector(`.${__pika_web_default_export_for_treeshaking__2.dataListItemDraggableButton}`).focus();
          }
        } else if (evt.key === "ArrowDown") {
          const nextSelection = dragItem.nextSibling;
          if (nextSelection) {
            this.dragOver0(nextSelection.id);
            dragItem.querySelector(`.${__pika_web_default_export_for_treeshaking__2.dataListItemDraggableButton}`).focus();
          }
        }
      }
    };
    this.html5DragDrop = Boolean(props.onDragFinish || props.onDragStart || props.onDragMove || props.onDragCancel);
    if (this.html5DragDrop) {
      console.warn("DataList's onDrag API is deprecated. Use DragDrop instead.");
    }
  }
  componentDidUpdate(oldProps) {
    if (this.dragFinished) {
      this.dragFinished = false;
      this.setState({
        tempItemOrder: [...this.props.itemOrder],
        draggedItemId: null,
        dragging: false
      });
    }
    if (oldProps.itemOrder !== this.props.itemOrder) {
      this.move(this.props.itemOrder);
    }
  }
  render() {
    const _a = this.props, {
      className,
      children: children2,
      onSelectDataListItem,
      selectedDataListItemId,
      isCompact,
      wrapModifier,
      onDragStart,
      onDragMove,
      onDragCancel,
      onDragFinish,
      gridBreakpoint,
      itemOrder
    } = _a, props = __rest(_a, ["className", "children", "onSelectDataListItem", "selectedDataListItemId", "isCompact", "wrapModifier", "onDragStart", "onDragMove", "onDragCancel", "onDragFinish", "gridBreakpoint", "itemOrder"]);
    const {dragging} = this.state;
    const isSelectable = onSelectDataListItem !== void 0;
    const updateSelectedDataListItem = (id3) => {
      onSelectDataListItem(id3);
    };
    const dragProps = this.html5DragDrop && {
      onDragOver: this.dragOver,
      onDrop: this.dragOver,
      onDragLeave: this.dragLeave
    };
    return react.createElement(DataListContext.Provider, {value: {
      isSelectable,
      selectedDataListItemId,
      updateSelectedDataListItem,
      isDraggable: this.html5DragDrop,
      dragStart: this.dragStart,
      dragEnd: this.dragEnd,
      drop: this.drop,
      dragKeyHandler: this.handleDragButtonKeys
    }}, react.createElement("ul", Object.assign({className: css(__pika_web_default_export_for_treeshaking__2.dataList, isCompact && __pika_web_default_export_for_treeshaking__2.modifiers.compact, gridBreakpointClasses[gridBreakpoint], wrapModifier && __pika_web_default_export_for_treeshaking__2.modifiers[wrapModifier], dragging && __pika_web_default_export_for_treeshaking__2.modifiers.dragOver, className), style: props.style}, props, dragProps, {ref: this.ref}), children2));
  }
};
DataList.displayName = "DataList";
DataList.defaultProps = {
  children: null,
  className: "",
  selectedDataListItemId: "",
  isCompact: false,
  gridBreakpoint: "md",
  wrapModifier: null
};
var DataListAction = (_a) => {
  var {
    children: children2,
    className,
    visibility,
    id: id3,
    "aria-label": ariaLabel,
    "aria-labelledby": ariaLabelledBy,
    isPlainButtonAction
  } = _a, props = __rest(_a, ["children", "className", "visibility", "id", "aria-label", "aria-labelledby", "isPlainButtonAction"]);
  return react.createElement("div", Object.assign({className: css(__pika_web_default_export_for_treeshaking__2.dataListItemAction, formatBreakpointMods(visibility, __pika_web_default_export_for_treeshaking__2), className)}, props), isPlainButtonAction ? react.createElement("div", {className: css(__pika_web_default_export_for_treeshaking__2.dataListAction)}, children2) : children2);
};
DataListAction.displayName = "DataListAction";
var DataListCell = (_a) => {
  var {children: children2 = null, className = "", width: width2 = 1, isFilled = true, alignRight = false, isIcon = false, wrapModifier = null} = _a, props = __rest(_a, ["children", "className", "width", "isFilled", "alignRight", "isIcon", "wrapModifier"]);
  return react.createElement("div", Object.assign({className: css(__pika_web_default_export_for_treeshaking__2.dataListCell, width2 > 1 && __pika_web_default_export_for_treeshaking__2.modifiers[`flex_${width2}`], !isFilled && __pika_web_default_export_for_treeshaking__2.modifiers.noFill, alignRight && __pika_web_default_export_for_treeshaking__2.modifiers.alignRight, isIcon && __pika_web_default_export_for_treeshaking__2.modifiers.icon, className, wrapModifier && __pika_web_default_export_for_treeshaking__2.modifiers[wrapModifier])}, props), children2);
};
DataListCell.displayName = "DataListCell";
var DataListCheck = (_a) => {
  var {
    className = "",
    onChange = (checked2, event) => {
    },
    isValid = true,
    isDisabled = false,
    isChecked = null,
    checked = null,
    otherControls = false
  } = _a, props = __rest(_a, ["className", "onChange", "isValid", "isDisabled", "isChecked", "checked", "otherControls"]);
  const check2 = react.createElement("div", {className: css(__pika_web_default_export_for_treeshaking__2.dataListCheck)}, react.createElement("input", Object.assign({}, props, {type: "checkbox", onChange: (event) => onChange(event.currentTarget.checked, event), "aria-invalid": !isValid, disabled: isDisabled, checked: isChecked || checked})));
  return react.createElement(react.Fragment, null, !otherControls && react.createElement("div", {className: css(__pika_web_default_export_for_treeshaking__2.dataListItemControl, className)}, check2), otherControls && check2);
};
DataListCheck.displayName = "DataListCheck";
var DataListControl = (_a) => {
  var {children: children2, className = ""} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("div", Object.assign({className: css(__pika_web_default_export_for_treeshaking__2.dataListItemControl, className)}, props), children2);
};
DataListControl.displayName = "DataListControl";
var DataListDragButton = (_a) => {
  var {className = "", isDisabled = false} = _a, props = __rest(_a, ["className", "isDisabled"]);
  return react.createElement(DataListContext.Consumer, null, ({dragKeyHandler}) => react.createElement("button", Object.assign({className: css(__pika_web_default_export_for_treeshaking__2.dataListItemDraggableButton, isDisabled && __pika_web_default_export_for_treeshaking__2.modifiers.disabled, className), onKeyDown: dragKeyHandler, type: "button", disabled: isDisabled}, props), react.createElement("span", {className: css(__pika_web_default_export_for_treeshaking__2.dataListItemDraggableIcon)}, react.createElement(GripVerticalIcon, null))));
};
DataListDragButton.displayName = "DataListDragButton";
function findDataListDragButton(node) {
  if (!react.isValidElement(node)) {
    return null;
  }
  if (node.type === DataListDragButton) {
    return node;
  }
  if (node.props.children) {
    for (const child of react.Children.toArray(node.props.children)) {
      const button2 = findDataListDragButton(child);
      if (button2) {
        return button2;
      }
    }
  }
  return null;
}
var DataListItem = class extends react.Component {
  render() {
    const _a = this.props, {children: children2, isExpanded, className, id: id3, "aria-labelledby": ariaLabelledBy} = _a, props = __rest(_a, ["children", "isExpanded", "className", "id", "aria-labelledby"]);
    return react.createElement(DataListContext.Consumer, null, ({isSelectable, selectedDataListItemId, updateSelectedDataListItem, isDraggable, dragStart, dragEnd, drop}) => {
      const selectDataListItem = (event) => {
        let target = event.target;
        while (event.currentTarget !== target) {
          if ("onclick" in target && target.onclick || target.parentNode.classList.contains(__pika_web_default_export_for_treeshaking__2.dataListItemAction) || target.parentNode.classList.contains(__pika_web_default_export_for_treeshaking__2.dataListItemControl)) {
            return;
          } else {
            target = target.parentNode;
          }
        }
        updateSelectedDataListItem(id3);
      };
      const onKeyDown = (event) => {
        if (event.key === KeyTypes.Enter) {
          updateSelectedDataListItem(id3);
        }
      };
      const dragButton = findDataListDragButton(children2);
      const dragProps = isDraggable && {
        draggable: dragButton ? !dragButton.props.isDisabled : true,
        onDrop: drop,
        onDragEnd: dragEnd,
        onDragStart: dragStart
      };
      return react.createElement("li", Object.assign({id: id3, className: css(__pika_web_default_export_for_treeshaking__2.dataListItem, isExpanded && __pika_web_default_export_for_treeshaking__2.modifiers.expanded, isSelectable && __pika_web_default_export_for_treeshaking__2.modifiers.selectable, selectedDataListItemId && selectedDataListItemId === id3 && __pika_web_default_export_for_treeshaking__2.modifiers.selected, className), "aria-labelledby": ariaLabelledBy}, isSelectable && {tabIndex: 0, onClick: selectDataListItem, onKeyDown}, isSelectable && selectedDataListItemId === id3 && {"aria-selected": true}, props, dragProps), react.Children.map(children2, (child) => react.isValidElement(child) && react.cloneElement(child, {
        rowid: ariaLabelledBy
      })));
    });
  }
};
DataListItem.displayName = "DataListItem";
DataListItem.defaultProps = {
  isExpanded: false,
  className: "",
  id: "",
  children: null,
  "aria-labelledby": ""
};
var DataListItemCells = (_a) => {
  var {
    className = "",
    dataListCells,
    rowid = ""
  } = _a, props = __rest(_a, ["className", "dataListCells", "rowid"]);
  return react.createElement("div", Object.assign({className: css(__pika_web_default_export_for_treeshaking__2.dataListItemContent, className)}, props), dataListCells);
};
DataListItemCells.displayName = "DataListItemCells";
var DataListItemRow = (_a) => {
  var {children: children2, className = "", rowid = "", wrapModifier = null} = _a, props = __rest(_a, ["children", "className", "rowid", "wrapModifier"]);
  return react.createElement("div", Object.assign({className: css(__pika_web_default_export_for_treeshaking__2.dataListItemRow, className, wrapModifier && __pika_web_default_export_for_treeshaking__2.modifiers[wrapModifier])}, props), react.Children.map(children2, (child) => react.isValidElement(child) && react.cloneElement(child, {
    rowid
  })));
};
DataListItemRow.displayName = "DataListItemRow";
var DataListToggle = (_a) => {
  var {className = "", isExpanded = false, "aria-controls": ariaControls = "", "aria-label": ariaLabel = "Details", rowid = "", id: id3} = _a, props = __rest(_a, ["className", "isExpanded", "aria-controls", "aria-label", "rowid", "id"]);
  return react.createElement("div", Object.assign({className: css(__pika_web_default_export_for_treeshaking__2.dataListItemControl, className)}, props), react.createElement("div", {className: css(__pika_web_default_export_for_treeshaking__2.dataListToggle)}, react.createElement(Button, {id: id3, variant: ButtonVariant.plain, "aria-controls": ariaControls !== "" && ariaControls, "aria-label": ariaLabel, "aria-labelledby": ariaLabel !== "Details" ? null : `${rowid} ${id3}`, "aria-expanded": isExpanded}, react.createElement("div", {className: css(__pika_web_default_export_for_treeshaking__2.dataListToggleIcon)}, react.createElement(AngleRightIcon, null)))));
};
DataListToggle.displayName = "DataListToggle";
var descriptionList = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    descriptionList: "pf-c-description-list",
    descriptionListDescription: "pf-c-description-list__description",
    descriptionListGroup: "pf-c-description-list__group",
    descriptionListTerm: "pf-c-description-list__term",
    descriptionListText: "pf-c-description-list__text",
    modifiers: {
      inlineGrid: "pf-m-inline-grid",
      autoColumnWidths: "pf-m-auto-column-widths",
      autoFit: "pf-m-auto-fit",
      compact: "pf-m-compact",
      fluid: "pf-m-fluid",
      helpText: "pf-m-help-text",
      "1Col": "pf-m-1-col",
      "2Col": "pf-m-2-col",
      "3Col": "pf-m-3-col",
      horizontal: "pf-m-horizontal",
      vertical: "pf-m-vertical",
      "1ColOnSm": "pf-m-1-col-on-sm",
      "2ColOnSm": "pf-m-2-col-on-sm",
      "3ColOnSm": "pf-m-3-col-on-sm",
      horizontalOnSm: "pf-m-horizontal-on-sm",
      verticalOnSm: "pf-m-vertical-on-sm",
      "1ColOnMd": "pf-m-1-col-on-md",
      "2ColOnMd": "pf-m-2-col-on-md",
      "3ColOnMd": "pf-m-3-col-on-md",
      horizontalOnMd: "pf-m-horizontal-on-md",
      verticalOnMd: "pf-m-vertical-on-md",
      "1ColOnLg": "pf-m-1-col-on-lg",
      "2ColOnLg": "pf-m-2-col-on-lg",
      "3ColOnLg": "pf-m-3-col-on-lg",
      horizontalOnLg: "pf-m-horizontal-on-lg",
      verticalOnLg: "pf-m-vertical-on-lg",
      "1ColOnXl": "pf-m-1-col-on-xl",
      "2ColOnXl": "pf-m-2-col-on-xl",
      "3ColOnXl": "pf-m-3-col-on-xl",
      horizontalOnXl: "pf-m-horizontal-on-xl",
      verticalOnXl: "pf-m-vertical-on-xl",
      "1ColOn_2xl": "pf-m-1-col-on-2xl",
      "2ColOn_2xl": "pf-m-2-col-on-2xl",
      "3ColOn_2xl": "pf-m-3-col-on-2xl",
      horizontalOn_2xl: "pf-m-horizontal-on-2xl",
      verticalOn_2xl: "pf-m-vertical-on-2xl"
    }
  };
});
var styles$d = /* @__PURE__ */ getDefaultExportFromCjs(descriptionList);
var setAutoFitMinModifiers = (autoFitMinModifier) => {
  const prefix2 = "--pf-c-description-list--GridTemplateColumns--min";
  const mods = autoFitMinModifier;
  return Object.keys(mods || {}).reduce((acc, curr) => curr === "default" ? Object.assign(Object.assign({}, acc), {[prefix2]: mods[curr]}) : Object.assign(Object.assign({}, acc), {[`${prefix2}-on-${curr}`]: mods[curr]}), {});
};
var DescriptionList = (_a) => {
  var {className = "", children: children2 = null, isHorizontal = false, isAutoColumnWidths, isAutoFit, isInlineGrid, isCompact, isFluid, columnModifier, autoFitMinModifier, orientation, style} = _a, props = __rest(_a, ["className", "children", "isHorizontal", "isAutoColumnWidths", "isAutoFit", "isInlineGrid", "isCompact", "isFluid", "columnModifier", "autoFitMinModifier", "orientation", "style"]);
  return react.createElement("dl", Object.assign({className: css(styles$d.descriptionList, (isHorizontal || isFluid) && styles$d.modifiers.horizontal, isAutoColumnWidths && styles$d.modifiers.autoColumnWidths, isAutoFit && styles$d.modifiers.autoFit, formatBreakpointMods(columnModifier, styles$d), formatBreakpointMods(orientation, styles$d), isInlineGrid && styles$d.modifiers.inlineGrid, isCompact && styles$d.modifiers.compact, isFluid && styles$d.modifiers.fluid, className), style: autoFitMinModifier || style ? Object.assign(Object.assign({}, isAutoFit ? setAutoFitMinModifiers(autoFitMinModifier) : {}), style) : void 0}, props), children2);
};
DescriptionList.displayName = "DescriptionList";
var DescriptionListDescription = (_a) => {
  var {children: children2 = null, className} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("dd", Object.assign({className: css(styles$d.descriptionListDescription, className)}, props), react.createElement("div", {className: "pf-c-description-list__text"}, children2));
};
DescriptionListDescription.displayName = "DescriptionListDescription";
var DescriptionListGroup = (_a) => {
  var {className, children: children2} = _a, props = __rest(_a, ["className", "children"]);
  return react.createElement("div", Object.assign({className: css(styles$d.descriptionListGroup, className)}, props), children2);
};
DescriptionListGroup.displayName = "DescriptionListGroup";
var DescriptionListTerm = (_a) => {
  var {children: children2, className} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("dt", Object.assign({className: css(styles$d.descriptionListTerm, className)}, props), react.createElement("span", {className: css(styles$d.descriptionListText)}, children2));
};
DescriptionListTerm.displayName = "DescriptionListTerm";
var drawer = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    drawer: "pf-c-drawer",
    drawerActions: "pf-c-drawer__actions",
    drawerBody: "pf-c-drawer__body",
    drawerClose: "pf-c-drawer__close",
    drawerContent: "pf-c-drawer__content",
    drawerHead: "pf-c-drawer__head",
    drawerMain: "pf-c-drawer__main",
    drawerPanel: "pf-c-drawer__panel",
    drawerPanelMain: "pf-c-drawer__panel-main",
    drawerSection: "pf-c-drawer__section",
    drawerSplitter: "pf-c-drawer__splitter",
    drawerSplitterHandle: "pf-c-drawer__splitter-handle",
    modifiers: {
      panelBottom: "pf-m-panel-bottom",
      inline: "pf-m-inline",
      noBorder: "pf-m-no-border",
      resizable: "pf-m-resizable",
      static: "pf-m-static",
      panelLeft: "pf-m-panel-left",
      expanded: "pf-m-expanded",
      resizing: "pf-m-resizing",
      noBackground: "pf-m-no-background",
      light_200: "pf-m-light-200",
      noPadding: "pf-m-no-padding",
      padding: "pf-m-padding",
      vertical: "pf-m-vertical",
      width_25: "pf-m-width-25",
      width_33: "pf-m-width-33",
      width_50: "pf-m-width-50",
      width_66: "pf-m-width-66",
      width_75: "pf-m-width-75",
      width_100: "pf-m-width-100",
      width_25OnLg: "pf-m-width-25-on-lg",
      width_33OnLg: "pf-m-width-33-on-lg",
      width_50OnLg: "pf-m-width-50-on-lg",
      width_66OnLg: "pf-m-width-66-on-lg",
      width_75OnLg: "pf-m-width-75-on-lg",
      width_100OnLg: "pf-m-width-100-on-lg",
      width_25OnXl: "pf-m-width-25-on-xl",
      width_33OnXl: "pf-m-width-33-on-xl",
      width_50OnXl: "pf-m-width-50-on-xl",
      width_66OnXl: "pf-m-width-66-on-xl",
      width_75OnXl: "pf-m-width-75-on-xl",
      width_100OnXl: "pf-m-width-100-on-xl",
      width_25On_2xl: "pf-m-width-25-on-2xl",
      width_33On_2xl: "pf-m-width-33-on-2xl",
      width_50On_2xl: "pf-m-width-50-on-2xl",
      width_66On_2xl: "pf-m-width-66-on-2xl",
      width_75On_2xl: "pf-m-width-75-on-2xl",
      width_100On_2xl: "pf-m-width-100-on-2xl",
      inlineOnLg: "pf-m-inline-on-lg",
      staticOnLg: "pf-m-static-on-lg",
      inlineOnXl: "pf-m-inline-on-xl",
      staticOnXl: "pf-m-static-on-xl",
      inlineOn_2xl: "pf-m-inline-on-2xl",
      staticOn_2xl: "pf-m-static-on-2xl"
    },
    pageMain: "pf-c-page__main"
  };
});
var styles$e = /* @__PURE__ */ getDefaultExportFromCjs(drawer);
var DrawerColorVariant;
(function(DrawerColorVariant2) {
  DrawerColorVariant2["default"] = "default";
  DrawerColorVariant2["light200"] = "light-200";
})(DrawerColorVariant || (DrawerColorVariant = {}));
var DrawerContext = react.createContext({
  isExpanded: false,
  isStatic: false,
  onExpand: () => {
  },
  position: "right",
  drawerRef: null
});
var Drawer = (_a) => {
  var {className = "", children: children2, isExpanded = false, isInline = false, isStatic = false, position: position2 = "right", onExpand = () => {
  }} = _a, props = __rest(_a, ["className", "children", "isExpanded", "isInline", "isStatic", "position", "onExpand"]);
  const drawerRef = react.useRef();
  return react.createElement(DrawerContext.Provider, {value: {isExpanded, isStatic, onExpand, position: position2, drawerRef}}, react.createElement("div", Object.assign({className: css(styles$e.drawer, isExpanded && styles$e.modifiers.expanded, isInline && styles$e.modifiers.inline, isStatic && styles$e.modifiers.static, position2 === "left" && styles$e.modifiers.panelLeft, position2 === "bottom" && styles$e.modifiers.panelBottom, className), ref: drawerRef}, props), children2));
};
Drawer.displayName = "Drawer";
var DrawerActions = (_a) => {
  var {
    className = "",
    children: children2
  } = _a, props = __rest(_a, ["className", "children"]);
  return react.createElement("div", Object.assign({className: css(styles$e.drawerActions, className)}, props), children2);
};
DrawerActions.displayName = "DrawerActions";
var DrawerCloseButton = (_a) => {
  var {
    className = "",
    onClose = () => void 0,
    "aria-label": ariaLabel = "Close drawer panel"
  } = _a, props = __rest(_a, ["className", "onClose", "aria-label"]);
  return react.createElement("div", Object.assign({className: css(styles$e.drawerClose, className)}, props), react.createElement(Button, {variant: "plain", onClick: onClose, "aria-label": ariaLabel}, react.createElement(TimesIcon, null)));
};
DrawerCloseButton.displayName = "DrawerCloseButton";
var DrawerMain = (_a) => {
  var {
    className = "",
    children: children2
  } = _a, props = __rest(_a, ["className", "children"]);
  return react.createElement("div", Object.assign({className: css(styles$e.drawerMain, className)}, props), children2);
};
DrawerMain.displayName = "DrawerMain";
var DrawerContent = (_a) => {
  var {
    className = "",
    children: children2,
    panelContent,
    colorVariant = DrawerColorVariant.default
  } = _a, props = __rest(_a, ["className", "children", "panelContent", "colorVariant"]);
  return react.createElement(DrawerMain, null, react.createElement("div", Object.assign({className: css(styles$e.drawerContent, colorVariant === DrawerColorVariant.light200 && styles$e.modifiers.light_200, className)}, props), children2), panelContent);
};
DrawerContent.displayName = "DrawerContent";
var DrawerContentBody = (_a) => {
  var {
    className = "",
    children: children2,
    hasPadding = false
  } = _a, props = __rest(_a, ["className", "children", "hasPadding"]);
  return react.createElement("div", Object.assign({className: css(styles$e.drawerBody, hasPadding && styles$e.modifiers.padding, className)}, props), children2);
};
DrawerContentBody.displayName = "DrawerContentBody";
var DrawerPanelBody = (_a) => {
  var {
    className = "",
    children: children2,
    hasNoPadding = false
  } = _a, props = __rest(_a, ["className", "children", "hasNoPadding"]);
  return react.createElement("div", Object.assign({className: css(styles$e.drawerBody, hasNoPadding && styles$e.modifiers.noPadding, className)}, props), children2);
};
DrawerPanelBody.displayName = "DrawerPanelBody";
var DrawerHead = (_a) => {
  var {
    className = "",
    children: children2,
    hasNoPadding = false
  } = _a, props = __rest(_a, ["className", "children", "hasNoPadding"]);
  return react.createElement(DrawerPanelBody, {hasNoPadding}, react.createElement("div", Object.assign({className: css(styles$e.drawerHead, className)}, props), children2));
};
DrawerHead.displayName = "DrawerHead";
var isResizing = null;
var newSize = 0;
var DrawerPanelContent = (_a) => {
  var {className = "", id: id3, children: children2, hasNoBorder = false, isResizable = false, onResize, minSize, defaultSize, maxSize, increment = 5, resizeAriaLabel = "Resize", resizeAriaDescribedBy = "Press space to begin resizing, and use the arrow keys to grow or shrink the panel. Press enter or escape to finish resizing.", widths, colorVariant = DrawerColorVariant.default} = _a, props = __rest(_a, ["className", "id", "children", "hasNoBorder", "isResizable", "onResize", "minSize", "defaultSize", "maxSize", "increment", "resizeAriaLabel", "resizeAriaDescribedBy", "widths", "colorVariant"]);
  const panel = react.useRef();
  const {position: position2, isExpanded, isStatic, onExpand, drawerRef} = react.useContext(DrawerContext);
  const hidden = isStatic ? false : !isExpanded;
  const [isExpandedInternal, setIsExpandedInternal] = react.useState(!hidden);
  let currWidth = 0;
  let panelRect;
  let right2;
  let left2;
  let bottom2;
  let setInitialVals = true;
  react.useEffect(() => {
    if (!isStatic && isExpanded) {
      setIsExpandedInternal(isExpanded);
    }
  }, [isStatic, isExpanded]);
  const handleTouchStart = (e2) => {
    e2.stopPropagation();
    document.addEventListener("touchmove", callbackTouchMove, {passive: false});
    document.addEventListener("touchend", callbackTouchEnd);
    isResizing = true;
  };
  const handleMousedown = (e2) => {
    e2.stopPropagation();
    e2.preventDefault();
    document.addEventListener("mousemove", callbackMouseMove);
    document.addEventListener("mouseup", callbackMouseUp);
    drawerRef.current.classList.add(css(styles$e.modifiers.resizing));
    isResizing = true;
    setInitialVals = true;
  };
  const handleMouseMove = (e2) => {
    const mousePos = position2 === "bottom" ? e2.clientY : e2.clientX;
    handleControlMove(e2, mousePos);
  };
  const handleTouchMove = (e2) => {
    e2.preventDefault();
    e2.stopImmediatePropagation();
    const touchPos = position2 === "bottom" ? e2.touches[0].clientY : e2.touches[0].clientX;
    handleControlMove(e2, touchPos);
  };
  const handleControlMove = (e2, controlPosition) => {
    e2.stopPropagation();
    if (!isResizing) {
      return;
    }
    if (setInitialVals) {
      panelRect = panel.current.getBoundingClientRect();
      right2 = panelRect.right;
      left2 = panelRect.left;
      bottom2 = panelRect.bottom;
      setInitialVals = false;
    }
    const mousePos = controlPosition;
    let newSize2 = 0;
    if (position2 === "right") {
      newSize2 = right2 - mousePos;
    } else if (position2 === "left") {
      newSize2 = mousePos - left2;
    } else {
      newSize2 = bottom2 - mousePos;
    }
    if (position2 === "bottom") {
      panel.current.style.overflowAnchor = "none";
    }
    panel.current.style.setProperty("--pf-c-drawer__panel--md--FlexBasis", newSize2 + "px");
    currWidth = newSize2;
  };
  const handleMouseup = () => {
    if (!isResizing) {
      return;
    }
    drawerRef.current.classList.remove(css(styles$e.modifiers.resizing));
    isResizing = false;
    onResize && onResize(currWidth, id3);
    setInitialVals = true;
    document.removeEventListener("mousemove", callbackMouseMove);
    document.removeEventListener("mouseup", callbackMouseUp);
  };
  const handleTouchEnd = (e2) => {
    e2.stopPropagation();
    if (!isResizing) {
      return;
    }
    isResizing = false;
    onResize && onResize(currWidth, id3);
    document.removeEventListener("touchmove", callbackTouchMove);
    document.removeEventListener("touchend", callbackTouchEnd);
  };
  const callbackMouseMove = react.useCallback(handleMouseMove, []);
  const callbackTouchEnd = react.useCallback(handleTouchEnd, []);
  const callbackTouchMove = react.useCallback(handleTouchMove, []);
  const callbackMouseUp = react.useCallback(handleMouseup, []);
  const handleKeys = (e2) => {
    const key = e2.key;
    if (key !== " " && key !== "Escape" && key !== "Enter" && key !== "ArrowUp" && key !== "ArrowDown" && key !== "ArrowLeft" && key !== "ArrowRight") {
      if (isResizing) {
        e2.preventDefault();
      }
      return;
    }
    e2.preventDefault();
    if (key === " " || key === "Escape" || key === "Enter") {
      if (key === " ") {
        isResizing = true;
      } else {
        isResizing = false;
        onResize && onResize(currWidth, id3);
      }
      const panelRect2 = panel.current.getBoundingClientRect();
      newSize = position2 === "bottom" ? panelRect2.height : panelRect2.width;
    }
    if (isResizing) {
      let delta = 0;
      if (key === "ArrowRight") {
        delta = position2 === "left" ? increment : -increment;
      } else if (key === "ArrowLeft") {
        delta = position2 === "left" ? -increment : increment;
      } else if (key === "ArrowUp") {
        delta = increment;
      } else if (key === "ArrowDown") {
        delta = -increment;
      }
      newSize = newSize + delta;
      if (position2 === "bottom") {
        panel.current.style.overflowAnchor = "none";
      }
      panel.current.style.setProperty("--pf-c-drawer__panel--md--FlexBasis", newSize + "px");
      currWidth = newSize;
    }
  };
  const boundaryCssVars = {};
  if (defaultSize) {
    boundaryCssVars["--pf-c-drawer__panel--md--FlexBasis"] = defaultSize;
  }
  if (minSize) {
    boundaryCssVars["--pf-c-drawer__panel--md--FlexBasis--min"] = minSize;
  }
  if (maxSize) {
    boundaryCssVars["--pf-c-drawer__panel--md--FlexBasis--max"] = maxSize;
  }
  return react.createElement("div", Object.assign({id: id3, className: css(styles$e.drawerPanel, isResizable && styles$e.modifiers.resizable, hasNoBorder && styles$e.modifiers.noBorder, formatBreakpointMods(widths, styles$e), colorVariant === DrawerColorVariant.light200 && styles$e.modifiers.light_200, className), ref: panel, onTransitionEnd: (ev) => {
    if (!hidden && ev.nativeEvent.propertyName === "transform") {
      onExpand();
    }
    setIsExpandedInternal(!hidden);
  }, hidden}, (defaultSize || minSize || maxSize) && {
    style: boundaryCssVars
  }, props), isExpandedInternal && react.createElement(react.Fragment, null, isResizable && react.createElement(react.Fragment, null, react.createElement("div", {className: css(styles$e.drawerSplitter, position2 !== "bottom" && styles$e.modifiers.vertical), role: "separator", tabIndex: 0, "aria-orientation": position2 === "bottom" ? "horizontal" : "vertical", "aria-label": resizeAriaLabel, "aria-describedby": resizeAriaDescribedBy, onMouseDown: handleMousedown, onKeyDown: handleKeys, onTouchStart: handleTouchStart}, react.createElement("div", {className: css(styles$e.drawerSplitterHandle), "aria-hidden": true})), react.createElement("div", {className: css(styles$e.drawerPanelMain)}, children2)), !isResizable && children2));
};
DrawerPanelContent.displayName = "DrawerPanelContent";
var AngleDoubleLeftIconConfig = {
  name: "AngleDoubleLeftIcon",
  height: 512,
  width: 448,
  svgPath: "M223.7 239l136-136c9.4-9.4 24.6-9.4 33.9 0l22.6 22.6c9.4 9.4 9.4 24.6 0 33.9L319.9 256l96.4 96.4c9.4 9.4 9.4 24.6 0 33.9L393.7 409c-9.4 9.4-24.6 9.4-33.9 0l-136-136c-9.5-9.4-9.5-24.6-.1-34zm-192 34l136 136c9.4 9.4 24.6 9.4 33.9 0l22.6-22.6c9.4-9.4 9.4-24.6 0-33.9L127.9 256l96.4-96.4c9.4-9.4 9.4-24.6 0-33.9L201.7 103c-9.4-9.4-24.6-9.4-33.9 0l-136 136c-9.5 9.4-9.5 24.6-.1 34z",
  yOffset: 0,
  xOffset: 0
};
var AngleDoubleLeftIcon = createIcon(AngleDoubleLeftIconConfig);
var AngleLeftIconConfig = {
  name: "AngleLeftIcon",
  height: 512,
  width: 256,
  svgPath: "M31.7 239l136-136c9.4-9.4 24.6-9.4 33.9 0l22.6 22.6c9.4 9.4 9.4 24.6 0 33.9L127.9 256l96.4 96.4c9.4 9.4 9.4 24.6 0 33.9L201.7 409c-9.4 9.4-24.6 9.4-33.9 0l-136-136c-9.5-9.4-9.5-24.6-.1-34z",
  yOffset: 0,
  xOffset: 0
};
var AngleLeftIcon = createIcon(AngleLeftIconConfig);
var AngleDoubleRightIconConfig = {
  name: "AngleDoubleRightIcon",
  height: 512,
  width: 448,
  svgPath: "M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34zm192-34l-136-136c-9.4-9.4-24.6-9.4-33.9 0l-22.6 22.6c-9.4 9.4-9.4 24.6 0 33.9l96.4 96.4-96.4 96.4c-9.4 9.4-9.4 24.6 0 33.9l22.6 22.6c9.4 9.4 24.6 9.4 33.9 0l136-136c9.4-9.2 9.4-24.4 0-33.8z",
  yOffset: 0,
  xOffset: 0
};
var AngleDoubleRightIcon = createIcon(AngleDoubleRightIconConfig);
var EmptyStatePrimary = (_a) => {
  var {children: children2, className = ""} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("div", Object.assign({className: css(styles$3.emptyStatePrimary, className)}, props), children2);
};
EmptyStatePrimary.displayName = "EmptyStatePrimary";
var expandableSection = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    expandableSection: "pf-c-expandable-section",
    expandableSectionContent: "pf-c-expandable-section__content",
    expandableSectionToggle: "pf-c-expandable-section__toggle",
    expandableSectionToggleIcon: "pf-c-expandable-section__toggle-icon",
    expandableSectionToggleText: "pf-c-expandable-section__toggle-text",
    modifiers: {
      expanded: "pf-m-expanded",
      detached: "pf-m-detached",
      limitWidth: "pf-m-limit-width",
      displayLg: "pf-m-display-lg",
      active: "pf-m-active",
      expandTop: "pf-m-expand-top",
      overpassFont: "pf-m-overpass-font"
    }
  };
});
var styles$f = /* @__PURE__ */ getDefaultExportFromCjs(expandableSection);
var ExpandableSection = class extends react.Component {
  constructor(props) {
    super(props);
    this.state = {
      isExpanded: props.isExpanded
    };
  }
  calculateToggleText(toggleText, toggleTextExpanded, toggleTextCollapsed, propOrStateIsExpanded) {
    if (propOrStateIsExpanded && toggleTextExpanded !== "") {
      return toggleTextExpanded;
    }
    if (!propOrStateIsExpanded && toggleTextCollapsed !== "") {
      return toggleTextCollapsed;
    }
    return toggleText;
  }
  render() {
    const _a = this.props, {
      onToggle: onToggleProp,
      isActive,
      className,
      toggleText,
      toggleTextExpanded,
      toggleTextCollapsed,
      children: children2,
      isExpanded,
      isDetached: isDetached2,
      displaySize,
      isWidthLimited,
      contentId
    } = _a, props = __rest(_a, ["onToggle", "isActive", "className", "toggleText", "toggleTextExpanded", "toggleTextCollapsed", "children", "isExpanded", "isDetached", "displaySize", "isWidthLimited", "contentId"]);
    let onToggle = onToggleProp;
    let propOrStateIsExpanded = isExpanded;
    if (isExpanded === void 0) {
      propOrStateIsExpanded = this.state.isExpanded;
      onToggle = (isOpen) => {
        this.setState({isExpanded: isOpen}, () => onToggleProp(this.state.isExpanded));
      };
    }
    const computedToggleText = this.calculateToggleText(toggleText, toggleTextExpanded, toggleTextCollapsed, propOrStateIsExpanded);
    return react.createElement("div", Object.assign({}, props, {className: css(styles$f.expandableSection, propOrStateIsExpanded && styles$f.modifiers.expanded, isActive && styles$f.modifiers.active, isDetached2 && styles$f.modifiers.detached, displaySize === "large" && styles$f.modifiers.displayLg, isWidthLimited && styles$f.modifiers.limitWidth, className)}), !isDetached2 && react.createElement("button", {className: css(styles$f.expandableSectionToggle), type: "button", "aria-expanded": propOrStateIsExpanded, onClick: () => onToggle(!propOrStateIsExpanded)}, react.createElement("span", {className: css(styles$f.expandableSectionToggleIcon)}, react.createElement(AngleRightIcon, {"aria-hidden": true})), react.createElement("span", {className: css(styles$f.expandableSectionToggleText)}, computedToggleText)), react.createElement("div", {className: css(styles$f.expandableSectionContent), hidden: !propOrStateIsExpanded, id: contentId}, children2));
  }
};
ExpandableSection.displayName = "ExpandableSection";
ExpandableSection.defaultProps = {
  className: "",
  toggleText: "",
  toggleTextExpanded: "",
  toggleTextCollapsed: "",
  onToggle: (isExpanded) => void 0,
  isActive: false,
  isDetached: false,
  displaySize: "default",
  isWidthLimited: false,
  contentId: ""
};
var fileUpload = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    fileUpload: "pf-c-file-upload",
    fileUploadFileDetails: "pf-c-file-upload__file-details",
    fileUploadFileDetailsSpinner: "pf-c-file-upload__file-details-spinner",
    fileUploadFileSelect: "pf-c-file-upload__file-select",
    formControl: "pf-c-form-control",
    modifiers: {
      dragHover: "pf-m-drag-hover",
      loading: "pf-m-loading",
      control: "pf-m-control"
    }
  };
});
var styles$g = /* @__PURE__ */ getDefaultExportFromCjs(fileUpload);
var fileReaderType;
(function(fileReaderType2) {
  fileReaderType2["text"] = "text";
  fileReaderType2["dataURL"] = "dataURL";
})(fileReaderType || (fileReaderType = {}));
function readFile(fileHandle, type) {
  return new Promise((resolve2, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve2(reader.result);
    reader.onerror = () => reject(reader.error);
    if (type === fileReaderType.text) {
      reader.readAsText(fileHandle);
    } else if (type === fileReaderType.dataURL) {
      reader.readAsDataURL(fileHandle);
    } else {
      reject("unknown type");
    }
  });
}
var FileUploadField = (_a) => {
  var {id: id3, type, value = "", filename = "", onChange = () => {
  }, onBrowseButtonClick = () => {
  }, onClearButtonClick = () => {
  }, onTextAreaClick, onTextChange, className = "", isDisabled = false, isReadOnly = false, isLoading = false, spinnerAriaValueText, isRequired = false, isDragActive = false, validated = "default", "aria-label": ariaLabel = "File upload", filenamePlaceholder = "Drag a file here or browse to upload", filenameAriaLabel = filename ? "Read only filename" : filenamePlaceholder, browseButtonText = "Browse...", clearButtonText = "Clear", isClearButtonDisabled = !filename && !value, containerRef = null, allowEditingUploadedText = false, hideDefaultPreview = false, children: children2 = null} = _a, props = __rest(_a, ["id", "type", "value", "filename", "onChange", "onBrowseButtonClick", "onClearButtonClick", "onTextAreaClick", "onTextChange", "className", "isDisabled", "isReadOnly", "isLoading", "spinnerAriaValueText", "isRequired", "isDragActive", "validated", "aria-label", "filenamePlaceholder", "filenameAriaLabel", "browseButtonText", "clearButtonText", "isClearButtonDisabled", "containerRef", "allowEditingUploadedText", "hideDefaultPreview", "children"]);
  const onTextAreaChange = (newValue, event) => {
    onChange(newValue, filename, event);
    onTextChange === null || onTextChange === void 0 ? void 0 : onTextChange(newValue);
  };
  return react.createElement("div", Object.assign({className: css(styles$g.fileUpload, isDragActive && styles$g.modifiers.dragHover, isLoading && styles$g.modifiers.loading, className), ref: containerRef}, props), react.createElement("div", {className: styles$g.fileUploadFileSelect}, react.createElement(InputGroup, null, react.createElement(TextInput, {isReadOnly: true, isDisabled, id: `${id3}-filename`, name: `${id3}-filename`, "aria-label": filenameAriaLabel, placeholder: filenamePlaceholder, "aria-describedby": `${id3}-browse-button`, value: filename}), react.createElement(Button, {id: `${id3}-browse-button`, variant: ButtonVariant.control, onClick: onBrowseButtonClick, isDisabled}, browseButtonText), react.createElement(Button, {variant: ButtonVariant.control, isDisabled: isDisabled || isClearButtonDisabled, onClick: onClearButtonClick}, clearButtonText))), react.createElement("div", {className: styles$g.fileUploadFileDetails}, !hideDefaultPreview && type === fileReaderType.text && react.createElement(TextArea, {readOnly: isReadOnly || !!filename && !allowEditingUploadedText, disabled: isDisabled, isRequired, resizeOrientation: TextAreResizeOrientation.vertical, validated, id: id3, name: id3, "aria-label": ariaLabel, value, onChange: onTextAreaChange, onClick: onTextAreaClick}), isLoading && react.createElement("div", {className: styles$g.fileUploadFileDetailsSpinner}, react.createElement(Spinner, {size: spinnerSize.lg, "aria-valuetext": spinnerAriaValueText}))), children2);
};
FileUploadField.displayName = "FileUploadField";
var FileUpload = (_a) => {
  var {id: id3, type, value = type === fileReaderType.text || type === fileReaderType.dataURL ? "" : null, filename = "", children: children2 = null, onChange = () => {
  }, onFileInputChange = null, onReadStarted = () => {
  }, onReadFinished = () => {
  }, onReadFailed = () => {
  }, onClearClick, onClick = (event) => event.preventDefault(), onTextChange, onDataChange, dropzoneProps = {}} = _a, props = __rest(_a, ["id", "type", "value", "filename", "children", "onChange", "onFileInputChange", "onReadStarted", "onReadFinished", "onReadFailed", "onClearClick", "onClick", "onTextChange", "onDataChange", "dropzoneProps"]);
  const onDropAccepted = (acceptedFiles, event) => {
    if (acceptedFiles.length > 0) {
      const fileHandle = acceptedFiles[0];
      if (event.type === "drop") {
        onFileInputChange === null || onFileInputChange === void 0 ? void 0 : onFileInputChange(event, fileHandle);
      }
      if (type === fileReaderType.text || type === fileReaderType.dataURL) {
        onChange("", fileHandle.name, event);
        onReadStarted(fileHandle);
        readFile(fileHandle, type).then((data2) => {
          onReadFinished(fileHandle);
          onChange(data2, fileHandle.name, event);
          onDataChange === null || onDataChange === void 0 ? void 0 : onDataChange(data2);
        }).catch((error2) => {
          onReadFailed(error2, fileHandle);
          onReadFinished(fileHandle);
          onChange("", "", event);
          onDataChange === null || onDataChange === void 0 ? void 0 : onDataChange("");
        });
      } else {
        onChange(fileHandle, fileHandle.name, event);
      }
    }
    dropzoneProps.onDropAccepted && dropzoneProps.onDropAccepted(acceptedFiles, event);
  };
  const onDropRejected = (rejectedFiles, event) => {
    if (rejectedFiles.length > 0) {
      onChange("", rejectedFiles[0].name, event);
    }
    dropzoneProps.onDropRejected && dropzoneProps.onDropRejected(rejectedFiles, event);
  };
  const fileInputRef = react.useRef();
  const setFileValue = (filename2) => {
    fileInputRef.current.value = filename2;
  };
  const onClearButtonClick = (event) => {
    onChange("", "", event);
    onClearClick === null || onClearClick === void 0 ? void 0 : onClearClick(event);
    setFileValue(null);
  };
  return react.createElement(Dropzone, Object.assign({multiple: false}, dropzoneProps, {onDropAccepted, onDropRejected}), ({getRootProps, getInputProps, isDragActive, open: open2}) => {
    const oldInputProps = getInputProps();
    const inputProps = Object.assign(Object.assign({}, oldInputProps), {onChange: (e2) => __awaiter(void 0, void 0, void 0, function* () {
      var _a2;
      (_a2 = oldInputProps.onChange) === null || _a2 === void 0 ? void 0 : _a2.call(oldInputProps, e2);
      const files = yield fromEvent(e2.nativeEvent);
      if (files.length === 1) {
        onFileInputChange === null || onFileInputChange === void 0 ? void 0 : onFileInputChange(e2, files[0]);
      }
    })});
    return react.createElement(FileUploadField, Object.assign({}, getRootProps(Object.assign(Object.assign({}, props), {refKey: "containerRef", onClick: (event) => event.preventDefault()})), {tabIndex: null, id: id3, type, filename, value, onChange, isDragActive, onBrowseButtonClick: open2, onClearButtonClick, onTextAreaClick: onClick, onTextChange}), react.createElement("input", Object.assign({}, inputProps, {ref: (input) => {
      fileInputRef.current = input;
      inputProps.ref(input);
    }})), children2);
  });
};
FileUpload.displayName = "FileUpload";
var ActionGroup = (_a) => {
  var {children: children2 = null, className = ""} = _a, props = __rest(_a, ["children", "className"]);
  const customClassName = css(formStyles$1.formGroup, formStyles$1.modifiers.action, className);
  const formActionsComponent = react.createElement("div", {className: css(formStyles$1.formActions)}, children2);
  return react.createElement("div", Object.assign({}, props, {className: customClassName}), react.createElement("div", {className: css(formStyles$1.formGroupControl)}, formActionsComponent));
};
ActionGroup.displayName = "ActionGroup";
var Form = (_a) => {
  var {children: children2 = null, className = "", isHorizontal = false, isWidthLimited = false} = _a, props = __rest(_a, ["children", "className", "isHorizontal", "isWidthLimited"]);
  return react.createElement("form", Object.assign({noValidate: true}, props, {className: css(formStyles$1.form, isHorizontal && formStyles$1.modifiers.horizontal, isWidthLimited && formStyles$1.modifiers.limitWidth, className)}), children2);
};
Form.displayName = "Form";
var FormGroup = (_a) => {
  var {children: children2 = null, className = "", label: label2, labelInfo, labelIcon, isRequired = false, validated = "default", isInline = false, hasNoPaddingTop = false, isStack = false, helperText, isHelperTextBeforeField = false, helperTextInvalid, helperTextIcon, helperTextInvalidIcon, fieldId} = _a, props = __rest(_a, ["children", "className", "label", "labelInfo", "labelIcon", "isRequired", "validated", "isInline", "hasNoPaddingTop", "isStack", "helperText", "isHelperTextBeforeField", "helperTextInvalid", "helperTextIcon", "helperTextInvalidIcon", "fieldId"]);
  const validHelperText = typeof helperText !== "string" ? helperText : react.createElement("div", {className: css(formStyles$1.formHelperText, validated === ValidatedOptions.success && formStyles$1.modifiers.success, validated === ValidatedOptions.warning && formStyles$1.modifiers.warning), id: `${fieldId}-helper`, "aria-live": "polite"}, helperTextIcon && react.createElement("span", {className: css(formStyles$1.formHelperTextIcon)}, helperTextIcon), helperText);
  const inValidHelperText = typeof helperTextInvalid !== "string" ? helperTextInvalid : react.createElement("div", {className: css(formStyles$1.formHelperText, formStyles$1.modifiers.error), id: `${fieldId}-helper`, "aria-live": "polite"}, helperTextInvalidIcon && react.createElement("span", {className: css(formStyles$1.formHelperTextIcon)}, helperTextInvalidIcon), helperTextInvalid);
  const showValidHelperTxt = (validationType) => validationType !== ValidatedOptions.error && helperText ? validHelperText : "";
  const helperTextToDisplay = validated === ValidatedOptions.error && helperTextInvalid ? inValidHelperText : showValidHelperTxt(validated);
  const labelContent = react.createElement(react.Fragment, null, react.createElement("label", {className: css(formStyles$1.formLabel), htmlFor: fieldId}, react.createElement("span", {className: css(formStyles$1.formLabelText)}, label2), isRequired && react.createElement("span", {className: css(formStyles$1.formLabelRequired), "aria-hidden": "true"}, " ", ASTERISK)), " ", react.isValidElement(labelIcon) && labelIcon);
  return react.createElement("div", Object.assign({}, props, {className: css(formStyles$1.formGroup, className)}), label2 && react.createElement("div", {className: css(formStyles$1.formGroupLabel, labelInfo && formStyles$1.modifiers.info, hasNoPaddingTop && formStyles$1.modifiers.noPaddingTop)}, labelInfo && react.createElement(react.Fragment, null, react.createElement("div", {className: css(formStyles$1.formGroupLabelMain)}, labelContent), react.createElement("div", {className: css(formStyles$1.formGroupLabelInfo)}, labelInfo)), !labelInfo && labelContent), react.createElement("div", {className: css(formStyles$1.formGroupControl, isInline && formStyles$1.modifiers.inline, isStack && formStyles$1.modifiers.stack)}, isHelperTextBeforeField && helperTextToDisplay, children2, !isHelperTextBeforeField && helperTextToDisplay));
};
FormGroup.displayName = "FormGroup";
var MinusIconConfig = {
  name: "MinusIcon",
  height: 512,
  width: 448,
  svgPath: "M416 208H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h384c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z",
  yOffset: 0,
  xOffset: 0
};
var MinusIcon = createIcon(MinusIconConfig);
var jumpLinks = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    jumpLinks: "pf-c-jump-links",
    jumpLinksItem: "pf-c-jump-links__item",
    jumpLinksLabel: "pf-c-jump-links__label",
    jumpLinksLink: "pf-c-jump-links__link",
    jumpLinksLinkText: "pf-c-jump-links__link-text",
    jumpLinksList: "pf-c-jump-links__list",
    jumpLinksMain: "pf-c-jump-links__main",
    jumpLinksToggle: "pf-c-jump-links__toggle",
    jumpLinksToggleIcon: "pf-c-jump-links__toggle-icon",
    jumpLinksToggleText: "pf-c-jump-links__toggle-text",
    modifiers: {
      center: "pf-m-center",
      vertical: "pf-m-vertical",
      expandable: "pf-m-expandable",
      nonExpandable: "pf-m-non-expandable",
      expandableOnSm: "pf-m-expandable-on-sm",
      nonExpandableOnSm: "pf-m-non-expandable-on-sm",
      expandableOnMd: "pf-m-expandable-on-md",
      nonExpandableOnMd: "pf-m-non-expandable-on-md",
      expandableOnLg: "pf-m-expandable-on-lg",
      nonExpandableOnLg: "pf-m-non-expandable-on-lg",
      expandableOnXl: "pf-m-expandable-on-xl",
      nonExpandableOnXl: "pf-m-non-expandable-on-xl",
      expandableOn_2xl: "pf-m-expandable-on-2xl",
      nonExpandableOn_2xl: "pf-m-non-expandable-on-2xl",
      expanded: "pf-m-expanded",
      current: "pf-m-current"
    }
  };
});
var styles$h = /* @__PURE__ */ getDefaultExportFromCjs(jumpLinks);
var sidebar = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    modifiers: {
      gutter: "pf-m-gutter",
      panelRight: "pf-m-panel-right",
      stack: "pf-m-stack",
      split: "pf-m-split",
      sticky: "pf-m-sticky",
      static: "pf-m-static",
      noBackground: "pf-m-no-background",
      widthDefault: "pf-m-width-default",
      width_25: "pf-m-width-25",
      width_33: "pf-m-width-33",
      width_50: "pf-m-width-50",
      width_66: "pf-m-width-66",
      width_75: "pf-m-width-75",
      width_100: "pf-m-width-100",
      widthDefaultOnSm: "pf-m-width-default-on-sm",
      width_25OnSm: "pf-m-width-25-on-sm",
      width_33OnSm: "pf-m-width-33-on-sm",
      width_50OnSm: "pf-m-width-50-on-sm",
      width_66OnSm: "pf-m-width-66-on-sm",
      width_75OnSm: "pf-m-width-75-on-sm",
      width_100OnSm: "pf-m-width-100-on-sm",
      widthDefaultOnMd: "pf-m-width-default-on-md",
      width_25OnMd: "pf-m-width-25-on-md",
      width_33OnMd: "pf-m-width-33-on-md",
      width_50OnMd: "pf-m-width-50-on-md",
      width_66OnMd: "pf-m-width-66-on-md",
      width_75OnMd: "pf-m-width-75-on-md",
      width_100OnMd: "pf-m-width-100-on-md",
      widthDefaultOnLg: "pf-m-width-default-on-lg",
      width_25OnLg: "pf-m-width-25-on-lg",
      width_33OnLg: "pf-m-width-33-on-lg",
      width_50OnLg: "pf-m-width-50-on-lg",
      width_66OnLg: "pf-m-width-66-on-lg",
      width_75OnLg: "pf-m-width-75-on-lg",
      width_100OnLg: "pf-m-width-100-on-lg",
      widthDefaultOnXl: "pf-m-width-default-on-xl",
      width_25OnXl: "pf-m-width-25-on-xl",
      width_33OnXl: "pf-m-width-33-on-xl",
      width_50OnXl: "pf-m-width-50-on-xl",
      width_66OnXl: "pf-m-width-66-on-xl",
      width_75OnXl: "pf-m-width-75-on-xl",
      width_100OnXl: "pf-m-width-100-on-xl",
      widthDefaultOn_2xl: "pf-m-width-default-on-2xl",
      width_25On_2xl: "pf-m-width-25-on-2xl",
      width_33On_2xl: "pf-m-width-33-on-2xl",
      width_50On_2xl: "pf-m-width-50-on-2xl",
      width_66On_2xl: "pf-m-width-66-on-2xl",
      width_75On_2xl: "pf-m-width-75-on-2xl",
      width_100On_2xl: "pf-m-width-100-on-2xl"
    },
    sidebar: "pf-c-sidebar",
    sidebarContent: "pf-c-sidebar__content",
    sidebarMain: "pf-c-sidebar__main",
    sidebarPanel: "pf-c-sidebar__panel"
  };
});
var styles$i = /* @__PURE__ */ getDefaultExportFromCjs(sidebar);
var JumpLinksList = (_a) => {
  var {children: children2, className} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("ul", Object.assign({className: css(styles$h.jumpLinksList, className)}, props), children2);
};
JumpLinksList.displayName = "JumpLinksList";
var JumpLinksItem = (_a) => {
  var {
    isActive,
    href,
    node,
    children: children2,
    onClick,
    className
  } = _a, props = __rest(_a, ["isActive", "href", "node", "children", "onClick", "className"]);
  const childrenArr = react.Children.toArray(children2);
  const sublists = childrenArr.filter((child) => child.type === JumpLinksList);
  children2 = childrenArr.filter((child) => child.type !== JumpLinksList);
  return react.createElement("li", Object.assign({className: css(styles$h.jumpLinksItem, isActive && styles$h.modifiers.current, className)}, props), react.createElement("a", {className: styles$h.jumpLinksLink, href, onClick}, react.createElement("span", {className: styles$h.jumpLinksLinkText}, children2)), sublists);
};
JumpLinksItem.displayName = "JumpLinksItem";
var c_jump_links__toggle_Display = {
  name: "--pf-c-jump-links__toggle--Display",
  value: "none",
  var: "var(--pf-c-jump-links__toggle--Display)"
};
var getScrollItems = (children2, res) => {
  react.Children.forEach(children2, (child) => {
    if (canUseDOM && document.getElementById && document.querySelector && child.type === JumpLinksItem) {
      const scrollNode = child.props.node || child.props.href;
      if (typeof scrollNode === "string") {
        if (scrollNode.startsWith("#")) {
          res.push(document.getElementById(scrollNode.substr(1)));
        } else {
          res.push(document.querySelector(scrollNode));
        }
      } else if (scrollNode instanceof HTMLElement) {
        res.push(scrollNode);
      }
    }
    if ([react.Fragment, JumpLinksList, JumpLinksItem].includes(child.type)) {
      getScrollItems(child.props.children, res);
    }
  });
  return res;
};
function isResponsive(jumpLinks2) {
  return jumpLinks2 && getComputedStyle(jumpLinks2).getPropertyValue(c_jump_links__toggle_Display.name).includes("block");
}
var JumpLinks = (_a) => {
  var {isCentered, isVertical, children: children2, label: label2, "aria-label": ariaLabel = typeof label2 === "string" ? label2 : null, scrollableSelector, activeIndex: activeIndexProp = 0, offset: offset2 = 0, expandable: expandable2, isExpanded: isExpandedProp = false, alwaysShowLabel = true, toggleAriaLabel = "Toggle jump links", className} = _a, props = __rest(_a, ["isCentered", "isVertical", "children", "label", "aria-label", "scrollableSelector", "activeIndex", "offset", "expandable", "isExpanded", "alwaysShowLabel", "toggleAriaLabel", "className"]);
  const hasScrollSpy = Boolean(scrollableSelector);
  const [scrollItems, setScrollItems] = react.useState(hasScrollSpy ? getScrollItems(children2, []) : []);
  const [activeIndex, setActiveIndex] = react.useState(activeIndexProp);
  const [isExpanded, setIsExpanded] = react.useState(isExpandedProp);
  const isLinkClicked = react.useRef(false);
  react.useEffect(() => setIsExpanded(isExpandedProp), [isExpandedProp]);
  const navRef = react.useRef();
  let scrollableElement;
  const scrollSpy = react.useCallback(() => {
    if (!canUseDOM || !hasScrollSpy || !(scrollableElement instanceof HTMLElement)) {
      return;
    }
    if (isLinkClicked.current) {
      isLinkClicked.current = false;
      return;
    }
    const scrollPosition = Math.ceil(scrollableElement.scrollTop + offset2);
    window.requestAnimationFrame(() => {
      let newScrollItems = scrollItems;
      if (!newScrollItems[0] || newScrollItems.includes(null)) {
        newScrollItems = getScrollItems(children2, []);
        setScrollItems(newScrollItems);
      }
      const scrollElements = newScrollItems.map((e2, index3) => ({
        y: e2 ? e2.offsetTop : null,
        index: index3
      })).filter(({y: y3}) => y3 !== null).sort((e1, e2) => e2.y - e1.y);
      for (const {y: y3, index: index3} of scrollElements) {
        if (scrollPosition >= y3) {
          return setActiveIndex(index3);
        }
      }
    });
  }, [scrollItems, hasScrollSpy, scrollableElement]);
  react.useEffect(() => {
    scrollableElement = document.querySelector(scrollableSelector);
    if (!(scrollableElement instanceof HTMLElement)) {
      return;
    }
    scrollableElement.addEventListener("scroll", scrollSpy);
    return () => scrollableElement.removeEventListener("scroll", scrollSpy);
  }, [scrollableSelector, scrollSpy]);
  react.useEffect(() => {
    scrollSpy();
  }, []);
  let jumpLinkIndex = 0;
  const cloneChildren = (children3) => !hasScrollSpy ? children3 : react.Children.map(children3, (child) => {
    if (child.type === JumpLinksItem) {
      const {onClick: onClickProp, isActive: isActiveProp} = child.props;
      const itemIndex = jumpLinkIndex++;
      const scrollItem = scrollItems[itemIndex];
      return react.cloneElement(child, {
        onClick(ev) {
          isLinkClicked.current = true;
          let newScrollItems;
          if (!scrollItem) {
            newScrollItems = getScrollItems(children3, []);
            setScrollItems(newScrollItems);
          }
          const newScrollItem = scrollItem || newScrollItems[itemIndex];
          if (newScrollItem) {
            const scrollableElement2 = document.querySelector(scrollableSelector);
            if (scrollableElement2 instanceof HTMLElement) {
              if (isResponsive(navRef.current)) {
                if (navRef.current) {
                  navRef.current.classList.remove(styles$h.modifiers.expanded);
                }
                let stickyParent = navRef.current && navRef.current.parentElement;
                while (stickyParent && !stickyParent.classList.contains(styles$i.modifiers.sticky)) {
                  stickyParent = stickyParent.parentElement;
                }
                setIsExpanded(false);
                if (stickyParent) {
                  offset2 += stickyParent.scrollHeight;
                }
              }
              scrollableElement2.scrollTo(0, newScrollItem.offsetTop - offset2);
            }
            newScrollItem.focus();
            ev.preventDefault();
            setActiveIndex(itemIndex);
          }
          if (onClickProp) {
            onClickProp(ev);
          }
        },
        isActive: isActiveProp || activeIndex === itemIndex,
        children: cloneChildren(child.props.children)
      });
    } else if (child.type === react.Fragment) {
      return cloneChildren(child.props.children);
    } else if (child.type === JumpLinksList) {
      return react.cloneElement(child, {children: cloneChildren(child.props.children)});
    }
    return child;
  });
  return react.createElement("nav", Object.assign({className: css(styles$h.jumpLinks, isCentered && styles$h.modifiers.center, isVertical && styles$h.modifiers.vertical, formatBreakpointMods(expandable2, styles$h), isExpanded && styles$h.modifiers.expanded, className), "aria-label": ariaLabel, ref: navRef}, props), react.createElement("div", {className: styles$h.jumpLinksMain}, react.createElement("div", {className: css("pf-c-jump-links__header")}, expandable2 && react.createElement("div", {className: styles$h.jumpLinksToggle}, react.createElement(Button, {variant: "plain", onClick: () => setIsExpanded(!isExpanded), "aria-label": toggleAriaLabel, "aria-expanded": isExpanded}, react.createElement("span", {className: styles$h.jumpLinksToggleIcon}, react.createElement(AngleRightIcon, null)), label2 && react.createElement("span", {className: css(styles$h.jumpLinksToggleText)}, " ", label2, " "))), label2 && alwaysShowLabel && react.createElement("div", {className: css(styles$h.jumpLinksLabel)}, label2)), react.createElement("ul", {className: styles$h.jumpLinksList}, cloneChildren(children2))));
};
JumpLinks.displayName = "JumpLinks";
var label = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    label: "pf-c-label",
    labelContent: "pf-c-label__content",
    labelIcon: "pf-c-label__icon",
    labelText: "pf-c-label__text",
    modifiers: {
      compact: "pf-m-compact",
      blue: "pf-m-blue",
      green: "pf-m-green",
      orange: "pf-m-orange",
      red: "pf-m-red",
      purple: "pf-m-purple",
      cyan: "pf-m-cyan",
      outline: "pf-m-outline",
      overflow: "pf-m-overflow",
      editableActive: "pf-m-editable-active"
    }
  };
});
var labelStyles = /* @__PURE__ */ getDefaultExportFromCjs(label);
var labelGroup = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    labelGroup: "pf-c-label-group",
    labelGroupClose: "pf-c-label-group__close",
    labelGroupLabel: "pf-c-label-group__label",
    labelGroupList: "pf-c-label-group__list",
    labelGroupListItem: "pf-c-label-group__list-item",
    labelGroupMain: "pf-c-label-group__main",
    labelGroupTextarea: "pf-c-label-group__textarea",
    modifiers: {
      category: "pf-m-category",
      vertical: "pf-m-vertical",
      editable: "pf-m-editable",
      textarea: "pf-m-textarea"
    }
  };
});
var styles$j = /* @__PURE__ */ getDefaultExportFromCjs(labelGroup);
var colorStyles = {
  blue: labelStyles.modifiers.blue,
  cyan: labelStyles.modifiers.cyan,
  green: labelStyles.modifiers.green,
  orange: labelStyles.modifiers.orange,
  purple: labelStyles.modifiers.purple,
  red: labelStyles.modifiers.red,
  grey: ""
};
var Label = (_a) => {
  var {children: children2, className = "", color: color2 = "grey", variant = "filled", isCompact = false, isEditable = false, editableProps, isTruncated = false, tooltipPosition, icon, onClose, onEditCancel, onEditComplete, closeBtn, closeBtnAriaLabel, closeBtnProps, href, isOverflowLabel, render: render4} = _a, props = __rest(_a, ["children", "className", "color", "variant", "isCompact", "isEditable", "editableProps", "isTruncated", "tooltipPosition", "icon", "onClose", "onEditCancel", "onEditComplete", "closeBtn", "closeBtnAriaLabel", "closeBtnProps", "href", "isOverflowLabel", "render"]);
  const [isEditableActive, setIsEditableActive] = react.useState(false);
  const editableDivRef = react.createRef();
  react.useEffect(() => {
    document.addEventListener("click", onDocClick);
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("click", onDocClick);
      document.removeEventListener("keydown", onKeyDown);
    };
  });
  const onDocClick = (event) => {
    if (isEditableActive && editableDivRef && editableDivRef.current && !editableDivRef.current.contains(event.target)) {
      onEditComplete && onEditComplete(editableDivRef.current.textContent);
      setIsEditableActive(false);
    }
  };
  const onKeyDown = (event) => {
    const key = event.key;
    if (!editableDivRef || !editableDivRef.current || !editableDivRef.current.contains(event.target)) {
      return;
    }
    if (isEditableActive && (key === "Enter" || key === "Tab")) {
      event.preventDefault();
      event.stopImmediatePropagation();
      onEditComplete && onEditComplete(editableDivRef.current.textContent);
      setIsEditableActive(false);
    }
    if (isEditableActive && key === "Escape") {
      event.preventDefault();
      event.stopImmediatePropagation();
      editableDivRef.current.textContent = children2;
      onEditCancel && onEditCancel(children2);
      setIsEditableActive(false);
    }
    if (!isEditableActive && key === "Enter") {
      event.preventDefault();
      event.stopImmediatePropagation();
      setIsEditableActive(true);
      const el = event.target;
      const range3 = document.createRange();
      const sel = window.getSelection();
      range3.selectNodeContents(el);
      range3.collapse(false);
      sel.removeAllRanges();
      sel.addRange(range3);
    }
  };
  const LabelComponent = isOverflowLabel ? "button" : "span";
  const Component = href ? "a" : "span";
  const button2 = closeBtn ? closeBtn : react.createElement(Button, Object.assign({type: "button", variant: "plain", onClick: onClose, "aria-label": closeBtnAriaLabel || `Close ${children2}`}, closeBtnProps), react.createElement(TimesIcon, null));
  const textRef = react.createRef();
  const componentRef = react.useRef();
  const [isTooltipVisible, setIsTooltipVisible] = react.useState(false);
  useIsomorphicLayoutEffect(() => {
    setIsTooltipVisible(textRef.current && textRef.current.offsetWidth < textRef.current.scrollWidth);
  }, []);
  let content2 = react.createElement(react.Fragment, null, icon && react.createElement("span", {className: css(labelStyles.labelIcon)}, icon), isTruncated && react.createElement("span", {ref: textRef, className: css(labelStyles.labelText)}, children2), !isTruncated && children2);
  if (isEditable) {
    content2 = react.createElement(react.Fragment, null, react.createElement("div", {className: css(inlineStyles.inlineEdit)}, react.createElement("div", Object.assign({tabIndex: 0, ref: editableDivRef, className: css(inlineStyles.inlineEditEditableText), role: "textbox"}, isEditableActive && {contentEditable: true}, {suppressContentEditableWarning: true}, editableProps), children2)));
  }
  let labelComponentChild = react.createElement(Component, Object.assign({className: css(labelStyles.labelContent)}, href && {href}), content2);
  if (render4) {
    labelComponentChild = react.createElement(react.Fragment, null, isTooltipVisible && react.createElement(Tooltip, {reference: componentRef, content: children2, position: tooltipPosition}), render4({
      className: labelStyles.labelContent,
      content: content2,
      componentRef
    }));
  } else if (isTooltipVisible) {
    labelComponentChild = react.createElement(Tooltip, {content: children2, position: tooltipPosition}, react.createElement(Component, Object.assign({className: css(labelStyles.labelContent)}, href && {href}), content2));
  }
  return react.createElement(LabelComponent, Object.assign({}, props, {className: css(labelStyles.label, colorStyles[color2], variant === "outline" && labelStyles.modifiers.outline, isOverflowLabel && labelStyles.modifiers.overflow, isCompact && labelStyles.modifiers.compact, isEditable && styles$j.modifiers.editable, isEditableActive && labelStyles.modifiers.editableActive, className)}, isEditable && {
    onClick: (evt) => {
      const isEvtFromButton = evt.target.closest("button");
      if (isEvtFromButton !== null) {
        return;
      }
      setIsEditableActive(true);
      editableDivRef.current.focus();
    }
  }), labelComponentChild, onClose && button2);
};
Label.displayName = "Label";
var list = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    list: "pf-c-list",
    listItem: "pf-c-list__item",
    listItemIcon: "pf-c-list__item-icon",
    modifiers: {
      iconLg: "pf-m-icon-lg",
      plain: "pf-m-plain",
      inline: "pf-m-inline",
      bordered: "pf-m-bordered"
    }
  };
});
var styles$k = /* @__PURE__ */ getDefaultExportFromCjs(list);
var OrderType;
(function(OrderType2) {
  OrderType2["number"] = "1";
  OrderType2["lowercaseLetter"] = "a";
  OrderType2["uppercaseLetter"] = "A";
  OrderType2["lowercaseRomanNumber"] = "i";
  OrderType2["uppercaseRomanNumber"] = "I";
})(OrderType || (OrderType = {}));
var ListVariant;
(function(ListVariant2) {
  ListVariant2["inline"] = "inline";
})(ListVariant || (ListVariant = {}));
var ListComponent;
(function(ListComponent3) {
  ListComponent3["ol"] = "ol";
  ListComponent3["ul"] = "ul";
})(ListComponent || (ListComponent = {}));
var List = (_a) => {
  var {className = "", children: children2 = null, variant = null, isBordered = false, isPlain = false, iconSize = "default", type = OrderType.number, ref = null, component = ListComponent.ul} = _a, props = __rest(_a, ["className", "children", "variant", "isBordered", "isPlain", "iconSize", "type", "ref", "component"]);
  return component === ListComponent.ol ? react.createElement("ol", Object.assign({ref, type}, props, {className: css(styles$k.list, variant && styles$k.modifiers[variant], isBordered && styles$k.modifiers.bordered, isPlain && styles$k.modifiers.plain, iconSize && iconSize === "large" && styles$k.modifiers.iconLg, className)}), children2) : react.createElement("ul", Object.assign({ref}, props, {className: css(styles$k.list, variant && styles$k.modifiers[variant], isBordered && styles$k.modifiers.bordered, isPlain && styles$k.modifiers.plain, iconSize && iconSize === "large" && styles$k.modifiers.iconLg, className)}), children2);
};
List.displayName = "List";
var ListItem = (_a) => {
  var {icon = null, children: children2 = null} = _a, props = __rest(_a, ["icon", "children"]);
  return react.createElement("li", Object.assign({className: css(icon && styles$k.listItem)}, props), icon && react.createElement("span", {className: css(styles$k.listItemIcon)}, icon), children2);
};
ListItem.displayName = "ListItem";
var modalBox = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    modalBox: "pf-c-modal-box",
    modalBoxBody: "pf-c-modal-box__body",
    modalBoxDescription: "pf-c-modal-box__description",
    modalBoxFooter: "pf-c-modal-box__footer",
    modalBoxHeader: "pf-c-modal-box__header",
    modalBoxHeaderMain: "pf-c-modal-box__header-main",
    modalBoxTitle: "pf-c-modal-box__title",
    modalBoxTitleIcon: "pf-c-modal-box__title-icon",
    modalBoxTitleText: "pf-c-modal-box__title-text",
    modifiers: {
      sm: "pf-m-sm",
      md: "pf-m-md",
      lg: "pf-m-lg",
      alignTop: "pf-m-align-top",
      danger: "pf-m-danger",
      warning: "pf-m-warning",
      success: "pf-m-success",
      default: "pf-m-default",
      info: "pf-m-info",
      help: "pf-m-help",
      icon: "pf-m-icon"
    }
  };
});
var modalStyles = /* @__PURE__ */ getDefaultExportFromCjs(modalBox);
var ModalBoxBody = (_a) => {
  var {children: children2 = null, className = ""} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("div", Object.assign({}, props, {className: css(modalStyles.modalBoxBody, className)}), children2);
};
ModalBoxBody.displayName = "ModalBoxBody";
var ModalBoxCloseButton = (_a) => {
  var {className = "", onClose = () => void 0} = _a, props = __rest(_a, ["className", "onClose"]);
  return react.createElement(Button, Object.assign({className, variant: "plain", onClick: onClose, "aria-label": "Close"}, props), react.createElement(TimesIcon, null));
};
ModalBoxCloseButton.displayName = "ModalBoxCloseButton";
var c_modal_box_m_align_top_spacer = {
  name: "--pf-c-modal-box--m-align-top--spacer",
  value: "0.5rem",
  var: "var(--pf-c-modal-box--m-align-top--spacer)"
};
var ModalBox = (_a) => {
  var {children: children2, className = "", variant = "default", position: position2, positionOffset, "aria-labelledby": ariaLabelledby, "aria-label": ariaLabel = "", "aria-describedby": ariaDescribedby, style} = _a, props = __rest(_a, ["children", "className", "variant", "position", "positionOffset", "aria-labelledby", "aria-label", "aria-describedby", "style"]);
  if (positionOffset) {
    style = style || {};
    style[c_modal_box_m_align_top_spacer.name] = positionOffset;
  }
  return react.createElement("div", Object.assign({}, props, {role: "dialog", "aria-label": ariaLabel || null, "aria-labelledby": ariaLabelledby || null, "aria-describedby": ariaDescribedby, "aria-modal": "true", className: css(modalStyles.modalBox, className, position2 === "top" && modalStyles.modifiers.alignTop, variant === "large" && modalStyles.modifiers.lg, variant === "small" && modalStyles.modifiers.sm, variant === "medium" && modalStyles.modifiers.md), style}), children2);
};
ModalBox.displayName = "ModalBox";
var ModalBoxFooter = (_a) => {
  var {children: children2 = null, className = ""} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("footer", Object.assign({}, props, {className: css(modalStyles.modalBoxFooter, className)}), children2);
};
ModalBoxFooter.displayName = "ModalBoxFooter";
var ModalBoxDescription = (_a) => {
  var {children: children2 = null, className = "", id: id3 = ""} = _a, props = __rest(_a, ["children", "className", "id"]);
  return react.createElement("div", Object.assign({}, props, {id: id3, className: css(modalStyles.modalBoxDescription, className)}), children2);
};
ModalBoxDescription.displayName = "ModalBoxDescription";
var ModalBoxHeader = (_a) => {
  var {children: children2 = null, className = "", help = null} = _a, props = __rest(_a, ["children", "className", "help"]);
  return react.createElement("header", Object.assign({className: css(modalStyles.modalBoxHeader, help && modalStyles.modifiers.help, className)}, props), help && react.createElement(react.Fragment, null, react.createElement("div", {className: css(modalStyles.modalBoxHeaderMain)}, children2), react.createElement("div", {className: "pf-c-modal-box__header-help"}, help)), !help && children2);
};
ModalBoxHeader.displayName = "ModalBoxHeader";
var isVariantIcon = (icon) => ["success", "danger", "warning", "info", "default"].includes(icon);
var ModalBoxTitle = (_a) => {
  var {className = "", id: id3, title: title3, titleIconVariant, titleLabel = ""} = _a, props = __rest(_a, ["className", "id", "title", "titleIconVariant", "titleLabel"]);
  const [isTooltipVisible, setIsTooltipVisible] = react.useState(false);
  const h1 = react.useRef();
  const label2 = titleLabel || (isVariantIcon(titleIconVariant) ? `${capitalize2(titleIconVariant)} alert:` : titleLabel);
  const variantIcons2 = {
    success: react.createElement(CheckCircleIcon, null),
    danger: react.createElement(ExclamationCircleIcon, null),
    warning: react.createElement(ExclamationTriangleIcon, null),
    info: react.createElement(InfoCircleIcon, null),
    default: react.createElement(BellIcon, null)
  };
  const CustomIcon = !isVariantIcon(titleIconVariant) && titleIconVariant;
  useIsomorphicLayoutEffect(() => {
    setIsTooltipVisible(h1.current && h1.current.offsetWidth < h1.current.scrollWidth);
  }, []);
  const content2 = react.createElement("h1", Object.assign({id: id3, ref: h1, className: css(modalStyles.modalBoxTitle, titleIconVariant && modalStyles.modifiers.icon, className)}, props), titleIconVariant && react.createElement("span", {className: css(modalStyles.modalBoxTitleIcon)}, isVariantIcon(titleIconVariant) ? variantIcons2[titleIconVariant] : react.createElement(CustomIcon, null)), label2 && react.createElement("span", {className: css(a11yStyles.screenReader)}, label2), react.createElement("span", {className: css(modalStyles.modalBoxTitleText)}, title3));
  return isTooltipVisible ? react.createElement(Tooltip, {content: title3, isVisible: true}, content2) : content2;
};
ModalBoxTitle.displayName = "ModalBoxTitle";
var ModalContent = (_a) => {
  var {children: children2, className = "", isOpen = false, header = null, help = null, description = null, title: title3 = "", titleIconVariant = null, titleLabel = "", "aria-label": ariaLabel = "", "aria-describedby": ariaDescribedby, "aria-labelledby": ariaLabelledby, showClose = true, footer = null, actions: actions2 = [], onClose = () => void 0, variant = "default", position: position2, positionOffset, width: width2 = -1, boxId, labelId, descriptorId, disableFocusTrap = false, hasNoBodyWrapper = false, ouiaId, ouiaSafe = true} = _a, props = __rest(_a, ["children", "className", "isOpen", "header", "help", "description", "title", "titleIconVariant", "titleLabel", "aria-label", "aria-describedby", "aria-labelledby", "showClose", "footer", "actions", "onClose", "variant", "position", "positionOffset", "width", "boxId", "labelId", "descriptorId", "disableFocusTrap", "hasNoBodyWrapper", "ouiaId", "ouiaSafe"]);
  if (!isOpen) {
    return null;
  }
  const modalBoxHeader = header ? react.createElement(ModalBoxHeader, {help}, header) : title3 && react.createElement(ModalBoxHeader, {help}, react.createElement(ModalBoxTitle, {title: title3, titleIconVariant, titleLabel, id: labelId}), description && react.createElement(ModalBoxDescription, {id: descriptorId}, description));
  const modalBoxFooter = footer ? react.createElement(ModalBoxFooter, null, footer) : actions2.length > 0 && react.createElement(ModalBoxFooter, null, actions2);
  const modalBody = hasNoBodyWrapper ? children2 : react.createElement(ModalBoxBody, Object.assign({}, props, !description && !ariaDescribedby && {id: descriptorId}), children2);
  const boxStyle = width2 === -1 ? {} : {width: width2};
  const ariaLabelledbyFormatted = () => {
    if (ariaLabelledby === null) {
      return null;
    }
    const idRefList = [];
    if ((ariaLabel && boxId) !== "") {
      idRefList.push(ariaLabel && boxId);
    }
    if (ariaLabelledby) {
      idRefList.push(ariaLabelledby);
    }
    if (title3) {
      idRefList.push(labelId);
    }
    return idRefList.join(" ");
  };
  const modalBox2 = react.createElement(ModalBox, Object.assign({id: boxId, style: boxStyle, className: css(className, isVariantIcon(titleIconVariant) && modalStyles.modifiers[titleIconVariant]), variant, position: position2, positionOffset, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledbyFormatted(), "aria-describedby": ariaDescribedby || (hasNoBodyWrapper ? null : descriptorId)}, getOUIAProps(ModalContent.displayName, ouiaId, ouiaSafe)), showClose && react.createElement(ModalBoxCloseButton, {onClose}), modalBoxHeader, modalBody, modalBoxFooter);
  return react.createElement(Backdrop, null, react.createElement(FocusTrap, {active: !disableFocusTrap, focusTrapOptions: {clickOutsideDeactivates: true}, className: css(styles2.bullseye)}, modalBox2));
};
ModalContent.displayName = "ModalContent";
var ModalVariant;
(function(ModalVariant2) {
  ModalVariant2["small"] = "small";
  ModalVariant2["medium"] = "medium";
  ModalVariant2["large"] = "large";
  ModalVariant2["default"] = "default";
})(ModalVariant || (ModalVariant = {}));
var Modal = class extends react.Component {
  constructor(props) {
    super(props);
    this.boxId = "";
    this.labelId = "";
    this.descriptorId = "";
    this.handleEscKeyClick = (event) => {
      const {onEscapePress} = this.props;
      if (event.keyCode === KEY_CODES.ESCAPE_KEY && this.props.isOpen) {
        onEscapePress ? onEscapePress(event) : this.props.onClose();
      }
    };
    this.getElement = (appendTo) => {
      if (typeof appendTo === "function") {
        return appendTo();
      }
      return appendTo || document.body;
    };
    this.toggleSiblingsFromScreenReaders = (hide3) => {
      const {appendTo} = this.props;
      const target = this.getElement(appendTo);
      const bodyChildren = target.children;
      for (const child of Array.from(bodyChildren)) {
        if (child !== this.state.container) {
          hide3 ? child.setAttribute("aria-hidden", "" + hide3) : child.removeAttribute("aria-hidden");
        }
      }
    };
    this.isEmpty = (value) => value === null || value === void 0 || value === "";
    const boxIdNum = Modal.currentId++;
    const labelIdNum = boxIdNum + 1;
    const descriptorIdNum = boxIdNum + 2;
    this.boxId = props.id || `pf-modal-part-${boxIdNum}`;
    this.labelId = `pf-modal-part-${labelIdNum}`;
    this.descriptorId = `pf-modal-part-${descriptorIdNum}`;
    this.state = {
      container: void 0,
      ouiaStateId: getDefaultOUIAId(Modal.displayName, props.variant)
    };
  }
  componentDidMount() {
    const {appendTo, title: title3, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledby, hasNoBodyWrapper, header} = this.props;
    const target = this.getElement(appendTo);
    const container = document.createElement("div");
    this.setState({container});
    target.appendChild(container);
    target.addEventListener("keydown", this.handleEscKeyClick, false);
    if (this.props.isOpen) {
      target.classList.add(css(styles3.backdropOpen));
    } else {
      target.classList.remove(css(styles3.backdropOpen));
    }
    if (this.isEmpty(title3) && this.isEmpty(ariaLabel) && this.isEmpty(ariaLabelledby)) {
      console.error("Modal: Specify at least one of: title, aria-label, aria-labelledby.");
    }
    if (this.isEmpty(ariaLabel) && this.isEmpty(ariaLabelledby) && (hasNoBodyWrapper || header)) {
      console.error("Modal: When using hasNoBodyWrapper or setting a custom header, ensure you assign an accessible name to the the modal container with aria-label or aria-labelledby.");
    }
  }
  componentDidUpdate() {
    const {appendTo} = this.props;
    const target = this.getElement(appendTo);
    if (this.props.isOpen) {
      target.classList.add(css(styles3.backdropOpen));
      this.toggleSiblingsFromScreenReaders(true);
    } else {
      target.classList.remove(css(styles3.backdropOpen));
      this.toggleSiblingsFromScreenReaders(false);
    }
  }
  componentWillUnmount() {
    const {appendTo} = this.props;
    const target = this.getElement(appendTo);
    if (this.state.container) {
      target.removeChild(this.state.container);
    }
    target.removeEventListener("keydown", this.handleEscKeyClick, false);
    target.classList.remove(css(styles3.backdropOpen));
  }
  render() {
    const _a = this.props, {
      appendTo,
      onEscapePress,
      "aria-labelledby": ariaLabelledby,
      "aria-label": ariaLabel,
      "aria-describedby": ariaDescribedby,
      title: title3,
      titleIconVariant,
      titleLabel,
      ouiaId,
      ouiaSafe
    } = _a, props = __rest(_a, ["appendTo", "onEscapePress", "aria-labelledby", "aria-label", "aria-describedby", "title", "titleIconVariant", "titleLabel", "ouiaId", "ouiaSafe"]);
    const {container} = this.state;
    if (!canUseDOM || !container) {
      return null;
    }
    return reactDom.createPortal(react.createElement(ModalContent, Object.assign({}, props, {boxId: this.boxId, labelId: this.labelId, descriptorId: this.descriptorId, title: title3, titleIconVariant, titleLabel, "aria-label": ariaLabel, "aria-describedby": ariaDescribedby, "aria-labelledby": ariaLabelledby, ouiaId: ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId, ouiaSafe})), container);
  }
};
Modal.displayName = "Modal";
Modal.currentId = 0;
Modal.defaultProps = {
  className: "",
  isOpen: false,
  title: "",
  titleIconVariant: null,
  titleLabel: "",
  "aria-label": "",
  showClose: true,
  "aria-describedby": "",
  "aria-labelledby": "",
  id: void 0,
  actions: [],
  onClose: () => void 0,
  variant: "default",
  hasNoBodyWrapper: false,
  appendTo: () => document.body,
  ouiaSafe: true
};
var nav = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    divider: "pf-c-divider",
    menu: "pf-c-menu",
    menuContent: "pf-c-menu__content",
    menuItem: "pf-c-menu__item",
    menuListItem: "pf-c-menu__list-item",
    modifiers: {
      flyout: "pf-m-flyout",
      top: "pf-m-top",
      left: "pf-m-left",
      current: "pf-m-current",
      horizontal: "pf-m-horizontal",
      tertiary: "pf-m-tertiary",
      horizontalSubnav: "pf-m-horizontal-subnav",
      light: "pf-m-light",
      scrollable: "pf-m-scrollable",
      overflowHidden: "pf-m-overflow-hidden",
      expandable: "pf-m-expandable",
      expanded: "pf-m-expanded",
      drilldown: "pf-m-drilldown",
      hover: "pf-m-hover",
      start: "pf-m-start"
    },
    nav: "pf-c-nav",
    navItem: "pf-c-nav__item",
    navLink: "pf-c-nav__link",
    navList: "pf-c-nav__list",
    navScrollButton: "pf-c-nav__scroll-button",
    navSection: "pf-c-nav__section",
    navSectionTitle: "pf-c-nav__section-title",
    navSubnav: "pf-c-nav__subnav",
    navToggle: "pf-c-nav__toggle",
    navToggleIcon: "pf-c-nav__toggle-icon"
  };
});
var styles$l = /* @__PURE__ */ getDefaultExportFromCjs(nav);
var NavContext = react.createContext({});
var Nav = class extends react.Component {
  constructor() {
    super(...arguments);
    this.state = {
      isScrollable: false,
      ouiaStateId: getDefaultOUIAId(Nav.displayName, this.props.variant),
      flyoutRef: null
    };
  }
  onSelect(event, groupId, itemId, to, preventDefault, onClick) {
    if (preventDefault) {
      event.preventDefault();
    }
    this.props.onSelect({groupId, itemId, event, to});
    if (onClick) {
      onClick(event, itemId, groupId, to);
    }
  }
  onToggle(event, groupId, toggleValue) {
    this.props.onToggle({
      event,
      groupId,
      isExpanded: toggleValue
    });
  }
  render() {
    const _a = this.props, {
      "aria-label": ariaLabel,
      children: children2,
      className,
      onSelect,
      onToggle,
      theme,
      ouiaId,
      ouiaSafe,
      variant
    } = _a, props = __rest(_a, ["aria-label", "children", "className", "onSelect", "onToggle", "theme", "ouiaId", "ouiaSafe", "variant"]);
    const isHorizontal = ["horizontal", "tertiary"].includes(variant);
    return react.createElement(NavContext.Provider, {value: {
      onSelect: (event, groupId, itemId, to, preventDefault, onClick) => this.onSelect(event, groupId, itemId, to, preventDefault, onClick),
      onToggle: (event, groupId, expanded) => this.onToggle(event, groupId, expanded),
      updateIsScrollable: (isScrollable) => this.setState({isScrollable}),
      isHorizontal: ["horizontal", "tertiary", "horizontal-subnav"].includes(variant),
      flyoutRef: this.state.flyoutRef,
      setFlyoutRef: (flyoutRef) => this.setState({flyoutRef})
    }}, react.createElement("nav", Object.assign({className: css(styles$l.nav, theme === "light" && styles$l.modifiers.light, isHorizontal && styles$l.modifiers.horizontal, variant === "tertiary" && styles$l.modifiers.tertiary, variant === "horizontal-subnav" && styles$l.modifiers.horizontalSubnav, this.state.isScrollable && styles$l.modifiers.scrollable, className), "aria-label": ariaLabel || (variant === "tertiary" ? "Local" : "Global")}, getOUIAProps(Nav.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId, ouiaSafe), props), children2));
  }
};
Nav.displayName = "Nav";
Nav.defaultProps = {
  onSelect: () => void 0,
  onToggle: () => void 0,
  theme: "dark",
  ouiaSafe: true
};
var page = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    avatar: "pf-c-avatar",
    brand: "pf-c-brand",
    button: "pf-c-button",
    card: "pf-c-card",
    contextSelector: "pf-c-context-selector",
    drawer: "pf-c-drawer",
    masthead: "pf-c-masthead",
    modifiers: {
      light: "pf-m-light",
      menu: "pf-m-menu",
      hidden: "pf-m-hidden",
      hiddenOnSm: "pf-m-hidden-on-sm",
      visibleOnSm: "pf-m-visible-on-sm",
      hiddenOnMd: "pf-m-hidden-on-md",
      visibleOnMd: "pf-m-visible-on-md",
      hiddenOnLg: "pf-m-hidden-on-lg",
      visibleOnLg: "pf-m-visible-on-lg",
      hiddenOnXl: "pf-m-hidden-on-xl",
      visibleOnXl: "pf-m-visible-on-xl",
      hiddenOn_2xl: "pf-m-hidden-on-2xl",
      visibleOn_2xl: "pf-m-visible-on-2xl",
      read: "pf-m-read",
      selected: "pf-m-selected",
      unread: "pf-m-unread",
      attention: "pf-m-attention",
      expanded: "pf-m-expanded",
      collapsed: "pf-m-collapsed",
      limitWidth: "pf-m-limit-width",
      alignCenter: "pf-m-align-center",
      stickyTop: "pf-m-sticky-top",
      stickyBottom: "pf-m-sticky-bottom",
      overflowScroll: "pf-m-overflow-scroll",
      shadowBottom: "pf-m-shadow-bottom",
      shadowTop: "pf-m-shadow-top",
      fill: "pf-m-fill",
      noFill: "pf-m-no-fill",
      dark_100: "pf-m-dark-100",
      dark_200: "pf-m-dark-200",
      padding: "pf-m-padding",
      noPadding: "pf-m-no-padding",
      paddingOnSm: "pf-m-padding-on-sm",
      noPaddingOnSm: "pf-m-no-padding-on-sm",
      paddingOnMd: "pf-m-padding-on-md",
      noPaddingOnMd: "pf-m-no-padding-on-md",
      paddingOnLg: "pf-m-padding-on-lg",
      noPaddingOnLg: "pf-m-no-padding-on-lg",
      paddingOnXl: "pf-m-padding-on-xl",
      noPaddingOnXl: "pf-m-no-padding-on-xl",
      paddingOn_2xl: "pf-m-padding-on-2xl",
      noPaddingOn_2xl: "pf-m-no-padding-on-2xl"
    },
    nav: "pf-c-nav",
    notificationBadge: "pf-c-notification-badge",
    page: "pf-c-page",
    pageDrawer: "pf-c-page__drawer",
    pageHeader: "pf-c-page__header",
    pageHeaderBrand: "pf-c-page__header-brand",
    pageHeaderBrandLink: "pf-c-page__header-brand-link",
    pageHeaderBrandToggle: "pf-c-page__header-brand-toggle",
    pageHeaderNav: "pf-c-page__header-nav",
    pageHeaderTools: "pf-c-page__header-tools",
    pageHeaderToolsGroup: "pf-c-page__header-tools-group",
    pageHeaderToolsItem: "pf-c-page__header-tools-item",
    pageMain: "pf-c-page__main",
    pageMainBody: "pf-c-page__main-body",
    pageMainBreadcrumb: "pf-c-page__main-breadcrumb",
    pageMainDrawer: "pf-c-page__main-drawer",
    pageMainGroup: "pf-c-page__main-group",
    pageMainNav: "pf-c-page__main-nav",
    pageMainSection: "pf-c-page__main-section",
    pageMainSubnav: "pf-c-page__main-subnav",
    pageMainTabs: "pf-c-page__main-tabs",
    pageMainWizard: "pf-c-page__main-wizard",
    pageSidebar: "pf-c-page__sidebar",
    pageSidebarBody: "pf-c-page__sidebar-body"
  };
});
var styles$m = /* @__PURE__ */ getDefaultExportFromCjs(page);
var global_breakpoint_xl = {
  name: "--pf-global--breakpoint--xl",
  value: "1200px",
  var: "var(--pf-global--breakpoint--xl)"
};
var PageGroup = (_a) => {
  var {className = "", children: children2, sticky, hasShadowTop = false, hasShadowBottom = false, hasOverflowScroll = false} = _a, props = __rest(_a, ["className", "children", "sticky", "hasShadowTop", "hasShadowBottom", "hasOverflowScroll"]);
  return react.createElement("div", Object.assign({}, props, {className: css(styles$m.pageMainGroup, sticky === "top" && styles$m.modifiers.stickyTop, sticky === "bottom" && styles$m.modifiers.stickyBottom, hasShadowTop && styles$m.modifiers.shadowTop, hasShadowBottom && styles$m.modifiers.shadowBottom, hasOverflowScroll && styles$m.modifiers.overflowScroll, className)}), children2);
};
PageGroup.displayName = "PageGroup";
var PageLayouts;
(function(PageLayouts2) {
  PageLayouts2["vertical"] = "vertical";
  PageLayouts2["horizontal"] = "horizontal";
})(PageLayouts || (PageLayouts = {}));
var PageContext = react.createContext({
  isManagedSidebar: false,
  isNavOpen: false,
  onNavToggle: () => null
});
var PageContextProvider = PageContext.Provider;
var PageContextConsumer = PageContext.Consumer;
var Page = class extends react.Component {
  constructor(props) {
    super(props);
    this.mainRef = react.createRef();
    this.getWindowWidth = () => canUseDOM ? window.innerWidth : 1200;
    this.isMobile = () => this.getWindowWidth() < Number.parseInt(global_breakpoint_xl.value, 10);
    this.resize = () => {
      const {onPageResize} = this.props;
      const mobileView = this.isMobile();
      if (onPageResize) {
        onPageResize({mobileView, windowSize: this.getWindowWidth()});
      }
      if (mobileView !== this.state.mobileView) {
        this.setState({mobileView});
      }
    };
    this.handleResize = debounce(this.resize, 250);
    this.handleMainClick = () => {
      if (this.isMobile() && this.state.mobileIsNavOpen && this.mainRef.current) {
        this.setState({mobileIsNavOpen: false});
      }
    };
    this.onNavToggleMobile = () => {
      this.setState((prevState) => ({
        mobileIsNavOpen: !prevState.mobileIsNavOpen
      }));
    };
    this.onNavToggleDesktop = () => {
      this.setState((prevState) => ({
        desktopIsNavOpen: !prevState.desktopIsNavOpen
      }));
    };
    const {isManagedSidebar, defaultManagedSidebarIsOpen} = props;
    const managedSidebarOpen = !isManagedSidebar ? true : defaultManagedSidebarIsOpen;
    this.state = {
      desktopIsNavOpen: managedSidebarOpen,
      mobileIsNavOpen: false,
      mobileView: false
    };
  }
  componentDidMount() {
    const {isManagedSidebar, onPageResize} = this.props;
    if (isManagedSidebar || onPageResize) {
      if (canUseDOM) {
        window.addEventListener("resize", this.handleResize);
      }
      const currentRef = this.mainRef.current;
      if (currentRef) {
        currentRef.addEventListener("mousedown", this.handleMainClick);
        currentRef.addEventListener("touchstart", this.handleMainClick);
      }
      this.resize();
    }
  }
  componentWillUnmount() {
    const {isManagedSidebar, onPageResize} = this.props;
    if (isManagedSidebar || onPageResize) {
      if (canUseDOM) {
        window.removeEventListener("resize", this.handleResize);
      }
      const currentRef = this.mainRef.current;
      if (currentRef) {
        currentRef.removeEventListener("mousedown", this.handleMainClick);
        currentRef.removeEventListener("touchstart", this.handleMainClick);
      }
    }
  }
  render() {
    const _a = this.props, {
      breadcrumb: breadcrumb2,
      isBreadcrumbWidthLimited,
      className,
      children: children2,
      header,
      sidebar: sidebar2,
      notificationDrawer,
      isNotificationDrawerExpanded,
      onNotificationDrawerExpand,
      isTertiaryNavWidthLimited,
      skipToContent,
      role,
      mainContainerId,
      isManagedSidebar,
      defaultManagedSidebarIsOpen,
      onPageResize,
      mainAriaLabel,
      mainTabIndex,
      tertiaryNav,
      isTertiaryNavGrouped,
      isBreadcrumbGrouped,
      additionalGroupedContent,
      groupProps
    } = _a, rest = __rest(_a, ["breadcrumb", "isBreadcrumbWidthLimited", "className", "children", "header", "sidebar", "notificationDrawer", "isNotificationDrawerExpanded", "onNotificationDrawerExpand", "isTertiaryNavWidthLimited", "skipToContent", "role", "mainContainerId", "isManagedSidebar", "defaultManagedSidebarIsOpen", "onPageResize", "mainAriaLabel", "mainTabIndex", "tertiaryNav", "isTertiaryNavGrouped", "isBreadcrumbGrouped", "additionalGroupedContent", "groupProps"]);
    const {mobileView, mobileIsNavOpen, desktopIsNavOpen} = this.state;
    const context2 = {
      isManagedSidebar,
      onNavToggle: mobileView ? this.onNavToggleMobile : this.onNavToggleDesktop,
      isNavOpen: mobileView ? mobileIsNavOpen : desktopIsNavOpen
    };
    let nav2 = null;
    if (tertiaryNav && isTertiaryNavWidthLimited) {
      nav2 = react.createElement("div", {className: css(styles$m.pageMainNav, styles$m.modifiers.limitWidth)}, react.createElement("div", {className: css(styles$m.pageMainBody)}, tertiaryNav));
    } else if (tertiaryNav) {
      nav2 = react.createElement("div", {className: css(styles$m.pageMainNav)}, tertiaryNav);
    }
    let crumb = null;
    if (breadcrumb2 && isBreadcrumbWidthLimited) {
      crumb = react.createElement("section", {className: css(styles$m.pageMainBreadcrumb, styles$m.modifiers.limitWidth)}, react.createElement("div", {className: css(styles$m.pageMainBody)}, breadcrumb2));
    } else if (breadcrumb2) {
      crumb = react.createElement("section", {className: css(styles$m.pageMainBreadcrumb)}, breadcrumb2);
    }
    const isGrouped = isTertiaryNavGrouped || isBreadcrumbGrouped || additionalGroupedContent;
    const group = isGrouped ? react.createElement(PageGroup, Object.assign({}, groupProps), isTertiaryNavGrouped && nav2, isBreadcrumbGrouped && crumb, additionalGroupedContent) : null;
    const main2 = react.createElement("main", {ref: this.mainRef, role, id: mainContainerId, className: css(styles$m.pageMain), tabIndex: mainTabIndex, "aria-label": mainAriaLabel}, group, !isTertiaryNavGrouped && nav2, !isBreadcrumbGrouped && crumb, children2);
    const panelContent = react.createElement(DrawerPanelContent, null, notificationDrawer);
    return react.createElement(PageContextProvider, {value: context2}, react.createElement("div", Object.assign({}, rest, {className: css(styles$m.page, className)}), skipToContent, header, sidebar2, notificationDrawer && react.createElement("div", {className: css(styles$m.pageDrawer)}, react.createElement(Drawer, {isExpanded: isNotificationDrawerExpanded, onExpand: onNotificationDrawerExpand}, react.createElement(DrawerContent, {panelContent}, react.createElement(DrawerContentBody, null, main2)))), !notificationDrawer && main2));
  }
};
Page.displayName = "Page";
Page.defaultProps = {
  isManagedSidebar: false,
  isBreadcrumbWidthLimited: false,
  defaultManagedSidebarIsOpen: true,
  onPageResize: () => null,
  mainTabIndex: -1,
  isNotificationDrawerExpanded: false,
  onNotificationDrawerExpand: () => null
};
var PageSidebarContext = react.createContext({
  isNavOpen: true
});
var PageSidebar = (_a) => {
  var {className = "", nav: nav2, isNavOpen = true, theme = "dark"} = _a, props = __rest(_a, ["className", "nav", "isNavOpen", "theme"]);
  return react.createElement(PageContextConsumer, null, ({isManagedSidebar, isNavOpen: managedIsNavOpen}) => {
    const navOpen = isManagedSidebar ? managedIsNavOpen : isNavOpen;
    return react.createElement("div", Object.assign({id: "page-sidebar", className: css(styles$m.pageSidebar, theme === "light" && styles$m.modifiers.light, navOpen && styles$m.modifiers.expanded, !navOpen && styles$m.modifiers.collapsed, className), "aria-hidden": !navOpen}, props), react.createElement("div", {className: css(styles$m.pageSidebarBody)}, react.createElement(PageSidebarContext.Provider, {value: {isNavOpen: navOpen}}, nav2)));
  });
};
PageSidebar.displayName = "PageSidebar";
var NavList = class extends react.Component {
  constructor() {
    super(...arguments);
    this.state = {
      scrollViewAtStart: false,
      scrollViewAtEnd: false
    };
    this.navList = react.createRef();
    this.handleScrollButtons = () => {
      const container = this.navList.current;
      if (container) {
        const scrollViewAtStart = isElementInView(container, container.firstChild, false);
        const scrollViewAtEnd = isElementInView(container, container.lastChild, false);
        this.setState({
          scrollViewAtStart,
          scrollViewAtEnd
        });
        this.context.updateIsScrollable(!scrollViewAtStart || !scrollViewAtEnd);
      }
    };
    this.scrollLeft = () => {
      const container = this.navList.current;
      if (container) {
        const childrenArr = Array.from(container.children);
        let firstElementInView;
        let lastElementOutOfView;
        for (let i3 = 0; i3 < childrenArr.length && !firstElementInView; i3++) {
          if (isElementInView(container, childrenArr[i3], false)) {
            firstElementInView = childrenArr[i3];
            lastElementOutOfView = childrenArr[i3 - 1];
          }
        }
        if (lastElementOutOfView) {
          container.scrollLeft -= lastElementOutOfView.scrollWidth;
        }
        this.handleScrollButtons();
      }
    };
    this.scrollRight = () => {
      const container = this.navList.current;
      if (container) {
        const childrenArr = Array.from(container.children);
        let lastElementInView;
        let firstElementOutOfView;
        for (let i3 = childrenArr.length - 1; i3 >= 0 && !lastElementInView; i3--) {
          if (isElementInView(container, childrenArr[i3], false)) {
            lastElementInView = childrenArr[i3];
            firstElementOutOfView = childrenArr[i3 + 1];
          }
        }
        if (firstElementOutOfView) {
          container.scrollLeft += firstElementOutOfView.scrollWidth;
        }
        this.handleScrollButtons();
      }
    };
  }
  componentDidMount() {
    if (canUseDOM) {
      window.addEventListener("resize", this.handleScrollButtons, false);
    }
    this.handleScrollButtons();
  }
  componentWillUnmount() {
    if (canUseDOM) {
      window.removeEventListener("resize", this.handleScrollButtons, false);
    }
  }
  render() {
    const _a = this.props, {children: children2, className, ariaLeftScroll, ariaRightScroll} = _a, props = __rest(_a, ["children", "className", "ariaLeftScroll", "ariaRightScroll"]);
    const {scrollViewAtStart, scrollViewAtEnd} = this.state;
    return react.createElement(NavContext.Consumer, null, ({isHorizontal}) => react.createElement(PageSidebarContext.Consumer, null, ({isNavOpen}) => react.createElement(react.Fragment, null, isHorizontal && react.createElement("button", {className: css(styles$l.navScrollButton), "aria-label": ariaLeftScroll, onClick: this.scrollLeft, disabled: scrollViewAtStart, tabIndex: isNavOpen ? null : -1}, react.createElement(AngleLeftIcon, null)), react.createElement("ul", Object.assign({ref: this.navList, className: css(styles$l.navList, className), onScroll: this.handleScrollButtons}, props), children2), isHorizontal && react.createElement("button", {className: css(styles$l.navScrollButton), "aria-label": ariaRightScroll, onClick: this.scrollRight, disabled: scrollViewAtEnd, tabIndex: isNavOpen ? null : -1}, react.createElement(AngleRightIcon, null)))));
  }
};
NavList.displayName = "NavList";
NavList.contextType = NavContext;
NavList.defaultProps = {
  ariaLeftScroll: "Scroll left",
  ariaRightScroll: "Scroll right"
};
var NavGroup = (_a) => {
  var {title: title3, children: children2 = null, className = "", id: id3 = getUniqueId()} = _a, props = __rest(_a, ["title", "children", "className", "id"]);
  return react.createElement("section", Object.assign({className: css(styles$l.navSection, className), "aria-labelledby": id3}, props), react.createElement("h2", {className: css(styles$l.navSectionTitle), id: id3}, title3), react.createElement("ul", {className: css(styles$l.navList, className)}, children2));
};
NavGroup.displayName = "NavGroup";
var NavItem = (_a) => {
  var {children: children2, styleChildren = true, className, to, isActive = false, groupId = null, itemId = null, preventDefault = false, onClick = null, component = "a", flyout, onShowFlyout, ouiaId, ouiaSafe} = _a, props = __rest(_a, ["children", "styleChildren", "className", "to", "isActive", "groupId", "itemId", "preventDefault", "onClick", "component", "flyout", "onShowFlyout", "ouiaId", "ouiaSafe"]);
  const {flyoutRef, setFlyoutRef} = react.useContext(NavContext);
  const {isNavOpen} = react.useContext(PageSidebarContext);
  const [flyoutTarget, setFlyoutTarget] = react.useState(null);
  const [isHovered, setIsHovered] = react.useState(false);
  const ref = react.useRef();
  const flyoutVisible = ref === flyoutRef;
  const popperRef = react.useRef();
  const Component = component;
  const hasFlyout = flyout !== void 0;
  const showFlyout = (show2, override) => {
    if ((!flyoutVisible || override) && show2) {
      setFlyoutRef(ref);
    } else if ((flyoutVisible || override) && !show2) {
      setFlyoutRef(null);
    }
    onShowFlyout && show2 && onShowFlyout();
  };
  const onMouseOver = (event) => {
    const evtContainedInFlyout = event.target.closest(".pf-c-nav__item.pf-m-flyout");
    if (hasFlyout && !flyoutVisible) {
      showFlyout(true);
    } else if (flyoutRef !== null && !evtContainedInFlyout) {
      setFlyoutRef(null);
    }
  };
  const onFlyoutClick = (event) => {
    const target = event.target;
    const closestItem = target.closest(".pf-m-flyout");
    if (!closestItem) {
      if (hasFlyout) {
        showFlyout(false, true);
      } else if (flyoutRef !== null) {
        setFlyoutRef(null);
      }
    }
  };
  const handleFlyout = (event) => {
    var _a2, _b;
    const key = event.key;
    const target = event.target;
    if (!(((_a2 = popperRef === null || popperRef === void 0 ? void 0 : popperRef.current) === null || _a2 === void 0 ? void 0 : _a2.contains(target)) || hasFlyout && ((_b = ref === null || ref === void 0 ? void 0 : ref.current) === null || _b === void 0 ? void 0 : _b.contains(target)))) {
      return;
    }
    if (key === " " || key === "ArrowRight") {
      event.stopPropagation();
      event.preventDefault();
      if (!flyoutVisible) {
        showFlyout(true);
        setFlyoutTarget(target);
      }
    }
    if (key === "Escape" || key === "ArrowLeft") {
      if (flyoutVisible) {
        event.stopPropagation();
        event.preventDefault();
        showFlyout(false);
      }
    }
  };
  react.useEffect(() => {
    if (hasFlyout) {
      window.addEventListener("click", onFlyoutClick);
    }
    return () => {
      if (hasFlyout) {
        window.removeEventListener("click", onFlyoutClick);
      }
    };
  }, []);
  react.useEffect(() => {
    if (flyoutTarget) {
      if (flyoutVisible) {
        const flyoutItems = Array.from(popperRef.current.getElementsByTagName("UL")[0].children).filter((el) => !(el.classList.contains("pf-m-disabled") || el.classList.contains("pf-c-divider")));
        flyoutItems[0].firstChild.focus();
      } else {
        flyoutTarget.focus();
      }
    }
  }, [flyoutVisible, flyoutTarget]);
  const flyoutButton = react.createElement("span", {className: css(styles$l.navToggle)}, react.createElement("span", {className: css(styles$l.navToggleIcon)}, react.createElement(AngleRightIcon, {"aria-hidden": true})));
  const renderDefaultLink = (context2) => {
    const preventLinkDefault = preventDefault || !to;
    return react.createElement(Component, Object.assign({href: to, onClick: (e2) => context2.onSelect(e2, groupId, itemId, to, preventLinkDefault, onClick), className: css(styles$l.navLink, isActive && styles$l.modifiers.current, isHovered && styles$l.modifiers.hover, className), "aria-current": isActive ? "page" : null, tabIndex: isNavOpen ? null : "-1"}, props), children2, flyout && flyoutButton);
  };
  const renderClonedChild = (context2, child) => react.cloneElement(child, Object.assign(Object.assign({onClick: (e2) => context2.onSelect(e2, groupId, itemId, to, preventDefault, onClick), "aria-current": isActive ? "page" : null}, styleChildren && {
    className: css(styles$l.navLink, isActive && styles$l.modifiers.current, child.props && child.props.className)
  }), {tabIndex: child.props.tabIndex || isNavOpen ? null : -1, children: hasFlyout ? react.createElement(react.Fragment, null, child.props.children, flyoutButton) : child.props.children}));
  const ouiaProps = useOUIAProps(NavItem.displayName, ouiaId, ouiaSafe);
  const handleMouseEnter = () => {
    setIsHovered(true);
  };
  const handleMouseLeave = () => {
    setIsHovered(false);
  };
  const flyoutPopper = react.createElement(Popper, {reference: ref, popper: react.createElement("div", {ref: popperRef, onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave}, flyout), placement: "right-start", isVisible: flyoutVisible, onDocumentKeyDown: handleFlyout});
  const navItem = react.createElement(react.Fragment, null, react.createElement("li", Object.assign({onMouseOver, className: css(styles$l.navItem, hasFlyout && styles$l.modifiers.flyout, className), ref}, ouiaProps), react.createElement(NavContext.Consumer, null, (context2) => react.isValidElement(children2) ? renderClonedChild(context2, children2) : renderDefaultLink(context2))), flyout && flyoutPopper);
  return navItem;
};
NavItem.displayName = "NavItem";
var TextContent = (_a) => {
  var {children: children2 = null, className = "", isVisited = false} = _a, props = __rest(_a, ["children", "className", "isVisited"]);
  return react.createElement("div", Object.assign({}, props, {className: css(styles$13.content, isVisited && styles$13.modifiers.visited, className)}), children2);
};
TextContent.displayName = "TextContent";
var TextVariants;
(function(TextVariants2) {
  TextVariants2["h1"] = "h1";
  TextVariants2["h2"] = "h2";
  TextVariants2["h3"] = "h3";
  TextVariants2["h4"] = "h4";
  TextVariants2["h5"] = "h5";
  TextVariants2["h6"] = "h6";
  TextVariants2["p"] = "p";
  TextVariants2["a"] = "a";
  TextVariants2["small"] = "small";
  TextVariants2["blockquote"] = "blockquote";
  TextVariants2["pre"] = "pre";
})(TextVariants || (TextVariants = {}));
var Text = (_a) => {
  var {children: children2 = null, className = "", component = TextVariants.p, isVisitedLink = false, ouiaId, ouiaSafe = true} = _a, props = __rest(_a, ["children", "className", "component", "isVisitedLink", "ouiaId", "ouiaSafe"]);
  const Component = component;
  const ouiaProps = useOUIAProps(Text.displayName, ouiaId, ouiaSafe);
  return react.createElement(Component, Object.assign({}, ouiaProps, props, {"data-pf-content": true, className: css(isVisitedLink && component === TextVariants.a && styles$13.modifiers.visited, className)}), children2);
};
Text.displayName = "Text";
var optionsMenu = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    divider: "pf-c-divider",
    modifiers: {
      plain: "pf-m-plain",
      text: "pf-m-text",
      active: "pf-m-active",
      expanded: "pf-m-expanded",
      disabled: "pf-m-disabled",
      top: "pf-m-top",
      alignRight: "pf-m-align-right"
    },
    optionsMenu: "pf-c-options-menu",
    optionsMenuGroup: "pf-c-options-menu__group",
    optionsMenuGroupTitle: "pf-c-options-menu__group-title",
    optionsMenuMenu: "pf-c-options-menu__menu",
    optionsMenuMenuItem: "pf-c-options-menu__menu-item",
    optionsMenuMenuItemIcon: "pf-c-options-menu__menu-item-icon",
    optionsMenuToggle: "pf-c-options-menu__toggle",
    optionsMenuToggleButton: "pf-c-options-menu__toggle-button",
    optionsMenuToggleButtonIcon: "pf-c-options-menu__toggle-button-icon",
    optionsMenuToggleIcon: "pf-c-options-menu__toggle-icon",
    optionsMenuToggleText: "pf-c-options-menu__toggle-text"
  };
});
var styles$n = /* @__PURE__ */ getDefaultExportFromCjs(optionsMenu);
var global_breakpoint_md = {
  name: "--pf-global--breakpoint--md",
  value: "768px",
  var: "var(--pf-global--breakpoint--md)"
};
var global_breakpoint_lg = {
  name: "--pf-global--breakpoint--lg",
  value: "992px",
  var: "var(--pf-global--breakpoint--lg)"
};
var global_breakpoint_2xl = {
  name: "--pf-global--breakpoint--2xl",
  value: "1450px",
  var: "var(--pf-global--breakpoint--2xl)"
};
var BarsIconConfig = {
  name: "BarsIcon",
  height: 512,
  width: 448,
  svgPath: "M16 132h416c8.837 0 16-7.163 16-16V76c0-8.837-7.163-16-16-16H16C7.163 60 0 67.163 0 76v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16z",
  yOffset: 0,
  xOffset: 0
};
var BarsIcon = createIcon(BarsIconConfig);
var PageHeader = (_a) => {
  var {className = "", logo = null, logoProps = null, logoComponent = "a", headerTools = null, topNav = null, isNavOpen = true, isManagedSidebar: deprecatedIsManagedSidebar = void 0, role = void 0, showNavToggle = false, onNavToggle = () => void 0, "aria-label": ariaLabel = "Global navigation", "aria-controls": ariaControls = null} = _a, props = __rest(_a, ["className", "logo", "logoProps", "logoComponent", "headerTools", "topNav", "isNavOpen", "isManagedSidebar", "role", "showNavToggle", "onNavToggle", "aria-label", "aria-controls"]);
  const LogoComponent = logoComponent;
  if ([false, true].includes(deprecatedIsManagedSidebar)) {
    console.warn("isManagedSidebar is deprecated in the PageHeader component. To make the sidebar toggle uncontrolled, pass this prop in the Page component");
  }
  return react.createElement(PageContextConsumer, null, ({isManagedSidebar, onNavToggle: managedOnNavToggle, isNavOpen: managedIsNavOpen}) => {
    const navToggle = isManagedSidebar ? managedOnNavToggle : onNavToggle;
    const navOpen = isManagedSidebar ? managedIsNavOpen : isNavOpen;
    return react.createElement("header", Object.assign({role, className: css(styles$m.pageHeader, className)}, props), (showNavToggle || logo) && react.createElement("div", {className: css(styles$m.pageHeaderBrand)}, showNavToggle && react.createElement("div", {className: css(styles$m.pageHeaderBrandToggle)}, react.createElement(Button, {id: "nav-toggle", onClick: navToggle, "aria-label": ariaLabel, "aria-controls": ariaControls, "aria-expanded": navOpen ? "true" : "false", variant: ButtonVariant.plain}, react.createElement(BarsIcon, null))), logo && react.createElement(LogoComponent, Object.assign({className: css(styles$m.pageHeaderBrandLink)}, logoProps), logo)), topNav && react.createElement("div", {className: css(styles$m.pageHeaderNav)}, topNav), headerTools);
  });
};
PageHeader.displayName = "PageHeader";
var PageSectionVariants;
(function(PageSectionVariants2) {
  PageSectionVariants2["default"] = "default";
  PageSectionVariants2["light"] = "light";
  PageSectionVariants2["dark"] = "dark";
  PageSectionVariants2["darker"] = "darker";
})(PageSectionVariants || (PageSectionVariants = {}));
var PageSectionTypes;
(function(PageSectionTypes2) {
  PageSectionTypes2["default"] = "default";
  PageSectionTypes2["nav"] = "nav";
  PageSectionTypes2["subNav"] = "subnav";
  PageSectionTypes2["breadcrumb"] = "breadcrumb";
  PageSectionTypes2["tabs"] = "tabs";
  PageSectionTypes2["wizard"] = "wizard";
})(PageSectionTypes || (PageSectionTypes = {}));
var variantType = {
  [PageSectionTypes.default]: styles$m.pageMainSection,
  [PageSectionTypes.nav]: styles$m.pageMainNav,
  [PageSectionTypes.subNav]: styles$m.pageMainSubnav,
  [PageSectionTypes.breadcrumb]: styles$m.pageMainBreadcrumb,
  [PageSectionTypes.tabs]: styles$m.pageMainTabs,
  [PageSectionTypes.wizard]: styles$m.pageMainWizard
};
var variantStyle = {
  [PageSectionVariants.default]: "",
  [PageSectionVariants.light]: styles$m.modifiers.light,
  [PageSectionVariants.dark]: styles$m.modifiers.dark_200,
  [PageSectionVariants.darker]: styles$m.modifiers.dark_100
};
var PageSection = (_a) => {
  var {className = "", children: children2, variant = "default", type = "default", padding, isFilled, isWidthLimited = false, sticky, hasShadowTop = false, hasShadowBottom = false, hasOverflowScroll = false} = _a, props = __rest(_a, ["className", "children", "variant", "type", "padding", "isFilled", "isWidthLimited", "sticky", "hasShadowTop", "hasShadowBottom", "hasOverflowScroll"]);
  return react.createElement("section", Object.assign({}, props, {className: css(variantType[type], formatBreakpointMods(padding, styles$m), variantStyle[variant], isFilled === false && styles$m.modifiers.noFill, isFilled === true && styles$m.modifiers.fill, isWidthLimited && styles$m.modifiers.limitWidth, sticky === "top" && styles$m.modifiers.stickyTop, sticky === "bottom" && styles$m.modifiers.stickyBottom, hasShadowTop && styles$m.modifiers.shadowTop, hasShadowBottom && styles$m.modifiers.shadowBottom, hasOverflowScroll && styles$m.modifiers.overflowScroll, className)}), isWidthLimited && react.createElement("div", {className: css(styles$m.pageMainBody)}, children2), !isWidthLimited && children2);
};
PageSection.displayName = "PageSection";
var PageHeaderTools = (_a) => {
  var {children: children2, className} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("div", Object.assign({className: css(styles$m.pageHeaderTools, className)}, props), children2);
};
PageHeaderTools.displayName = "PageHeaderTools";
var PageHeaderToolsGroup = (_a) => {
  var {children: children2, className, visibility} = _a, props = __rest(_a, ["children", "className", "visibility"]);
  return react.createElement("div", Object.assign({className: css(styles$m.pageHeaderToolsGroup, formatBreakpointMods(visibility, styles$m), className)}, props), children2);
};
PageHeaderToolsGroup.displayName = "PageHeaderToolsGroup";
var PageHeaderToolsItem = ({children: children2, id: id3, className, visibility, isSelected}) => react.createElement("div", {className: css(styles$m.pageHeaderToolsItem, isSelected && styles$m.modifiers.selected, formatBreakpointMods(visibility, styles$m), className), id: id3}, children2);
PageHeaderToolsItem.displayName = "PageHeaderToolsItem";
var ToggleTemplate = ({firstIndex: firstIndex2 = 0, lastIndex = 0, itemCount = 0, itemsTitle = "items", ofWord = "of"}) => react.createElement(react.Fragment, null, react.createElement("b", null, firstIndex2, " - ", lastIndex), " ", ofWord, " ", react.createElement("b", null, itemCount), " ", itemsTitle);
ToggleTemplate.displayName = "ToggleTemplate";
var pagination = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    formControl: "pf-c-form-control",
    modifiers: {
      bottom: "pf-m-bottom",
      static: "pf-m-static",
      first: "pf-m-first",
      last: "pf-m-last",
      sticky: "pf-m-sticky",
      compact: "pf-m-compact",
      displaySummary: "pf-m-display-summary",
      displayFull: "pf-m-display-full",
      displaySummaryOnSm: "pf-m-display-summary-on-sm",
      displayFullOnSm: "pf-m-display-full-on-sm",
      displaySummaryOnMd: "pf-m-display-summary-on-md",
      displayFullOnMd: "pf-m-display-full-on-md",
      displaySummaryOnLg: "pf-m-display-summary-on-lg",
      displayFullOnLg: "pf-m-display-full-on-lg",
      displaySummaryOnXl: "pf-m-display-summary-on-xl",
      displayFullOnXl: "pf-m-display-full-on-xl",
      displaySummaryOn_2xl: "pf-m-display-summary-on-2xl",
      displayFullOn_2xl: "pf-m-display-full-on-2xl"
    },
    optionsMenu: "pf-c-options-menu",
    optionsMenuToggle: "pf-c-options-menu__toggle",
    pagination: "pf-c-pagination",
    paginationNav: "pf-c-pagination__nav",
    paginationNavControl: "pf-c-pagination__nav-control",
    paginationNavPageSelect: "pf-c-pagination__nav-page-select",
    paginationTotalItems: "pf-c-pagination__total-items"
  };
});
var styles$o = /* @__PURE__ */ getDefaultExportFromCjs(pagination);
var Navigation = class extends react.Component {
  constructor(props) {
    super(props);
    this.handleNewPage = (_evt, newPage) => {
      const {perPage, onSetPage} = this.props;
      const startIdx = (newPage - 1) * perPage;
      const endIdx = newPage * perPage;
      return onSetPage(_evt, newPage, perPage, startIdx, endIdx);
    };
    this.state = {userInputPage: this.props.page};
  }
  static parseInteger(input, lastPage) {
    let inputPage = Number.parseInt(input, 10);
    if (!Number.isNaN(inputPage)) {
      inputPage = inputPage > lastPage ? lastPage : inputPage;
      inputPage = inputPage < 1 ? 1 : inputPage;
    }
    return inputPage;
  }
  onChange(event, lastPage) {
    const inputPage = Navigation.parseInteger(event.target.value, lastPage);
    this.setState({userInputPage: Number.isNaN(inputPage) ? event.target.value : inputPage});
  }
  onKeyDown(event, page2, lastPage, onPageInput) {
    if (event.keyCode === KEY_CODES.ENTER) {
      const inputPage = Navigation.parseInteger(this.state.userInputPage, lastPage);
      onPageInput(event, Number.isNaN(inputPage) ? page2 : inputPage);
      this.handleNewPage(event, Number.isNaN(inputPage) ? page2 : inputPage);
    }
  }
  componentDidUpdate(lastState) {
    if (this.props.page !== lastState.page && this.props.page <= this.props.lastPage && this.state.userInputPage !== this.props.page) {
      this.setState({userInputPage: this.props.page});
    }
  }
  render() {
    const _a = this.props, {
      page: page2,
      perPage,
      onSetPage,
      isDisabled,
      itemCount,
      lastPage,
      firstPage,
      pagesTitle,
      toLastPage,
      toNextPage,
      toFirstPage,
      toPreviousPage,
      currPage,
      paginationTitle,
      ofWord,
      onNextClick,
      onPreviousClick,
      onFirstClick,
      onLastClick,
      onPageInput,
      className,
      isCompact
    } = _a, props = __rest(_a, ["page", "perPage", "onSetPage", "isDisabled", "itemCount", "lastPage", "firstPage", "pagesTitle", "toLastPage", "toNextPage", "toFirstPage", "toPreviousPage", "currPage", "paginationTitle", "ofWord", "onNextClick", "onPreviousClick", "onFirstClick", "onLastClick", "onPageInput", "className", "isCompact"]);
    const {userInputPage} = this.state;
    return react.createElement("nav", Object.assign({className: css(styles$o.paginationNav, className), "aria-label": paginationTitle}, props), !isCompact && react.createElement("div", {className: css(styles$o.paginationNavControl, styles$o.modifiers.first)}, react.createElement(Button, {variant: ButtonVariant.plain, isDisabled: isDisabled || page2 === firstPage || page2 === 0, "aria-label": toFirstPage, "data-action": "first", onClick: (event) => {
      onFirstClick(event, 1);
      this.handleNewPage(event, 1);
      this.setState({userInputPage: 1});
    }}, react.createElement(AngleDoubleLeftIcon, null))), react.createElement("div", {className: styles$o.paginationNavControl}, react.createElement(Button, {variant: ButtonVariant.plain, isDisabled: isDisabled || page2 === firstPage || page2 === 0, "data-action": "previous", onClick: (event) => {
      const newPage = page2 - 1 >= 1 ? page2 - 1 : 1;
      onPreviousClick(event, newPage);
      this.handleNewPage(event, newPage);
      this.setState({userInputPage: newPage});
    }, "aria-label": toPreviousPage}, react.createElement(AngleLeftIcon, null))), !isCompact && react.createElement("div", {className: styles$o.paginationNavPageSelect}, react.createElement("input", {className: css(styles$o.formControl), "aria-label": currPage, type: "number", disabled: isDisabled || itemCount && page2 === firstPage && page2 === lastPage && itemCount >= 0 || page2 === 0, min: lastPage <= 0 && firstPage <= 0 ? 0 : 1, max: lastPage, value: userInputPage, onKeyDown: (event) => this.onKeyDown(event, page2, lastPage, onPageInput), onChange: (event) => this.onChange(event, lastPage)}), (itemCount || itemCount === 0) && react.createElement("span", {"aria-hidden": "true"}, ofWord, " ", pagesTitle ? pluralize(lastPage, pagesTitle) : lastPage)), react.createElement("div", {className: styles$o.paginationNavControl}, react.createElement(Button, {variant: ButtonVariant.plain, isDisabled: isDisabled || page2 === lastPage, "aria-label": toNextPage, "data-action": "next", onClick: (event) => {
      const newPage = page2 + 1 <= lastPage ? page2 + 1 : lastPage;
      onNextClick(event, newPage);
      this.handleNewPage(event, newPage);
      this.setState({userInputPage: newPage});
    }}, react.createElement(AngleRightIcon, null))), !isCompact && react.createElement("div", {className: css(styles$o.paginationNavControl, styles$o.modifiers.last)}, react.createElement(Button, {variant: ButtonVariant.plain, isDisabled: isDisabled || page2 === lastPage, "aria-label": toLastPage, "data-action": "last", onClick: (event) => {
      onLastClick(event, lastPage);
      this.handleNewPage(event, lastPage);
      this.setState({userInputPage: lastPage});
    }}, react.createElement(AngleDoubleRightIcon, null))));
  }
};
Navigation.displayName = "Navigation";
Navigation.defaultProps = {
  className: "",
  isDisabled: false,
  isCompact: false,
  lastPage: 0,
  firstPage: 0,
  pagesTitle: "",
  toLastPage: "Go to last page",
  toNextPage: "Go to next page",
  toFirstPage: "Go to first page",
  toPreviousPage: "Go to previous page",
  currPage: "Current page",
  paginationTitle: "Pagination",
  ofWord: "of",
  onNextClick: () => void 0,
  onPreviousClick: () => void 0,
  onFirstClick: () => void 0,
  onLastClick: () => void 0,
  onPageInput: () => void 0
};
var toggleId = 0;
var OptionsToggle = ({
  itemsTitle = "items",
  optionsToggle = "Items per page",
  itemsPerPageTitle = "Items per page",
  ofWord = "of",
  firstIndex: firstIndex2 = 0,
  lastIndex = 0,
  itemCount,
  widgetId = "",
  showToggle = true,
  onToggle = (_isOpen) => void 0,
  isOpen = false,
  isDisabled = false,
  parentRef = null,
  toggleTemplate: ToggleTemplate2,
  onEnter = null
}) => react.createElement("div", {className: css(styles$n.optionsMenuToggle, isDisabled && styles$n.modifiers.disabled, styles$n.modifiers.plain, styles$n.modifiers.text)}, showToggle && react.createElement(react.Fragment, null, react.createElement("span", {className: css(styles$n.optionsMenuToggleText)}, typeof ToggleTemplate2 === "string" ? fillTemplate(ToggleTemplate2, {firstIndex: firstIndex2, lastIndex, ofWord, itemCount, itemsTitle}) : react.createElement(ToggleTemplate2, {firstIndex: firstIndex2, lastIndex, ofWord, itemCount, itemsTitle})), react.createElement(DropdownToggle, {onEnter, "aria-label": optionsToggle, onToggle, isDisabled: isDisabled || itemCount && itemCount <= 0, isOpen, id: `${widgetId}-toggle-${toggleId++}`, className: styles$n.optionsMenuToggleButton, parentRef})));
OptionsToggle.displayName = "OptionsToggle";
var PaginationOptionsMenu = class extends react.Component {
  constructor(props) {
    super(props);
    this.parentRef = react.createRef();
    this.onToggle = (isOpen) => {
      this.setState({isOpen});
    };
    this.onSelect = () => {
      this.setState((prevState) => ({isOpen: !prevState.isOpen}));
    };
    this.handleNewPerPage = (_evt, newPerPage) => {
      const {page: page2, onPerPageSelect, itemCount, defaultToFullPage} = this.props;
      let newPage = page2;
      while (Math.ceil(itemCount / newPerPage) < newPage) {
        newPage--;
      }
      if (defaultToFullPage) {
        if (itemCount / newPerPage !== newPage) {
          while (newPage > 1 && itemCount - newPerPage * newPage < 0) {
            newPage--;
          }
        }
      }
      const startIdx = (newPage - 1) * newPerPage;
      const endIdx = newPage * newPerPage;
      return onPerPageSelect(_evt, newPerPage, newPage, startIdx, endIdx);
    };
    this.renderItems = () => {
      const {perPageOptions, perPage, perPageSuffix} = this.props;
      return perPageOptions.map(({value, title: title3}) => react.createElement(DropdownItem, {key: value, component: "button", "data-action": `per-page-${value}`, className: css(perPage === value && "pf-m-selected"), onClick: (event) => this.handleNewPerPage(event, value)}, title3, ` ${perPageSuffix}`, perPage === value && react.createElement("div", {className: css(styles$n.optionsMenuMenuItemIcon)}, react.createElement(CheckIcon, null))));
    };
    this.state = {
      isOpen: false
    };
  }
  render() {
    const {widgetId, isDisabled, itemsPerPageTitle, dropDirection, optionsToggle, perPageOptions, toggleTemplate, firstIndex: firstIndex2, lastIndex, itemCount, itemsTitle, ofWord} = this.props;
    const {isOpen} = this.state;
    return react.createElement(DropdownContext.Provider, {value: {
      id: widgetId,
      onSelect: this.onSelect,
      toggleIndicatorClass: styles$n.optionsMenuToggleButtonIcon,
      toggleTextClass: styles$n.optionsMenuToggleText,
      menuClass: styles$n.optionsMenuMenu,
      itemClass: styles$n.optionsMenuMenuItem,
      toggleClass: " ",
      baseClass: styles$n.optionsMenu,
      disabledClass: styles$n.modifiers.disabled,
      menuComponent: "ul",
      baseComponent: "div",
      ouiaComponentType: PaginationOptionsMenu.displayName
    }}, react.createElement(DropdownWithContext, {direction: dropDirection, isOpen, toggle: react.createElement(OptionsToggle, {optionsToggle, itemsPerPageTitle, showToggle: perPageOptions && perPageOptions.length > 0, onToggle: this.onToggle, isOpen, widgetId, firstIndex: firstIndex2, lastIndex, itemCount, itemsTitle, ofWord, toggleTemplate, parentRef: this.parentRef.current, isDisabled}), dropdownItems: this.renderItems(), isPlain: true}));
  }
};
PaginationOptionsMenu.displayName = "PaginationOptionsMenu";
PaginationOptionsMenu.defaultProps = {
  className: "",
  widgetId: "",
  isDisabled: false,
  dropDirection: DropdownDirection.down,
  perPageOptions: [],
  itemsPerPageTitle: "Items per page",
  perPageSuffix: "per page",
  optionsToggle: "Items per page",
  ofWord: "of",
  perPage: 0,
  firstIndex: 0,
  lastIndex: 0,
  defaultToFullPage: false,
  itemsTitle: "items",
  toggleTemplate: ToggleTemplate,
  onPerPageSelect: () => null
};
var c_pagination__nav_page_select_c_form_control_width_chars = {
  name: "--pf-c-pagination__nav-page-select--c-form-control--width-chars",
  value: "2",
  var: "var(--pf-c-pagination__nav-page-select--c-form-control--width-chars)"
};
var PaginationVariant;
(function(PaginationVariant2) {
  PaginationVariant2["top"] = "top";
  PaginationVariant2["bottom"] = "bottom";
})(PaginationVariant || (PaginationVariant = {}));
var defaultPerPageOptions = [
  {
    title: "10",
    value: 10
  },
  {
    title: "20",
    value: 20
  },
  {
    title: "50",
    value: 50
  },
  {
    title: "100",
    value: 100
  }
];
var handleInputWidth = (lastPage, node) => {
  if (!node) {
    return;
  }
  const len2 = String(lastPage).length;
  if (len2 >= 3) {
    node.style.setProperty(c_pagination__nav_page_select_c_form_control_width_chars.name, `${len2}`);
  } else {
    node.style.setProperty(c_pagination__nav_page_select_c_form_control_width_chars.name, "2");
  }
};
var paginationId = 0;
var Pagination = class extends react.Component {
  constructor() {
    super(...arguments);
    this.paginationRef = react.createRef();
    this.state = {
      ouiaStateId: getDefaultOUIAId(Pagination.displayName, this.props.variant)
    };
  }
  getLastPage() {
    const {itemCount, perPage, page: page2} = this.props;
    return itemCount || itemCount === 0 ? Math.ceil(itemCount / perPage) || 0 : page2 + 1;
  }
  componentDidMount() {
    const node = this.paginationRef.current;
    handleInputWidth(this.getLastPage(), node);
  }
  componentDidUpdate(prevProps) {
    const node = this.paginationRef.current;
    if (prevProps.perPage !== this.props.perPage || prevProps.itemCount !== this.props.itemCount) {
      handleInputWidth(this.getLastPage(), node);
    }
  }
  render() {
    const _a = this.props, {children: children2, className, variant, isDisabled, isCompact, isStatic, isSticky, perPage, titles, firstPage, page: propPage, offset: offset2, defaultToFullPage, itemCount, itemsStart, itemsEnd, perPageOptions, dropDirection: dropDirectionProp, widgetId, toggleTemplate, onSetPage, onPerPageSelect, onFirstClick, onPreviousClick, onNextClick, onPageInput, onLastClick, ouiaId, ouiaSafe} = _a, props = __rest(_a, ["children", "className", "variant", "isDisabled", "isCompact", "isStatic", "isSticky", "perPage", "titles", "firstPage", "page", "offset", "defaultToFullPage", "itemCount", "itemsStart", "itemsEnd", "perPageOptions", "dropDirection", "widgetId", "toggleTemplate", "onSetPage", "onPerPageSelect", "onFirstClick", "onPreviousClick", "onNextClick", "onPageInput", "onLastClick", "ouiaId", "ouiaSafe"]);
    const dropDirection = dropDirectionProp || (variant === "bottom" && !isStatic ? "up" : "down");
    let page2 = propPage;
    if (!page2 && offset2) {
      page2 = Math.ceil(offset2 / perPage);
    }
    if (page2 === 0 && !itemCount) {
      page2 = 1;
    }
    const lastPage = this.getLastPage();
    let firstIndex2 = (page2 - 1) * perPage + 1;
    let lastIndex = page2 * perPage;
    if (itemCount || itemCount === 0) {
      firstIndex2 = itemCount <= 0 ? 0 : (page2 - 1) * perPage + 1;
      if (page2 < firstPage && itemCount > 0) {
        page2 = firstPage;
      } else if (page2 > lastPage) {
        page2 = lastPage;
      }
      if (itemCount >= 0) {
        lastIndex = page2 === lastPage || itemCount === 0 ? itemCount : page2 * perPage;
      }
    }
    const toggleTemplateProps = {firstIndex: firstIndex2, lastIndex, itemCount, itemsTitle: titles.items, ofWord: titles.ofWord};
    return react.createElement("div", Object.assign({ref: this.paginationRef, className: css(styles$o.pagination, variant === PaginationVariant.bottom && styles$o.modifiers.bottom, isCompact && styles$o.modifiers.compact, isStatic && styles$o.modifiers.static, isSticky && styles$o.modifiers.sticky, className), id: `${widgetId}-${paginationId++}`}, getOUIAProps(Pagination.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId, ouiaSafe), props), variant === PaginationVariant.top && react.createElement("div", {className: css(styles$o.paginationTotalItems)}, toggleTemplate && typeof toggleTemplate === "string" && fillTemplate(toggleTemplate, toggleTemplateProps), toggleTemplate && typeof toggleTemplate !== "string" && toggleTemplate(toggleTemplateProps), !toggleTemplate && react.createElement(ToggleTemplate, {firstIndex: firstIndex2, lastIndex, itemCount, itemsTitle: titles.items, ofWord: titles.ofWord})), react.createElement(PaginationOptionsMenu, {itemsPerPageTitle: titles.itemsPerPage, perPageSuffix: titles.perPageSuffix, itemsTitle: isCompact ? "" : titles.items, optionsToggle: titles.optionsToggle, perPageOptions, firstIndex: itemsStart !== null ? itemsStart : firstIndex2, lastIndex: itemsEnd !== null ? itemsEnd : lastIndex, ofWord: titles.ofWord, defaultToFullPage, itemCount, page: page2, perPage, lastPage, onPerPageSelect, dropDirection, widgetId, toggleTemplate, isDisabled}), react.createElement(Navigation, {pagesTitle: titles.page, toLastPage: titles.toLastPage, toPreviousPage: titles.toPreviousPage, toNextPage: titles.toNextPage, toFirstPage: titles.toFirstPage, currPage: titles.currPage, paginationTitle: titles.paginationTitle, ofWord: titles.ofWord, page: itemCount && itemCount <= 0 ? 0 : page2, perPage, itemCount, firstPage: itemsStart !== null ? itemsStart : 1, lastPage, onSetPage, onFirstClick, onPreviousClick, onNextClick, onLastClick, onPageInput, isDisabled, isCompact}), children2);
  }
};
Pagination.displayName = "Pagination";
Pagination.defaultProps = {
  children: null,
  className: "",
  variant: PaginationVariant.top,
  isDisabled: false,
  isCompact: false,
  isSticky: false,
  perPage: defaultPerPageOptions[0].value,
  titles: {
    items: "",
    page: "",
    itemsPerPage: "Items per page",
    perPageSuffix: "per page",
    toFirstPage: "Go to first page",
    toPreviousPage: "Go to previous page",
    toLastPage: "Go to last page",
    toNextPage: "Go to next page",
    optionsToggle: "Items per page",
    currPage: "Current page",
    paginationTitle: "Pagination",
    ofWord: "of"
  },
  firstPage: 1,
  page: 0,
  offset: 0,
  defaultToFullPage: false,
  itemsStart: null,
  itemsEnd: null,
  perPageOptions: defaultPerPageOptions,
  widgetId: "pagination-options-menu",
  onSetPage: () => void 0,
  onPerPageSelect: () => void 0,
  onFirstClick: () => void 0,
  onPreviousClick: () => void 0,
  onNextClick: () => void 0,
  onPageInput: () => void 0,
  onLastClick: () => void 0,
  ouiaSafe: true
};
var radio = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    modifiers: {
      standalone: "pf-m-standalone",
      disabled: "pf-m-disabled"
    },
    radio: "pf-c-radio",
    radioBody: "pf-c-radio__body",
    radioDescription: "pf-c-radio__description",
    radioInput: "pf-c-radio__input",
    radioLabel: "pf-c-radio__label"
  };
});
var styles$p = /* @__PURE__ */ getDefaultExportFromCjs(radio);
var Radio = class extends react.Component {
  constructor(props) {
    super(props);
    this.handleChange = (event) => {
      this.props.onChange(event.currentTarget.checked, event);
    };
    if (!props.label && !props["aria-label"]) {
      console.error("Radio:", "Radio requires an aria-label to be specified");
    }
    this.state = {
      ouiaStateId: getDefaultOUIAId(Radio.displayName)
    };
  }
  render() {
    const _a = this.props, {
      "aria-label": ariaLabel,
      checked,
      className,
      defaultChecked,
      isLabelWrapped,
      isLabelBeforeButton,
      isChecked,
      isDisabled,
      isValid,
      label: label2,
      onChange,
      description,
      body,
      ouiaId,
      ouiaSafe = true
    } = _a, props = __rest(_a, ["aria-label", "checked", "className", "defaultChecked", "isLabelWrapped", "isLabelBeforeButton", "isChecked", "isDisabled", "isValid", "label", "onChange", "description", "body", "ouiaId", "ouiaSafe"]);
    if (!props.id) {
      console.error("Radio:", "id is required to make input accessible");
    }
    const inputRendered = react.createElement("input", Object.assign({}, props, {className: css(styles$p.radioInput), type: "radio", onChange: this.handleChange, "aria-invalid": !isValid, disabled: isDisabled, checked: checked || isChecked}, checked === void 0 && {defaultChecked}, !label2 && {"aria-label": ariaLabel}, getOUIAProps(Radio.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId, ouiaSafe)));
    let labelRendered = null;
    if (label2 && isLabelWrapped) {
      labelRendered = react.createElement("span", {className: css(styles$p.radioLabel, isDisabled && styles$p.modifiers.disabled)}, label2);
    } else if (label2) {
      labelRendered = react.createElement("label", {className: css(styles$p.radioLabel, isDisabled && styles$p.modifiers.disabled), htmlFor: props.id}, label2);
    }
    const descRender = description ? react.createElement("span", {className: css(styles$p.radioDescription)}, description) : null;
    const bodyRender = body ? react.createElement("span", {className: css(styles$p.radioBody)}, body) : null;
    const childrenRendered = isLabelBeforeButton ? react.createElement(react.Fragment, null, labelRendered, inputRendered, descRender, bodyRender) : react.createElement(react.Fragment, null, inputRendered, labelRendered, descRender, bodyRender);
    return isLabelWrapped ? react.createElement("label", {className: css(styles$p.radio, className), htmlFor: props.id}, childrenRendered) : react.createElement("div", {className: css(styles$p.radio, !label2 && styles$p.modifiers.standalone, className)}, childrenRendered);
  }
};
Radio.displayName = "Radio";
Radio.defaultProps = {
  className: "",
  isDisabled: false,
  isValid: true,
  onChange: () => {
  }
};
var _switch = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    modifiers: {
      reverse: "pf-m-reverse",
      off: "pf-m-off",
      on: "pf-m-on"
    },
    switch: "pf-c-switch",
    switchInput: "pf-c-switch__input",
    switchLabel: "pf-c-switch__label",
    switchToggle: "pf-c-switch__toggle",
    switchToggleIcon: "pf-c-switch__toggle-icon"
  };
});
var styles$q = /* @__PURE__ */ getDefaultExportFromCjs(_switch);
var Switch = class extends react.Component {
  constructor(props) {
    super(props);
    if (!props.label && !props["aria-label"]) {
      console.error("Switch: Switch requires either a label or an aria-label to be specified");
    }
    this.id = props.id || getUniqueId();
    this.state = {
      ouiaStateId: getDefaultOUIAId(Switch.displayName)
    };
  }
  render() {
    const _a = this.props, {
      id: id3,
      className,
      label: label2,
      labelOff,
      isChecked,
      isDisabled,
      onChange,
      isReversed,
      ouiaId,
      ouiaSafe
    } = _a, props = __rest(_a, ["id", "className", "label", "labelOff", "isChecked", "isDisabled", "onChange", "isReversed", "ouiaId", "ouiaSafe"]);
    const isAriaLabelledBy = props["aria-label"] === "";
    return react.createElement("label", Object.assign({className: css(styles$q.switch, isReversed && styles$q.modifiers.reverse, className), htmlFor: this.id}, getOUIAProps(Switch.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId, ouiaSafe)), react.createElement("input", Object.assign({id: this.id, className: css(styles$q.switchInput), type: "checkbox", onChange: (event) => onChange(event.target.checked, event), checked: isChecked, disabled: isDisabled, "aria-labelledby": isAriaLabelledBy ? `${this.id}-on` : null}, props)), label2 !== void 0 ? react.createElement(react.Fragment, null, react.createElement("span", {className: css(styles$q.switchToggle)}), react.createElement("span", {className: css(styles$q.switchLabel, styles$q.modifiers.on), id: isAriaLabelledBy ? `${this.id}-on` : null, "aria-hidden": "true"}, label2), react.createElement("span", {className: css(styles$q.switchLabel, styles$q.modifiers.off), id: isAriaLabelledBy ? `${this.id}-off` : null, "aria-hidden": "true"}, labelOff !== void 0 ? labelOff : label2)) : react.createElement("span", {className: css(styles$q.switchToggle)}, react.createElement("div", {className: css(styles$q.switchToggleIcon), "aria-hidden": "true"}, react.createElement(CheckIcon, {noVerticalAlign: true}))));
  }
};
Switch.displayName = "Switch";
Switch.defaultProps = {
  isChecked: true,
  isDisabled: false,
  isReversed: false,
  "aria-label": "",
  onChange: () => void 0
};
var tabs = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    modifiers: {
      fill: "pf-m-fill",
      scrollable: "pf-m-scrollable",
      secondary: "pf-m-secondary",
      noBorderBottom: "pf-m-no-border-bottom",
      box: "pf-m-box",
      vertical: "pf-m-vertical",
      current: "pf-m-current",
      colorSchemeLight_300: "pf-m-color-scheme--light-300",
      expandable: "pf-m-expandable",
      nonExpandable: "pf-m-non-expandable",
      expandableOnSm: "pf-m-expandable-on-sm",
      nonExpandableOnSm: "pf-m-non-expandable-on-sm",
      expandableOnMd: "pf-m-expandable-on-md",
      nonExpandableOnMd: "pf-m-non-expandable-on-md",
      expandableOnLg: "pf-m-expandable-on-lg",
      nonExpandableOnLg: "pf-m-non-expandable-on-lg",
      expandableOnXl: "pf-m-expandable-on-xl",
      nonExpandableOnXl: "pf-m-non-expandable-on-xl",
      expandableOn_2xl: "pf-m-expandable-on-2xl",
      nonExpandableOn_2xl: "pf-m-non-expandable-on-2xl",
      expanded: "pf-m-expanded",
      pageInsets: "pf-m-page-insets",
      disabled: "pf-m-disabled",
      ariaDisabled: "pf-m-aria-disabled",
      insetNone: "pf-m-inset-none",
      insetSm: "pf-m-inset-sm",
      insetMd: "pf-m-inset-md",
      insetLg: "pf-m-inset-lg",
      insetXl: "pf-m-inset-xl",
      inset_2xl: "pf-m-inset-2xl",
      insetNoneOnSm: "pf-m-inset-none-on-sm",
      insetSmOnSm: "pf-m-inset-sm-on-sm",
      insetMdOnSm: "pf-m-inset-md-on-sm",
      insetLgOnSm: "pf-m-inset-lg-on-sm",
      insetXlOnSm: "pf-m-inset-xl-on-sm",
      inset_2xlOnSm: "pf-m-inset-2xl-on-sm",
      insetNoneOnMd: "pf-m-inset-none-on-md",
      insetSmOnMd: "pf-m-inset-sm-on-md",
      insetMdOnMd: "pf-m-inset-md-on-md",
      insetLgOnMd: "pf-m-inset-lg-on-md",
      insetXlOnMd: "pf-m-inset-xl-on-md",
      inset_2xlOnMd: "pf-m-inset-2xl-on-md",
      insetNoneOnLg: "pf-m-inset-none-on-lg",
      insetSmOnLg: "pf-m-inset-sm-on-lg",
      insetMdOnLg: "pf-m-inset-md-on-lg",
      insetLgOnLg: "pf-m-inset-lg-on-lg",
      insetXlOnLg: "pf-m-inset-xl-on-lg",
      inset_2xlOnLg: "pf-m-inset-2xl-on-lg",
      insetNoneOnXl: "pf-m-inset-none-on-xl",
      insetSmOnXl: "pf-m-inset-sm-on-xl",
      insetMdOnXl: "pf-m-inset-md-on-xl",
      insetLgOnXl: "pf-m-inset-lg-on-xl",
      insetXlOnXl: "pf-m-inset-xl-on-xl",
      inset_2xlOnXl: "pf-m-inset-2xl-on-xl",
      insetNoneOn_2xl: "pf-m-inset-none-on-2xl",
      insetSmOn_2xl: "pf-m-inset-sm-on-2xl",
      insetMdOn_2xl: "pf-m-inset-md-on-2xl",
      insetLgOn_2xl: "pf-m-inset-lg-on-2xl",
      insetXlOn_2xl: "pf-m-inset-xl-on-2xl",
      inset_2xlOn_2xl: "pf-m-inset-2xl-on-2xl"
    },
    tabs: "pf-c-tabs",
    tabsItem: "pf-c-tabs__item",
    tabsItemIcon: "pf-c-tabs__item-icon",
    tabsItemText: "pf-c-tabs__item-text",
    tabsLink: "pf-c-tabs__link",
    tabsList: "pf-c-tabs__list",
    tabsScrollButton: "pf-c-tabs__scroll-button",
    tabsToggle: "pf-c-tabs__toggle",
    tabsToggleButton: "pf-c-tabs__toggle-button",
    tabsToggleIcon: "pf-c-tabs__toggle-icon",
    tabsToggleText: "pf-c-tabs__toggle-text"
  };
});
var styles$r = /* @__PURE__ */ getDefaultExportFromCjs(tabs);
var TabButton = (_a) => {
  var {
    children: children2,
    tabContentRef,
    ouiaId,
    ouiaSafe
  } = _a, props = __rest(_a, ["children", "tabContentRef", "ouiaId", "ouiaSafe"]);
  const Component = props.href ? "a" : "button";
  return react.createElement(Component, Object.assign({}, getOUIAProps(TabButton.displayName, ouiaId, ouiaSafe), props), children2);
};
TabButton.displayName = "TabButton";
var TabsContext = react.createContext({
  variant: "default",
  mountOnEnter: false,
  unmountOnExit: false,
  localActiveKey: "",
  uniqueId: "",
  handleTabClick: () => null
});
var TabsContextProvider = TabsContext.Provider;
var TabsContextConsumer = TabsContext.Consumer;
var TabBase = (_a) => {
  var {title: title3, eventKey, tabContentRef, id: childId, tabContentId, className: childClassName = "", ouiaId: childOuiaId, isDisabled, isAriaDisabled, inoperableEvents = ["onClick", "onKeyPress"], href, innerRef} = _a, props = __rest(_a, ["title", "eventKey", "tabContentRef", "id", "tabContentId", "className", "ouiaId", "isDisabled", "isAriaDisabled", "inoperableEvents", "href", "innerRef"]);
  const preventedEvents2 = inoperableEvents.reduce((handlers, eventToPrevent) => Object.assign(Object.assign({}, handlers), {[eventToPrevent]: (event) => {
    event.preventDefault();
  }}), {});
  const {mountOnEnter, localActiveKey, unmountOnExit, uniqueId: uniqueId2, handleTabClick} = react.useContext(TabsContext);
  let ariaControls = tabContentId ? `${tabContentId}` : `pf-tab-section-${eventKey}-${childId || uniqueId2}`;
  if ((mountOnEnter || unmountOnExit) && eventKey !== localActiveKey) {
    ariaControls = void 0;
  }
  const isButtonElement = Boolean(!href);
  const getDefaultTabIdx = () => {
    if (isDisabled) {
      return isButtonElement ? null : -1;
    } else if (isAriaDisabled) {
      return null;
    }
  };
  return react.createElement("li", {className: css(styles$r.tabsItem, eventKey === localActiveKey && styles$r.modifiers.current, childClassName), ref: innerRef}, react.createElement(TabButton, Object.assign({className: css(styles$r.tabsLink, isDisabled && href && styles$r.modifiers.disabled, isAriaDisabled && styles$r.modifiers.ariaDisabled), disabled: isButtonElement ? isDisabled : null, "aria-disabled": isDisabled || isAriaDisabled, tabIndex: getDefaultTabIdx(), onClick: (event) => handleTabClick(event, eventKey, tabContentRef)}, isAriaDisabled ? preventedEvents2 : null, {id: `pf-tab-${eventKey}-${childId || uniqueId2}`, "aria-controls": ariaControls, tabContentRef, ouiaId: childOuiaId, href}, props), title3));
};
var Tab = react.forwardRef((props, ref) => react.createElement(TabBase, Object.assign({innerRef: ref}, props)));
Tab.displayName = "Tab";
var tabContent = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    modifiers: {
      light_300: "pf-m-light-300",
      padding: "pf-m-padding"
    },
    tabContent: "pf-c-tab-content",
    tabContentBody: "pf-c-tab-content__body"
  };
});
var styles$s = /* @__PURE__ */ getDefaultExportFromCjs(tabContent);
var variantStyle$1 = {
  default: "",
  light300: styles$s.modifiers.light_300
};
var TabContentBase = (_a) => {
  var {id: id3, activeKey, "aria-label": ariaLabel, child, children: children2, className, eventKey, innerRef, ouiaId, ouiaSafe} = _a, props = __rest(_a, ["id", "activeKey", "aria-label", "child", "children", "className", "eventKey", "innerRef", "ouiaId", "ouiaSafe"]);
  if (children2 || child) {
    let labelledBy;
    if (ariaLabel) {
      labelledBy = null;
    } else {
      labelledBy = children2 ? `pf-tab-${eventKey}-${id3}` : `pf-tab-${child.props.eventKey}-${id3}`;
    }
    return react.createElement(TabsContextConsumer, null, ({variant}) => react.createElement("section", Object.assign({ref: innerRef, hidden: children2 ? null : child.props.eventKey !== activeKey, className: children2 ? css("pf-c-tab-content", className, variantStyle$1[variant]) : css("pf-c-tab-content", child.props.className, variantStyle$1[variant]), id: children2 ? id3 : `pf-tab-section-${child.props.eventKey}-${id3}`, "aria-label": ariaLabel, "aria-labelledby": labelledBy, role: "tabpanel", tabIndex: 0}, getOUIAProps("TabContent", ouiaId, ouiaSafe), props), children2 || child.props.children));
  }
  return null;
};
var TabContent = react.forwardRef((props, ref) => react.createElement(TabContentBase, Object.assign({}, props, {innerRef: ref})));
var TabsComponent;
(function(TabsComponent2) {
  TabsComponent2["div"] = "div";
  TabsComponent2["nav"] = "nav";
})(TabsComponent || (TabsComponent = {}));
var variantStyle$2 = {
  default: "",
  light300: styles$r.modifiers.colorSchemeLight_300
};
var Tabs = class extends react.Component {
  constructor(props) {
    super(props);
    this.tabList = react.createRef();
    this.handleScrollButtons = () => {
      const container = this.tabList.current;
      let disableLeftScrollButton = true;
      let disableRightScrollButton = true;
      let showScrollButtons = false;
      if (container && !this.props.isVertical) {
        const overflowOnLeft = !isElementInView(container, container.firstChild, false);
        const overflowOnRight = !isElementInView(container, container.lastChild, false);
        showScrollButtons = overflowOnLeft || overflowOnRight;
        disableLeftScrollButton = !overflowOnLeft;
        disableRightScrollButton = !overflowOnRight;
      }
      this.setState({
        showScrollButtons,
        disableLeftScrollButton,
        disableRightScrollButton
      });
    };
    this.scrollLeft = () => {
      if (this.tabList.current) {
        const container = this.tabList.current;
        const childrenArr = Array.from(container.children);
        let firstElementInView;
        let lastElementOutOfView;
        let i3;
        for (i3 = 0; i3 < childrenArr.length && !firstElementInView; i3++) {
          if (isElementInView(container, childrenArr[i3], false)) {
            firstElementInView = childrenArr[i3];
            lastElementOutOfView = childrenArr[i3 - 1];
          }
        }
        if (lastElementOutOfView) {
          container.scrollLeft -= lastElementOutOfView.scrollWidth;
        }
      }
    };
    this.scrollRight = () => {
      if (this.tabList.current) {
        const container = this.tabList.current;
        const childrenArr = Array.from(container.children);
        let lastElementInView;
        let firstElementOutOfView;
        for (let i3 = childrenArr.length - 1; i3 >= 0 && !lastElementInView; i3--) {
          if (isElementInView(container, childrenArr[i3], false)) {
            lastElementInView = childrenArr[i3];
            firstElementOutOfView = childrenArr[i3 + 1];
          }
        }
        if (firstElementOutOfView) {
          container.scrollLeft += firstElementOutOfView.scrollWidth;
        }
      }
    };
    this.state = {
      showScrollButtons: false,
      disableLeftScrollButton: true,
      disableRightScrollButton: true,
      shownKeys: this.props.defaultActiveKey !== void 0 ? [this.props.defaultActiveKey] : [this.props.activeKey],
      uncontrolledActiveKey: this.props.defaultActiveKey,
      uncontrolledIsExpandedLocal: this.props.defaultIsExpanded,
      ouiaStateId: getDefaultOUIAId(Tabs.displayName)
    };
    if (this.props.isVertical && this.props.expandable !== void 0) {
      if (!this.props.toggleAriaLabel && !this.props.toggleText) {
        console.error("Tabs:", "toggleAriaLabel or the toggleText prop is required to make the toggle button accessible");
      }
    }
  }
  handleTabClick(event, eventKey, tabContentRef) {
    event.preventDefault();
    const {shownKeys} = this.state;
    const {onSelect, defaultActiveKey} = this.props;
    if (defaultActiveKey !== void 0) {
      this.setState({
        uncontrolledActiveKey: eventKey
      });
    } else {
      onSelect(event, eventKey);
    }
    if (tabContentRef) {
      react.Children.toArray(this.props.children).map((child) => child).filter((child) => child.props && child.props.tabContentRef && child.props.tabContentRef.current).forEach((child) => child.props.tabContentRef.current.hidden = true);
      if (tabContentRef.current) {
        tabContentRef.current.hidden = false;
      }
    }
    if (this.props.mountOnEnter) {
      this.setState({
        shownKeys: shownKeys.concat(eventKey)
      });
    }
  }
  componentDidMount() {
    if (!this.props.isVertical) {
      if (canUseDOM) {
        window.addEventListener("resize", this.handleScrollButtons, false);
      }
      this.handleScrollButtons();
    }
  }
  componentWillUnmount() {
    if (!this.props.isVertical) {
      if (canUseDOM) {
        window.removeEventListener("resize", this.handleScrollButtons, false);
      }
    }
  }
  componentDidUpdate(prevProps) {
    const {activeKey, mountOnEnter} = this.props;
    const {shownKeys} = this.state;
    if (prevProps.activeKey !== activeKey && mountOnEnter && shownKeys.indexOf(activeKey) < 0) {
      this.setState({
        shownKeys: shownKeys.concat(activeKey)
      });
    }
  }
  render() {
    const _a = this.props, {className, children: children2, activeKey, defaultActiveKey, id: id3, isFilled, isSecondary, isVertical, isBox, leftScrollAriaLabel, rightScrollAriaLabel, "aria-label": ariaLabel, component, ouiaId, ouiaSafe, mountOnEnter, unmountOnExit, usePageInsets, inset, variant, expandable: expandable2, isExpanded, defaultIsExpanded, toggleText, toggleAriaLabel, onToggle} = _a, props = __rest(_a, ["className", "children", "activeKey", "defaultActiveKey", "id", "isFilled", "isSecondary", "isVertical", "isBox", "leftScrollAriaLabel", "rightScrollAriaLabel", "aria-label", "component", "ouiaId", "ouiaSafe", "mountOnEnter", "unmountOnExit", "usePageInsets", "inset", "variant", "expandable", "isExpanded", "defaultIsExpanded", "toggleText", "toggleAriaLabel", "onToggle"]);
    const {showScrollButtons, disableLeftScrollButton, disableRightScrollButton, shownKeys, uncontrolledActiveKey, uncontrolledIsExpandedLocal} = this.state;
    const filteredChildren = react.Children.toArray(children2).filter(Boolean).filter((child) => !child.props.isHidden);
    const uniqueId2 = id3 || getUniqueId();
    const Component = component === TabsComponent.nav ? "nav" : "div";
    const localActiveKey = defaultActiveKey !== void 0 ? uncontrolledActiveKey : activeKey;
    const isExpandedLocal = defaultIsExpanded !== void 0 ? uncontrolledIsExpandedLocal : isExpanded;
    const toggleTabs = (newValue) => {
      if (isExpanded === void 0) {
        this.setState({uncontrolledIsExpandedLocal: newValue});
      } else {
        onToggle(newValue);
      }
    };
    return react.createElement(TabsContextProvider, {value: {
      variant,
      mountOnEnter,
      unmountOnExit,
      localActiveKey,
      uniqueId: uniqueId2,
      handleTabClick: (...args) => this.handleTabClick(...args)
    }}, react.createElement(Component, Object.assign({"aria-label": ariaLabel, className: css(styles$r.tabs, isFilled && styles$r.modifiers.fill, isSecondary && styles$r.modifiers.secondary, isVertical && styles$r.modifiers.vertical, isVertical && expandable2 && formatBreakpointMods(expandable2, styles$r), isVertical && expandable2 && isExpandedLocal && styles$r.modifiers.expanded, isBox && styles$r.modifiers.box, showScrollButtons && !isVertical && styles$r.modifiers.scrollable, usePageInsets && styles$r.modifiers.pageInsets, formatBreakpointMods(inset, styles$r), variantStyle$2[variant], className)}, getOUIAProps(Tabs.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId, ouiaSafe), {id: id3 && id3}, props), expandable2 && isVertical && react.createElement(GenerateId, null, (randomId) => react.createElement("div", {className: css(styles$r.tabsToggle)}, react.createElement("div", {className: css(styles$r.tabsToggleButton)}, react.createElement(Button, {onClick: () => toggleTabs(!isExpandedLocal), variant: "plain", "aria-label": toggleAriaLabel, "aria-expanded": isExpandedLocal, id: `${randomId}-button`, "aria-labelledby": `${randomId}-text ${randomId}-button`}, react.createElement("span", {className: css(styles$r.tabsToggleIcon)}, react.createElement(AngleRightIcon, {"arian-hidden": "true"})), toggleText && react.createElement("span", {className: css("pf-c-tabs__toggle-text"), id: `${randomId}-text`}, toggleText))))), react.createElement("button", {className: css(styles$r.tabsScrollButton, isSecondary && buttonStyles.modifiers.secondary), "aria-label": leftScrollAriaLabel, onClick: this.scrollLeft, disabled: disableLeftScrollButton, "aria-hidden": disableLeftScrollButton}, react.createElement(AngleLeftIcon, null)), react.createElement("ul", {className: css(styles$r.tabsList), ref: this.tabList, onScroll: this.handleScrollButtons}, filteredChildren), react.createElement("button", {className: css(styles$r.tabsScrollButton, isSecondary && buttonStyles.modifiers.secondary), "aria-label": rightScrollAriaLabel, onClick: this.scrollRight, disabled: disableRightScrollButton, "aria-hidden": disableRightScrollButton}, react.createElement(AngleRightIcon, null))), filteredChildren.filter((child) => child.props.children && !(unmountOnExit && child.props.eventKey !== localActiveKey) && !(mountOnEnter && shownKeys.indexOf(child.props.eventKey) === -1)).map((child, index3) => react.createElement(TabContent, {key: index3, activeKey: localActiveKey, child, id: child.props.id || uniqueId2, ouiaId: child.props.ouiaId})));
  }
};
Tabs.displayName = "Tabs";
Tabs.defaultProps = {
  activeKey: 0,
  onSelect: () => void 0,
  isFilled: false,
  isSecondary: false,
  isVertical: false,
  isBox: false,
  leftScrollAriaLabel: "Scroll left",
  rightScrollAriaLabel: "Scroll right",
  component: TabsComponent.div,
  mountOnEnter: false,
  unmountOnExit: false,
  ouiaSafe: true,
  variant: "default",
  onToggle: (isExpanded) => void 0
};
var TabTitleText = (_a) => {
  var {children: children2, className = ""} = _a, props = __rest(_a, ["children", "className"]);
  return react.createElement("span", Object.assign({className: css(styles$r.tabsItemText, className)}, props), children2);
};
TabTitleText.displayName = "TabTitleText";
var toggleGroup = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    modifiers: {
      compact: "pf-m-compact",
      selected: "pf-m-selected",
      disabled: "pf-m-disabled"
    },
    toggleGroup: "pf-c-toggle-group",
    toggleGroupButton: "pf-c-toggle-group__button",
    toggleGroupIcon: "pf-c-toggle-group__icon",
    toggleGroupItem: "pf-c-toggle-group__item",
    toggleGroupText: "pf-c-toggle-group__text"
  };
});
var styles$t = /* @__PURE__ */ getDefaultExportFromCjs(toggleGroup);
var ToggleGroup = (_a) => {
  var {className, children: children2, isCompact = false, "aria-label": ariaLabel} = _a, props = __rest(_a, ["className", "children", "isCompact", "aria-label"]);
  const toggleGroupItemList = [];
  react.Children.forEach(children2, (child) => {
    toggleGroupItemList.push(child);
  });
  return react.createElement("div", Object.assign({className: css(styles$t.toggleGroup, isCompact && styles$t.modifiers.compact, className), role: "group", "aria-label": ariaLabel}, props), toggleGroupItemList);
};
ToggleGroup.displayName = "ToggleGroup";
var ToggleGroupItemVariant;
(function(ToggleGroupItemVariant2) {
  ToggleGroupItemVariant2["icon"] = "icon";
  ToggleGroupItemVariant2["text"] = "text";
})(ToggleGroupItemVariant || (ToggleGroupItemVariant = {}));
var ToggleGroupItemElement = ({variant, children: children2}) => react.createElement("span", {className: css(variant === "icon" && styles$t.toggleGroupIcon, variant === "text" && styles$t.toggleGroupText)}, children2);
ToggleGroupItemElement.displayName = "ToggleGroupItemElement";
var ToggleGroupItem = (_a) => {
  var {text, icon, className, isDisabled = false, isSelected = false, "aria-label": ariaLabel = "", onChange = () => {
  }, buttonId = ""} = _a, props = __rest(_a, ["text", "icon", "className", "isDisabled", "isSelected", "aria-label", "onChange", "buttonId"]);
  const handleChange = (event) => {
    onChange(!isSelected, event);
  };
  if (!ariaLabel && icon && !text) {
    console.warn("An accessible aria-label is required when using the toggle group item icon variant.");
  }
  return react.createElement("div", Object.assign({className: css(styles$t.toggleGroupItem, className)}, props), react.createElement("button", Object.assign({type: "button", className: css(styles$t.toggleGroupButton, isSelected && styles$t.modifiers.selected), "aria-pressed": isSelected, onClick: handleChange}, ariaLabel && {"aria-label": ariaLabel}, isDisabled && {disabled: true}, buttonId && {id: buttonId}), icon ? react.createElement(ToggleGroupItemElement, {variant: ToggleGroupItemVariant.icon}, icon) : null, text ? react.createElement(ToggleGroupItemElement, {variant: ToggleGroupItemVariant.text}, text) : null));
};
ToggleGroupItem.displayName = "ToggleGroupItem";
var toolbar = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    chipGroup: "pf-c-chip-group",
    divider: "pf-c-divider",
    modifiers: {
      hidden: "pf-m-hidden",
      hiddenOnSm: "pf-m-hidden-on-sm",
      visibleOnSm: "pf-m-visible-on-sm",
      hiddenOnMd: "pf-m-hidden-on-md",
      visibleOnMd: "pf-m-visible-on-md",
      hiddenOnLg: "pf-m-hidden-on-lg",
      visibleOnLg: "pf-m-visible-on-lg",
      hiddenOnXl: "pf-m-hidden-on-xl",
      visibleOnXl: "pf-m-visible-on-xl",
      hiddenOn_2xl: "pf-m-hidden-on-2xl",
      visibleOn_2xl: "pf-m-visible-on-2xl",
      pageInsets: "pf-m-page-insets",
      sticky: "pf-m-sticky",
      fullHeight: "pf-m-full-height",
      static: "pf-m-static",
      vertical: "pf-m-vertical",
      buttonGroup: "pf-m-button-group",
      iconButtonGroup: "pf-m-icon-button-group",
      filterGroup: "pf-m-filter-group",
      toggleGroup: "pf-m-toggle-group",
      overflowMenu: "pf-m-overflow-menu",
      bulkSelect: "pf-m-bulk-select",
      expandAll: "pf-m-expand-all",
      expanded: "pf-m-expanded",
      searchFilter: "pf-m-search-filter",
      chipGroup: "pf-m-chip-group",
      label: "pf-m-label",
      pagination: "pf-m-pagination",
      chipContainer: "pf-m-chip-container",
      plain: "pf-m-plain",
      show: "pf-m-show",
      showOnSm: "pf-m-show-on-sm",
      showOnMd: "pf-m-show-on-md",
      showOnLg: "pf-m-show-on-lg",
      showOnXl: "pf-m-show-on-xl",
      showOn_2xl: "pf-m-show-on-2xl",
      alignRight: "pf-m-align-right",
      alignLeft: "pf-m-align-left",
      nowrap: "pf-m-nowrap",
      wrap: "pf-m-wrap",
      alignRightOnSm: "pf-m-align-right-on-sm",
      alignLeftOnSm: "pf-m-align-left-on-sm",
      nowrapOnSm: "pf-m-nowrap-on-sm",
      wrapOnSm: "pf-m-wrap-on-sm",
      alignRightOnMd: "pf-m-align-right-on-md",
      alignLeftOnMd: "pf-m-align-left-on-md",
      nowrapOnMd: "pf-m-nowrap-on-md",
      wrapOnMd: "pf-m-wrap-on-md",
      alignRightOnLg: "pf-m-align-right-on-lg",
      alignLeftOnLg: "pf-m-align-left-on-lg",
      nowrapOnLg: "pf-m-nowrap-on-lg",
      wrapOnLg: "pf-m-wrap-on-lg",
      alignRightOnXl: "pf-m-align-right-on-xl",
      alignLeftOnXl: "pf-m-align-left-on-xl",
      nowrapOnXl: "pf-m-nowrap-on-xl",
      wrapOnXl: "pf-m-wrap-on-xl",
      alignRightOn_2xl: "pf-m-align-right-on-2xl",
      alignLeftOn_2xl: "pf-m-align-left-on-2xl",
      nowrapOn_2xl: "pf-m-nowrap-on-2xl",
      wrapOn_2xl: "pf-m-wrap-on-2xl",
      spaceItemsNone: "pf-m-space-items-none",
      spaceItemsSm: "pf-m-space-items-sm",
      spaceItemsMd: "pf-m-space-items-md",
      spaceItemsLg: "pf-m-space-items-lg",
      spaceItemsNoneOnSm: "pf-m-space-items-none-on-sm",
      spaceItemsSmOnSm: "pf-m-space-items-sm-on-sm",
      spaceItemsMdOnSm: "pf-m-space-items-md-on-sm",
      spaceItemsLgOnSm: "pf-m-space-items-lg-on-sm",
      spaceItemsNoneOnMd: "pf-m-space-items-none-on-md",
      spaceItemsSmOnMd: "pf-m-space-items-sm-on-md",
      spaceItemsMdOnMd: "pf-m-space-items-md-on-md",
      spaceItemsLgOnMd: "pf-m-space-items-lg-on-md",
      spaceItemsNoneOnLg: "pf-m-space-items-none-on-lg",
      spaceItemsSmOnLg: "pf-m-space-items-sm-on-lg",
      spaceItemsMdOnLg: "pf-m-space-items-md-on-lg",
      spaceItemsLgOnLg: "pf-m-space-items-lg-on-lg",
      spaceItemsNoneOnXl: "pf-m-space-items-none-on-xl",
      spaceItemsSmOnXl: "pf-m-space-items-sm-on-xl",
      spaceItemsMdOnXl: "pf-m-space-items-md-on-xl",
      spaceItemsLgOnXl: "pf-m-space-items-lg-on-xl",
      spaceItemsNoneOn_2xl: "pf-m-space-items-none-on-2xl",
      spaceItemsSmOn_2xl: "pf-m-space-items-sm-on-2xl",
      spaceItemsMdOn_2xl: "pf-m-space-items-md-on-2xl",
      spaceItemsLgOn_2xl: "pf-m-space-items-lg-on-2xl",
      spacerNone: "pf-m-spacer-none",
      spacerSm: "pf-m-spacer-sm",
      spacerMd: "pf-m-spacer-md",
      spacerLg: "pf-m-spacer-lg",
      spacerNoneOnSm: "pf-m-spacer-none-on-sm",
      spacerSmOnSm: "pf-m-spacer-sm-on-sm",
      spacerMdOnSm: "pf-m-spacer-md-on-sm",
      spacerLgOnSm: "pf-m-spacer-lg-on-sm",
      spacerNoneOnMd: "pf-m-spacer-none-on-md",
      spacerSmOnMd: "pf-m-spacer-sm-on-md",
      spacerMdOnMd: "pf-m-spacer-md-on-md",
      spacerLgOnMd: "pf-m-spacer-lg-on-md",
      spacerNoneOnLg: "pf-m-spacer-none-on-lg",
      spacerSmOnLg: "pf-m-spacer-sm-on-lg",
      spacerMdOnLg: "pf-m-spacer-md-on-lg",
      spacerLgOnLg: "pf-m-spacer-lg-on-lg",
      spacerNoneOnXl: "pf-m-spacer-none-on-xl",
      spacerSmOnXl: "pf-m-spacer-sm-on-xl",
      spacerMdOnXl: "pf-m-spacer-md-on-xl",
      spacerLgOnXl: "pf-m-spacer-lg-on-xl",
      spacerNoneOn_2xl: "pf-m-spacer-none-on-2xl",
      spacerSmOn_2xl: "pf-m-spacer-sm-on-2xl",
      spacerMdOn_2xl: "pf-m-spacer-md-on-2xl",
      spacerLgOn_2xl: "pf-m-spacer-lg-on-2xl",
      insetNone: "pf-m-inset-none",
      insetSm: "pf-m-inset-sm",
      insetMd: "pf-m-inset-md",
      insetLg: "pf-m-inset-lg",
      insetXl: "pf-m-inset-xl",
      inset_2xl: "pf-m-inset-2xl",
      insetNoneOnSm: "pf-m-inset-none-on-sm",
      insetSmOnSm: "pf-m-inset-sm-on-sm",
      insetMdOnSm: "pf-m-inset-md-on-sm",
      insetLgOnSm: "pf-m-inset-lg-on-sm",
      insetXlOnSm: "pf-m-inset-xl-on-sm",
      inset_2xlOnSm: "pf-m-inset-2xl-on-sm",
      insetNoneOnMd: "pf-m-inset-none-on-md",
      insetSmOnMd: "pf-m-inset-sm-on-md",
      insetMdOnMd: "pf-m-inset-md-on-md",
      insetLgOnMd: "pf-m-inset-lg-on-md",
      insetXlOnMd: "pf-m-inset-xl-on-md",
      inset_2xlOnMd: "pf-m-inset-2xl-on-md",
      insetNoneOnLg: "pf-m-inset-none-on-lg",
      insetSmOnLg: "pf-m-inset-sm-on-lg",
      insetMdOnLg: "pf-m-inset-md-on-lg",
      insetLgOnLg: "pf-m-inset-lg-on-lg",
      insetXlOnLg: "pf-m-inset-xl-on-lg",
      inset_2xlOnLg: "pf-m-inset-2xl-on-lg",
      insetNoneOnXl: "pf-m-inset-none-on-xl",
      insetSmOnXl: "pf-m-inset-sm-on-xl",
      insetMdOnXl: "pf-m-inset-md-on-xl",
      insetLgOnXl: "pf-m-inset-lg-on-xl",
      insetXlOnXl: "pf-m-inset-xl-on-xl",
      inset_2xlOnXl: "pf-m-inset-2xl-on-xl",
      insetNoneOn_2xl: "pf-m-inset-none-on-2xl",
      insetSmOn_2xl: "pf-m-inset-sm-on-2xl",
      insetMdOn_2xl: "pf-m-inset-md-on-2xl",
      insetLgOn_2xl: "pf-m-inset-lg-on-2xl",
      insetXlOn_2xl: "pf-m-inset-xl-on-2xl",
      inset_2xlOn_2xl: "pf-m-inset-2xl-on-2xl"
    },
    pagination: "pf-c-pagination",
    toolbar: "pf-c-toolbar",
    toolbarContent: "pf-c-toolbar__content",
    toolbarContentSection: "pf-c-toolbar__content-section",
    toolbarExpandAllIcon: "pf-c-toolbar__expand-all-icon",
    toolbarExpandableContent: "pf-c-toolbar__expandable-content",
    toolbarGroup: "pf-c-toolbar__group",
    toolbarItem: "pf-c-toolbar__item",
    toolbarToggle: "pf-c-toolbar__toggle"
  };
});
var styles$u = /* @__PURE__ */ getDefaultExportFromCjs(toolbar);
var ToolbarContext = react.createContext({
  isExpanded: false,
  toggleIsExpanded: () => {
  },
  chipGroupContentRef: null,
  updateNumberFilters: () => {
  },
  numberOfFilters: 0,
  clearAllFilters: () => {
  }
});
var ToolbarContentContext = react.createContext({
  expandableContentRef: null,
  expandableContentId: "",
  chipContainerRef: null
});
var globalBreakpoints = {
  md: parseInt(global_breakpoint_md.value),
  lg: parseInt(global_breakpoint_lg.value),
  xl: parseInt(global_breakpoint_xl.value),
  "2xl": parseInt(global_breakpoint_2xl.value)
};
var ToolbarItemVariant;
(function(ToolbarItemVariant2) {
  ToolbarItemVariant2["separator"] = "separator";
  ToolbarItemVariant2["bulk-select"] = "bulk-select";
  ToolbarItemVariant2["overflow-menu"] = "overflow-menu";
  ToolbarItemVariant2["pagination"] = "pagination";
  ToolbarItemVariant2["search-filter"] = "search-filter";
  ToolbarItemVariant2["label"] = "label";
  ToolbarItemVariant2["chip-group"] = "chip-group";
  ToolbarItemVariant2["expand-all"] = "expand-all";
})(ToolbarItemVariant || (ToolbarItemVariant = {}));
var ToolbarItem = (_a) => {
  var {className, variant, visibility, visiblity, alignment, spacer, widths, id: id3, children: children2, isAllExpanded} = _a, props = __rest(_a, ["className", "variant", "visibility", "visiblity", "alignment", "spacer", "widths", "id", "children", "isAllExpanded"]);
  if (variant === ToolbarItemVariant.separator) {
    return react.createElement(Divider, Object.assign({className: css(styles$u.modifiers.vertical, className)}, props));
  }
  if (visiblity !== void 0) {
    console.warn("The ToolbarItem visiblity prop has been deprecated. Please use the correctly spelled visibility prop instead.");
  }
  const widthStyles = {};
  if (widths) {
    Object.entries(widths || {}).map(([breakpoint, value]) => widthStyles[`--pf-c-toolbar__item--Width${breakpoint !== "default" ? `-on-${breakpoint}` : ""}`] = value);
  }
  return react.createElement("div", Object.assign({className: css(styles$u.toolbarItem, variant && styles$u.modifiers[toCamel(variant)], isAllExpanded && styles$u.modifiers.expanded, formatBreakpointMods(visibility || visiblity, styles$u), formatBreakpointMods(alignment, styles$u), formatBreakpointMods(spacer, styles$u), className)}, variant === "label" && {"aria-hidden": true}, {id: id3}, props, widths && {style: Object.assign(Object.assign({}, widthStyles), props.style)}), children2);
};
ToolbarItem.displayName = "ToolbarItem";
var ToolbarGroupVariant;
(function(ToolbarGroupVariant2) {
  ToolbarGroupVariant2["filter-group"] = "filter-group";
  ToolbarGroupVariant2["icon-button-group"] = "icon-button-group";
  ToolbarGroupVariant2["button-group"] = "button-group";
})(ToolbarGroupVariant || (ToolbarGroupVariant = {}));
var ToolbarGroupWithRef = class extends react.Component {
  render() {
    const _a = this.props, {visibility, visiblity, alignment, spacer, spaceItems, className, variant, children: children2, innerRef} = _a, props = __rest(_a, ["visibility", "visiblity", "alignment", "spacer", "spaceItems", "className", "variant", "children", "innerRef"]);
    if (visiblity !== void 0) {
      console.warn("The ToolbarGroup visiblity prop has been deprecated. Please use the correctly spelled visibility prop instead.");
    }
    return react.createElement("div", Object.assign({className: css(styles$u.toolbarGroup, variant && styles$u.modifiers[toCamel(variant)], formatBreakpointMods(visibility || visiblity, styles$u), formatBreakpointMods(alignment, styles$u), formatBreakpointMods(spacer, styles$u), formatBreakpointMods(spaceItems, styles$u), className)}, props, {ref: innerRef}), children2);
  }
};
var ToolbarGroup = react.forwardRef((props, ref) => react.createElement(ToolbarGroupWithRef, Object.assign({}, props, {innerRef: ref})));
var ToolbarChipGroupContent = class extends react.Component {
  render() {
    const _a = this.props, {className, isExpanded, chipGroupContentRef, clearAllFilters, showClearFiltersButton, clearFiltersButtonText, collapseListedFiltersBreakpoint, numberOfFilters} = _a, props = __rest(_a, ["className", "isExpanded", "chipGroupContentRef", "clearAllFilters", "showClearFiltersButton", "clearFiltersButtonText", "collapseListedFiltersBreakpoint", "numberOfFilters"]);
    const clearChipGroups = () => {
      clearAllFilters();
    };
    let collapseListedFilters = false;
    if (collapseListedFiltersBreakpoint === "all") {
      collapseListedFilters = true;
    } else if (canUseDOM) {
      collapseListedFilters = (canUseDOM ? window.innerWidth : 1200) < globalBreakpoints[collapseListedFiltersBreakpoint];
    }
    return react.createElement("div", Object.assign({className: css(styles$u.toolbarContent, (numberOfFilters === 0 || isExpanded) && styles$u.modifiers.hidden, className)}, (numberOfFilters === 0 || isExpanded) && {hidden: true}, {ref: chipGroupContentRef}, props), react.createElement(ToolbarGroup, Object.assign({className: css(collapseListedFilters && styles$u.modifiers.hidden)}, collapseListedFilters && {hidden: true}, collapseListedFilters && {"aria-hidden": true})), collapseListedFilters && numberOfFilters > 0 && !isExpanded && react.createElement(ToolbarGroup, null, react.createElement(ToolbarItem, null, numberOfFilters, " filters applied")), showClearFiltersButton && !isExpanded && react.createElement(ToolbarItem, null, react.createElement(Button, {variant: "link", onClick: clearChipGroups, isInline: true}, clearFiltersButtonText)));
  }
};
ToolbarChipGroupContent.displayName = "ToolbarChipGroupContent";
ToolbarChipGroupContent.defaultProps = {
  clearFiltersButtonText: "Clear all filters",
  collapseListedFiltersBreakpoint: "lg"
};
var Toolbar = class extends react.Component {
  constructor() {
    super(...arguments);
    this.chipGroupContentRef = react.createRef();
    this.staticFilterInfo = {};
    this.state = {
      isManagedToggleExpanded: false,
      filterInfo: {},
      windowWidth: canUseDOM ? window.innerWidth : 1200,
      ouiaStateId: getDefaultOUIAId(Toolbar.displayName)
    };
    this.isToggleManaged = () => !(this.props.isExpanded || !!this.props.toggleIsExpanded);
    this.toggleIsExpanded = () => {
      this.setState((prevState) => ({
        isManagedToggleExpanded: !prevState.isManagedToggleExpanded
      }));
    };
    this.closeExpandableContent = (e2) => {
      if (e2.target.innerWidth !== this.state.windowWidth) {
        this.setState(() => ({
          isManagedToggleExpanded: false,
          windowWidth: e2.target.innerWidth
        }));
      }
    };
    this.updateNumberFilters = (categoryName, numberOfFilters) => {
      const filterInfoToUpdate = Object.assign({}, this.staticFilterInfo);
      if (!filterInfoToUpdate.hasOwnProperty(categoryName) || filterInfoToUpdate[categoryName] !== numberOfFilters) {
        filterInfoToUpdate[categoryName] = numberOfFilters;
        this.staticFilterInfo = filterInfoToUpdate;
        this.setState({filterInfo: filterInfoToUpdate});
      }
    };
    this.getNumberOfFilters = () => Object.values(this.state.filterInfo).reduce((acc, cur) => acc + cur, 0);
    this.renderToolbar = (randomId) => {
      const _a = this.props, {clearAllFilters, clearFiltersButtonText, collapseListedFiltersBreakpoint, isExpanded: isExpandedProp, toggleIsExpanded, className, children: children2, isFullHeight, isStatic, inset, usePageInsets, isSticky, ouiaId} = _a, props = __rest(_a, ["clearAllFilters", "clearFiltersButtonText", "collapseListedFiltersBreakpoint", "isExpanded", "toggleIsExpanded", "className", "children", "isFullHeight", "isStatic", "inset", "usePageInsets", "isSticky", "ouiaId"]);
      const {isManagedToggleExpanded} = this.state;
      const isToggleManaged = this.isToggleManaged();
      const isExpanded = isToggleManaged ? isManagedToggleExpanded : isExpandedProp;
      const numberOfFilters = this.getNumberOfFilters();
      const showClearFiltersButton = numberOfFilters > 0;
      return react.createElement("div", Object.assign({className: css(styles$u.toolbar, isFullHeight && styles$u.modifiers.fullHeight, isStatic && styles$u.modifiers.static, usePageInsets && styles$u.modifiers.pageInsets, isSticky && styles$u.modifiers.sticky, formatBreakpointMods(inset, styles$u), className), id: randomId}, getOUIAProps(Toolbar.displayName, ouiaId !== void 0 ? ouiaId : this.state.ouiaStateId), props), react.createElement(ToolbarContext.Provider, {value: {
        isExpanded,
        toggleIsExpanded: isToggleManaged ? this.toggleIsExpanded : toggleIsExpanded,
        chipGroupContentRef: this.chipGroupContentRef,
        updateNumberFilters: this.updateNumberFilters,
        numberOfFilters,
        clearAllFilters,
        clearFiltersButtonText,
        showClearFiltersButton,
        toolbarId: randomId
      }}, children2, react.createElement(ToolbarChipGroupContent, {isExpanded, chipGroupContentRef: this.chipGroupContentRef, clearAllFilters, showClearFiltersButton, clearFiltersButtonText, numberOfFilters, collapseListedFiltersBreakpoint})));
    };
  }
  componentDidMount() {
    if (this.isToggleManaged() && canUseDOM) {
      window.addEventListener("resize", this.closeExpandableContent);
    }
  }
  componentWillUnmount() {
    if (this.isToggleManaged() && canUseDOM) {
      window.removeEventListener("resize", this.closeExpandableContent);
    }
  }
  render() {
    return this.props.id ? this.renderToolbar(this.props.id) : react.createElement(GenerateId, null, (randomId) => this.renderToolbar(randomId));
  }
};
Toolbar.displayName = "Toolbar";
var ToolbarExpandableContent = class extends react.Component {
  render() {
    const _a = this.props, {
      className,
      expandableContentRef,
      chipContainerRef,
      isExpanded,
      clearAllFilters,
      clearFiltersButtonText,
      showClearFiltersButton
    } = _a, props = __rest(_a, ["className", "expandableContentRef", "chipContainerRef", "isExpanded", "clearAllFilters", "clearFiltersButtonText", "showClearFiltersButton"]);
    const {numberOfFilters} = this.context;
    const clearChipGroups = () => {
      clearAllFilters();
    };
    return react.createElement("div", Object.assign({className: css(styles$u.toolbarExpandableContent, className), ref: expandableContentRef}, props), react.createElement(ToolbarGroup, null), numberOfFilters > 0 && react.createElement(ToolbarGroup, {className: styles$u.modifiers.chipContainer}, react.createElement(ToolbarGroup, {ref: chipContainerRef}), showClearFiltersButton && react.createElement(ToolbarItem, null, react.createElement(Button, {variant: "link", onClick: clearChipGroups, isInline: true}, clearFiltersButtonText))));
  }
};
ToolbarExpandableContent.displayName = "ToolbarExpandableContent";
ToolbarExpandableContent.contextType = ToolbarContext;
ToolbarExpandableContent.defaultProps = {
  isExpanded: false,
  clearFiltersButtonText: "Clear all filters"
};
var ToolbarContent = class extends react.Component {
  constructor() {
    super(...arguments);
    this.expandableContentRef = react.createRef();
    this.chipContainerRef = react.createRef();
  }
  render() {
    const _a = this.props, {className, children: children2, isExpanded, toolbarId, visibility, visiblity, alignment, clearAllFilters, showClearFiltersButton, clearFiltersButtonText} = _a, props = __rest(_a, ["className", "children", "isExpanded", "toolbarId", "visibility", "visiblity", "alignment", "clearAllFilters", "showClearFiltersButton", "clearFiltersButtonText"]);
    if (visiblity !== void 0) {
      console.warn("The ToolbarContent visiblity prop has been deprecated. Please use the correctly spelled visibility prop instead.");
    }
    return react.createElement("div", Object.assign({className: css(styles$u.toolbarContent, formatBreakpointMods(visibility || visiblity, styles$u), formatBreakpointMods(alignment, styles$u), className)}, props), react.createElement(ToolbarContext.Consumer, null, ({clearAllFilters: clearAllFiltersContext, clearFiltersButtonText: clearFiltersButtonContext, showClearFiltersButton: showClearFiltersButtonContext, toolbarId: toolbarIdContext}) => {
      const expandableContentId = `${toolbarId || toolbarIdContext}-expandable-content-${ToolbarContent.currentId++}`;
      return react.createElement(ToolbarContentContext.Provider, {value: {
        expandableContentRef: this.expandableContentRef,
        expandableContentId,
        chipContainerRef: this.chipContainerRef
      }}, react.createElement("div", {className: css(styles$u.toolbarContentSection)}, children2), react.createElement(ToolbarExpandableContent, {id: expandableContentId, isExpanded, expandableContentRef: this.expandableContentRef, chipContainerRef: this.chipContainerRef, clearAllFilters: clearAllFilters || clearAllFiltersContext, showClearFiltersButton: showClearFiltersButton || showClearFiltersButtonContext, clearFiltersButtonText: clearFiltersButtonText || clearFiltersButtonContext}));
    }));
  }
};
ToolbarContent.displayName = "ToolbarContent";
ToolbarContent.currentId = 0;
ToolbarContent.defaultProps = {
  isExpanded: false,
  showClearFiltersButton: false
};
var numberInput = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    formControl: "pf-c-form-control",
    inputGroup: "pf-c-input-group",
    numberInput: "pf-c-number-input",
    numberInputIcon: "pf-c-number-input__icon",
    numberInputUnit: "pf-c-number-input__unit"
  };
});
var styles$v = /* @__PURE__ */ getDefaultExportFromCjs(numberInput);
var NumberInput = (_a) => {
  var {value = 0, className, widthChars, isDisabled = false, onMinus = () => {
  }, onChange, onPlus = () => {
  }, unit, unitPosition = "after", min: min2, max: max2, inputName, inputAriaLabel = "Input", minusBtnAriaLabel = "Minus", plusBtnAriaLabel = "Plus", inputProps, minusBtnProps, plusBtnProps} = _a, props = __rest(_a, ["value", "className", "widthChars", "isDisabled", "onMinus", "onChange", "onPlus", "unit", "unitPosition", "min", "max", "inputName", "inputAriaLabel", "minusBtnAriaLabel", "plusBtnAriaLabel", "inputProps", "minusBtnProps", "plusBtnProps"]);
  const numberInputUnit = react.createElement("div", {className: css(styles$v.numberInputUnit)}, unit);
  return react.createElement("div", Object.assign({className: css(styles$v.numberInput, className)}, widthChars && {
    style: Object.assign({"--pf-c-number-input--c-form-control--width-chars": widthChars}, props.style)
  }, props), unit && unitPosition === "before" && numberInputUnit, react.createElement("div", {className: css(styles$v.inputGroup)}, react.createElement(Button, Object.assign({variant: "control", "aria-label": minusBtnAriaLabel, isDisabled: isDisabled || value === min2, onClick: (evt) => onMinus(evt, inputName)}, minusBtnProps), react.createElement("span", {className: css(styles$v.numberInputIcon)}, react.createElement(MinusIcon, {"aria-hidden": "true"}))), react.createElement("input", Object.assign({className: css(styles$v.formControl), type: "number", value, name: inputName, "aria-label": inputAriaLabel}, isDisabled && {disabled: isDisabled}, onChange && {onChange}, !onChange && {readOnly: true}, inputProps)), react.createElement(Button, Object.assign({variant: "control", "aria-label": plusBtnAriaLabel, isDisabled: isDisabled || value === max2, onClick: (evt) => onPlus(evt, inputName)}, plusBtnProps), react.createElement("span", {className: css(styles$v.numberInputIcon)}, react.createElement(PlusIcon, {"aria-hidden": "true"})))), unit && unitPosition === "after" && numberInputUnit);
};
NumberInput.displayName = "NumberInput";
var wizard = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    card: "pf-c-card",
    modalBox: "pf-c-modal-box",
    modifiers: {
      finished: "pf-m-finished",
      expanded: "pf-m-expanded",
      current: "pf-m-current",
      expandable: "pf-m-expandable",
      disabled: "pf-m-disabled",
      noPadding: "pf-m-no-padding"
    },
    pageMainWizard: "pf-c-page__main-wizard",
    wizard: "pf-c-wizard",
    wizardClose: "pf-c-wizard__close",
    wizardDescription: "pf-c-wizard__description",
    wizardFooter: "pf-c-wizard__footer",
    wizardFooterCancel: "pf-c-wizard__footer-cancel",
    wizardHeader: "pf-c-wizard__header",
    wizardInnerWrap: "pf-c-wizard__inner-wrap",
    wizardMain: "pf-c-wizard__main",
    wizardMainBody: "pf-c-wizard__main-body",
    wizardNav: "pf-c-wizard__nav",
    wizardNavItem: "pf-c-wizard__nav-item",
    wizardNavLink: "pf-c-wizard__nav-link",
    wizardNavLinkText: "pf-c-wizard__nav-link-text",
    wizardNavLinkToggle: "pf-c-wizard__nav-link-toggle",
    wizardNavLinkToggleIcon: "pf-c-wizard__nav-link-toggle-icon",
    wizardNavList: "pf-c-wizard__nav-list",
    wizardOuterWrap: "pf-c-wizard__outer-wrap",
    wizardTitle: "pf-c-wizard__title",
    wizardToggle: "pf-c-wizard__toggle",
    wizardToggleIcon: "pf-c-wizard__toggle-icon",
    wizardToggleList: "pf-c-wizard__toggle-list",
    wizardToggleListItem: "pf-c-wizard__toggle-list-item",
    wizardToggleNum: "pf-c-wizard__toggle-num",
    wizardToggleSeparator: "pf-c-wizard__toggle-separator"
  };
});
var styles$w = /* @__PURE__ */ getDefaultExportFromCjs(wizard);
var WizardFooterInternal = ({onNext, onBack, onClose, isValid, firstStep, activeStep, nextButtonText, backButtonText, cancelButtonText}) => react.createElement("footer", {className: css(styles$w.wizardFooter)}, react.createElement(Button, {variant: ButtonVariant.primary, type: "submit", onClick: onNext, isDisabled: !isValid}, nextButtonText), !activeStep.hideBackButton && react.createElement(Button, {variant: ButtonVariant.secondary, onClick: onBack, isDisabled: firstStep}, backButtonText), !activeStep.hideCancelButton && react.createElement("div", {className: styles$w.wizardFooterCancel}, react.createElement(Button, {variant: ButtonVariant.link, onClick: onClose}, cancelButtonText)));
WizardFooterInternal.displayName = "WizardFooterInternal";
var WizardBody = ({children: children2, hasNoBodyPadding = false, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, mainComponent = "div"}) => {
  const MainComponent = mainComponent;
  return react.createElement(MainComponent, {"aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, className: css(styles$w.wizardMain)}, react.createElement("div", {className: css(styles$w.wizardMainBody, hasNoBodyPadding && styles$w.modifiers.noPadding)}, children2));
};
WizardBody.displayName = "WizardBody";
var WizardToggle = ({isNavOpen, onNavToggle, nav: nav2, steps, activeStep, children: children2, hasNoBodyPadding = false, "aria-label": ariaLabel = "Wizard Toggle", mainAriaLabelledBy = null, mainAriaLabel = null, isInPage = true}) => {
  let activeStepIndex;
  let activeStepName;
  let activeStepSubName;
  for (let i3 = 0; i3 < steps.length; i3++) {
    if (activeStep.id && steps[i3].id === activeStep.id || steps[i3].name === activeStep.name) {
      activeStepIndex = i3 + 1;
      activeStepName = steps[i3].name;
      break;
    } else if (steps[i3].steps) {
      for (const step of steps[i3].steps) {
        if (activeStep.id && step.id === activeStep.id || step.name === activeStep.name) {
          activeStepIndex = i3 + 1;
          activeStepName = steps[i3].name;
          activeStepSubName = step.name;
          break;
        }
      }
    }
  }
  return react.createElement(react.Fragment, null, react.createElement("button", {onClick: () => onNavToggle(!isNavOpen), className: css(styles$w.wizardToggle, isNavOpen && "pf-m-expanded"), "aria-label": ariaLabel, "aria-expanded": isNavOpen}, react.createElement("span", {className: css(styles$w.wizardToggleList)}, react.createElement("span", {className: css(styles$w.wizardToggleListItem)}, react.createElement("span", {className: css(styles$w.wizardToggleNum)}, activeStepIndex), " ", activeStepName, activeStepSubName && react.createElement(AngleRightIcon, {className: css(styles$w.wizardToggleSeparator), "aria-hidden": "true"})), activeStepSubName && react.createElement("span", {className: css(styles$w.wizardToggleListItem)}, activeStepSubName)), react.createElement("span", {className: css(styles$w.wizardToggleIcon)}, react.createElement(CaretDownIcon, {"aria-hidden": "true"}))), react.createElement("div", {className: css(styles$w.wizardOuterWrap)}, react.createElement("div", {className: css(styles$w.wizardInnerWrap)}, nav2(isNavOpen), react.createElement(WizardBody, {mainComponent: isInPage ? "div" : "main", "aria-label": mainAriaLabel, "aria-labelledby": mainAriaLabelledBy, hasNoBodyPadding}, activeStep.component)), children2));
};
WizardToggle.displayName = "WizardToggle";
var WizardNav = ({children: children2, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, isOpen = false, returnList = false}) => {
  const innerList = react.createElement("ol", {className: css(styles$w.wizardNavList)}, children2);
  if (returnList) {
    return innerList;
  }
  return react.createElement("nav", {className: css(styles$w.wizardNav, isOpen && styles$w.modifiers.expanded), "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy}, react.createElement("ol", {className: css(styles$w.wizardNavList)}, children2));
};
WizardNav.displayName = "WizardNav";
var WizardNavItem = (_a) => {
  var {children: children2 = null, content: content2 = "", isCurrent = false, isDisabled = false, step, onNavItemClick = () => void 0, navItemComponent = "button", href = null, isExpandable = false} = _a, rest = __rest(_a, ["children", "content", "isCurrent", "isDisabled", "step", "onNavItemClick", "navItemComponent", "href", "isExpandable"]);
  const NavItemComponent = navItemComponent;
  const [isExpanded, setIsExpanded] = react.useState(false);
  react.useEffect(() => {
    setIsExpanded(isCurrent);
  }, [isCurrent]);
  if (navItemComponent === "a" && !href && false) {
    console.error("WizardNavItem: When using an anchor, please provide an href");
  }
  const btnProps = {
    disabled: isDisabled
  };
  const linkProps = {
    tabIndex: isDisabled ? -1 : void 0,
    href
  };
  return react.createElement("li", {className: css(styles$w.wizardNavItem, isExpandable && styles$w.modifiers.expandable, isExpandable && isExpanded && styles$w.modifiers.expanded)}, react.createElement(NavItemComponent, Object.assign({}, rest, navItemComponent === "a" ? Object.assign({}, linkProps) : Object.assign({}, btnProps), {onClick: () => isExpandable ? setIsExpanded(!isExpanded || isCurrent) : onNavItemClick(step), className: css(styles$w.wizardNavLink, isCurrent && styles$w.modifiers.current, isDisabled && styles$w.modifiers.disabled), "aria-disabled": isDisabled ? true : null, "aria-current": isCurrent && !children2 ? "step" : false}, isExpandable && {"aria-expanded": isExpanded}), isExpandable ? react.createElement(react.Fragment, null, react.createElement("span", {className: css(styles$w.wizardNavLinkText)}, content2), react.createElement("span", {className: css(styles$w.wizardNavLinkToggle)}, react.createElement("span", {className: css(styles$w.wizardNavLinkToggleIcon)}, react.createElement(AngleRightIcon, null)))) : content2), children2);
};
WizardNavItem.displayName = "WizardNavItem";
var WizardContext = react.createContext({
  goToStepById: () => null,
  goToStepByName: () => null,
  onNext: () => null,
  onBack: () => null,
  onClose: () => null,
  activeStep: {name: null}
});
var WizardContextProvider = WizardContext.Provider;
var WizardContextConsumer = WizardContext.Consumer;
var WizardHeader = ({onClose = () => void 0, title: title3, description, hideClose, closeButtonAriaLabel, titleId, descriptionId}) => react.createElement("div", {className: css(styles$w.wizardHeader)}, !hideClose && react.createElement(Button, {variant: "plain", className: css(styles$w.wizardClose), "aria-label": closeButtonAriaLabel, onClick: onClose}, react.createElement(TimesIcon, {"aria-hidden": "true"})), react.createElement(Title, {headingLevel: "h2", size: "3xl", className: css(styles$w.wizardTitle), "aria-label": title3, id: titleId}, title3 || react.createElement(react.Fragment, null, " ")), description && react.createElement("p", {className: css(styles$w.wizardDescription), id: descriptionId}, description));
WizardHeader.displayName = "WizardHeader";
var Wizard = class extends react.Component {
  constructor(props) {
    super(props);
    this.handleKeyClicks = (event) => {
      if (event.keyCode === KEY_CODES.ESCAPE_KEY) {
        if (this.state.isNavOpen) {
          this.setState({isNavOpen: !this.state.isNavOpen});
        } else if (this.props.isOpen) {
          this.props.onClose();
        }
      }
    };
    this.onNext = () => {
      const {onNext, onClose, onSave} = this.props;
      const {currentStep} = this.state;
      const flattenedSteps = this.getFlattenedSteps();
      const maxSteps = flattenedSteps.length;
      if (currentStep >= maxSteps) {
        if (onSave) {
          return onSave();
        }
        return onClose();
      } else {
        const newStep = currentStep + 1;
        this.setState({
          currentStep: newStep
        });
        const {id: prevId, name: prevName} = flattenedSteps[currentStep - 1];
        const {id: id3, name} = flattenedSteps[newStep - 1];
        return onNext && onNext({id: id3, name}, {prevId, prevName});
      }
    };
    this.onBack = () => {
      const {onBack} = this.props;
      const {currentStep} = this.state;
      const flattenedSteps = this.getFlattenedSteps();
      if (flattenedSteps.length < currentStep) {
        const adjustedStep = flattenedSteps.length;
        this.setState({
          currentStep: adjustedStep
        });
      } else {
        const newStep = currentStep - 1 <= 0 ? 0 : currentStep - 1;
        this.setState({
          currentStep: newStep
        });
        const {id: prevId, name: prevName} = flattenedSteps[newStep];
        const {id: id3, name} = flattenedSteps[newStep - 1];
        return onBack && onBack({id: id3, name}, {prevId, prevName});
      }
    };
    this.goToStep = (step) => {
      const {onGoToStep} = this.props;
      const {currentStep} = this.state;
      const flattenedSteps = this.getFlattenedSteps();
      const maxSteps = flattenedSteps.length;
      if (step < 1) {
        step = 1;
      } else if (step > maxSteps) {
        step = maxSteps;
      }
      this.setState({currentStep: step, isNavOpen: false});
      const {id: prevId, name: prevName} = flattenedSteps[currentStep - 1];
      const {id: id3, name} = flattenedSteps[step - 1];
      return onGoToStep && onGoToStep({id: id3, name}, {prevId, prevName});
    };
    this.goToStepById = (stepId) => {
      const flattenedSteps = this.getFlattenedSteps();
      let step;
      for (let i3 = 0; i3 < flattenedSteps.length; i3++) {
        if (flattenedSteps[i3].id === stepId) {
          step = i3 + 1;
          break;
        }
      }
      if (step) {
        this.setState({currentStep: step});
      }
    };
    this.goToStepByName = (stepName) => {
      const flattenedSteps = this.getFlattenedSteps();
      let step;
      for (let i3 = 0; i3 < flattenedSteps.length; i3++) {
        if (flattenedSteps[i3].name === stepName) {
          step = i3 + 1;
          break;
        }
      }
      if (step) {
        this.setState({currentStep: step});
      }
    };
    this.getFlattenedSteps = () => {
      const {steps} = this.props;
      const flattenedSteps = [];
      for (const step of steps) {
        if (step.steps) {
          for (const childStep of step.steps) {
            flattenedSteps.push(childStep);
          }
        } else {
          flattenedSteps.push(step);
        }
      }
      return flattenedSteps;
    };
    this.getFlattenedStepsIndex = (flattenedSteps, stepName) => {
      for (let i3 = 0; i3 < flattenedSteps.length; i3++) {
        if (flattenedSteps[i3].name === stepName) {
          return i3 + 1;
        }
      }
      return 0;
    };
    this.initSteps = (steps) => {
      for (let i3 = 0; i3 < steps.length; i3++) {
        if (steps[i3].steps) {
          for (let j = 0; j < steps[i3].steps.length; j++) {
            steps[i3].steps[j] = Object.assign({canJumpTo: true}, steps[i3].steps[j]);
          }
        }
        steps[i3] = Object.assign({canJumpTo: true}, steps[i3]);
      }
      return steps;
    };
    this.getElement = (appendTo) => {
      if (typeof appendTo === "function") {
        return appendTo();
      }
      return appendTo || document.body;
    };
    const newId3 = Wizard.currentId++;
    this.titleId = props.titleId || `pf-wizard-title-${newId3}`;
    this.descriptionId = props.descriptionId || `pf-wizard-description-${newId3}`;
    this.state = {
      currentStep: this.props.startAtStep && Number.isInteger(this.props.startAtStep) ? this.props.startAtStep : 1,
      isNavOpen: false
    };
  }
  componentDidMount() {
    const target = typeof document !== "undefined" ? document.body : null;
    if (target) {
      target.addEventListener("keydown", this.handleKeyClicks, false);
    }
  }
  componentWillUnmount() {
    const target = typeof document !== "undefined" && document.body || null;
    if (target) {
      target.removeEventListener("keydown", this.handleKeyClicks, false);
    }
  }
  render() {
    const _a = this.props, {
      width: width2,
      height,
      title: title3,
      description,
      onClose,
      onSave,
      onBack,
      onNext,
      onGoToStep,
      className,
      steps,
      startAtStep,
      nextButtonText = "Next",
      backButtonText = "Back",
      cancelButtonText = "Cancel",
      hideClose,
      closeButtonAriaLabel = "Close",
      navAriaLabel,
      navAriaLabelledBy,
      mainAriaLabel,
      mainAriaLabelledBy,
      hasNoBodyPadding,
      footer,
      appendTo,
      isOpen,
      titleId,
      descriptionId,
      isNavExpandable
    } = _a, rest = __rest(_a, ["width", "height", "title", "description", "onClose", "onSave", "onBack", "onNext", "onGoToStep", "className", "steps", "startAtStep", "nextButtonText", "backButtonText", "cancelButtonText", "hideClose", "closeButtonAriaLabel", "navAriaLabel", "navAriaLabelledBy", "mainAriaLabel", "mainAriaLabelledBy", "hasNoBodyPadding", "footer", "appendTo", "isOpen", "titleId", "descriptionId", "isNavExpandable"]);
    const {currentStep} = this.state;
    const flattenedSteps = this.getFlattenedSteps();
    const adjustedStep = flattenedSteps.length < currentStep ? flattenedSteps.length : currentStep;
    const activeStep = flattenedSteps[adjustedStep - 1];
    const computedSteps = this.initSteps(steps);
    const firstStep = activeStep === flattenedSteps[0];
    const isValid = activeStep && activeStep.enableNext !== void 0 ? activeStep.enableNext : true;
    const nav2 = (isWizardNavOpen) => {
      const wizNavAProps = {
        isOpen: isWizardNavOpen,
        "aria-label": navAriaLabel,
        "aria-labelledby": (title3 || navAriaLabelledBy) && (navAriaLabelledBy || this.titleId)
      };
      return react.createElement(WizardNav, Object.assign({}, wizNavAProps), computedSteps.map((step, index3) => {
        if (step.isFinishedStep) {
          return;
        }
        let enabled;
        let navItemStep;
        if (step.steps) {
          let hasActiveChild = false;
          let canJumpToParent = false;
          for (const subStep of step.steps) {
            if (activeStep.name === subStep.name) {
              hasActiveChild = true;
            }
            if (subStep.canJumpTo) {
              canJumpToParent = true;
            }
          }
          navItemStep = this.getFlattenedStepsIndex(flattenedSteps, step.steps[0].name);
          return react.createElement(WizardNavItem, {key: index3, content: step.name, isExpandable: isNavExpandable, isCurrent: hasActiveChild, isDisabled: !canJumpToParent, step: navItemStep, onNavItemClick: this.goToStep}, react.createElement(WizardNav, Object.assign({}, wizNavAProps, {returnList: true}), step.steps.map((childStep, indexChild) => {
            if (childStep.isFinishedStep) {
              return;
            }
            navItemStep = this.getFlattenedStepsIndex(flattenedSteps, childStep.name);
            enabled = childStep.canJumpTo;
            return react.createElement(WizardNavItem, {key: `child_${indexChild}`, content: childStep.name, isCurrent: activeStep.name === childStep.name, isDisabled: !enabled, step: navItemStep, onNavItemClick: this.goToStep});
          })));
        }
        navItemStep = this.getFlattenedStepsIndex(flattenedSteps, step.name);
        enabled = step.canJumpTo;
        return react.createElement(WizardNavItem, Object.assign({}, step.stepNavItemProps, {key: index3, content: step.name, isCurrent: activeStep.name === step.name, isDisabled: !enabled, step: navItemStep, onNavItemClick: this.goToStep}));
      }));
    };
    const context2 = {
      goToStepById: this.goToStepById,
      goToStepByName: this.goToStepByName,
      onNext: this.onNext,
      onBack: this.onBack,
      onClose,
      activeStep
    };
    const divStyles = Object.assign(Object.assign({}, height ? {height} : {}), width2 ? {width: width2} : {});
    const wizard2 = react.createElement(WizardContextProvider, {value: context2}, react.createElement("div", Object.assign({}, rest, {className: css(styles$w.wizard, activeStep && activeStep.isFinishedStep && "pf-m-finished", className), style: Object.keys(divStyles).length ? divStyles : void 0}), title3 && react.createElement(WizardHeader, {titleId: this.titleId, descriptionId: this.descriptionId, onClose, title: title3, description, closeButtonAriaLabel, hideClose}), react.createElement(WizardToggle, {mainAriaLabel, isInPage: isOpen === void 0, mainAriaLabelledBy: (title3 || mainAriaLabelledBy) && (mainAriaLabelledBy || this.titleId), isNavOpen: this.state.isNavOpen, onNavToggle: (isNavOpen) => this.setState({isNavOpen}), nav: nav2, steps, activeStep, hasNoBodyPadding}, footer || react.createElement(WizardFooterInternal, {onNext: this.onNext, onBack: this.onBack, onClose, isValid, firstStep, activeStep, nextButtonText: activeStep && activeStep.nextButtonText || nextButtonText, backButtonText, cancelButtonText}))));
    if (isOpen !== void 0) {
      return react.createElement(Modal, {width: width2 !== null ? width2 : void 0, isOpen, variant: ModalVariant.large, "aria-labelledby": this.titleId, "aria-describedby": this.descriptionId, showClose: false, hasNoBodyWrapper: true}, wizard2);
    }
    return wizard2;
  }
};
Wizard.displayName = "Wizard";
Wizard.currentId = 0;
Wizard.defaultProps = {
  title: null,
  description: "",
  className: "",
  startAtStep: 1,
  nextButtonText: "Next",
  backButtonText: "Back",
  cancelButtonText: "Cancel",
  hideClose: false,
  closeButtonAriaLabel: "Close",
  navAriaLabel: null,
  navAriaLabelledBy: null,
  mainAriaLabel: null,
  mainAriaLabelledBy: null,
  hasNoBodyPadding: false,
  onBack: null,
  onNext: null,
  onGoToStep: null,
  width: null,
  height: null,
  footer: null,
  onClose: () => void 0,
  appendTo: null,
  isOpen: void 0,
  isNavExpandable: false
};
var WizardFooter = ({children: children2}) => react.createElement("footer", {className: css(styles$w.wizardFooter)}, children2);
WizardFooter.displayName = "WizardFooter";
var flex = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    flex: "pf-l-flex",
    modifiers: {
      flex: "pf-m-flex",
      inlineFlex: "pf-m-inline-flex",
      column: "pf-m-column",
      columnReverse: "pf-m-column-reverse",
      row: "pf-m-row",
      rowReverse: "pf-m-row-reverse",
      wrap: "pf-m-wrap",
      wrapReverse: "pf-m-wrap-reverse",
      nowrap: "pf-m-nowrap",
      justifyContentFlexStart: "pf-m-justify-content-flex-start",
      justifyContentFlexEnd: "pf-m-justify-content-flex-end",
      justifyContentCenter: "pf-m-justify-content-center",
      justifyContentSpaceBetween: "pf-m-justify-content-space-between",
      justifyContentSpaceAround: "pf-m-justify-content-space-around",
      justifyContentSpaceEvenly: "pf-m-justify-content-space-evenly",
      alignItemsFlexStart: "pf-m-align-items-flex-start",
      alignItemsFlexEnd: "pf-m-align-items-flex-end",
      alignItemsCenter: "pf-m-align-items-center",
      alignItemsStretch: "pf-m-align-items-stretch",
      alignItemsBaseline: "pf-m-align-items-baseline",
      alignContentFlexStart: "pf-m-align-content-flex-start",
      alignContentFlexEnd: "pf-m-align-content-flex-end",
      alignContentCenter: "pf-m-align-content-center",
      alignContentStretch: "pf-m-align-content-stretch",
      alignContentSpaceBetween: "pf-m-align-content-space-between",
      alignContentSpaceAround: "pf-m-align-content-space-around",
      alignRight: "pf-m-align-right",
      alignLeft: "pf-m-align-left",
      grow: "pf-m-grow",
      shrink: "pf-m-shrink",
      fullWidth: "pf-m-full-width",
      flex_1: "pf-m-flex-1",
      flex_2: "pf-m-flex-2",
      flex_3: "pf-m-flex-3",
      flex_4: "pf-m-flex-4",
      flexDefault: "pf-m-flex-default",
      flexNone: "pf-m-flex-none",
      alignSelfFlexStart: "pf-m-align-self-flex-start",
      alignSelfFlexEnd: "pf-m-align-self-flex-end",
      alignSelfCenter: "pf-m-align-self-center",
      alignSelfBaseline: "pf-m-align-self-baseline",
      alignSelfStretch: "pf-m-align-self-stretch",
      flexOnSm: "pf-m-flex-on-sm",
      inlineFlexOnSm: "pf-m-inline-flex-on-sm",
      columnOnSm: "pf-m-column-on-sm",
      columnReverseOnSm: "pf-m-column-reverse-on-sm",
      rowOnSm: "pf-m-row-on-sm",
      rowReverseOnSm: "pf-m-row-reverse-on-sm",
      wrapOnSm: "pf-m-wrap-on-sm",
      wrapReverseOnSm: "pf-m-wrap-reverse-on-sm",
      nowrapOnSm: "pf-m-nowrap-on-sm",
      justifyContentFlexStartOnSm: "pf-m-justify-content-flex-start-on-sm",
      justifyContentFlexEndOnSm: "pf-m-justify-content-flex-end-on-sm",
      justifyContentCenterOnSm: "pf-m-justify-content-center-on-sm",
      justifyContentSpaceBetweenOnSm: "pf-m-justify-content-space-between-on-sm",
      justifyContentSpaceAroundOnSm: "pf-m-justify-content-space-around-on-sm",
      justifyContentSpaceEvenlyOnSm: "pf-m-justify-content-space-evenly-on-sm",
      alignItemsFlexStartOnSm: "pf-m-align-items-flex-start-on-sm",
      alignItemsFlexEndOnSm: "pf-m-align-items-flex-end-on-sm",
      alignItemsCenterOnSm: "pf-m-align-items-center-on-sm",
      alignItemsStretchOnSm: "pf-m-align-items-stretch-on-sm",
      alignItemsBaselineOnSm: "pf-m-align-items-baseline-on-sm",
      alignContentFlexStartOnSm: "pf-m-align-content-flex-start-on-sm",
      alignContentFlexEndOnSm: "pf-m-align-content-flex-end-on-sm",
      alignContentCenterOnSm: "pf-m-align-content-center-on-sm",
      alignContentStretchOnSm: "pf-m-align-content-stretch-on-sm",
      alignContentSpaceBetweenOnSm: "pf-m-align-content-space-between-on-sm",
      alignContentSpaceAroundOnSm: "pf-m-align-content-space-around-on-sm",
      alignRightOnSm: "pf-m-align-right-on-sm",
      alignLeftOnSm: "pf-m-align-left-on-sm",
      growOnSm: "pf-m-grow-on-sm",
      shrinkOnSm: "pf-m-shrink-on-sm",
      fullWidthOnSm: "pf-m-full-width-on-sm",
      flex_1OnSm: "pf-m-flex-1-on-sm",
      flex_2OnSm: "pf-m-flex-2-on-sm",
      flex_3OnSm: "pf-m-flex-3-on-sm",
      flex_4OnSm: "pf-m-flex-4-on-sm",
      flexDefaultOnSm: "pf-m-flex-default-on-sm",
      flexNoneOnSm: "pf-m-flex-none-on-sm",
      alignSelfFlexStartOnSm: "pf-m-align-self-flex-start-on-sm",
      alignSelfFlexEndOnSm: "pf-m-align-self-flex-end-on-sm",
      alignSelfCenterOnSm: "pf-m-align-self-center-on-sm",
      alignSelfBaselineOnSm: "pf-m-align-self-baseline-on-sm",
      alignSelfStretchOnSm: "pf-m-align-self-stretch-on-sm",
      flexOnMd: "pf-m-flex-on-md",
      inlineFlexOnMd: "pf-m-inline-flex-on-md",
      columnOnMd: "pf-m-column-on-md",
      columnReverseOnMd: "pf-m-column-reverse-on-md",
      rowOnMd: "pf-m-row-on-md",
      rowReverseOnMd: "pf-m-row-reverse-on-md",
      wrapOnMd: "pf-m-wrap-on-md",
      wrapReverseOnMd: "pf-m-wrap-reverse-on-md",
      nowrapOnMd: "pf-m-nowrap-on-md",
      justifyContentFlexStartOnMd: "pf-m-justify-content-flex-start-on-md",
      justifyContentFlexEndOnMd: "pf-m-justify-content-flex-end-on-md",
      justifyContentCenterOnMd: "pf-m-justify-content-center-on-md",
      justifyContentSpaceBetweenOnMd: "pf-m-justify-content-space-between-on-md",
      justifyContentSpaceAroundOnMd: "pf-m-justify-content-space-around-on-md",
      justifyContentSpaceEvenlyOnMd: "pf-m-justify-content-space-evenly-on-md",
      alignItemsFlexStartOnMd: "pf-m-align-items-flex-start-on-md",
      alignItemsFlexEndOnMd: "pf-m-align-items-flex-end-on-md",
      alignItemsCenterOnMd: "pf-m-align-items-center-on-md",
      alignItemsStretchOnMd: "pf-m-align-items-stretch-on-md",
      alignItemsBaselineOnMd: "pf-m-align-items-baseline-on-md",
      alignContentFlexStartOnMd: "pf-m-align-content-flex-start-on-md",
      alignContentFlexEndOnMd: "pf-m-align-content-flex-end-on-md",
      alignContentCenterOnMd: "pf-m-align-content-center-on-md",
      alignContentStretchOnMd: "pf-m-align-content-stretch-on-md",
      alignContentSpaceBetweenOnMd: "pf-m-align-content-space-between-on-md",
      alignContentSpaceAroundOnMd: "pf-m-align-content-space-around-on-md",
      alignRightOnMd: "pf-m-align-right-on-md",
      alignLeftOnMd: "pf-m-align-left-on-md",
      growOnMd: "pf-m-grow-on-md",
      shrinkOnMd: "pf-m-shrink-on-md",
      fullWidthOnMd: "pf-m-full-width-on-md",
      flex_1OnMd: "pf-m-flex-1-on-md",
      flex_2OnMd: "pf-m-flex-2-on-md",
      flex_3OnMd: "pf-m-flex-3-on-md",
      flex_4OnMd: "pf-m-flex-4-on-md",
      flexDefaultOnMd: "pf-m-flex-default-on-md",
      flexNoneOnMd: "pf-m-flex-none-on-md",
      alignSelfFlexStartOnMd: "pf-m-align-self-flex-start-on-md",
      alignSelfFlexEndOnMd: "pf-m-align-self-flex-end-on-md",
      alignSelfCenterOnMd: "pf-m-align-self-center-on-md",
      alignSelfBaselineOnMd: "pf-m-align-self-baseline-on-md",
      alignSelfStretchOnMd: "pf-m-align-self-stretch-on-md",
      flexOnLg: "pf-m-flex-on-lg",
      inlineFlexOnLg: "pf-m-inline-flex-on-lg",
      columnOnLg: "pf-m-column-on-lg",
      columnReverseOnLg: "pf-m-column-reverse-on-lg",
      rowOnLg: "pf-m-row-on-lg",
      rowReverseOnLg: "pf-m-row-reverse-on-lg",
      wrapOnLg: "pf-m-wrap-on-lg",
      wrapReverseOnLg: "pf-m-wrap-reverse-on-lg",
      nowrapOnLg: "pf-m-nowrap-on-lg",
      justifyContentFlexStartOnLg: "pf-m-justify-content-flex-start-on-lg",
      justifyContentFlexEndOnLg: "pf-m-justify-content-flex-end-on-lg",
      justifyContentCenterOnLg: "pf-m-justify-content-center-on-lg",
      justifyContentSpaceBetweenOnLg: "pf-m-justify-content-space-between-on-lg",
      justifyContentSpaceAroundOnLg: "pf-m-justify-content-space-around-on-lg",
      justifyContentSpaceEvenlyOnLg: "pf-m-justify-content-space-evenly-on-lg",
      alignItemsFlexStartOnLg: "pf-m-align-items-flex-start-on-lg",
      alignItemsFlexEndOnLg: "pf-m-align-items-flex-end-on-lg",
      alignItemsCenterOnLg: "pf-m-align-items-center-on-lg",
      alignItemsStretchOnLg: "pf-m-align-items-stretch-on-lg",
      alignItemsBaselineOnLg: "pf-m-align-items-baseline-on-lg",
      alignContentFlexStartOnLg: "pf-m-align-content-flex-start-on-lg",
      alignContentFlexEndOnLg: "pf-m-align-content-flex-end-on-lg",
      alignContentCenterOnLg: "pf-m-align-content-center-on-lg",
      alignContentStretchOnLg: "pf-m-align-content-stretch-on-lg",
      alignContentSpaceBetweenOnLg: "pf-m-align-content-space-between-on-lg",
      alignContentSpaceAroundOnLg: "pf-m-align-content-space-around-on-lg",
      alignRightOnLg: "pf-m-align-right-on-lg",
      alignLeftOnLg: "pf-m-align-left-on-lg",
      growOnLg: "pf-m-grow-on-lg",
      shrinkOnLg: "pf-m-shrink-on-lg",
      fullWidthOnLg: "pf-m-full-width-on-lg",
      flex_1OnLg: "pf-m-flex-1-on-lg",
      flex_2OnLg: "pf-m-flex-2-on-lg",
      flex_3OnLg: "pf-m-flex-3-on-lg",
      flex_4OnLg: "pf-m-flex-4-on-lg",
      flexDefaultOnLg: "pf-m-flex-default-on-lg",
      flexNoneOnLg: "pf-m-flex-none-on-lg",
      alignSelfFlexStartOnLg: "pf-m-align-self-flex-start-on-lg",
      alignSelfFlexEndOnLg: "pf-m-align-self-flex-end-on-lg",
      alignSelfCenterOnLg: "pf-m-align-self-center-on-lg",
      alignSelfBaselineOnLg: "pf-m-align-self-baseline-on-lg",
      alignSelfStretchOnLg: "pf-m-align-self-stretch-on-lg",
      flexOnXl: "pf-m-flex-on-xl",
      inlineFlexOnXl: "pf-m-inline-flex-on-xl",
      columnOnXl: "pf-m-column-on-xl",
      columnReverseOnXl: "pf-m-column-reverse-on-xl",
      rowOnXl: "pf-m-row-on-xl",
      rowReverseOnXl: "pf-m-row-reverse-on-xl",
      wrapOnXl: "pf-m-wrap-on-xl",
      wrapReverseOnXl: "pf-m-wrap-reverse-on-xl",
      nowrapOnXl: "pf-m-nowrap-on-xl",
      justifyContentFlexStartOnXl: "pf-m-justify-content-flex-start-on-xl",
      justifyContentFlexEndOnXl: "pf-m-justify-content-flex-end-on-xl",
      justifyContentCenterOnXl: "pf-m-justify-content-center-on-xl",
      justifyContentSpaceBetweenOnXl: "pf-m-justify-content-space-between-on-xl",
      justifyContentSpaceAroundOnXl: "pf-m-justify-content-space-around-on-xl",
      justifyContentSpaceEvenlyOnXl: "pf-m-justify-content-space-evenly-on-xl",
      alignItemsFlexStartOnXl: "pf-m-align-items-flex-start-on-xl",
      alignItemsFlexEndOnXl: "pf-m-align-items-flex-end-on-xl",
      alignItemsCenterOnXl: "pf-m-align-items-center-on-xl",
      alignItemsStretchOnXl: "pf-m-align-items-stretch-on-xl",
      alignItemsBaselineOnXl: "pf-m-align-items-baseline-on-xl",
      alignContentFlexStartOnXl: "pf-m-align-content-flex-start-on-xl",
      alignContentFlexEndOnXl: "pf-m-align-content-flex-end-on-xl",
      alignContentCenterOnXl: "pf-m-align-content-center-on-xl",
      alignContentStretchOnXl: "pf-m-align-content-stretch-on-xl",
      alignContentSpaceBetweenOnXl: "pf-m-align-content-space-between-on-xl",
      alignContentSpaceAroundOnXl: "pf-m-align-content-space-around-on-xl",
      alignRightOnXl: "pf-m-align-right-on-xl",
      alignLeftOnXl: "pf-m-align-left-on-xl",
      growOnXl: "pf-m-grow-on-xl",
      shrinkOnXl: "pf-m-shrink-on-xl",
      fullWidthOnXl: "pf-m-full-width-on-xl",
      flex_1OnXl: "pf-m-flex-1-on-xl",
      flex_2OnXl: "pf-m-flex-2-on-xl",
      flex_3OnXl: "pf-m-flex-3-on-xl",
      flex_4OnXl: "pf-m-flex-4-on-xl",
      flexDefaultOnXl: "pf-m-flex-default-on-xl",
      flexNoneOnXl: "pf-m-flex-none-on-xl",
      alignSelfFlexStartOnXl: "pf-m-align-self-flex-start-on-xl",
      alignSelfFlexEndOnXl: "pf-m-align-self-flex-end-on-xl",
      alignSelfCenterOnXl: "pf-m-align-self-center-on-xl",
      alignSelfBaselineOnXl: "pf-m-align-self-baseline-on-xl",
      alignSelfStretchOnXl: "pf-m-align-self-stretch-on-xl",
      flexOn_2xl: "pf-m-flex-on-2xl",
      inlineFlexOn_2xl: "pf-m-inline-flex-on-2xl",
      columnOn_2xl: "pf-m-column-on-2xl",
      columnReverseOn_2xl: "pf-m-column-reverse-on-2xl",
      rowOn_2xl: "pf-m-row-on-2xl",
      rowReverseOn_2xl: "pf-m-row-reverse-on-2xl",
      wrapOn_2xl: "pf-m-wrap-on-2xl",
      wrapReverseOn_2xl: "pf-m-wrap-reverse-on-2xl",
      nowrapOn_2xl: "pf-m-nowrap-on-2xl",
      justifyContentFlexStartOn_2xl: "pf-m-justify-content-flex-start-on-2xl",
      justifyContentFlexEndOn_2xl: "pf-m-justify-content-flex-end-on-2xl",
      justifyContentCenterOn_2xl: "pf-m-justify-content-center-on-2xl",
      justifyContentSpaceBetweenOn_2xl: "pf-m-justify-content-space-between-on-2xl",
      justifyContentSpaceAroundOn_2xl: "pf-m-justify-content-space-around-on-2xl",
      justifyContentSpaceEvenlyOn_2xl: "pf-m-justify-content-space-evenly-on-2xl",
      alignItemsFlexStartOn_2xl: "pf-m-align-items-flex-start-on-2xl",
      alignItemsFlexEndOn_2xl: "pf-m-align-items-flex-end-on-2xl",
      alignItemsCenterOn_2xl: "pf-m-align-items-center-on-2xl",
      alignItemsStretchOn_2xl: "pf-m-align-items-stretch-on-2xl",
      alignItemsBaselineOn_2xl: "pf-m-align-items-baseline-on-2xl",
      alignContentFlexStartOn_2xl: "pf-m-align-content-flex-start-on-2xl",
      alignContentFlexEndOn_2xl: "pf-m-align-content-flex-end-on-2xl",
      alignContentCenterOn_2xl: "pf-m-align-content-center-on-2xl",
      alignContentStretchOn_2xl: "pf-m-align-content-stretch-on-2xl",
      alignContentSpaceBetweenOn_2xl: "pf-m-align-content-space-between-on-2xl",
      alignContentSpaceAroundOn_2xl: "pf-m-align-content-space-around-on-2xl",
      alignRightOn_2xl: "pf-m-align-right-on-2xl",
      alignLeftOn_2xl: "pf-m-align-left-on-2xl",
      growOn_2xl: "pf-m-grow-on-2xl",
      shrinkOn_2xl: "pf-m-shrink-on-2xl",
      fullWidthOn_2xl: "pf-m-full-width-on-2xl",
      flex_1On_2xl: "pf-m-flex-1-on-2xl",
      flex_2On_2xl: "pf-m-flex-2-on-2xl",
      flex_3On_2xl: "pf-m-flex-3-on-2xl",
      flex_4On_2xl: "pf-m-flex-4-on-2xl",
      flexDefaultOn_2xl: "pf-m-flex-default-on-2xl",
      flexNoneOn_2xl: "pf-m-flex-none-on-2xl",
      alignSelfFlexStartOn_2xl: "pf-m-align-self-flex-start-on-2xl",
      alignSelfFlexEndOn_2xl: "pf-m-align-self-flex-end-on-2xl",
      alignSelfCenterOn_2xl: "pf-m-align-self-center-on-2xl",
      alignSelfBaselineOn_2xl: "pf-m-align-self-baseline-on-2xl",
      alignSelfStretchOn_2xl: "pf-m-align-self-stretch-on-2xl",
      spaceItemsNone: "pf-m-space-items-none",
      spaceItemsXs: "pf-m-space-items-xs",
      spaceItemsSm: "pf-m-space-items-sm",
      spaceItemsMd: "pf-m-space-items-md",
      spaceItemsLg: "pf-m-space-items-lg",
      spaceItemsXl: "pf-m-space-items-xl",
      spaceItems_2xl: "pf-m-space-items-2xl",
      spaceItems_3xl: "pf-m-space-items-3xl",
      spaceItems_4xl: "pf-m-space-items-4xl",
      spaceItemsNoneOnSm: "pf-m-space-items-none-on-sm",
      spaceItemsXsOnSm: "pf-m-space-items-xs-on-sm",
      spaceItemsSmOnSm: "pf-m-space-items-sm-on-sm",
      spaceItemsMdOnSm: "pf-m-space-items-md-on-sm",
      spaceItemsLgOnSm: "pf-m-space-items-lg-on-sm",
      spaceItemsXlOnSm: "pf-m-space-items-xl-on-sm",
      spaceItems_2xlOnSm: "pf-m-space-items-2xl-on-sm",
      spaceItems_3xlOnSm: "pf-m-space-items-3xl-on-sm",
      spaceItems_4xlOnSm: "pf-m-space-items-4xl-on-sm",
      spaceItemsNoneOnMd: "pf-m-space-items-none-on-md",
      spaceItemsXsOnMd: "pf-m-space-items-xs-on-md",
      spaceItemsSmOnMd: "pf-m-space-items-sm-on-md",
      spaceItemsMdOnMd: "pf-m-space-items-md-on-md",
      spaceItemsLgOnMd: "pf-m-space-items-lg-on-md",
      spaceItemsXlOnMd: "pf-m-space-items-xl-on-md",
      spaceItems_2xlOnMd: "pf-m-space-items-2xl-on-md",
      spaceItems_3xlOnMd: "pf-m-space-items-3xl-on-md",
      spaceItems_4xlOnMd: "pf-m-space-items-4xl-on-md",
      spaceItemsNoneOnLg: "pf-m-space-items-none-on-lg",
      spaceItemsXsOnLg: "pf-m-space-items-xs-on-lg",
      spaceItemsSmOnLg: "pf-m-space-items-sm-on-lg",
      spaceItemsMdOnLg: "pf-m-space-items-md-on-lg",
      spaceItemsLgOnLg: "pf-m-space-items-lg-on-lg",
      spaceItemsXlOnLg: "pf-m-space-items-xl-on-lg",
      spaceItems_2xlOnLg: "pf-m-space-items-2xl-on-lg",
      spaceItems_3xlOnLg: "pf-m-space-items-3xl-on-lg",
      spaceItems_4xlOnLg: "pf-m-space-items-4xl-on-lg",
      spaceItemsNoneOnXl: "pf-m-space-items-none-on-xl",
      spaceItemsXsOnXl: "pf-m-space-items-xs-on-xl",
      spaceItemsSmOnXl: "pf-m-space-items-sm-on-xl",
      spaceItemsMdOnXl: "pf-m-space-items-md-on-xl",
      spaceItemsLgOnXl: "pf-m-space-items-lg-on-xl",
      spaceItemsXlOnXl: "pf-m-space-items-xl-on-xl",
      spaceItems_2xlOnXl: "pf-m-space-items-2xl-on-xl",
      spaceItems_3xlOnXl: "pf-m-space-items-3xl-on-xl",
      spaceItems_4xlOnXl: "pf-m-space-items-4xl-on-xl",
      spaceItemsNoneOn_2xl: "pf-m-space-items-none-on-2xl",
      spaceItemsXsOn_2xl: "pf-m-space-items-xs-on-2xl",
      spaceItemsSmOn_2xl: "pf-m-space-items-sm-on-2xl",
      spaceItemsMdOn_2xl: "pf-m-space-items-md-on-2xl",
      spaceItemsLgOn_2xl: "pf-m-space-items-lg-on-2xl",
      spaceItemsXlOn_2xl: "pf-m-space-items-xl-on-2xl",
      spaceItems_2xlOn_2xl: "pf-m-space-items-2xl-on-2xl",
      spaceItems_3xlOn_2xl: "pf-m-space-items-3xl-on-2xl",
      spaceItems_4xlOn_2xl: "pf-m-space-items-4xl-on-2xl",
      spacerNone: "pf-m-spacer-none",
      spacerXs: "pf-m-spacer-xs",
      spacerSm: "pf-m-spacer-sm",
      spacerMd: "pf-m-spacer-md",
      spacerLg: "pf-m-spacer-lg",
      spacerXl: "pf-m-spacer-xl",
      spacer_2xl: "pf-m-spacer-2xl",
      spacer_3xl: "pf-m-spacer-3xl",
      spacer_4xl: "pf-m-spacer-4xl",
      spacerNoneOnSm: "pf-m-spacer-none-on-sm",
      spacerXsOnSm: "pf-m-spacer-xs-on-sm",
      spacerSmOnSm: "pf-m-spacer-sm-on-sm",
      spacerMdOnSm: "pf-m-spacer-md-on-sm",
      spacerLgOnSm: "pf-m-spacer-lg-on-sm",
      spacerXlOnSm: "pf-m-spacer-xl-on-sm",
      spacer_2xlOnSm: "pf-m-spacer-2xl-on-sm",
      spacer_3xlOnSm: "pf-m-spacer-3xl-on-sm",
      spacer_4xlOnSm: "pf-m-spacer-4xl-on-sm",
      spacerNoneOnMd: "pf-m-spacer-none-on-md",
      spacerXsOnMd: "pf-m-spacer-xs-on-md",
      spacerSmOnMd: "pf-m-spacer-sm-on-md",
      spacerMdOnMd: "pf-m-spacer-md-on-md",
      spacerLgOnMd: "pf-m-spacer-lg-on-md",
      spacerXlOnMd: "pf-m-spacer-xl-on-md",
      spacer_2xlOnMd: "pf-m-spacer-2xl-on-md",
      spacer_3xlOnMd: "pf-m-spacer-3xl-on-md",
      spacer_4xlOnMd: "pf-m-spacer-4xl-on-md",
      spacerNoneOnLg: "pf-m-spacer-none-on-lg",
      spacerXsOnLg: "pf-m-spacer-xs-on-lg",
      spacerSmOnLg: "pf-m-spacer-sm-on-lg",
      spacerMdOnLg: "pf-m-spacer-md-on-lg",
      spacerLgOnLg: "pf-m-spacer-lg-on-lg",
      spacerXlOnLg: "pf-m-spacer-xl-on-lg",
      spacer_2xlOnLg: "pf-m-spacer-2xl-on-lg",
      spacer_3xlOnLg: "pf-m-spacer-3xl-on-lg",
      spacer_4xlOnLg: "pf-m-spacer-4xl-on-lg",
      spacerNoneOnXl: "pf-m-spacer-none-on-xl",
      spacerXsOnXl: "pf-m-spacer-xs-on-xl",
      spacerSmOnXl: "pf-m-spacer-sm-on-xl",
      spacerMdOnXl: "pf-m-spacer-md-on-xl",
      spacerLgOnXl: "pf-m-spacer-lg-on-xl",
      spacerXlOnXl: "pf-m-spacer-xl-on-xl",
      spacer_2xlOnXl: "pf-m-spacer-2xl-on-xl",
      spacer_3xlOnXl: "pf-m-spacer-3xl-on-xl",
      spacer_4xlOnXl: "pf-m-spacer-4xl-on-xl",
      spacerNoneOn_2xl: "pf-m-spacer-none-on-2xl",
      spacerXsOn_2xl: "pf-m-spacer-xs-on-2xl",
      spacerSmOn_2xl: "pf-m-spacer-sm-on-2xl",
      spacerMdOn_2xl: "pf-m-spacer-md-on-2xl",
      spacerLgOn_2xl: "pf-m-spacer-lg-on-2xl",
      spacerXlOn_2xl: "pf-m-spacer-xl-on-2xl",
      spacer_2xlOn_2xl: "pf-m-spacer-2xl-on-2xl",
      spacer_3xlOn_2xl: "pf-m-spacer-3xl-on-2xl",
      spacer_4xlOn_2xl: "pf-m-spacer-4xl-on-2xl"
    }
  };
});
var styles$x = /* @__PURE__ */ getDefaultExportFromCjs(flex);
var l_flex_item_Order = {
  name: "--pf-l-flex--item--Order",
  value: "0",
  var: "var(--pf-l-flex--item--Order)"
};
var Flex = (_a) => {
  var {children: children2 = null, className = "", component = "div", spacer, spaceItems, grow, shrink, flex: flex2, direction, alignItems, alignContent, alignSelf, align, justifyContent, display, fullWidth, flexWrap, order: order3, style} = _a, props = __rest(_a, ["children", "className", "component", "spacer", "spaceItems", "grow", "shrink", "flex", "direction", "alignItems", "alignContent", "alignSelf", "align", "justifyContent", "display", "fullWidth", "flexWrap", "order", "style"]);
  const Component = component;
  return react.createElement(Component, Object.assign({className: css(styles$x.flex, formatBreakpointMods(spacer, styles$x), formatBreakpointMods(spaceItems, styles$x), formatBreakpointMods(grow, styles$x), formatBreakpointMods(shrink, styles$x), formatBreakpointMods(flex2, styles$x), formatBreakpointMods(direction, styles$x), formatBreakpointMods(alignItems, styles$x), formatBreakpointMods(alignContent, styles$x), formatBreakpointMods(alignSelf, styles$x), formatBreakpointMods(align, styles$x), formatBreakpointMods(justifyContent, styles$x), formatBreakpointMods(display, styles$x), formatBreakpointMods(fullWidth, styles$x), formatBreakpointMods(flexWrap, styles$x), className), style: style || order3 ? Object.assign(Object.assign({}, style), setBreakpointCssVars(order3, l_flex_item_Order.name)) : void 0}, props), children2);
};
Flex.displayName = "Flex";
var FlexItem = (_a) => {
  var {children: children2 = null, className = "", component = "div", spacer, grow, shrink, flex: flex2, alignSelf, align, fullWidth, order: order3, style} = _a, props = __rest(_a, ["children", "className", "component", "spacer", "grow", "shrink", "flex", "alignSelf", "align", "fullWidth", "order", "style"]);
  const Component = component;
  return react.createElement(Component, Object.assign({}, props, {className: css(formatBreakpointMods(spacer, styles$x), formatBreakpointMods(grow, styles$x), formatBreakpointMods(shrink, styles$x), formatBreakpointMods(flex2, styles$x), formatBreakpointMods(alignSelf, styles$x), formatBreakpointMods(align, styles$x), formatBreakpointMods(fullWidth, styles$x), className), style: style || order3 ? Object.assign(Object.assign({}, style), setBreakpointCssVars(order3, l_flex_item_Order.name)) : void 0}), children2);
};
FlexItem.displayName = "FlexItem";
var gallery = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    gallery: "pf-l-gallery",
    modifiers: {
      gutter: "pf-m-gutter"
    }
  };
});
var styles$y = /* @__PURE__ */ getDefaultExportFromCjs(gallery);
var Gallery = (_a) => {
  var {children: children2 = null, className = "", component = "div", hasGutter = false, minWidths, maxWidths} = _a, props = __rest(_a, ["children", "className", "component", "hasGutter", "minWidths", "maxWidths"]);
  const minWidthStyles = {};
  const Component = component;
  if (minWidths) {
    Object.entries(minWidths || {}).map(([breakpoint, value]) => minWidthStyles[`--pf-l-gallery--GridTemplateColumns--min${breakpoint !== "default" ? `-on-${breakpoint}` : ""}`] = value);
  }
  const maxWidthStyles = {};
  if (maxWidths) {
    Object.entries(maxWidths || {}).map(([breakpoint, value]) => maxWidthStyles[`--pf-l-gallery--GridTemplateColumns--max${breakpoint !== "default" ? `-on-${breakpoint}` : ""}`] = value);
  }
  const widthStyles = Object.assign(Object.assign({}, minWidthStyles), maxWidthStyles);
  return react.createElement(Component, Object.assign({className: css(styles$y.gallery, hasGutter && styles$y.modifiers.gutter, className)}, props, (minWidths || maxWidths) && {style: Object.assign(Object.assign({}, widthStyles), props.style)}), children2);
};
Gallery.displayName = "Gallery";
var GalleryItem = (_a) => {
  var {children: children2 = null, component = "div"} = _a, props = __rest(_a, ["children", "component"]);
  const Component = component;
  return react.createElement(Component, Object.assign({}, props), children2);
};
GalleryItem.displayName = "GalleryItem";
var grid = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    grid: "pf-l-grid",
    gridItem: "pf-l-grid__item",
    modifiers: {
      all_1Col: "pf-m-all-1-col",
      all_2Col: "pf-m-all-2-col",
      all_3Col: "pf-m-all-3-col",
      all_4Col: "pf-m-all-4-col",
      all_5Col: "pf-m-all-5-col",
      all_6Col: "pf-m-all-6-col",
      all_7Col: "pf-m-all-7-col",
      all_8Col: "pf-m-all-8-col",
      all_9Col: "pf-m-all-9-col",
      all_10Col: "pf-m-all-10-col",
      all_11Col: "pf-m-all-11-col",
      all_12Col: "pf-m-all-12-col",
      all_1ColOnSm: "pf-m-all-1-col-on-sm",
      all_2ColOnSm: "pf-m-all-2-col-on-sm",
      all_3ColOnSm: "pf-m-all-3-col-on-sm",
      all_4ColOnSm: "pf-m-all-4-col-on-sm",
      all_5ColOnSm: "pf-m-all-5-col-on-sm",
      all_6ColOnSm: "pf-m-all-6-col-on-sm",
      all_7ColOnSm: "pf-m-all-7-col-on-sm",
      all_8ColOnSm: "pf-m-all-8-col-on-sm",
      all_9ColOnSm: "pf-m-all-9-col-on-sm",
      all_10ColOnSm: "pf-m-all-10-col-on-sm",
      all_11ColOnSm: "pf-m-all-11-col-on-sm",
      all_12ColOnSm: "pf-m-all-12-col-on-sm",
      all_1ColOnMd: "pf-m-all-1-col-on-md",
      all_2ColOnMd: "pf-m-all-2-col-on-md",
      all_3ColOnMd: "pf-m-all-3-col-on-md",
      all_4ColOnMd: "pf-m-all-4-col-on-md",
      all_5ColOnMd: "pf-m-all-5-col-on-md",
      all_6ColOnMd: "pf-m-all-6-col-on-md",
      all_7ColOnMd: "pf-m-all-7-col-on-md",
      all_8ColOnMd: "pf-m-all-8-col-on-md",
      all_9ColOnMd: "pf-m-all-9-col-on-md",
      all_10ColOnMd: "pf-m-all-10-col-on-md",
      all_11ColOnMd: "pf-m-all-11-col-on-md",
      all_12ColOnMd: "pf-m-all-12-col-on-md",
      all_1ColOnLg: "pf-m-all-1-col-on-lg",
      all_2ColOnLg: "pf-m-all-2-col-on-lg",
      all_3ColOnLg: "pf-m-all-3-col-on-lg",
      all_4ColOnLg: "pf-m-all-4-col-on-lg",
      all_5ColOnLg: "pf-m-all-5-col-on-lg",
      all_6ColOnLg: "pf-m-all-6-col-on-lg",
      all_7ColOnLg: "pf-m-all-7-col-on-lg",
      all_8ColOnLg: "pf-m-all-8-col-on-lg",
      all_9ColOnLg: "pf-m-all-9-col-on-lg",
      all_10ColOnLg: "pf-m-all-10-col-on-lg",
      all_11ColOnLg: "pf-m-all-11-col-on-lg",
      all_12ColOnLg: "pf-m-all-12-col-on-lg",
      all_1ColOnXl: "pf-m-all-1-col-on-xl",
      all_2ColOnXl: "pf-m-all-2-col-on-xl",
      all_3ColOnXl: "pf-m-all-3-col-on-xl",
      all_4ColOnXl: "pf-m-all-4-col-on-xl",
      all_5ColOnXl: "pf-m-all-5-col-on-xl",
      all_6ColOnXl: "pf-m-all-6-col-on-xl",
      all_7ColOnXl: "pf-m-all-7-col-on-xl",
      all_8ColOnXl: "pf-m-all-8-col-on-xl",
      all_9ColOnXl: "pf-m-all-9-col-on-xl",
      all_10ColOnXl: "pf-m-all-10-col-on-xl",
      all_11ColOnXl: "pf-m-all-11-col-on-xl",
      all_12ColOnXl: "pf-m-all-12-col-on-xl",
      all_1ColOn_2xl: "pf-m-all-1-col-on-2xl",
      all_2ColOn_2xl: "pf-m-all-2-col-on-2xl",
      all_3ColOn_2xl: "pf-m-all-3-col-on-2xl",
      all_4ColOn_2xl: "pf-m-all-4-col-on-2xl",
      all_5ColOn_2xl: "pf-m-all-5-col-on-2xl",
      all_6ColOn_2xl: "pf-m-all-6-col-on-2xl",
      all_7ColOn_2xl: "pf-m-all-7-col-on-2xl",
      all_8ColOn_2xl: "pf-m-all-8-col-on-2xl",
      all_9ColOn_2xl: "pf-m-all-9-col-on-2xl",
      all_10ColOn_2xl: "pf-m-all-10-col-on-2xl",
      all_11ColOn_2xl: "pf-m-all-11-col-on-2xl",
      all_12ColOn_2xl: "pf-m-all-12-col-on-2xl",
      "1Col": "pf-m-1-col",
      "2Col": "pf-m-2-col",
      "3Col": "pf-m-3-col",
      "4Col": "pf-m-4-col",
      "5Col": "pf-m-5-col",
      "6Col": "pf-m-6-col",
      "7Col": "pf-m-7-col",
      "8Col": "pf-m-8-col",
      "9Col": "pf-m-9-col",
      "10Col": "pf-m-10-col",
      "11Col": "pf-m-11-col",
      "12Col": "pf-m-12-col",
      offset_1Col: "pf-m-offset-1-col",
      offset_2Col: "pf-m-offset-2-col",
      offset_3Col: "pf-m-offset-3-col",
      offset_4Col: "pf-m-offset-4-col",
      offset_5Col: "pf-m-offset-5-col",
      offset_6Col: "pf-m-offset-6-col",
      offset_7Col: "pf-m-offset-7-col",
      offset_8Col: "pf-m-offset-8-col",
      offset_9Col: "pf-m-offset-9-col",
      offset_10Col: "pf-m-offset-10-col",
      offset_11Col: "pf-m-offset-11-col",
      offset_12Col: "pf-m-offset-12-col",
      "1Row": "pf-m-1-row",
      "2Row": "pf-m-2-row",
      "3Row": "pf-m-3-row",
      "4Row": "pf-m-4-row",
      "5Row": "pf-m-5-row",
      "6Row": "pf-m-6-row",
      "7Row": "pf-m-7-row",
      "8Row": "pf-m-8-row",
      "9Row": "pf-m-9-row",
      "10Row": "pf-m-10-row",
      "11Row": "pf-m-11-row",
      "12Row": "pf-m-12-row",
      "1ColOnSm": "pf-m-1-col-on-sm",
      "2ColOnSm": "pf-m-2-col-on-sm",
      "3ColOnSm": "pf-m-3-col-on-sm",
      "4ColOnSm": "pf-m-4-col-on-sm",
      "5ColOnSm": "pf-m-5-col-on-sm",
      "6ColOnSm": "pf-m-6-col-on-sm",
      "7ColOnSm": "pf-m-7-col-on-sm",
      "8ColOnSm": "pf-m-8-col-on-sm",
      "9ColOnSm": "pf-m-9-col-on-sm",
      "10ColOnSm": "pf-m-10-col-on-sm",
      "11ColOnSm": "pf-m-11-col-on-sm",
      "12ColOnSm": "pf-m-12-col-on-sm",
      offset_1ColOnSm: "pf-m-offset-1-col-on-sm",
      offset_2ColOnSm: "pf-m-offset-2-col-on-sm",
      offset_3ColOnSm: "pf-m-offset-3-col-on-sm",
      offset_4ColOnSm: "pf-m-offset-4-col-on-sm",
      offset_5ColOnSm: "pf-m-offset-5-col-on-sm",
      offset_6ColOnSm: "pf-m-offset-6-col-on-sm",
      offset_7ColOnSm: "pf-m-offset-7-col-on-sm",
      offset_8ColOnSm: "pf-m-offset-8-col-on-sm",
      offset_9ColOnSm: "pf-m-offset-9-col-on-sm",
      offset_10ColOnSm: "pf-m-offset-10-col-on-sm",
      offset_11ColOnSm: "pf-m-offset-11-col-on-sm",
      offset_12ColOnSm: "pf-m-offset-12-col-on-sm",
      "1RowOnSm": "pf-m-1-row-on-sm",
      "2RowOnSm": "pf-m-2-row-on-sm",
      "3RowOnSm": "pf-m-3-row-on-sm",
      "4RowOnSm": "pf-m-4-row-on-sm",
      "5RowOnSm": "pf-m-5-row-on-sm",
      "6RowOnSm": "pf-m-6-row-on-sm",
      "7RowOnSm": "pf-m-7-row-on-sm",
      "8RowOnSm": "pf-m-8-row-on-sm",
      "9RowOnSm": "pf-m-9-row-on-sm",
      "10RowOnSm": "pf-m-10-row-on-sm",
      "11RowOnSm": "pf-m-11-row-on-sm",
      "12RowOnSm": "pf-m-12-row-on-sm",
      "1ColOnMd": "pf-m-1-col-on-md",
      "2ColOnMd": "pf-m-2-col-on-md",
      "3ColOnMd": "pf-m-3-col-on-md",
      "4ColOnMd": "pf-m-4-col-on-md",
      "5ColOnMd": "pf-m-5-col-on-md",
      "6ColOnMd": "pf-m-6-col-on-md",
      "7ColOnMd": "pf-m-7-col-on-md",
      "8ColOnMd": "pf-m-8-col-on-md",
      "9ColOnMd": "pf-m-9-col-on-md",
      "10ColOnMd": "pf-m-10-col-on-md",
      "11ColOnMd": "pf-m-11-col-on-md",
      "12ColOnMd": "pf-m-12-col-on-md",
      offset_1ColOnMd: "pf-m-offset-1-col-on-md",
      offset_2ColOnMd: "pf-m-offset-2-col-on-md",
      offset_3ColOnMd: "pf-m-offset-3-col-on-md",
      offset_4ColOnMd: "pf-m-offset-4-col-on-md",
      offset_5ColOnMd: "pf-m-offset-5-col-on-md",
      offset_6ColOnMd: "pf-m-offset-6-col-on-md",
      offset_7ColOnMd: "pf-m-offset-7-col-on-md",
      offset_8ColOnMd: "pf-m-offset-8-col-on-md",
      offset_9ColOnMd: "pf-m-offset-9-col-on-md",
      offset_10ColOnMd: "pf-m-offset-10-col-on-md",
      offset_11ColOnMd: "pf-m-offset-11-col-on-md",
      offset_12ColOnMd: "pf-m-offset-12-col-on-md",
      "1RowOnMd": "pf-m-1-row-on-md",
      "2RowOnMd": "pf-m-2-row-on-md",
      "3RowOnMd": "pf-m-3-row-on-md",
      "4RowOnMd": "pf-m-4-row-on-md",
      "5RowOnMd": "pf-m-5-row-on-md",
      "6RowOnMd": "pf-m-6-row-on-md",
      "7RowOnMd": "pf-m-7-row-on-md",
      "8RowOnMd": "pf-m-8-row-on-md",
      "9RowOnMd": "pf-m-9-row-on-md",
      "10RowOnMd": "pf-m-10-row-on-md",
      "11RowOnMd": "pf-m-11-row-on-md",
      "12RowOnMd": "pf-m-12-row-on-md",
      "1ColOnLg": "pf-m-1-col-on-lg",
      "2ColOnLg": "pf-m-2-col-on-lg",
      "3ColOnLg": "pf-m-3-col-on-lg",
      "4ColOnLg": "pf-m-4-col-on-lg",
      "5ColOnLg": "pf-m-5-col-on-lg",
      "6ColOnLg": "pf-m-6-col-on-lg",
      "7ColOnLg": "pf-m-7-col-on-lg",
      "8ColOnLg": "pf-m-8-col-on-lg",
      "9ColOnLg": "pf-m-9-col-on-lg",
      "10ColOnLg": "pf-m-10-col-on-lg",
      "11ColOnLg": "pf-m-11-col-on-lg",
      "12ColOnLg": "pf-m-12-col-on-lg",
      offset_1ColOnLg: "pf-m-offset-1-col-on-lg",
      offset_2ColOnLg: "pf-m-offset-2-col-on-lg",
      offset_3ColOnLg: "pf-m-offset-3-col-on-lg",
      offset_4ColOnLg: "pf-m-offset-4-col-on-lg",
      offset_5ColOnLg: "pf-m-offset-5-col-on-lg",
      offset_6ColOnLg: "pf-m-offset-6-col-on-lg",
      offset_7ColOnLg: "pf-m-offset-7-col-on-lg",
      offset_8ColOnLg: "pf-m-offset-8-col-on-lg",
      offset_9ColOnLg: "pf-m-offset-9-col-on-lg",
      offset_10ColOnLg: "pf-m-offset-10-col-on-lg",
      offset_11ColOnLg: "pf-m-offset-11-col-on-lg",
      offset_12ColOnLg: "pf-m-offset-12-col-on-lg",
      "1RowOnLg": "pf-m-1-row-on-lg",
      "2RowOnLg": "pf-m-2-row-on-lg",
      "3RowOnLg": "pf-m-3-row-on-lg",
      "4RowOnLg": "pf-m-4-row-on-lg",
      "5RowOnLg": "pf-m-5-row-on-lg",
      "6RowOnLg": "pf-m-6-row-on-lg",
      "7RowOnLg": "pf-m-7-row-on-lg",
      "8RowOnLg": "pf-m-8-row-on-lg",
      "9RowOnLg": "pf-m-9-row-on-lg",
      "10RowOnLg": "pf-m-10-row-on-lg",
      "11RowOnLg": "pf-m-11-row-on-lg",
      "12RowOnLg": "pf-m-12-row-on-lg",
      "1ColOnXl": "pf-m-1-col-on-xl",
      "2ColOnXl": "pf-m-2-col-on-xl",
      "3ColOnXl": "pf-m-3-col-on-xl",
      "4ColOnXl": "pf-m-4-col-on-xl",
      "5ColOnXl": "pf-m-5-col-on-xl",
      "6ColOnXl": "pf-m-6-col-on-xl",
      "7ColOnXl": "pf-m-7-col-on-xl",
      "8ColOnXl": "pf-m-8-col-on-xl",
      "9ColOnXl": "pf-m-9-col-on-xl",
      "10ColOnXl": "pf-m-10-col-on-xl",
      "11ColOnXl": "pf-m-11-col-on-xl",
      "12ColOnXl": "pf-m-12-col-on-xl",
      offset_1ColOnXl: "pf-m-offset-1-col-on-xl",
      offset_2ColOnXl: "pf-m-offset-2-col-on-xl",
      offset_3ColOnXl: "pf-m-offset-3-col-on-xl",
      offset_4ColOnXl: "pf-m-offset-4-col-on-xl",
      offset_5ColOnXl: "pf-m-offset-5-col-on-xl",
      offset_6ColOnXl: "pf-m-offset-6-col-on-xl",
      offset_7ColOnXl: "pf-m-offset-7-col-on-xl",
      offset_8ColOnXl: "pf-m-offset-8-col-on-xl",
      offset_9ColOnXl: "pf-m-offset-9-col-on-xl",
      offset_10ColOnXl: "pf-m-offset-10-col-on-xl",
      offset_11ColOnXl: "pf-m-offset-11-col-on-xl",
      offset_12ColOnXl: "pf-m-offset-12-col-on-xl",
      "1RowOnXl": "pf-m-1-row-on-xl",
      "2RowOnXl": "pf-m-2-row-on-xl",
      "3RowOnXl": "pf-m-3-row-on-xl",
      "4RowOnXl": "pf-m-4-row-on-xl",
      "5RowOnXl": "pf-m-5-row-on-xl",
      "6RowOnXl": "pf-m-6-row-on-xl",
      "7RowOnXl": "pf-m-7-row-on-xl",
      "8RowOnXl": "pf-m-8-row-on-xl",
      "9RowOnXl": "pf-m-9-row-on-xl",
      "10RowOnXl": "pf-m-10-row-on-xl",
      "11RowOnXl": "pf-m-11-row-on-xl",
      "12RowOnXl": "pf-m-12-row-on-xl",
      "1ColOn_2xl": "pf-m-1-col-on-2xl",
      "2ColOn_2xl": "pf-m-2-col-on-2xl",
      "3ColOn_2xl": "pf-m-3-col-on-2xl",
      "4ColOn_2xl": "pf-m-4-col-on-2xl",
      "5ColOn_2xl": "pf-m-5-col-on-2xl",
      "6ColOn_2xl": "pf-m-6-col-on-2xl",
      "7ColOn_2xl": "pf-m-7-col-on-2xl",
      "8ColOn_2xl": "pf-m-8-col-on-2xl",
      "9ColOn_2xl": "pf-m-9-col-on-2xl",
      "10ColOn_2xl": "pf-m-10-col-on-2xl",
      "11ColOn_2xl": "pf-m-11-col-on-2xl",
      "12ColOn_2xl": "pf-m-12-col-on-2xl",
      offset_1ColOn_2xl: "pf-m-offset-1-col-on-2xl",
      offset_2ColOn_2xl: "pf-m-offset-2-col-on-2xl",
      offset_3ColOn_2xl: "pf-m-offset-3-col-on-2xl",
      offset_4ColOn_2xl: "pf-m-offset-4-col-on-2xl",
      offset_5ColOn_2xl: "pf-m-offset-5-col-on-2xl",
      offset_6ColOn_2xl: "pf-m-offset-6-col-on-2xl",
      offset_7ColOn_2xl: "pf-m-offset-7-col-on-2xl",
      offset_8ColOn_2xl: "pf-m-offset-8-col-on-2xl",
      offset_9ColOn_2xl: "pf-m-offset-9-col-on-2xl",
      offset_10ColOn_2xl: "pf-m-offset-10-col-on-2xl",
      offset_11ColOn_2xl: "pf-m-offset-11-col-on-2xl",
      offset_12ColOn_2xl: "pf-m-offset-12-col-on-2xl",
      "1RowOn_2xl": "pf-m-1-row-on-2xl",
      "2RowOn_2xl": "pf-m-2-row-on-2xl",
      "3RowOn_2xl": "pf-m-3-row-on-2xl",
      "4RowOn_2xl": "pf-m-4-row-on-2xl",
      "5RowOn_2xl": "pf-m-5-row-on-2xl",
      "6RowOn_2xl": "pf-m-6-row-on-2xl",
      "7RowOn_2xl": "pf-m-7-row-on-2xl",
      "8RowOn_2xl": "pf-m-8-row-on-2xl",
      "9RowOn_2xl": "pf-m-9-row-on-2xl",
      "10RowOn_2xl": "pf-m-10-row-on-2xl",
      "11RowOn_2xl": "pf-m-11-row-on-2xl",
      "12RowOn_2xl": "pf-m-12-row-on-2xl",
      gutter: "pf-m-gutter"
    }
  };
});
var styles$z = /* @__PURE__ */ getDefaultExportFromCjs(grid);
var BaseSizes;
(function(BaseSizes2) {
  BaseSizes2["xs"] = "xs";
  BaseSizes2["sm"] = "sm";
  BaseSizes2["md"] = "md";
  BaseSizes2["lg"] = "lg";
  BaseSizes2["xl"] = "xl";
  BaseSizes2["2xl"] = "2xl";
  BaseSizes2["3xl"] = "3xl";
  BaseSizes2["4xl"] = "4xl";
})(BaseSizes || (BaseSizes = {}));
var DeviceSizes;
(function(DeviceSizes2) {
  DeviceSizes2["sm"] = "Sm";
  DeviceSizes2["md"] = "Md";
  DeviceSizes2["lg"] = "Lg";
  DeviceSizes2["xl"] = "Xl";
  DeviceSizes2["xl2"] = "_2xl";
})(DeviceSizes || (DeviceSizes = {}));
var l_grid_item_Order = {
  name: "--pf-l-grid--item--Order",
  value: "0",
  var: "var(--pf-l-grid--item--Order)"
};
var Grid = (_a) => {
  var {children: children2 = null, className = "", component = "div", hasGutter, span = null, order: order3, style} = _a, props = __rest(_a, ["children", "className", "component", "hasGutter", "span", "order", "style"]);
  const classes = [styles$z.grid, span && styles$z.modifiers[`all_${span}Col`]];
  const Component = component;
  Object.entries(DeviceSizes).forEach(([propKey, gridSpanModifier]) => {
    const key = propKey;
    const propValue = props[key];
    if (propValue) {
      classes.push(styles$z.modifiers[`all_${propValue}ColOn${gridSpanModifier}`]);
    }
    delete props[key];
  });
  return react.createElement(Component, Object.assign({className: css(...classes, hasGutter && styles$z.modifiers.gutter, className), style: style || order3 ? Object.assign(Object.assign({}, style), setBreakpointCssVars(order3, l_grid_item_Order.name)) : void 0}, props), children2);
};
Grid.displayName = "Grid";
var GridItem = (_a) => {
  var {children: children2 = null, className = "", component = "div", span = null, rowSpan = null, offset: offset2 = null, order: order3, style} = _a, props = __rest(_a, ["children", "className", "component", "span", "rowSpan", "offset", "order", "style"]);
  const classes = [
    styles$z.gridItem,
    span && styles$z.modifiers[`${span}Col`],
    rowSpan && styles$z.modifiers[`${rowSpan}Row`],
    offset2 && styles$z.modifiers[`offset_${offset2}Col`]
  ];
  const Component = component;
  Object.entries(DeviceSizes).forEach(([propKey, classModifier]) => {
    const key = propKey;
    const rowSpanKey = `${key}RowSpan`;
    const offsetKey = `${key}Offset`;
    const spanValue = props[key];
    const rowSpanValue = props[rowSpanKey];
    const offsetValue = props[offsetKey];
    if (spanValue) {
      classes.push(styles$z.modifiers[`${spanValue}ColOn${classModifier}`]);
    }
    if (rowSpanValue) {
      classes.push(styles$z.modifiers[`${rowSpanValue}RowOn${classModifier}`]);
    }
    if (offsetValue) {
      classes.push(styles$z.modifiers[`offset_${offsetValue}ColOn${classModifier}`]);
    }
    delete props[key];
    delete props[rowSpanKey];
    delete props[offsetKey];
  });
  return react.createElement(Component, Object.assign({className: css(...classes, className), style: style || order3 ? Object.assign(Object.assign({}, style), setBreakpointCssVars(order3, l_grid_item_Order.name)) : void 0}, props), children2);
};
GridItem.displayName = "GridItem";
var level = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    level: "pf-l-level",
    modifiers: {
      gutter: "pf-m-gutter"
    }
  };
});
var styles$A = /* @__PURE__ */ getDefaultExportFromCjs(level);
var Level = (_a) => {
  var {hasGutter, className = "", children: children2 = null} = _a, props = __rest(_a, ["hasGutter", "className", "children"]);
  return react.createElement("div", Object.assign({}, props, {className: css(styles$A.level, hasGutter && styles$A.modifiers.gutter, className)}), children2);
};
Level.displayName = "Level";
var LevelItem = (_a) => {
  var {children: children2 = null} = _a, props = __rest(_a, ["children"]);
  return react.createElement("div", Object.assign({}, props), children2);
};
LevelItem.displayName = "LevelItem";
var split = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    modifiers: {
      wrap: "pf-m-wrap",
      fill: "pf-m-fill",
      gutter: "pf-m-gutter"
    },
    split: "pf-l-split",
    splitItem: "pf-l-split__item"
  };
});
var styles$B = /* @__PURE__ */ getDefaultExportFromCjs(split);
var Split = (_a) => {
  var {hasGutter = false, isWrappable = false, className = "", children: children2 = null, component = "div"} = _a, props = __rest(_a, ["hasGutter", "isWrappable", "className", "children", "component"]);
  const Component = component;
  return react.createElement(Component, Object.assign({}, props, {className: css(styles$B.split, hasGutter && styles$B.modifiers.gutter, isWrappable && styles$B.modifiers.wrap, className)}), children2);
};
Split.displayName = "Split";
var SplitItem = (_a) => {
  var {isFilled = false, className = "", children: children2 = null} = _a, props = __rest(_a, ["isFilled", "className", "children"]);
  return react.createElement("div", Object.assign({}, props, {className: css(styles$B.splitItem, isFilled && styles$B.modifiers.fill, className)}), children2);
};
SplitItem.displayName = "SplitItem";
var stack = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    modifiers: {
      fill: "pf-m-fill",
      gutter: "pf-m-gutter"
    },
    stack: "pf-l-stack",
    stackItem: "pf-l-stack__item"
  };
});
var styles$C = /* @__PURE__ */ getDefaultExportFromCjs(stack);
var Stack = (_a) => {
  var {hasGutter = false, className = "", children: children2 = null, component = "div"} = _a, props = __rest(_a, ["hasGutter", "className", "children", "component"]);
  const Component = component;
  return react.createElement(Component, Object.assign({}, props, {className: css(styles$C.stack, hasGutter && styles$C.modifiers.gutter, className)}), children2);
};
Stack.displayName = "Stack";
var StackItem = (_a) => {
  var {isFilled = false, className = "", children: children2 = null} = _a, props = __rest(_a, ["isFilled", "className", "children"]);
  return react.createElement("div", Object.assign({}, props, {className: css(styles$C.stackItem, isFilled && styles$C.modifiers.fill, className)}), children2);
};
StackItem.displayName = "StackItem";

// build/_snowpack/pkg/common/setPrototypeOf-adc775f4.js
function _setPrototypeOf(o, p2) {
  _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf3(o2, p3) {
    o2.__proto__ = p3;
    return o2;
  };
  return _setPrototypeOf(o, p2);
}

// build/_snowpack/pkg/common/inheritsLoose-978d85dc.js
function _inheritsLoose(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  _setPrototypeOf(subClass, superClass);
}

// build/_snowpack/pkg/common/react-router-ea29949b.js
function _extends2() {
  _extends2 = Object.assign || function(target) {
    for (var i3 = 1; i3 < arguments.length; i3++) {
      var source2 = arguments[i3];
      for (var key in source2) {
        if (Object.prototype.hasOwnProperty.call(source2, key)) {
          target[key] = source2[key];
        }
      }
    }
    return target;
  };
  return _extends2.apply(this, arguments);
}
function isAbsolute(pathname) {
  return pathname.charAt(0) === "/";
}
function spliceOne(list3, index3) {
  for (var i3 = index3, k2 = i3 + 1, n3 = list3.length; k2 < n3; i3 += 1, k2 += 1) {
    list3[i3] = list3[k2];
  }
  list3.pop();
}
function resolvePathname(to, from) {
  if (from === void 0)
    from = "";
  var toParts = to && to.split("/") || [];
  var fromParts = from && from.split("/") || [];
  var isToAbs = to && isAbsolute(to);
  var isFromAbs = from && isAbsolute(from);
  var mustEndAbs = isToAbs || isFromAbs;
  if (to && isAbsolute(to)) {
    fromParts = toParts;
  } else if (toParts.length) {
    fromParts.pop();
    fromParts = fromParts.concat(toParts);
  }
  if (!fromParts.length)
    return "/";
  var hasTrailingSlash;
  if (fromParts.length) {
    var last2 = fromParts[fromParts.length - 1];
    hasTrailingSlash = last2 === "." || last2 === ".." || last2 === "";
  } else {
    hasTrailingSlash = false;
  }
  var up = 0;
  for (var i3 = fromParts.length; i3 >= 0; i3--) {
    var part = fromParts[i3];
    if (part === ".") {
      spliceOne(fromParts, i3);
    } else if (part === "..") {
      spliceOne(fromParts, i3);
      up++;
    } else if (up) {
      spliceOne(fromParts, i3);
      up--;
    }
  }
  if (!mustEndAbs)
    for (; up--; up)
      fromParts.unshift("..");
  if (mustEndAbs && fromParts[0] !== "" && (!fromParts[0] || !isAbsolute(fromParts[0])))
    fromParts.unshift("");
  var result = fromParts.join("/");
  if (hasTrailingSlash && result.substr(-1) !== "/")
    result += "/";
  return result;
}
var prefix = "Invariant failed";
function invariant(condition, message) {
  if (condition) {
    return;
  }
  {
    throw new Error(prefix);
  }
}
function addLeadingSlash(path) {
  return path.charAt(0) === "/" ? path : "/" + path;
}
function stripLeadingSlash(path) {
  return path.charAt(0) === "/" ? path.substr(1) : path;
}
function hasBasename(path, prefix2) {
  return path.toLowerCase().indexOf(prefix2.toLowerCase()) === 0 && "/?#".indexOf(path.charAt(prefix2.length)) !== -1;
}
function stripBasename(path, prefix2) {
  return hasBasename(path, prefix2) ? path.substr(prefix2.length) : path;
}
function stripTrailingSlash(path) {
  return path.charAt(path.length - 1) === "/" ? path.slice(0, -1) : path;
}
function parsePath(path) {
  var pathname = path || "/";
  var search2 = "";
  var hash2 = "";
  var hashIndex = pathname.indexOf("#");
  if (hashIndex !== -1) {
    hash2 = pathname.substr(hashIndex);
    pathname = pathname.substr(0, hashIndex);
  }
  var searchIndex = pathname.indexOf("?");
  if (searchIndex !== -1) {
    search2 = pathname.substr(searchIndex);
    pathname = pathname.substr(0, searchIndex);
  }
  return {
    pathname,
    search: search2 === "?" ? "" : search2,
    hash: hash2 === "#" ? "" : hash2
  };
}
function createPath(location2) {
  var pathname = location2.pathname, search2 = location2.search, hash2 = location2.hash;
  var path = pathname || "/";
  if (search2 && search2 !== "?")
    path += search2.charAt(0) === "?" ? search2 : "?" + search2;
  if (hash2 && hash2 !== "#")
    path += hash2.charAt(0) === "#" ? hash2 : "#" + hash2;
  return path;
}
function createLocation(path, state, key, currentLocation) {
  var location2;
  if (typeof path === "string") {
    location2 = parsePath(path);
    location2.state = state;
  } else {
    location2 = _extends2({}, path);
    if (location2.pathname === void 0)
      location2.pathname = "";
    if (location2.search) {
      if (location2.search.charAt(0) !== "?")
        location2.search = "?" + location2.search;
    } else {
      location2.search = "";
    }
    if (location2.hash) {
      if (location2.hash.charAt(0) !== "#")
        location2.hash = "#" + location2.hash;
    } else {
      location2.hash = "";
    }
    if (state !== void 0 && location2.state === void 0)
      location2.state = state;
  }
  try {
    location2.pathname = decodeURI(location2.pathname);
  } catch (e2) {
    if (e2 instanceof URIError) {
      throw new URIError('Pathname "' + location2.pathname + '" could not be decoded. This is likely caused by an invalid percent-encoding.');
    } else {
      throw e2;
    }
  }
  if (key)
    location2.key = key;
  if (currentLocation) {
    if (!location2.pathname) {
      location2.pathname = currentLocation.pathname;
    } else if (location2.pathname.charAt(0) !== "/") {
      location2.pathname = resolvePathname(location2.pathname, currentLocation.pathname);
    }
  } else {
    if (!location2.pathname) {
      location2.pathname = "/";
    }
  }
  return location2;
}
function createTransitionManager() {
  var prompt = null;
  function setPrompt(nextPrompt) {
    prompt = nextPrompt;
    return function() {
      if (prompt === nextPrompt)
        prompt = null;
    };
  }
  function confirmTransitionTo(location2, action, getUserConfirmation, callback) {
    if (prompt != null) {
      var result = typeof prompt === "function" ? prompt(location2, action) : prompt;
      if (typeof result === "string") {
        if (typeof getUserConfirmation === "function") {
          getUserConfirmation(result, callback);
        } else {
          callback(true);
        }
      } else {
        callback(result !== false);
      }
    } else {
      callback(true);
    }
  }
  var listeners = [];
  function appendListener(fn) {
    var isActive = true;
    function listener() {
      if (isActive)
        fn.apply(void 0, arguments);
    }
    listeners.push(listener);
    return function() {
      isActive = false;
      listeners = listeners.filter(function(item) {
        return item !== listener;
      });
    };
  }
  function notifyListeners() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    listeners.forEach(function(listener) {
      return listener.apply(void 0, args);
    });
  }
  return {
    setPrompt,
    confirmTransitionTo,
    appendListener,
    notifyListeners
  };
}
var canUseDOM2 = !!(typeof window !== "undefined" && window.document && window.document.createElement);
function getConfirmation(message, callback) {
  callback(window.confirm(message));
}
function supportsHistory() {
  var ua2 = window.navigator.userAgent;
  if ((ua2.indexOf("Android 2.") !== -1 || ua2.indexOf("Android 4.0") !== -1) && ua2.indexOf("Mobile Safari") !== -1 && ua2.indexOf("Chrome") === -1 && ua2.indexOf("Windows Phone") === -1)
    return false;
  return window.history && "pushState" in window.history;
}
function supportsPopStateOnHashChange() {
  return window.navigator.userAgent.indexOf("Trident") === -1;
}
function supportsGoWithoutReloadUsingHash() {
  return window.navigator.userAgent.indexOf("Firefox") === -1;
}
function isExtraneousPopstateEvent(event) {
  return event.state === void 0 && navigator.userAgent.indexOf("CriOS") === -1;
}
var PopStateEvent = "popstate";
var HashChangeEvent = "hashchange";
function getHistoryState() {
  try {
    return window.history.state || {};
  } catch (e2) {
    return {};
  }
}
function createBrowserHistory(props) {
  if (props === void 0) {
    props = {};
  }
  !canUseDOM2 ? invariant(false) : void 0;
  var globalHistory = window.history;
  var canUseHistory = supportsHistory();
  var needsHashChangeListener = !supportsPopStateOnHashChange();
  var _props = props, _props$forceRefresh = _props.forceRefresh, forceRefresh = _props$forceRefresh === void 0 ? false : _props$forceRefresh, _props$getUserConfirm = _props.getUserConfirmation, getUserConfirmation = _props$getUserConfirm === void 0 ? getConfirmation : _props$getUserConfirm, _props$keyLength = _props.keyLength, keyLength = _props$keyLength === void 0 ? 6 : _props$keyLength;
  var basename2 = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : "";
  function getDOMLocation(historyState) {
    var _ref = historyState || {}, key = _ref.key, state = _ref.state;
    var _window$location = window.location, pathname = _window$location.pathname, search2 = _window$location.search, hash2 = _window$location.hash;
    var path = pathname + search2 + hash2;
    if (basename2)
      path = stripBasename(path, basename2);
    return createLocation(path, state, key);
  }
  function createKey() {
    return Math.random().toString(36).substr(2, keyLength);
  }
  var transitionManager = createTransitionManager();
  function setState(nextState) {
    _extends2(history, nextState);
    history.length = globalHistory.length;
    transitionManager.notifyListeners(history.location, history.action);
  }
  function handlePopState(event) {
    if (isExtraneousPopstateEvent(event))
      return;
    handlePop(getDOMLocation(event.state));
  }
  function handleHashChange() {
    handlePop(getDOMLocation(getHistoryState()));
  }
  var forceNextPop = false;
  function handlePop(location2) {
    if (forceNextPop) {
      forceNextPop = false;
      setState();
    } else {
      var action = "POP";
      transitionManager.confirmTransitionTo(location2, action, getUserConfirmation, function(ok3) {
        if (ok3) {
          setState({
            action,
            location: location2
          });
        } else {
          revertPop(location2);
        }
      });
    }
  }
  function revertPop(fromLocation) {
    var toLocation = history.location;
    var toIndex = allKeys.indexOf(toLocation.key);
    if (toIndex === -1)
      toIndex = 0;
    var fromIndex = allKeys.indexOf(fromLocation.key);
    if (fromIndex === -1)
      fromIndex = 0;
    var delta = toIndex - fromIndex;
    if (delta) {
      forceNextPop = true;
      go(delta);
    }
  }
  var initialLocation = getDOMLocation(getHistoryState());
  var allKeys = [initialLocation.key];
  function createHref(location2) {
    return basename2 + createPath(location2);
  }
  function push(path, state) {
    var action = "PUSH";
    var location2 = createLocation(path, state, createKey(), history.location);
    transitionManager.confirmTransitionTo(location2, action, getUserConfirmation, function(ok3) {
      if (!ok3)
        return;
      var href = createHref(location2);
      var key = location2.key, state2 = location2.state;
      if (canUseHistory) {
        globalHistory.pushState({
          key,
          state: state2
        }, null, href);
        if (forceRefresh) {
          window.location.href = href;
        } else {
          var prevIndex = allKeys.indexOf(history.location.key);
          var nextKeys = allKeys.slice(0, prevIndex + 1);
          nextKeys.push(location2.key);
          allKeys = nextKeys;
          setState({
            action,
            location: location2
          });
        }
      } else {
        window.location.href = href;
      }
    });
  }
  function replace2(path, state) {
    var action = "REPLACE";
    var location2 = createLocation(path, state, createKey(), history.location);
    transitionManager.confirmTransitionTo(location2, action, getUserConfirmation, function(ok3) {
      if (!ok3)
        return;
      var href = createHref(location2);
      var key = location2.key, state2 = location2.state;
      if (canUseHistory) {
        globalHistory.replaceState({
          key,
          state: state2
        }, null, href);
        if (forceRefresh) {
          window.location.replace(href);
        } else {
          var prevIndex = allKeys.indexOf(history.location.key);
          if (prevIndex !== -1)
            allKeys[prevIndex] = location2.key;
          setState({
            action,
            location: location2
          });
        }
      } else {
        window.location.replace(href);
      }
    });
  }
  function go(n3) {
    globalHistory.go(n3);
  }
  function goBack() {
    go(-1);
  }
  function goForward() {
    go(1);
  }
  var listenerCount = 0;
  function checkDOMListeners(delta) {
    listenerCount += delta;
    if (listenerCount === 1 && delta === 1) {
      window.addEventListener(PopStateEvent, handlePopState);
      if (needsHashChangeListener)
        window.addEventListener(HashChangeEvent, handleHashChange);
    } else if (listenerCount === 0) {
      window.removeEventListener(PopStateEvent, handlePopState);
      if (needsHashChangeListener)
        window.removeEventListener(HashChangeEvent, handleHashChange);
    }
  }
  var isBlocked = false;
  function block(prompt) {
    if (prompt === void 0) {
      prompt = false;
    }
    var unblock = transitionManager.setPrompt(prompt);
    if (!isBlocked) {
      checkDOMListeners(1);
      isBlocked = true;
    }
    return function() {
      if (isBlocked) {
        isBlocked = false;
        checkDOMListeners(-1);
      }
      return unblock();
    };
  }
  function listen(listener) {
    var unlisten = transitionManager.appendListener(listener);
    checkDOMListeners(1);
    return function() {
      checkDOMListeners(-1);
      unlisten();
    };
  }
  var history = {
    length: globalHistory.length,
    action: "POP",
    location: initialLocation,
    createHref,
    push,
    replace: replace2,
    go,
    goBack,
    goForward,
    block,
    listen
  };
  return history;
}
var HashChangeEvent$1 = "hashchange";
var HashPathCoders = {
  hashbang: {
    encodePath: function encodePath(path) {
      return path.charAt(0) === "!" ? path : "!/" + stripLeadingSlash(path);
    },
    decodePath: function decodePath(path) {
      return path.charAt(0) === "!" ? path.substr(1) : path;
    }
  },
  noslash: {
    encodePath: stripLeadingSlash,
    decodePath: addLeadingSlash
  },
  slash: {
    encodePath: addLeadingSlash,
    decodePath: addLeadingSlash
  }
};
function stripHash(url) {
  var hashIndex = url.indexOf("#");
  return hashIndex === -1 ? url : url.slice(0, hashIndex);
}
function getHashPath() {
  var href = window.location.href;
  var hashIndex = href.indexOf("#");
  return hashIndex === -1 ? "" : href.substring(hashIndex + 1);
}
function pushHashPath(path) {
  window.location.hash = path;
}
function replaceHashPath(path) {
  window.location.replace(stripHash(window.location.href) + "#" + path);
}
function createHashHistory(props) {
  if (props === void 0) {
    props = {};
  }
  !canUseDOM2 ? invariant(false) : void 0;
  var globalHistory = window.history;
  var canGoWithoutReload = supportsGoWithoutReloadUsingHash();
  var _props = props, _props$getUserConfirm = _props.getUserConfirmation, getUserConfirmation = _props$getUserConfirm === void 0 ? getConfirmation : _props$getUserConfirm, _props$hashType = _props.hashType, hashType = _props$hashType === void 0 ? "slash" : _props$hashType;
  var basename2 = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : "";
  var _HashPathCoders$hashT = HashPathCoders[hashType], encodePath2 = _HashPathCoders$hashT.encodePath, decodePath2 = _HashPathCoders$hashT.decodePath;
  function getDOMLocation() {
    var path2 = decodePath2(getHashPath());
    if (basename2)
      path2 = stripBasename(path2, basename2);
    return createLocation(path2);
  }
  var transitionManager = createTransitionManager();
  function setState(nextState) {
    _extends2(history, nextState);
    history.length = globalHistory.length;
    transitionManager.notifyListeners(history.location, history.action);
  }
  var forceNextPop = false;
  var ignorePath = null;
  function locationsAreEqual$$1(a2, b2) {
    return a2.pathname === b2.pathname && a2.search === b2.search && a2.hash === b2.hash;
  }
  function handleHashChange() {
    var path2 = getHashPath();
    var encodedPath2 = encodePath2(path2);
    if (path2 !== encodedPath2) {
      replaceHashPath(encodedPath2);
    } else {
      var location2 = getDOMLocation();
      var prevLocation = history.location;
      if (!forceNextPop && locationsAreEqual$$1(prevLocation, location2))
        return;
      if (ignorePath === createPath(location2))
        return;
      ignorePath = null;
      handlePop(location2);
    }
  }
  function handlePop(location2) {
    if (forceNextPop) {
      forceNextPop = false;
      setState();
    } else {
      var action = "POP";
      transitionManager.confirmTransitionTo(location2, action, getUserConfirmation, function(ok3) {
        if (ok3) {
          setState({
            action,
            location: location2
          });
        } else {
          revertPop(location2);
        }
      });
    }
  }
  function revertPop(fromLocation) {
    var toLocation = history.location;
    var toIndex = allPaths.lastIndexOf(createPath(toLocation));
    if (toIndex === -1)
      toIndex = 0;
    var fromIndex = allPaths.lastIndexOf(createPath(fromLocation));
    if (fromIndex === -1)
      fromIndex = 0;
    var delta = toIndex - fromIndex;
    if (delta) {
      forceNextPop = true;
      go(delta);
    }
  }
  var path = getHashPath();
  var encodedPath = encodePath2(path);
  if (path !== encodedPath)
    replaceHashPath(encodedPath);
  var initialLocation = getDOMLocation();
  var allPaths = [createPath(initialLocation)];
  function createHref(location2) {
    var baseTag = document.querySelector("base");
    var href = "";
    if (baseTag && baseTag.getAttribute("href")) {
      href = stripHash(window.location.href);
    }
    return href + "#" + encodePath2(basename2 + createPath(location2));
  }
  function push(path2, state) {
    var action = "PUSH";
    var location2 = createLocation(path2, void 0, void 0, history.location);
    transitionManager.confirmTransitionTo(location2, action, getUserConfirmation, function(ok3) {
      if (!ok3)
        return;
      var path3 = createPath(location2);
      var encodedPath2 = encodePath2(basename2 + path3);
      var hashChanged = getHashPath() !== encodedPath2;
      if (hashChanged) {
        ignorePath = path3;
        pushHashPath(encodedPath2);
        var prevIndex = allPaths.lastIndexOf(createPath(history.location));
        var nextPaths = allPaths.slice(0, prevIndex + 1);
        nextPaths.push(path3);
        allPaths = nextPaths;
        setState({
          action,
          location: location2
        });
      } else {
        setState();
      }
    });
  }
  function replace2(path2, state) {
    var action = "REPLACE";
    var location2 = createLocation(path2, void 0, void 0, history.location);
    transitionManager.confirmTransitionTo(location2, action, getUserConfirmation, function(ok3) {
      if (!ok3)
        return;
      var path3 = createPath(location2);
      var encodedPath2 = encodePath2(basename2 + path3);
      var hashChanged = getHashPath() !== encodedPath2;
      if (hashChanged) {
        ignorePath = path3;
        replaceHashPath(encodedPath2);
      }
      var prevIndex = allPaths.indexOf(createPath(history.location));
      if (prevIndex !== -1)
        allPaths[prevIndex] = path3;
      setState({
        action,
        location: location2
      });
    });
  }
  function go(n3) {
    globalHistory.go(n3);
  }
  function goBack() {
    go(-1);
  }
  function goForward() {
    go(1);
  }
  var listenerCount = 0;
  function checkDOMListeners(delta) {
    listenerCount += delta;
    if (listenerCount === 1 && delta === 1) {
      window.addEventListener(HashChangeEvent$1, handleHashChange);
    } else if (listenerCount === 0) {
      window.removeEventListener(HashChangeEvent$1, handleHashChange);
    }
  }
  var isBlocked = false;
  function block(prompt) {
    if (prompt === void 0) {
      prompt = false;
    }
    var unblock = transitionManager.setPrompt(prompt);
    if (!isBlocked) {
      checkDOMListeners(1);
      isBlocked = true;
    }
    return function() {
      if (isBlocked) {
        isBlocked = false;
        checkDOMListeners(-1);
      }
      return unblock();
    };
  }
  function listen(listener) {
    var unlisten = transitionManager.appendListener(listener);
    checkDOMListeners(1);
    return function() {
      checkDOMListeners(-1);
      unlisten();
    };
  }
  var history = {
    length: globalHistory.length,
    action: "POP",
    location: initialLocation,
    createHref,
    push,
    replace: replace2,
    go,
    goBack,
    goForward,
    block,
    listen
  };
  return history;
}
function clamp(n3, lowerBound, upperBound) {
  return Math.min(Math.max(n3, lowerBound), upperBound);
}
function createMemoryHistory(props) {
  if (props === void 0) {
    props = {};
  }
  var _props = props, getUserConfirmation = _props.getUserConfirmation, _props$initialEntries = _props.initialEntries, initialEntries = _props$initialEntries === void 0 ? ["/"] : _props$initialEntries, _props$initialIndex = _props.initialIndex, initialIndex = _props$initialIndex === void 0 ? 0 : _props$initialIndex, _props$keyLength = _props.keyLength, keyLength = _props$keyLength === void 0 ? 6 : _props$keyLength;
  var transitionManager = createTransitionManager();
  function setState(nextState) {
    _extends2(history, nextState);
    history.length = history.entries.length;
    transitionManager.notifyListeners(history.location, history.action);
  }
  function createKey() {
    return Math.random().toString(36).substr(2, keyLength);
  }
  var index3 = clamp(initialIndex, 0, initialEntries.length - 1);
  var entries = initialEntries.map(function(entry) {
    return typeof entry === "string" ? createLocation(entry, void 0, createKey()) : createLocation(entry, void 0, entry.key || createKey());
  });
  var createHref = createPath;
  function push(path, state) {
    var action = "PUSH";
    var location2 = createLocation(path, state, createKey(), history.location);
    transitionManager.confirmTransitionTo(location2, action, getUserConfirmation, function(ok3) {
      if (!ok3)
        return;
      var prevIndex = history.index;
      var nextIndex = prevIndex + 1;
      var nextEntries = history.entries.slice(0);
      if (nextEntries.length > nextIndex) {
        nextEntries.splice(nextIndex, nextEntries.length - nextIndex, location2);
      } else {
        nextEntries.push(location2);
      }
      setState({
        action,
        location: location2,
        index: nextIndex,
        entries: nextEntries
      });
    });
  }
  function replace2(path, state) {
    var action = "REPLACE";
    var location2 = createLocation(path, state, createKey(), history.location);
    transitionManager.confirmTransitionTo(location2, action, getUserConfirmation, function(ok3) {
      if (!ok3)
        return;
      history.entries[history.index] = location2;
      setState({
        action,
        location: location2
      });
    });
  }
  function go(n3) {
    var nextIndex = clamp(history.index + n3, 0, history.entries.length - 1);
    var action = "POP";
    var location2 = history.entries[nextIndex];
    transitionManager.confirmTransitionTo(location2, action, getUserConfirmation, function(ok3) {
      if (ok3) {
        setState({
          action,
          location: location2,
          index: nextIndex
        });
      } else {
        setState();
      }
    });
  }
  function goBack() {
    go(-1);
  }
  function goForward() {
    go(1);
  }
  function canGo(n3) {
    var nextIndex = history.index + n3;
    return nextIndex >= 0 && nextIndex < history.entries.length;
  }
  function block(prompt) {
    if (prompt === void 0) {
      prompt = false;
    }
    return transitionManager.setPrompt(prompt);
  }
  function listen(listener) {
    return transitionManager.appendListener(listener);
  }
  var history = {
    length: entries.length,
    action: "POP",
    location: entries[index3],
    index: index3,
    entries,
    createHref,
    push,
    replace: replace2,
    go,
    goBack,
    goForward,
    canGo,
    block,
    listen
  };
  return history;
}
var MAX_SIGNED_31_BIT_INT = 1073741823;
var commonjsGlobal2 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
function getUniqueId2() {
  var key = "__global_unique_id__";
  return commonjsGlobal2[key] = (commonjsGlobal2[key] || 0) + 1;
}
function objectIs(x2, y3) {
  if (x2 === y3) {
    return x2 !== 0 || 1 / x2 === 1 / y3;
  } else {
    return x2 !== x2 && y3 !== y3;
  }
}
function createEventEmitter(value) {
  var handlers = [];
  return {
    on: function on2(handler) {
      handlers.push(handler);
    },
    off: function off2(handler) {
      handlers = handlers.filter(function(h2) {
        return h2 !== handler;
      });
    },
    get: function get7() {
      return value;
    },
    set: function set3(newValue, changedBits) {
      value = newValue;
      handlers.forEach(function(handler) {
        return handler(value, changedBits);
      });
    }
  };
}
function onlyChild(children2) {
  return Array.isArray(children2) ? children2[0] : children2;
}
function createReactContext(defaultValue, calculateChangedBits) {
  var _Provider$childContex, _Consumer$contextType;
  var contextProp = "__create-react-context-" + getUniqueId2() + "__";
  var Provider3 = /* @__PURE__ */ function(_Component) {
    _inheritsLoose(Provider4, _Component);
    function Provider4() {
      var _this;
      _this = _Component.apply(this, arguments) || this;
      _this.emitter = createEventEmitter(_this.props.value);
      return _this;
    }
    var _proto = Provider4.prototype;
    _proto.getChildContext = function getChildContext() {
      var _ref;
      return _ref = {}, _ref[contextProp] = this.emitter, _ref;
    };
    _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
      if (this.props.value !== nextProps.value) {
        var oldValue = this.props.value;
        var newValue = nextProps.value;
        var changedBits;
        if (objectIs(oldValue, newValue)) {
          changedBits = 0;
        } else {
          changedBits = typeof calculateChangedBits === "function" ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
          changedBits |= 0;
          if (changedBits !== 0) {
            this.emitter.set(nextProps.value, changedBits);
          }
        }
      }
    };
    _proto.render = function render4() {
      return this.props.children;
    };
    return Provider4;
  }(react.Component);
  Provider3.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = propTypes.object.isRequired, _Provider$childContex);
  var Consumer = /* @__PURE__ */ function(_Component2) {
    _inheritsLoose(Consumer2, _Component2);
    function Consumer2() {
      var _this2;
      _this2 = _Component2.apply(this, arguments) || this;
      _this2.state = {
        value: _this2.getValue()
      };
      _this2.onUpdate = function(newValue, changedBits) {
        var observedBits = _this2.observedBits | 0;
        if ((observedBits & changedBits) !== 0) {
          _this2.setState({
            value: _this2.getValue()
          });
        }
      };
      return _this2;
    }
    var _proto2 = Consumer2.prototype;
    _proto2.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
      var observedBits = nextProps.observedBits;
      this.observedBits = observedBits === void 0 || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;
    };
    _proto2.componentDidMount = function componentDidMount() {
      if (this.context[contextProp]) {
        this.context[contextProp].on(this.onUpdate);
      }
      var observedBits = this.props.observedBits;
      this.observedBits = observedBits === void 0 || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;
    };
    _proto2.componentWillUnmount = function componentWillUnmount() {
      if (this.context[contextProp]) {
        this.context[contextProp].off(this.onUpdate);
      }
    };
    _proto2.getValue = function getValue2() {
      if (this.context[contextProp]) {
        return this.context[contextProp].get();
      } else {
        return defaultValue;
      }
    };
    _proto2.render = function render4() {
      return onlyChild(this.props.children)(this.state.value);
    };
    return Consumer2;
  }(react.Component);
  Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = propTypes.object, _Consumer$contextType);
  return {
    Provider: Provider3,
    Consumer
  };
}
var index = react.createContext || createReactContext;
var isarray = Array.isArray || function(arr) {
  return Object.prototype.toString.call(arr) == "[object Array]";
};
var pathToRegexp_1 = pathToRegexp;
var parse_1 = parse;
var compile_1 = compile;
var tokensToFunction_1 = tokensToFunction;
var tokensToRegExp_1 = tokensToRegExp;
var PATH_REGEXP = new RegExp([
  "(\\\\.)",
  "([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))"
].join("|"), "g");
function parse(str, options) {
  var tokens = [];
  var key = 0;
  var index3 = 0;
  var path = "";
  var defaultDelimiter = options && options.delimiter || "/";
  var res;
  while ((res = PATH_REGEXP.exec(str)) != null) {
    var m2 = res[0];
    var escaped = res[1];
    var offset2 = res.index;
    path += str.slice(index3, offset2);
    index3 = offset2 + m2.length;
    if (escaped) {
      path += escaped[1];
      continue;
    }
    var next = str[index3];
    var prefix2 = res[2];
    var name = res[3];
    var capture = res[4];
    var group = res[5];
    var modifier = res[6];
    var asterisk = res[7];
    if (path) {
      tokens.push(path);
      path = "";
    }
    var partial = prefix2 != null && next != null && next !== prefix2;
    var repeat = modifier === "+" || modifier === "*";
    var optional2 = modifier === "?" || modifier === "*";
    var delimiter = res[2] || defaultDelimiter;
    var pattern = capture || group;
    tokens.push({
      name: name || key++,
      prefix: prefix2 || "",
      delimiter,
      optional: optional2,
      repeat,
      partial,
      asterisk: !!asterisk,
      pattern: pattern ? escapeGroup(pattern) : asterisk ? ".*" : "[^" + escapeString(delimiter) + "]+?"
    });
  }
  if (index3 < str.length) {
    path += str.substr(index3);
  }
  if (path) {
    tokens.push(path);
  }
  return tokens;
}
function compile(str, options) {
  return tokensToFunction(parse(str, options), options);
}
function encodeURIComponentPretty(str) {
  return encodeURI(str).replace(/[\/?#]/g, function(c3) {
    return "%" + c3.charCodeAt(0).toString(16).toUpperCase();
  });
}
function encodeAsterisk(str) {
  return encodeURI(str).replace(/[?#]/g, function(c3) {
    return "%" + c3.charCodeAt(0).toString(16).toUpperCase();
  });
}
function tokensToFunction(tokens, options) {
  var matches2 = new Array(tokens.length);
  for (var i3 = 0; i3 < tokens.length; i3++) {
    if (typeof tokens[i3] === "object") {
      matches2[i3] = new RegExp("^(?:" + tokens[i3].pattern + ")$", flags(options));
    }
  }
  return function(obj, opts) {
    var path = "";
    var data2 = obj || {};
    var options2 = opts || {};
    var encode2 = options2.pretty ? encodeURIComponentPretty : encodeURIComponent;
    for (var i4 = 0; i4 < tokens.length; i4++) {
      var token2 = tokens[i4];
      if (typeof token2 === "string") {
        path += token2;
        continue;
      }
      var value = data2[token2.name];
      var segment;
      if (value == null) {
        if (token2.optional) {
          if (token2.partial) {
            path += token2.prefix;
          }
          continue;
        } else {
          throw new TypeError('Expected "' + token2.name + '" to be defined');
        }
      }
      if (isarray(value)) {
        if (!token2.repeat) {
          throw new TypeError('Expected "' + token2.name + '" to not repeat, but received `' + JSON.stringify(value) + "`");
        }
        if (value.length === 0) {
          if (token2.optional) {
            continue;
          } else {
            throw new TypeError('Expected "' + token2.name + '" to not be empty');
          }
        }
        for (var j = 0; j < value.length; j++) {
          segment = encode2(value[j]);
          if (!matches2[i4].test(segment)) {
            throw new TypeError('Expected all "' + token2.name + '" to match "' + token2.pattern + '", but received `' + JSON.stringify(segment) + "`");
          }
          path += (j === 0 ? token2.prefix : token2.delimiter) + segment;
        }
        continue;
      }
      segment = token2.asterisk ? encodeAsterisk(value) : encode2(value);
      if (!matches2[i4].test(segment)) {
        throw new TypeError('Expected "' + token2.name + '" to match "' + token2.pattern + '", but received "' + segment + '"');
      }
      path += token2.prefix + segment;
    }
    return path;
  };
}
function escapeString(str) {
  return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, "\\$1");
}
function escapeGroup(group) {
  return group.replace(/([=!:$\/()])/g, "\\$1");
}
function attachKeys(re2, keys2) {
  re2.keys = keys2;
  return re2;
}
function flags(options) {
  return options && options.sensitive ? "" : "i";
}
function regexpToRegexp(path, keys2) {
  var groups2 = path.source.match(/\((?!\?)/g);
  if (groups2) {
    for (var i3 = 0; i3 < groups2.length; i3++) {
      keys2.push({
        name: i3,
        prefix: null,
        delimiter: null,
        optional: false,
        repeat: false,
        partial: false,
        asterisk: false,
        pattern: null
      });
    }
  }
  return attachKeys(path, keys2);
}
function arrayToRegexp(path, keys2, options) {
  var parts = [];
  for (var i3 = 0; i3 < path.length; i3++) {
    parts.push(pathToRegexp(path[i3], keys2, options).source);
  }
  var regexp = new RegExp("(?:" + parts.join("|") + ")", flags(options));
  return attachKeys(regexp, keys2);
}
function stringToRegexp(path, keys2, options) {
  return tokensToRegExp(parse(path, options), keys2, options);
}
function tokensToRegExp(tokens, keys2, options) {
  if (!isarray(keys2)) {
    options = keys2 || options;
    keys2 = [];
  }
  options = options || {};
  var strict = options.strict;
  var end2 = options.end !== false;
  var route = "";
  for (var i3 = 0; i3 < tokens.length; i3++) {
    var token2 = tokens[i3];
    if (typeof token2 === "string") {
      route += escapeString(token2);
    } else {
      var prefix2 = escapeString(token2.prefix);
      var capture = "(?:" + token2.pattern + ")";
      keys2.push(token2);
      if (token2.repeat) {
        capture += "(?:" + prefix2 + capture + ")*";
      }
      if (token2.optional) {
        if (!token2.partial) {
          capture = "(?:" + prefix2 + "(" + capture + "))?";
        } else {
          capture = prefix2 + "(" + capture + ")?";
        }
      } else {
        capture = prefix2 + "(" + capture + ")";
      }
      route += capture;
    }
  }
  var delimiter = escapeString(options.delimiter || "/");
  var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
  if (!strict) {
    route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + "(?:" + delimiter + "(?=$))?";
  }
  if (end2) {
    route += "$";
  } else {
    route += strict && endsWithDelimiter ? "" : "(?=" + delimiter + "|$)";
  }
  return attachKeys(new RegExp("^" + route, flags(options)), keys2);
}
function pathToRegexp(path, keys2, options) {
  if (!isarray(keys2)) {
    options = keys2 || options;
    keys2 = [];
  }
  options = options || {};
  if (path instanceof RegExp) {
    return regexpToRegexp(path, keys2);
  }
  if (isarray(path)) {
    return arrayToRegexp(path, keys2, options);
  }
  return stringToRegexp(path, keys2, options);
}
pathToRegexp_1.parse = parse_1;
pathToRegexp_1.compile = compile_1;
pathToRegexp_1.tokensToFunction = tokensToFunction_1;
pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
/** @license React v16.13.1
 * react-is.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var b = typeof Symbol === "function" && Symbol.for;
var c = b ? Symbol.for("react.element") : 60103;
var d = b ? Symbol.for("react.portal") : 60106;
var e = b ? Symbol.for("react.fragment") : 60107;
var f = b ? Symbol.for("react.strict_mode") : 60108;
var g = b ? Symbol.for("react.profiler") : 60114;
var h = b ? Symbol.for("react.provider") : 60109;
var k = b ? Symbol.for("react.context") : 60110;
var l = b ? Symbol.for("react.async_mode") : 60111;
var m = b ? Symbol.for("react.concurrent_mode") : 60111;
var n = b ? Symbol.for("react.forward_ref") : 60112;
var p = b ? Symbol.for("react.suspense") : 60113;
var q = b ? Symbol.for("react.suspense_list") : 60120;
var r = b ? Symbol.for("react.memo") : 60115;
var t = b ? Symbol.for("react.lazy") : 60116;
var v = b ? Symbol.for("react.block") : 60121;
var w = b ? Symbol.for("react.fundamental") : 60117;
var x = b ? Symbol.for("react.responder") : 60118;
var y2 = b ? Symbol.for("react.scope") : 60119;
function z(a2) {
  if (typeof a2 === "object" && a2 !== null) {
    var u = a2.$$typeof;
    switch (u) {
      case c:
        switch (a2 = a2.type, a2) {
          case l:
          case m:
          case e:
          case g:
          case f:
          case p:
            return a2;
          default:
            switch (a2 = a2 && a2.$$typeof, a2) {
              case k:
              case n:
              case t:
              case r:
              case h:
                return a2;
              default:
                return u;
            }
        }
      case d:
        return u;
    }
  }
}
function A(a2) {
  return z(a2) === m;
}
var AsyncMode = l;
var ConcurrentMode = m;
var ContextConsumer = k;
var ContextProvider = h;
var Element2 = c;
var ForwardRef = n;
var Fragment2 = e;
var Lazy = t;
var Memo = r;
var Portal = d;
var Profiler = g;
var StrictMode2 = f;
var Suspense2 = p;
var isAsyncMode = function(a2) {
  return A(a2) || z(a2) === l;
};
var isConcurrentMode = A;
var isContextConsumer = function(a2) {
  return z(a2) === k;
};
var isContextProvider = function(a2) {
  return z(a2) === h;
};
var isElement2 = function(a2) {
  return typeof a2 === "object" && a2 !== null && a2.$$typeof === c;
};
var isForwardRef = function(a2) {
  return z(a2) === n;
};
var isFragment = function(a2) {
  return z(a2) === e;
};
var isLazy = function(a2) {
  return z(a2) === t;
};
var isMemo = function(a2) {
  return z(a2) === r;
};
var isPortal = function(a2) {
  return z(a2) === d;
};
var isProfiler = function(a2) {
  return z(a2) === g;
};
var isStrictMode = function(a2) {
  return z(a2) === f;
};
var isSuspense = function(a2) {
  return z(a2) === p;
};
var isValidElementType = function(a2) {
  return typeof a2 === "string" || typeof a2 === "function" || a2 === e || a2 === m || a2 === g || a2 === f || a2 === p || a2 === q || typeof a2 === "object" && a2 !== null && (a2.$$typeof === t || a2.$$typeof === r || a2.$$typeof === h || a2.$$typeof === k || a2.$$typeof === n || a2.$$typeof === w || a2.$$typeof === x || a2.$$typeof === y2 || a2.$$typeof === v);
};
var typeOf = z;
var reactIs_production_min = {
  AsyncMode,
  ConcurrentMode,
  ContextConsumer,
  ContextProvider,
  Element: Element2,
  ForwardRef,
  Fragment: Fragment2,
  Lazy,
  Memo,
  Portal,
  Profiler,
  StrictMode: StrictMode2,
  Suspense: Suspense2,
  isAsyncMode,
  isConcurrentMode,
  isContextConsumer,
  isContextProvider,
  isElement: isElement2,
  isForwardRef,
  isFragment,
  isLazy,
  isMemo,
  isPortal,
  isProfiler,
  isStrictMode,
  isSuspense,
  isValidElementType,
  typeOf
};
var reactIs = createCommonjsModule(function(module2) {
  {
    module2.exports = reactIs_production_min;
  }
});
function _objectWithoutPropertiesLoose(source2, excluded) {
  if (source2 == null)
    return {};
  var target = {};
  var sourceKeys = Object.keys(source2);
  var key, i3;
  for (i3 = 0; i3 < sourceKeys.length; i3++) {
    key = sourceKeys[i3];
    if (excluded.indexOf(key) >= 0)
      continue;
    target[key] = source2[key];
  }
  return target;
}
/** @license React v16.13.1
 * react-is.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var b$1 = typeof Symbol === "function" && Symbol.for;
var c$1 = b$1 ? Symbol.for("react.element") : 60103;
var d$1 = b$1 ? Symbol.for("react.portal") : 60106;
var e$1 = b$1 ? Symbol.for("react.fragment") : 60107;
var f$1 = b$1 ? Symbol.for("react.strict_mode") : 60108;
var g$1 = b$1 ? Symbol.for("react.profiler") : 60114;
var h$1 = b$1 ? Symbol.for("react.provider") : 60109;
var k$1 = b$1 ? Symbol.for("react.context") : 60110;
var l$1 = b$1 ? Symbol.for("react.async_mode") : 60111;
var m$1 = b$1 ? Symbol.for("react.concurrent_mode") : 60111;
var n$1 = b$1 ? Symbol.for("react.forward_ref") : 60112;
var p$1 = b$1 ? Symbol.for("react.suspense") : 60113;
var q$1 = b$1 ? Symbol.for("react.suspense_list") : 60120;
var r$1 = b$1 ? Symbol.for("react.memo") : 60115;
var t$1 = b$1 ? Symbol.for("react.lazy") : 60116;
var v$1 = b$1 ? Symbol.for("react.block") : 60121;
var w$1 = b$1 ? Symbol.for("react.fundamental") : 60117;
var x$1 = b$1 ? Symbol.for("react.responder") : 60118;
var y$1 = b$1 ? Symbol.for("react.scope") : 60119;
function z$1(a2) {
  if (typeof a2 === "object" && a2 !== null) {
    var u = a2.$$typeof;
    switch (u) {
      case c$1:
        switch (a2 = a2.type, a2) {
          case l$1:
          case m$1:
          case e$1:
          case g$1:
          case f$1:
          case p$1:
            return a2;
          default:
            switch (a2 = a2 && a2.$$typeof, a2) {
              case k$1:
              case n$1:
              case t$1:
              case r$1:
              case h$1:
                return a2;
              default:
                return u;
            }
        }
      case d$1:
        return u;
    }
  }
}
function A$1(a2) {
  return z$1(a2) === m$1;
}
var AsyncMode$1 = l$1;
var ConcurrentMode$1 = m$1;
var ContextConsumer$1 = k$1;
var ContextProvider$1 = h$1;
var Element$1 = c$1;
var ForwardRef$1 = n$1;
var Fragment$1 = e$1;
var Lazy$1 = t$1;
var Memo$1 = r$1;
var Portal$1 = d$1;
var Profiler$1 = g$1;
var StrictMode$1 = f$1;
var Suspense$1 = p$1;
var isAsyncMode$1 = function(a2) {
  return A$1(a2) || z$1(a2) === l$1;
};
var isConcurrentMode$1 = A$1;
var isContextConsumer$1 = function(a2) {
  return z$1(a2) === k$1;
};
var isContextProvider$1 = function(a2) {
  return z$1(a2) === h$1;
};
var isElement$1 = function(a2) {
  return typeof a2 === "object" && a2 !== null && a2.$$typeof === c$1;
};
var isForwardRef$1 = function(a2) {
  return z$1(a2) === n$1;
};
var isFragment$1 = function(a2) {
  return z$1(a2) === e$1;
};
var isLazy$1 = function(a2) {
  return z$1(a2) === t$1;
};
var isMemo$1 = function(a2) {
  return z$1(a2) === r$1;
};
var isPortal$1 = function(a2) {
  return z$1(a2) === d$1;
};
var isProfiler$1 = function(a2) {
  return z$1(a2) === g$1;
};
var isStrictMode$1 = function(a2) {
  return z$1(a2) === f$1;
};
var isSuspense$1 = function(a2) {
  return z$1(a2) === p$1;
};
var isValidElementType$1 = function(a2) {
  return typeof a2 === "string" || typeof a2 === "function" || a2 === e$1 || a2 === m$1 || a2 === g$1 || a2 === f$1 || a2 === p$1 || a2 === q$1 || typeof a2 === "object" && a2 !== null && (a2.$$typeof === t$1 || a2.$$typeof === r$1 || a2.$$typeof === h$1 || a2.$$typeof === k$1 || a2.$$typeof === n$1 || a2.$$typeof === w$1 || a2.$$typeof === x$1 || a2.$$typeof === y$1 || a2.$$typeof === v$1);
};
var typeOf$1 = z$1;
var reactIs_production_min$1 = {
  AsyncMode: AsyncMode$1,
  ConcurrentMode: ConcurrentMode$1,
  ContextConsumer: ContextConsumer$1,
  ContextProvider: ContextProvider$1,
  Element: Element$1,
  ForwardRef: ForwardRef$1,
  Fragment: Fragment$1,
  Lazy: Lazy$1,
  Memo: Memo$1,
  Portal: Portal$1,
  Profiler: Profiler$1,
  StrictMode: StrictMode$1,
  Suspense: Suspense$1,
  isAsyncMode: isAsyncMode$1,
  isConcurrentMode: isConcurrentMode$1,
  isContextConsumer: isContextConsumer$1,
  isContextProvider: isContextProvider$1,
  isElement: isElement$1,
  isForwardRef: isForwardRef$1,
  isFragment: isFragment$1,
  isLazy: isLazy$1,
  isMemo: isMemo$1,
  isPortal: isPortal$1,
  isProfiler: isProfiler$1,
  isStrictMode: isStrictMode$1,
  isSuspense: isSuspense$1,
  isValidElementType: isValidElementType$1,
  typeOf: typeOf$1
};
var reactIs$1 = createCommonjsModule(function(module2) {
  {
    module2.exports = reactIs_production_min$1;
  }
});
var FORWARD_REF_STATICS = {
  $$typeof: true,
  render: true,
  defaultProps: true,
  displayName: true,
  propTypes: true
};
var MEMO_STATICS = {
  $$typeof: true,
  compare: true,
  defaultProps: true,
  displayName: true,
  propTypes: true,
  type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs$1.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs$1.Memo] = MEMO_STATICS;
var createNamedContext = function createNamedContext2(name) {
  var context2 = index();
  context2.displayName = name;
  return context2;
};
var historyContext = /* @__PURE__ */ createNamedContext("Router-History");
var context = /* @__PURE__ */ createNamedContext("Router");
var Router = /* @__PURE__ */ function(_React$Component) {
  _inheritsLoose(Router2, _React$Component);
  Router2.computeRootMatch = function computeRootMatch(pathname) {
    return {
      path: "/",
      url: "/",
      params: {},
      isExact: pathname === "/"
    };
  };
  function Router2(props) {
    var _this;
    _this = _React$Component.call(this, props) || this;
    _this.state = {
      location: props.history.location
    };
    _this._isMounted = false;
    _this._pendingLocation = null;
    if (!props.staticContext) {
      _this.unlisten = props.history.listen(function(location2) {
        if (_this._isMounted) {
          _this.setState({
            location: location2
          });
        } else {
          _this._pendingLocation = location2;
        }
      });
    }
    return _this;
  }
  var _proto = Router2.prototype;
  _proto.componentDidMount = function componentDidMount() {
    this._isMounted = true;
    if (this._pendingLocation) {
      this.setState({
        location: this._pendingLocation
      });
    }
  };
  _proto.componentWillUnmount = function componentWillUnmount() {
    if (this.unlisten) {
      this.unlisten();
      this._isMounted = false;
      this._pendingLocation = null;
    }
  };
  _proto.render = function render4() {
    return /* @__PURE__ */ react.createElement(context.Provider, {
      value: {
        history: this.props.history,
        location: this.state.location,
        match: Router2.computeRootMatch(this.state.location.pathname),
        staticContext: this.props.staticContext
      }
    }, /* @__PURE__ */ react.createElement(historyContext.Provider, {
      children: this.props.children || null,
      value: this.props.history
    }));
  };
  return Router2;
}(react.Component);
var MemoryRouter = /* @__PURE__ */ function(_React$Component) {
  _inheritsLoose(MemoryRouter2, _React$Component);
  function MemoryRouter2() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _this.history = createMemoryHistory(_this.props);
    return _this;
  }
  var _proto = MemoryRouter2.prototype;
  _proto.render = function render4() {
    return /* @__PURE__ */ react.createElement(Router, {
      history: this.history,
      children: this.props.children
    });
  };
  return MemoryRouter2;
}(react.Component);
var Lifecycle = /* @__PURE__ */ function(_React$Component) {
  _inheritsLoose(Lifecycle2, _React$Component);
  function Lifecycle2() {
    return _React$Component.apply(this, arguments) || this;
  }
  var _proto = Lifecycle2.prototype;
  _proto.componentDidMount = function componentDidMount() {
    if (this.props.onMount)
      this.props.onMount.call(this, this);
  };
  _proto.componentDidUpdate = function componentDidUpdate(prevProps) {
    if (this.props.onUpdate)
      this.props.onUpdate.call(this, this, prevProps);
  };
  _proto.componentWillUnmount = function componentWillUnmount() {
    if (this.props.onUnmount)
      this.props.onUnmount.call(this, this);
  };
  _proto.render = function render4() {
    return null;
  };
  return Lifecycle2;
}(react.Component);
var cache2 = {};
var cacheLimit = 1e4;
var cacheCount = 0;
function compilePath(path) {
  if (cache2[path])
    return cache2[path];
  var generator = pathToRegexp_1.compile(path);
  if (cacheCount < cacheLimit) {
    cache2[path] = generator;
    cacheCount++;
  }
  return generator;
}
function generatePath(path, params) {
  if (path === void 0) {
    path = "/";
  }
  if (params === void 0) {
    params = {};
  }
  return path === "/" ? path : compilePath(path)(params, {
    pretty: true
  });
}
var cache$1 = {};
var cacheLimit$1 = 1e4;
var cacheCount$1 = 0;
function compilePath$1(path, options) {
  var cacheKey = "" + options.end + options.strict + options.sensitive;
  var pathCache = cache$1[cacheKey] || (cache$1[cacheKey] = {});
  if (pathCache[path])
    return pathCache[path];
  var keys2 = [];
  var regexp = pathToRegexp_1(path, keys2, options);
  var result = {
    regexp,
    keys: keys2
  };
  if (cacheCount$1 < cacheLimit$1) {
    pathCache[path] = result;
    cacheCount$1++;
  }
  return result;
}
function matchPath(pathname, options) {
  if (options === void 0) {
    options = {};
  }
  if (typeof options === "string" || Array.isArray(options)) {
    options = {
      path: options
    };
  }
  var _options = options, path = _options.path, _options$exact = _options.exact, exact = _options$exact === void 0 ? false : _options$exact, _options$strict = _options.strict, strict = _options$strict === void 0 ? false : _options$strict, _options$sensitive = _options.sensitive, sensitive = _options$sensitive === void 0 ? false : _options$sensitive;
  var paths = [].concat(path);
  return paths.reduce(function(matched, path2) {
    if (!path2 && path2 !== "")
      return null;
    if (matched)
      return matched;
    var _compilePath = compilePath$1(path2, {
      end: exact,
      strict,
      sensitive
    }), regexp = _compilePath.regexp, keys2 = _compilePath.keys;
    var match2 = regexp.exec(pathname);
    if (!match2)
      return null;
    var url = match2[0], values2 = match2.slice(1);
    var isExact = pathname === url;
    if (exact && !isExact)
      return null;
    return {
      path: path2,
      url: path2 === "/" && url === "" ? "/" : url,
      isExact,
      params: keys2.reduce(function(memo2, key, index3) {
        memo2[key.name] = values2[index3];
        return memo2;
      }, {})
    };
  }, null);
}
function isEmptyChildren(children2) {
  return react.Children.count(children2) === 0;
}
var Route = /* @__PURE__ */ function(_React$Component) {
  _inheritsLoose(Route2, _React$Component);
  function Route2() {
    return _React$Component.apply(this, arguments) || this;
  }
  var _proto = Route2.prototype;
  _proto.render = function render4() {
    var _this = this;
    return /* @__PURE__ */ react.createElement(context.Consumer, null, function(context$1) {
      !context$1 ? invariant(false) : void 0;
      var location2 = _this.props.location || context$1.location;
      var match2 = _this.props.computedMatch ? _this.props.computedMatch : _this.props.path ? matchPath(location2.pathname, _this.props) : context$1.match;
      var props = _extends2({}, context$1, {
        location: location2,
        match: match2
      });
      var _this$props = _this.props, children2 = _this$props.children, component = _this$props.component, render5 = _this$props.render;
      if (Array.isArray(children2) && isEmptyChildren(children2)) {
        children2 = null;
      }
      return /* @__PURE__ */ react.createElement(context.Provider, {
        value: props
      }, props.match ? children2 ? typeof children2 === "function" ? children2(props) : children2 : component ? /* @__PURE__ */ react.createElement(component, props) : render5 ? render5(props) : null : typeof children2 === "function" ? children2(props) : null);
    });
  };
  return Route2;
}(react.Component);
function addLeadingSlash$1(path) {
  return path.charAt(0) === "/" ? path : "/" + path;
}
function addBasename(basename2, location2) {
  if (!basename2)
    return location2;
  return _extends2({}, location2, {
    pathname: addLeadingSlash$1(basename2) + location2.pathname
  });
}
function stripBasename$1(basename2, location2) {
  if (!basename2)
    return location2;
  var base = addLeadingSlash$1(basename2);
  if (location2.pathname.indexOf(base) !== 0)
    return location2;
  return _extends2({}, location2, {
    pathname: location2.pathname.substr(base.length)
  });
}
function createURL(location2) {
  return typeof location2 === "string" ? location2 : createPath(location2);
}
function staticHandler(methodName) {
  return function() {
    invariant(false);
  };
}
function noop() {
}
var StaticRouter = /* @__PURE__ */ function(_React$Component) {
  _inheritsLoose(StaticRouter2, _React$Component);
  function StaticRouter2() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _this.handlePush = function(location2) {
      return _this.navigateTo(location2, "PUSH");
    };
    _this.handleReplace = function(location2) {
      return _this.navigateTo(location2, "REPLACE");
    };
    _this.handleListen = function() {
      return noop;
    };
    _this.handleBlock = function() {
      return noop;
    };
    return _this;
  }
  var _proto = StaticRouter2.prototype;
  _proto.navigateTo = function navigateTo(location2, action) {
    var _this$props = this.props, _this$props$basename = _this$props.basename, basename2 = _this$props$basename === void 0 ? "" : _this$props$basename, _this$props$context = _this$props.context, context2 = _this$props$context === void 0 ? {} : _this$props$context;
    context2.action = action;
    context2.location = addBasename(basename2, createLocation(location2));
    context2.url = createURL(context2.location);
  };
  _proto.render = function render4() {
    var _this$props2 = this.props, _this$props2$basename = _this$props2.basename, basename2 = _this$props2$basename === void 0 ? "" : _this$props2$basename, _this$props2$context = _this$props2.context, context2 = _this$props2$context === void 0 ? {} : _this$props2$context, _this$props2$location = _this$props2.location, location2 = _this$props2$location === void 0 ? "/" : _this$props2$location, rest = _objectWithoutPropertiesLoose(_this$props2, ["basename", "context", "location"]);
    var history = {
      createHref: function createHref(path) {
        return addLeadingSlash$1(basename2 + createURL(path));
      },
      action: "POP",
      location: stripBasename$1(basename2, createLocation(location2)),
      push: this.handlePush,
      replace: this.handleReplace,
      go: staticHandler(),
      goBack: staticHandler(),
      goForward: staticHandler(),
      listen: this.handleListen,
      block: this.handleBlock
    };
    return /* @__PURE__ */ react.createElement(Router, _extends2({}, rest, {
      history,
      staticContext: context2
    }));
  };
  return StaticRouter2;
}(react.Component);
var Switch2 = /* @__PURE__ */ function(_React$Component) {
  _inheritsLoose(Switch3, _React$Component);
  function Switch3() {
    return _React$Component.apply(this, arguments) || this;
  }
  var _proto = Switch3.prototype;
  _proto.render = function render4() {
    var _this = this;
    return /* @__PURE__ */ react.createElement(context.Consumer, null, function(context2) {
      !context2 ? invariant(false) : void 0;
      var location2 = _this.props.location || context2.location;
      var element, match2;
      react.Children.forEach(_this.props.children, function(child) {
        if (match2 == null && /* @__PURE__ */ react.isValidElement(child)) {
          element = child;
          var path = child.props.path || child.props.from;
          match2 = path ? matchPath(location2.pathname, _extends2({}, child.props, {
            path
          })) : context2.match;
        }
      });
      return match2 ? /* @__PURE__ */ react.cloneElement(element, {
        location: location2,
        computedMatch: match2
      }) : null;
    });
  };
  return Switch3;
}(react.Component);
var useContext2 = react.useContext;
function useHistory() {
  return useContext2(historyContext);
}
function useLocation() {
  return useContext2(context).location;
}
function useParams() {
  var match2 = useContext2(context).match;
  return match2 ? match2.params : {};
}
function useRouteMatch(path) {
  var location2 = useLocation();
  var match2 = useContext2(context).match;
  return path ? matchPath(location2.pathname, path) : match2;
}

// build/_snowpack/pkg/react-router-dom.js
var BrowserRouter = /* @__PURE__ */ function(_React$Component) {
  _inheritsLoose(BrowserRouter2, _React$Component);
  function BrowserRouter2() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _this.history = createBrowserHistory(_this.props);
    return _this;
  }
  var _proto = BrowserRouter2.prototype;
  _proto.render = function render4() {
    return /* @__PURE__ */ react.createElement(Router, {
      history: this.history,
      children: this.props.children
    });
  };
  return BrowserRouter2;
}(react.Component);
var HashRouter = /* @__PURE__ */ function(_React$Component) {
  _inheritsLoose(HashRouter2, _React$Component);
  function HashRouter2() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _this.history = createHashHistory(_this.props);
    return _this;
  }
  var _proto = HashRouter2.prototype;
  _proto.render = function render4() {
    return /* @__PURE__ */ react.createElement(Router, {
      history: this.history,
      children: this.props.children
    });
  };
  return HashRouter2;
}(react.Component);
var resolveToLocation = function resolveToLocation2(to, currentLocation) {
  return typeof to === "function" ? to(currentLocation) : to;
};
var normalizeToLocation = function normalizeToLocation2(to, currentLocation) {
  return typeof to === "string" ? createLocation(to, null, null, currentLocation) : to;
};
var forwardRefShim = function forwardRefShim2(C) {
  return C;
};
var forwardRef = react.forwardRef;
if (typeof forwardRef === "undefined") {
  forwardRef = forwardRefShim;
}
function isModifiedEvent(event) {
  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
var LinkAnchor = forwardRef(function(_ref, forwardedRef) {
  var innerRef = _ref.innerRef, navigate = _ref.navigate, _onClick = _ref.onClick, rest = _objectWithoutPropertiesLoose(_ref, ["innerRef", "navigate", "onClick"]);
  var target = rest.target;
  var props = _extends2({}, rest, {
    onClick: function onClick(event) {
      try {
        if (_onClick)
          _onClick(event);
      } catch (ex) {
        event.preventDefault();
        throw ex;
      }
      if (!event.defaultPrevented && event.button === 0 && (!target || target === "_self") && !isModifiedEvent(event)) {
        event.preventDefault();
        navigate();
      }
    }
  });
  if (forwardRefShim !== forwardRef) {
    props.ref = forwardedRef || innerRef;
  } else {
    props.ref = innerRef;
  }
  return /* @__PURE__ */ react.createElement("a", props);
});
var Link = forwardRef(function(_ref2, forwardedRef) {
  var _ref2$component = _ref2.component, component = _ref2$component === void 0 ? LinkAnchor : _ref2$component, replace2 = _ref2.replace, to = _ref2.to, innerRef = _ref2.innerRef, rest = _objectWithoutPropertiesLoose(_ref2, ["component", "replace", "to", "innerRef"]);
  return /* @__PURE__ */ react.createElement(context.Consumer, null, function(context2) {
    !context2 ? invariant(false) : void 0;
    var history = context2.history;
    var location2 = normalizeToLocation(resolveToLocation(to, context2.location), context2.location);
    var href = location2 ? history.createHref(location2) : "";
    var props = _extends2({}, rest, {
      href,
      navigate: function navigate() {
        var location3 = resolveToLocation(to, context2.location);
        var isDuplicateNavigation = createPath(context2.location) === createPath(normalizeToLocation(location3));
        var method = replace2 || isDuplicateNavigation ? history.replace : history.push;
        method(location3);
      }
    });
    if (forwardRefShim !== forwardRef) {
      props.ref = forwardedRef || innerRef;
    } else {
      props.innerRef = innerRef;
    }
    return /* @__PURE__ */ react.createElement(component, props);
  });
});
var forwardRefShim$1 = function forwardRefShim3(C) {
  return C;
};
var forwardRef$1 = react.forwardRef;
if (typeof forwardRef$1 === "undefined") {
  forwardRef$1 = forwardRefShim$1;
}
function joinClassnames() {
  for (var _len = arguments.length, classnames = new Array(_len), _key = 0; _key < _len; _key++) {
    classnames[_key] = arguments[_key];
  }
  return classnames.filter(function(i3) {
    return i3;
  }).join(" ");
}
var NavLink = forwardRef$1(function(_ref, forwardedRef) {
  var _ref$ariaCurrent = _ref["aria-current"], ariaCurrent = _ref$ariaCurrent === void 0 ? "page" : _ref$ariaCurrent, _ref$activeClassName = _ref.activeClassName, activeClassName = _ref$activeClassName === void 0 ? "active" : _ref$activeClassName, activeStyle = _ref.activeStyle, classNameProp = _ref.className, exact = _ref.exact, isActiveProp = _ref.isActive, locationProp = _ref.location, sensitive = _ref.sensitive, strict = _ref.strict, styleProp = _ref.style, to = _ref.to, innerRef = _ref.innerRef, rest = _objectWithoutPropertiesLoose(_ref, ["aria-current", "activeClassName", "activeStyle", "className", "exact", "isActive", "location", "sensitive", "strict", "style", "to", "innerRef"]);
  return /* @__PURE__ */ react.createElement(context.Consumer, null, function(context2) {
    !context2 ? invariant(false) : void 0;
    var currentLocation = locationProp || context2.location;
    var toLocation = normalizeToLocation(resolveToLocation(to, currentLocation), currentLocation);
    var path = toLocation.pathname;
    var escapedPath = path && path.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1");
    var match2 = escapedPath ? matchPath(currentLocation.pathname, {
      path: escapedPath,
      exact,
      sensitive,
      strict
    }) : null;
    var isActive = !!(isActiveProp ? isActiveProp(match2, currentLocation) : match2);
    var className = typeof classNameProp === "function" ? classNameProp(isActive) : classNameProp;
    var style = typeof styleProp === "function" ? styleProp(isActive) : styleProp;
    if (isActive) {
      className = joinClassnames(className, activeClassName);
      style = _extends2({}, style, activeStyle);
    }
    var props = _extends2({
      "aria-current": isActive && ariaCurrent || null,
      className,
      style,
      to: toLocation
    }, rest);
    if (forwardRefShim$1 !== forwardRef$1) {
      props.ref = forwardedRef || innerRef;
    } else {
      props.innerRef = innerRef;
    }
    return /* @__PURE__ */ react.createElement(Link, props);
  });
});

// build/_snowpack/pkg/react-error-boundary.js
var changedArray = function changedArray2(a2, b2) {
  if (a2 === void 0) {
    a2 = [];
  }
  if (b2 === void 0) {
    b2 = [];
  }
  return a2.length !== b2.length || a2.some(function(item, index3) {
    return !Object.is(item, b2[index3]);
  });
};
var initialState = {
  error: null
};
var ErrorBoundary = /* @__PURE__ */ function(_React$Component) {
  _inheritsLoose(ErrorBoundary2, _React$Component);
  function ErrorBoundary2() {
    var _this;
    for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
      _args[_key] = arguments[_key];
    }
    _this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
    _this.state = initialState;
    _this.resetErrorBoundary = function() {
      var _this$props;
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }
      _this.props.onReset == null ? void 0 : (_this$props = _this.props).onReset.apply(_this$props, args);
      _this.reset();
    };
    return _this;
  }
  ErrorBoundary2.getDerivedStateFromError = function getDerivedStateFromError(error2) {
    return {
      error: error2
    };
  };
  var _proto = ErrorBoundary2.prototype;
  _proto.reset = function reset2() {
    this.setState(initialState);
  };
  _proto.componentDidCatch = function componentDidCatch(error2, info2) {
    var _this$props$onError, _this$props2;
    (_this$props$onError = (_this$props2 = this.props).onError) == null ? void 0 : _this$props$onError.call(_this$props2, error2, info2);
  };
  _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
    var error2 = this.state.error;
    var resetKeys = this.props.resetKeys;
    if (error2 !== null && prevState.error !== null && changedArray(prevProps.resetKeys, resetKeys)) {
      var _this$props$onResetKe, _this$props3;
      (_this$props$onResetKe = (_this$props3 = this.props).onResetKeysChange) == null ? void 0 : _this$props$onResetKe.call(_this$props3, prevProps.resetKeys, resetKeys);
      this.reset();
    }
  };
  _proto.render = function render4() {
    var error2 = this.state.error;
    var _this$props4 = this.props, fallbackRender = _this$props4.fallbackRender, FallbackComponent = _this$props4.FallbackComponent, fallback = _this$props4.fallback;
    if (error2 !== null) {
      var _props = {
        error: error2,
        resetErrorBoundary: this.resetErrorBoundary
      };
      if (/* @__PURE__ */ react.isValidElement(fallback)) {
        return fallback;
      } else if (typeof fallbackRender === "function") {
        return fallbackRender(_props);
      } else if (FallbackComponent) {
        return /* @__PURE__ */ react.createElement(FallbackComponent, _props);
      } else {
        throw new Error("react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop");
      }
    }
    return this.props.children;
  };
  return ErrorBoundary2;
}(react.Component);
function useErrorHandler(givenError) {
  var _React$useState = react.useState(null), error2 = _React$useState[0], setError = _React$useState[1];
  if (givenError != null)
    throw givenError;
  if (error2 != null)
    throw error2;
  return setError;
}

// build/_snowpack/pkg/common/pencil-alt-icon-49c71830.js
var HelpIconConfig = {
  name: "HelpIcon",
  height: 1024,
  width: 1024,
  svgPath: "M521.3,576 C627.5,576 713.7,502 713.7,413.7 C713.7,325.4 627.6,253.6 521.3,253.6 C366,253.6 334.5,337.7 329.2,407.2 C329.2,414.3 335.2,416 343.5,416 L445,416 C450.5,416 458,415.5 460.8,406.5 C460.8,362.6 582.9,357.1 582.9,413.6 C582.9,441.9 556.2,470.9 521.3,473 C486.4,475.1 447.3,479.8 447.3,521.7 L447.3,553.8 C447.3,570.8 456.1,576 472,576 C487.9,576 521.3,576 521.3,576 M575.3,751.3 L575.3,655.3 C575.313862,651.055109 573.620137,646.982962 570.6,644 C567.638831,640.947672 563.552355,639.247987 559.3,639.29884 L463.3,639.29884 C459.055109,639.286138 454.982962,640.979863 452,644 C448.947672,646.961169 447.247987,651.047645 447.29884,655.3 L447.29884,751.3 C447.286138,755.544891 448.979863,759.617038 452,762.6 C454.961169,765.652328 459.047645,767.352013 463.3,767.30116 L559.3,767.30116 C563.544891,767.313862 567.617038,765.620137 570.6,762.6 C573.659349,759.643612 575.360354,755.553963 575.3,751.3 M512,896 C300.2,896 128,723.9 128,512 C128,300.3 300.2,128 512,128 C723.8,128 896,300.2 896,512 C896,723.8 723.7,896 512,896 M512.1,0 C229.7,0 0,229.8 0,512 C0,794.2 229.8,1024 512.1,1024 C794.4,1024 1024,794.3 1024,512 C1024,229.7 794.4,0 512.1,0",
  yOffset: 0,
  xOffset: 0
};
var HelpIcon = createIcon(HelpIconConfig);
var PencilAltIconConfig = {
  name: "PencilAltIcon",
  height: 512,
  width: 512,
  svgPath: "M497.9 142.1l-46.1 46.1c-4.7 4.7-12.3 4.7-17 0l-111-111c-4.7-4.7-4.7-12.3 0-17l46.1-46.1c18.7-18.7 49.1-18.7 67.9 0l60.1 60.1c18.8 18.7 18.8 49.1 0 67.9zM284.2 99.8L21.6 362.4.4 483.9c-2.9 16.4 11.4 30.6 27.8 27.8l121.5-21.3 262.6-262.6c4.7-4.7 4.7-12.3 0-17l-111-111c-4.8-4.7-12.4-4.7-17.1 0zM124.1 339.9c-5.5-5.5-5.5-14.3 0-19.8l154-154c5.5-5.5 14.3-5.5 19.8 0s5.5 14.3 0 19.8l-154 154c-5.5 5.5-14.3 5.5-19.8 0zM88 424h48v36.3l-64.5 11.3-31.1-31.1L51.7 376H88v48z",
  yOffset: 0,
  xOffset: 0
};
var PencilAltIcon = createIcon(PencilAltIconConfig);

// build/_snowpack/pkg/@patternfly/react-icons.js
var ExternalLinkAltIconConfig = {
  name: "ExternalLinkAltIcon",
  height: 512,
  width: 512,
  svgPath: "M432,320H400a16,16,0,0,0-16,16V448H64V128H208a16,16,0,0,0,16-16V80a16,16,0,0,0-16-16H48A48,48,0,0,0,0,112V464a48,48,0,0,0,48,48H400a48,48,0,0,0,48-48V336A16,16,0,0,0,432,320ZM488,0h-128c-21.37,0-32.05,25.91-17,41l35.73,35.73L135,320.37a24,24,0,0,0,0,34L157.67,377a24,24,0,0,0,34,0L435.28,133.32,471,169c15,15,41,4.5,41-17V24A24,24,0,0,0,488,0Z",
  yOffset: 0,
  xOffset: 0
};
var ExternalLinkAltIcon = createIcon(ExternalLinkAltIconConfig);
var EyeSlashIconConfig = {
  name: "EyeSlashIcon",
  height: 512,
  width: 640,
  svgPath: "M320 400c-75.85 0-137.25-58.71-142.9-133.11L72.2 185.82c-13.79 17.3-26.48 35.59-36.72 55.59a32.35 32.35 0 0 0 0 29.19C89.71 376.41 197.07 448 320 448c26.91 0 52.87-4 77.89-10.46L346 397.39a144.13 144.13 0 0 1-26 2.61zm313.82 58.1l-110.55-85.44a331.25 331.25 0 0 0 81.25-102.07 32.35 32.35 0 0 0 0-29.19C550.29 135.59 442.93 64 320 64a308.15 308.15 0 0 0-147.32 37.7L45.46 3.37A16 16 0 0 0 23 6.18L3.37 31.45A16 16 0 0 0 6.18 53.9l588.36 454.73a16 16 0 0 0 22.46-2.81l19.64-25.27a16 16 0 0 0-2.82-22.45zm-183.72-142l-39.3-30.38A94.75 94.75 0 0 0 416 256a94.76 94.76 0 0 0-121.31-92.21A47.65 47.65 0 0 1 304 192a46.64 46.64 0 0 1-1.54 10l-73.61-56.89A142.31 142.31 0 0 1 320 112a143.92 143.92 0 0 1 144 144c0 21.63-5.29 41.79-13.9 60.11z",
  yOffset: 0,
  xOffset: 0
};
var EyeSlashIcon = createIcon(EyeSlashIconConfig);
var EyeIconConfig = {
  name: "EyeIcon",
  height: 512,
  width: 576,
  svgPath: "M572.52 241.4C518.29 135.59 410.93 64 288 64S57.68 135.64 3.48 241.41a32.35 32.35 0 0 0 0 29.19C57.71 376.41 165.07 448 288 448s230.32-71.64 284.52-177.41a32.35 32.35 0 0 0 0-29.19zM288 400a144 144 0 1 1 144-144 143.93 143.93 0 0 1-144 144zm0-240a95.31 95.31 0 0 0-25.31 3.79 47.85 47.85 0 0 1-66.9 66.9A95.78 95.78 0 1 0 288 160z",
  yOffset: 0,
  xOffset: 0
};
var EyeIcon = createIcon(EyeIconConfig);
var CaretUpIconConfig = {
  name: "CaretUpIcon",
  height: 512,
  width: 320,
  svgPath: "M288.662 352H31.338c-17.818 0-26.741-21.543-14.142-34.142l128.662-128.662c7.81-7.81 20.474-7.81 28.284 0l128.662 128.662c12.6 12.599 3.676 34.142-14.142 34.142z",
  yOffset: 0,
  xOffset: 0
};
var CaretUpIcon = createIcon(CaretUpIconConfig);
var CogIconConfig = {
  name: "CogIcon",
  height: 512,
  width: 512,
  svgPath: "M487.4 315.7l-42.6-24.6c4.3-23.2 4.3-47 0-70.2l42.6-24.6c4.9-2.8 7.1-8.6 5.5-14-11.1-35.6-30-67.8-54.7-94.6-3.8-4.1-10-5.1-14.8-2.3L380.8 110c-17.9-15.4-38.5-27.3-60.8-35.1V25.8c0-5.6-3.9-10.5-9.4-11.7-36.7-8.2-74.3-7.8-109.2 0-5.5 1.2-9.4 6.1-9.4 11.7V75c-22.2 7.9-42.8 19.8-60.8 35.1L88.7 85.5c-4.9-2.8-11-1.9-14.8 2.3-24.7 26.7-43.6 58.9-54.7 94.6-1.7 5.4.6 11.2 5.5 14L67.3 221c-4.3 23.2-4.3 47 0 70.2l-42.6 24.6c-4.9 2.8-7.1 8.6-5.5 14 11.1 35.6 30 67.8 54.7 94.6 3.8 4.1 10 5.1 14.8 2.3l42.6-24.6c17.9 15.4 38.5 27.3 60.8 35.1v49.2c0 5.6 3.9 10.5 9.4 11.7 36.7 8.2 74.3 7.8 109.2 0 5.5-1.2 9.4-6.1 9.4-11.7v-49.2c22.2-7.9 42.8-19.8 60.8-35.1l42.6 24.6c4.9 2.8 11 1.9 14.8-2.3 24.7-26.7 43.6-58.9 54.7-94.6 1.5-5.5-.7-11.3-5.6-14.1zM256 336c-44.1 0-80-35.9-80-80s35.9-80 80-80 80 35.9 80 80-35.9 80-80 80z",
  yOffset: 0,
  xOffset: 0
};
var CogIcon = createIcon(CogIconConfig);
var CubeIconConfig = {
  name: "CubeIcon",
  height: 512,
  width: 512,
  svgPath: "M239.1 6.3l-208 78c-18.7 7-31.1 25-31.1 45v225.1c0 18.2 10.3 34.8 26.5 42.9l208 104c13.5 6.8 29.4 6.8 42.9 0l208-104c16.3-8.1 26.5-24.8 26.5-42.9V129.3c0-20-12.4-37.9-31.1-44.9l-208-78C262 2.2 250 2.2 239.1 6.3zM256 68.4l192 72v1.1l-192 78-192-78v-1.1l192-72zm32 356V275.5l160-65v133.9l-160 80z",
  yOffset: 0,
  xOffset: 0
};
var CubeIcon = createIcon(CubeIconConfig);
var CubesIconConfig = {
  name: "CubesIcon",
  height: 512,
  width: 512,
  svgPath: "M488.6 250.2L392 214V105.5c0-15-9.3-28.4-23.4-33.7l-100-37.5c-8.1-3.1-17.1-3.1-25.3 0l-100 37.5c-14.1 5.3-23.4 18.7-23.4 33.7V214l-96.6 36.2C9.3 255.5 0 268.9 0 283.9V394c0 13.6 7.7 26.1 19.9 32.2l100 50c10.1 5.1 22.1 5.1 32.2 0l103.9-52 103.9 52c10.1 5.1 22.1 5.1 32.2 0l100-50c12.2-6.1 19.9-18.6 19.9-32.2V283.9c0-15-9.3-28.4-23.4-33.7zM358 214.8l-85 31.9v-68.2l85-37v73.3zM154 104.1l102-38.2 102 38.2v.6l-102 41.4-102-41.4v-.6zm84 291.1l-85 42.5v-79.1l85-38.8v75.4zm0-112l-102 41.4-102-41.4v-.6l102-38.2 102 38.2v.6zm240 112l-85 42.5v-79.1l85-38.8v75.4zm0-112l-102 41.4-102-41.4v-.6l102-38.2 102 38.2v.6z",
  yOffset: 0,
  xOffset: 0
};
var CubesIcon = createIcon(CubesIconConfig);
var DatabaseIconConfig = {
  name: "DatabaseIcon",
  height: 512,
  width: 448,
  svgPath: "M448 73.143v45.714C448 159.143 347.667 192 224 192S0 159.143 0 118.857V73.143C0 32.857 100.333 0 224 0s224 32.857 224 73.143zM448 176v102.857C448 319.143 347.667 352 224 352S0 319.143 0 278.857V176c48.125 33.143 136.208 48.572 224 48.572S399.874 209.143 448 176zm0 160v102.857C448 479.143 347.667 512 224 512S0 479.143 0 438.857V336c48.125 33.143 136.208 48.572 224 48.572S399.874 369.143 448 336z",
  yOffset: 0,
  xOffset: 0
};
var DatabaseIcon = createIcon(DatabaseIconConfig);
var FacebookSquareIconConfig = {
  name: "FacebookSquareIcon",
  height: 512,
  width: 448,
  svgPath: "M400 32H48A48 48 0 0 0 0 80v352a48 48 0 0 0 48 48h137.25V327.69h-63V256h63v-54.64c0-62.15 37-96.48 93.67-96.48 27.14 0 55.52 4.84 55.52 4.84v61h-31.27c-30.81 0-40.42 19.12-40.42 38.73V256h68.78l-11 71.69h-57.78V480H400a48 48 0 0 0 48-48V80a48 48 0 0 0-48-48z",
  yOffset: 0,
  xOffset: 0
};
var FacebookSquareIcon = createIcon(FacebookSquareIconConfig);
var FilterIconConfig = {
  name: "FilterIcon",
  height: 512,
  width: 512,
  svgPath: "M487.976 0H24.028C2.71 0-8.047 25.866 7.058 40.971L192 225.941V432c0 7.831 3.821 15.17 10.237 19.662l80 55.98C298.02 518.69 320 507.493 320 487.98V225.941l184.947-184.97C520.021 25.896 509.338 0 487.976 0z",
  yOffset: 0,
  xOffset: 0
};
var FilterIcon = createIcon(FilterIconConfig);
var GithubIconConfig = {
  name: "GithubIcon",
  height: 512,
  width: 496,
  svgPath: "M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z",
  yOffset: 0,
  xOffset: 0
};
var GithubIcon = createIcon(GithubIconConfig);
var GitlabIconConfig = {
  name: "GitlabIcon",
  height: 512,
  width: 512,
  svgPath: "M105.2 24.9c-3.1-8.9-15.7-8.9-18.9 0L29.8 199.7h132c-.1 0-56.6-174.8-56.6-174.8zM.9 287.7c-2.6 8 .3 16.9 7.1 22l247.9 184-226.2-294zm160.8-88l94.3 294 94.3-294zm349.4 88l-28.8-88-226.3 294 247.9-184c6.9-5.1 9.7-14 7.2-22zM425.7 24.9c-3.1-8.9-15.7-8.9-18.9 0l-56.6 174.8h132z",
  yOffset: 0,
  xOffset: 0
};
var GitlabIcon = createIcon(GitlabIconConfig);
var GoogleIconConfig = {
  name: "GoogleIcon",
  height: 512,
  width: 488,
  svgPath: "M488 261.8C488 403.3 391.1 504 248 504 110.8 504 0 393.2 0 256S110.8 8 248 8c66.8 0 123 24.5 166.3 64.9l-67.5 64.9C258.5 52.6 94.3 116.6 94.3 256c0 86.5 69.1 156.6 153.7 156.6 98.2 0 135-70.4 140.8-106.9H248v-85.3h236.1c2.3 12.7 3.9 24.9 3.9 41.4z",
  yOffset: 0,
  xOffset: 0
};
var GoogleIcon = createIcon(GoogleIconConfig);
var LinkedinIconConfig = {
  name: "LinkedinIcon",
  height: 512,
  width: 448,
  svgPath: "M416 32H31.9C14.3 32 0 46.5 0 64.3v383.4C0 465.5 14.3 480 31.9 480H416c17.6 0 32-14.5 32-32.3V64.3c0-17.8-14.4-32.3-32-32.3zM135.4 416H69V202.2h66.5V416zm-33.2-243c-21.3 0-38.5-17.3-38.5-38.5S80.9 96 102.2 96c21.2 0 38.5 17.3 38.5 38.5 0 21.3-17.2 38.5-38.5 38.5zm282.1 243h-66.4V312c0-24.8-.5-56.7-34.5-56.7-34.6 0-39.9 27-39.9 54.9V416h-66.4V202.2h63.7v29.2h.9c8.9-16.8 30.6-34.5 62.9-34.5 67.2 0 79.7 44.3 79.7 101.9V416z",
  yOffset: 0,
  xOffset: 0
};
var LinkedinIcon = createIcon(LinkedinIconConfig);
var MinusCircleIconConfig = {
  name: "MinusCircleIcon",
  height: 512,
  width: 512,
  svgPath: "M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zM124 296c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h264c6.6 0 12 5.4 12 12v56c0 6.6-5.4 12-12 12H124z",
  yOffset: 0,
  xOffset: 0
};
var MinusCircleIcon = createIcon(MinusCircleIconConfig);
var OpenshiftIconConfig = {
  name: "OpenshiftIcon",
  height: 100,
  width: 100,
  svgPath: "M145.7,45.3l-16.1,5.8c0.2,2.6,0.6,5.1,1.3,7.6l15.3-5.6C145.7,50.6,145.5,47.9,145.7,45.3M216.7,27.5c-1.1-2.3-2.4-4.5-3.9-6.6l-16.1,5.8c1.9,1.9,3.4,4.1,4.7,6.4L216.7,27.5zM181.4,23c3.3,1.6,6.2,3.7,8.7,6.2l16.1-5.8c-4.4-6.2-10.5-11.5-17.9-14.9c-22.9-10.7-50.3-0.7-61,22.2c-3.5,7.4-4.8,15.3-4.1,23l16.1-5.8c0.3-3.5,1.1-7,2.7-10.3C148.7,22.5,166.4,16,181.4,23M131.9,58.4l-15.3,5.6c1.4,5.6,3.8,10.8,7.2,15.5l16-5.8C135.8,69.4,133,64.1,131.9,58.4M198.5,52.3c-0.3,3.5-1.1,7-2.7,10.3C188.8,77.5,171,84,156.1,77c-3.3-1.6-6.3-3.7-8.7-6.2l-16,5.8c4.4,6.2,10.5,11.5,17.9,14.9c22.9,10.7,50.3,0.7,61-22.2c3.5-7.4,4.7-15.3,4.1-22.9L198.5,52.3zM202.4,32.7l-15.3,5.6c2.8,5.1,4.2,10.9,3.7,16.8l16-5.8C206.5,43.5,204.9,37.9,202.4,32.7",
  yOffset: 0,
  xOffset: 116
};
var OpenshiftIcon = createIcon(OpenshiftIconConfig);
var PlusCircleIconConfig = {
  name: "PlusCircleIcon",
  height: 512,
  width: 512,
  svgPath: "M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm144 276c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92h-92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z",
  yOffset: 0,
  xOffset: 0
};
var PlusCircleIcon = createIcon(PlusCircleIconConfig);
var QuestionCircleIconConfig = {
  name: "QuestionCircleIcon",
  height: 512,
  width: 512,
  svgPath: "M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zM262.655 90c-54.497 0-89.255 22.957-116.549 63.758-3.536 5.286-2.353 12.415 2.715 16.258l34.699 26.31c5.205 3.947 12.621 3.008 16.665-2.122 17.864-22.658 30.113-35.797 57.303-35.797 20.429 0 45.698 13.148 45.698 32.958 0 14.976-12.363 22.667-32.534 33.976C247.128 238.528 216 254.941 216 296v4c0 6.627 5.373 12 12 12h56c6.627 0 12-5.373 12-12v-1.333c0-28.462 83.186-29.647 83.186-106.667 0-58.002-60.165-102-116.531-102zM256 338c-25.365 0-46 20.635-46 46 0 25.364 20.635 46 46 46s46-20.636 46-46c0-25.365-20.635-46-46-46z",
  yOffset: 0,
  xOffset: 0
};
var QuestionCircleIcon = createIcon(QuestionCircleIconConfig);
var StackOverflowIconConfig = {
  name: "StackOverflowIcon",
  height: 512,
  width: 384,
  svgPath: "M290.7 311L95 269.7 86.8 309l195.7 41zm51-87L188.2 95.7l-25.5 30.8 153.5 128.3zm-31.2 39.7L129.2 179l-16.7 36.5L293.7 300zM262 32l-32 24 119.3 160.3 32-24zm20.5 328h-200v39.7h200zm39.7 80H42.7V320h-40v160h359.5V320h-40z",
  yOffset: 0,
  xOffset: 0
};
var StackOverflowIcon = createIcon(StackOverflowIconConfig);
var TableIconConfig = {
  name: "TableIcon",
  height: 512,
  width: 512,
  svgPath: "M464 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48 48 48h416c26.51 0 48-21.49 48-48V80c0-26.51-21.49-48-48-48zM224 416H64v-96h160v96zm0-160H64v-96h160v96zm224 160H288v-96h160v96zm0-160H288v-96h160v96z",
  yOffset: 0,
  xOffset: 0
};
var TableIcon = createIcon(TableIconConfig);
var TrashIconConfig = {
  name: "TrashIcon",
  height: 512,
  width: 448,
  svgPath: "M432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16zM53.2 467a48 48 0 0 0 47.9 45h245.8a48 48 0 0 0 47.9-45L416 128H32z",
  yOffset: 0,
  xOffset: 0
};
var TrashIcon = createIcon(TrashIconConfig);
var TwitterIconConfig = {
  name: "TwitterIcon",
  height: 512,
  width: 512,
  svgPath: "M459.37 151.716c.325 4.548.325 9.097.325 13.645 0 138.72-105.583 298.558-298.558 298.558-59.452 0-114.68-17.219-161.137-47.106 8.447.974 16.568 1.299 25.34 1.299 49.055 0 94.213-16.568 130.274-44.832-46.132-.975-84.792-31.188-98.112-72.772 6.498.974 12.995 1.624 19.818 1.624 9.421 0 18.843-1.3 27.614-3.573-48.081-9.747-84.143-51.98-84.143-102.985v-1.299c13.969 7.797 30.214 12.67 47.431 13.319-28.264-18.843-46.781-51.005-46.781-87.391 0-19.492 5.197-37.36 14.294-52.954 51.655 63.675 129.3 105.258 216.365 109.807-1.624-7.797-2.599-15.918-2.599-24.04 0-57.828 46.782-104.934 104.934-104.934 30.213 0 57.502 12.67 76.67 33.137 23.715-4.548 46.456-13.32 66.599-25.34-7.798 24.366-24.366 44.833-46.132 57.827 21.117-2.273 41.584-8.122 60.426-16.243-14.292 20.791-32.161 39.308-52.628 54.253z",
  yOffset: 0,
  xOffset: 0
};
var TwitterIcon = createIcon(TwitterIconConfig);
var WarningTriangleIconConfig = {
  name: "WarningTriangleIcon",
  height: 1024,
  width: 1088,
  svgPath: "M1057.10141,663.5 L845.101405,215.4 C787.101405,71.8 665.401405,0 542.901405,0 C420.201405,0 296.701405,71.9 235.001405,215.6 L31.7014051,648.5 C10.4014051,700 -0.0985948775,752.3 0.000697596367,800.8 C0.301405123,924.8 70.2014051,1024 209.101405,1024 L868.401405,1024 C1005.80141,1024 1087.70141,918.6 1088.00215,795.5 C1088.10141,752.4 1078.20141,707.2 1057.10141,663.5 Z M959.401405,800.3 C958.701405,822.9 952.901405,843.5 942.601405,859.7 C926.801405,884.6 902.601405,896.7 868.301405,896.7 L209.101405,896.7 C191.201405,896.7 176.601405,893.8 165.401405,888.2 C157.301405,884 150.801405,878.4 145.401405,870.3 C135.101405,855 129.101405,832 128.401405,805.6 C127.601405,772.8 134.901405,736.5 149.401405,700.5 L353.001405,266.7 C363.201405,242.9 376.101405,221.5 391.101405,203.2 C404.801405,186.6 420.301405,172.4 437.401405,161.1 C469.201405,139.9 505.701405,128.8 542.901405,128.8 C579.701405,128.8 615.401405,139.8 646.001405,160.5 C662.401405,171.6 677.101405,185.4 690.101405,201.6 C704.501405,219.6 716.401405,240.6 725.901405,264 L940.901405,718.9 L941.101405,719.3 L941.301405,719.7 C953.901405,746 960.201405,773.9 959.401405,800.3 Z M586.601405,832 L501.301405,832 C489.501405,831.8 480.201405,821.5 480.001405,808.7 L480.001405,727.3 C480.201405,714.5 489.601405,704.3 501.301405,704 L586.601405,704 C598.401405,704.2 607.701405,714.5 607.901405,727.3 L607.901405,808.7 L608.001405,808.7 C607.701405,821.5 598.301405,831.8 586.601405,832 M639.901405,290.7 L613.201405,610.4 C611.801405,626.9 598.001405,640 581.301405,640 L506.601405,640 C490.001405,640 476.101405,627.2 474.701405,610.7 L448.101405,291 C446.501405,272.3 461.301405,256.3 480.001405,256.3 L608.001405,256 C626.701405,256 641.401405,272 639.901405,290.7",
  yOffset: 0,
  xOffset: 0
};
var WarningTriangleIcon = createIcon(WarningTriangleIconConfig);

// build/_snowpack/pkg/common/unsupportedIterableToArray-5dd32933.js
var arrayLikeToArray = createCommonjsModule(function(module2) {
  function _arrayLikeToArray3(arr, len2) {
    if (len2 == null || len2 > arr.length)
      len2 = arr.length;
    for (var i3 = 0, arr2 = new Array(len2); i3 < len2; i3++) {
      arr2[i3] = arr[i3];
    }
    return arr2;
  }
  module2.exports = _arrayLikeToArray3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var unsupportedIterableToArray = createCommonjsModule(function(module2) {
  function _unsupportedIterableToArray3(o, minLen) {
    if (!o)
      return;
    if (typeof o === "string")
      return arrayLikeToArray(o, minLen);
    var n3 = Object.prototype.toString.call(o).slice(8, -1);
    if (n3 === "Object" && o.constructor)
      n3 = o.constructor.name;
    if (n3 === "Map" || n3 === "Set")
      return Array.from(o);
    if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3))
      return arrayLikeToArray(o, minLen);
  }
  module2.exports = _unsupportedIterableToArray3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});

// build/_snowpack/pkg/common/typeof-acae9cd0.js
var _typeof_1 = createCommonjsModule(function(module2) {
  function _typeof4(obj) {
    "@babel/helpers - typeof";
    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
      module2.exports = _typeof4 = function _typeof5(obj2) {
        return typeof obj2;
      };
      module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
    } else {
      module2.exports = _typeof4 = function _typeof5(obj2) {
        return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
      };
      module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
    }
    return _typeof4(obj);
  }
  module2.exports = _typeof4;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var _typeof = /* @__PURE__ */ getDefaultExportFromCjs(_typeof_1);

// build/_snowpack/pkg/react-i18next.js
var objectWithoutPropertiesLoose = createCommonjsModule(function(module2) {
  function _objectWithoutPropertiesLoose3(source2, excluded) {
    if (source2 == null)
      return {};
    var target = {};
    var sourceKeys = Object.keys(source2);
    var key, i3;
    for (i3 = 0; i3 < sourceKeys.length; i3++) {
      key = sourceKeys[i3];
      if (excluded.indexOf(key) >= 0)
        continue;
      target[key] = source2[key];
    }
    return target;
  }
  module2.exports = _objectWithoutPropertiesLoose3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var objectWithoutProperties = createCommonjsModule(function(module2) {
  function _objectWithoutProperties4(source2, excluded) {
    if (source2 == null)
      return {};
    var target = objectWithoutPropertiesLoose(source2, excluded);
    var key, i3;
    if (Object.getOwnPropertySymbols) {
      var sourceSymbolKeys = Object.getOwnPropertySymbols(source2);
      for (i3 = 0; i3 < sourceSymbolKeys.length; i3++) {
        key = sourceSymbolKeys[i3];
        if (excluded.indexOf(key) >= 0)
          continue;
        if (!Object.prototype.propertyIsEnumerable.call(source2, key))
          continue;
        target[key] = source2[key];
      }
    }
    return target;
  }
  module2.exports = _objectWithoutProperties4;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var _objectWithoutProperties2 = /* @__PURE__ */ getDefaultExportFromCjs(objectWithoutProperties);
var defineProperty = createCommonjsModule(function(module2) {
  function _defineProperty7(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, {
        value,
        enumerable: true,
        configurable: true,
        writable: true
      });
    } else {
      obj[key] = value;
    }
    return obj;
  }
  module2.exports = _defineProperty7;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var _defineProperty3 = /* @__PURE__ */ getDefaultExportFromCjs(defineProperty);
var voidElements = {
  area: true,
  base: true,
  br: true,
  col: true,
  embed: true,
  hr: true,
  img: true,
  input: true,
  link: true,
  meta: true,
  param: true,
  source: true,
  track: true,
  wbr: true
};
var t2 = /\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;
function n2(n3) {
  var r3 = {type: "tag", name: "", voidElement: false, attrs: {}, children: []}, i3 = n3.match(/<\/?([^\s]+?)[/\s>]/);
  if (i3 && (r3.name = i3[1], (voidElements[i3[1]] || n3.charAt(n3.length - 2) === "/") && (r3.voidElement = true), r3.name.startsWith("!--"))) {
    var s2 = n3.indexOf("-->");
    return {type: "comment", comment: s2 !== -1 ? n3.slice(4, s2) : ""};
  }
  for (var a2 = new RegExp(t2), c3 = null; (c3 = a2.exec(n3)) !== null; )
    if (c3[0].trim())
      if (c3[1]) {
        var o = c3[1].trim(), l2 = [o, ""];
        o.indexOf("=") > -1 && (l2 = o.split("=")), r3.attrs[l2[0]] = l2[1], a2.lastIndex--;
      } else
        c3[2] && (r3.attrs[c3[2]] = c3[3].trim().substring(1, c3[3].length - 1));
  return r3;
}
var r2 = /<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g;
var i2 = /^\s*$/;
var s = Object.create(null);
function a(e2, t5) {
  switch (t5.type) {
    case "text":
      return e2 + t5.content;
    case "tag":
      return e2 += "<" + t5.name + (t5.attrs ? function(e3) {
        var t6 = [];
        for (var n3 in e3)
          t6.push(n3 + '="' + e3[n3] + '"');
        return t6.length ? " " + t6.join(" ") : "";
      }(t5.attrs) : "") + (t5.voidElement ? "/>" : ">"), t5.voidElement ? e2 : e2 + t5.children.reduce(a, "") + "</" + t5.name + ">";
    case "comment":
      return e2 + "<!--" + t5.comment + "-->";
  }
}
var c2 = {parse: function(e2, t5) {
  t5 || (t5 = {}), t5.components || (t5.components = s);
  var a2, c3 = [], o = [], l2 = -1, m2 = false;
  if (e2.indexOf("<") !== 0) {
    var u = e2.indexOf("<");
    c3.push({type: "text", content: u === -1 ? e2 : e2.substring(0, u)});
  }
  return e2.replace(r2, function(r3, s2) {
    if (m2) {
      if (r3 !== "</" + a2.name + ">")
        return;
      m2 = false;
    }
    var u2, f2 = r3.charAt(1) !== "/", h2 = r3.startsWith("<!--"), p2 = s2 + r3.length, d2 = e2.charAt(p2);
    if (h2) {
      var v2 = n2(r3);
      return l2 < 0 ? (c3.push(v2), c3) : ((u2 = o[l2]).children.push(v2), c3);
    }
    if (f2 && (l2++, (a2 = n2(r3)).type === "tag" && t5.components[a2.name] && (a2.type = "component", m2 = true), a2.voidElement || m2 || !d2 || d2 === "<" || a2.children.push({type: "text", content: e2.slice(p2, e2.indexOf("<", p2))}), l2 === 0 && c3.push(a2), (u2 = o[l2 - 1]) && u2.children.push(a2), o[l2] = a2), (!f2 || a2.voidElement) && (l2 > -1 && (a2.voidElement || a2.name === r3.slice(2, -1)) && (l2--, a2 = l2 === -1 ? c3 : o[l2]), !m2 && d2 !== "<" && d2)) {
      u2 = l2 === -1 ? c3 : o[l2].children;
      var x2 = e2.indexOf("<", p2), g2 = e2.slice(p2, x2 === -1 ? void 0 : x2);
      i2.test(g2) && (g2 = " "), (x2 > -1 && l2 + u2.length >= 0 || g2 !== " ") && u2.push({type: "text", content: g2});
    }
  }), c3;
}, stringify: function(e2) {
  return e2.reduce(function(e3, t5) {
    return e3 + a("", t5);
  }, "");
}};
var replace = "".replace;
var es = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g;
var unes = {
  "&amp;": "&",
  "&#38;": "&",
  "&lt;": "<",
  "&#60;": "<",
  "&gt;": ">",
  "&#62;": ">",
  "&apos;": "'",
  "&#39;": "'",
  "&quot;": '"',
  "&#34;": '"'
};
function unescape2(un) {
  return replace.call(un, es, cape);
}
function cape(m2) {
  return unes[m2];
}
var classCallCheck = createCommonjsModule(function(module2) {
  function _classCallCheck5(instance2, Constructor) {
    if (!(instance2 instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }
  module2.exports = _classCallCheck5;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var _classCallCheck2 = /* @__PURE__ */ getDefaultExportFromCjs(classCallCheck);
var createClass = createCommonjsModule(function(module2) {
  function _defineProperties3(target, props) {
    for (var i3 = 0; i3 < props.length; i3++) {
      var descriptor = props[i3];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass5(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties3(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties3(Constructor, staticProps);
    return Constructor;
  }
  module2.exports = _createClass5;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var _createClass2 = /* @__PURE__ */ getDefaultExportFromCjs(createClass);
function ownKeys2(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys2(Object(source2), true).forEach(function(key) {
        _defineProperty3(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys2(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var defaultOptions = {
  bindI18n: "languageChanged",
  bindI18nStore: "",
  transEmptyNodeValue: "",
  transSupportBasicHtmlNodes: true,
  transWrapTextNodes: "",
  transKeepBasicHtmlNodesFor: ["br", "strong", "i", "p"],
  useSuspense: true
};
var i18nInstance;
var I18nContext = react.createContext();
function setDefaults() {
  var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
  defaultOptions = _objectSpread(_objectSpread({}, defaultOptions), options);
}
function getDefaults() {
  return defaultOptions;
}
var ReportNamespaces = function() {
  function ReportNamespaces2() {
    _classCallCheck2(this, ReportNamespaces2);
    this.usedNamespaces = {};
  }
  _createClass2(ReportNamespaces2, [{
    key: "addUsedNamespaces",
    value: function addUsedNamespaces(namespaces2) {
      var _this = this;
      namespaces2.forEach(function(ns) {
        if (!_this.usedNamespaces[ns])
          _this.usedNamespaces[ns] = true;
      });
    }
  }, {
    key: "getUsedNamespaces",
    value: function getUsedNamespaces() {
      return Object.keys(this.usedNamespaces);
    }
  }]);
  return ReportNamespaces2;
}();
function setI18n(instance2) {
  i18nInstance = instance2;
}
function getI18n() {
  return i18nInstance;
}
var initReactI18next = {
  type: "3rdParty",
  init: function init(instance2) {
    setDefaults(instance2.options.react);
    setI18n(instance2);
  }
};
function warn() {
  if (console && console.warn) {
    var _console;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    if (typeof args[0] === "string")
      args[0] = "react-i18next:: ".concat(args[0]);
    (_console = console).warn.apply(_console, args);
  }
}
var alreadyWarned = {};
function warnOnce() {
  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
    args[_key2] = arguments[_key2];
  }
  if (typeof args[0] === "string" && alreadyWarned[args[0]])
    return;
  if (typeof args[0] === "string")
    alreadyWarned[args[0]] = new Date();
  warn.apply(void 0, args);
}
function loadNamespaces(i18n, ns, cb2) {
  i18n.loadNamespaces(ns, function() {
    if (i18n.isInitialized) {
      cb2();
    } else {
      var initialized = function initialized2() {
        setTimeout(function() {
          i18n.off("initialized", initialized2);
        }, 0);
        cb2();
      };
      i18n.on("initialized", initialized);
    }
  });
}
function hasLoadedNamespace(ns, i18n) {
  var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
  if (!i18n.languages || !i18n.languages.length) {
    warnOnce("i18n.languages were undefined or empty", i18n.languages);
    return true;
  }
  var lng = i18n.languages[0];
  var fallbackLng = i18n.options ? i18n.options.fallbackLng : false;
  var lastLng = i18n.languages[i18n.languages.length - 1];
  if (lng.toLowerCase() === "cimode")
    return true;
  var loadNotPending = function loadNotPending2(l2, n3) {
    var loadState = i18n.services.backendConnector.state["".concat(l2, "|").concat(n3)];
    return loadState === -1 || loadState === 2;
  };
  if (options.bindI18n && options.bindI18n.indexOf("languageChanging") > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns))
    return false;
  if (i18n.hasResourceBundle(lng, ns))
    return true;
  if (!i18n.services.backendConnector.backend)
    return true;
  if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns)))
    return true;
  return false;
}
var _excluded = ["format"];
var _excluded2 = ["children", "count", "parent", "i18nKey", "tOptions", "values", "defaults", "components", "ns", "i18n", "t", "shouldUnescape"];
function ownKeys$1(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$1(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$1(Object(source2), true).forEach(function(key) {
        _defineProperty3(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$1(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
function hasChildren(node, checkLength) {
  if (!node)
    return false;
  var base = node.props ? node.props.children : node.children;
  if (checkLength)
    return base.length > 0;
  return !!base;
}
function getChildren(node) {
  if (!node)
    return [];
  return node && node.children ? node.children : node.props && node.props.children;
}
function hasValidReactChildren(children2) {
  if (Object.prototype.toString.call(children2) !== "[object Array]")
    return false;
  return children2.every(function(child) {
    return react.isValidElement(child);
  });
}
function getAsArray(data2) {
  return Array.isArray(data2) ? data2 : [data2];
}
function mergeProps(source2, target) {
  var newTarget = _objectSpread$1({}, target);
  newTarget.props = Object.assign(source2.props, target.props);
  return newTarget;
}
function nodesToString(children2, i18nOptions) {
  if (!children2)
    return "";
  var stringNode = "";
  var childrenArray = getAsArray(children2);
  var keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
  childrenArray.forEach(function(child, childIndex) {
    if (typeof child === "string") {
      stringNode += "".concat(child);
    } else if (react.isValidElement(child)) {
      var childPropsCount = Object.keys(child.props).length;
      var shouldKeepChild = keepArray.indexOf(child.type) > -1;
      var childChildren = child.props.children;
      if (!childChildren && shouldKeepChild && childPropsCount === 0) {
        stringNode += "<".concat(child.type, "/>");
      } else if (!childChildren && (!shouldKeepChild || childPropsCount !== 0)) {
        stringNode += "<".concat(childIndex, "></").concat(childIndex, ">");
      } else if (child.props.i18nIsDynamicList) {
        stringNode += "<".concat(childIndex, "></").concat(childIndex, ">");
      } else if (shouldKeepChild && childPropsCount === 1 && typeof childChildren === "string") {
        stringNode += "<".concat(child.type, ">").concat(childChildren, "</").concat(child.type, ">");
      } else {
        var content2 = nodesToString(childChildren, i18nOptions);
        stringNode += "<".concat(childIndex, ">").concat(content2, "</").concat(childIndex, ">");
      }
    } else if (child === null) {
      warn("Trans: the passed in value is invalid - seems you passed in a null child.");
    } else if (_typeof(child) === "object") {
      var format2 = child.format, clone2 = _objectWithoutProperties2(child, _excluded);
      var keys2 = Object.keys(clone2);
      if (keys2.length === 1) {
        var value = format2 ? "".concat(keys2[0], ", ").concat(format2) : keys2[0];
        stringNode += "{{".concat(value, "}}");
      } else {
        warn("react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.", child);
      }
    } else {
      warn("Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.", child);
    }
  });
  return stringNode;
}
function renderNodes(children2, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) {
  if (targetString === "")
    return [];
  var keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
  var emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.join("|")).test(targetString);
  if (!children2 && !emptyChildrenButNeedsHandling)
    return [targetString];
  var data2 = {};
  function getData(childs) {
    var childrenArray = getAsArray(childs);
    childrenArray.forEach(function(child) {
      if (typeof child === "string")
        return;
      if (hasChildren(child))
        getData(getChildren(child));
      else if (_typeof(child) === "object" && !react.isValidElement(child))
        Object.assign(data2, child);
    });
  }
  getData(children2);
  var ast = c2.parse("<0>".concat(targetString, "</0>"));
  var opts = _objectSpread$1(_objectSpread$1({}, data2), combinedTOpts);
  function renderInner(child, node, rootReactNode) {
    var childs = getChildren(child);
    var mappedChildren = mapAST(childs, node.children, rootReactNode);
    return hasValidReactChildren(childs) && mappedChildren.length === 0 ? childs : mappedChildren;
  }
  function pushTranslatedJSX(child, inner, mem, i3, isVoid) {
    if (child.dummy)
      child.children = inner;
    mem.push(react.cloneElement(child, _objectSpread$1(_objectSpread$1({}, child.props), {}, {
      key: i3
    }), isVoid ? void 0 : inner));
  }
  function mapAST(reactNode, astNode, rootReactNode) {
    var reactNodes = getAsArray(reactNode);
    var astNodes = getAsArray(astNode);
    return astNodes.reduce(function(mem, node, i3) {
      var translationContent = node.children && node.children[0] && node.children[0].content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language);
      if (node.type === "tag") {
        var tmp = reactNodes[parseInt(node.name, 10)];
        if (!tmp && rootReactNode.length === 1 && rootReactNode[0][node.name])
          tmp = rootReactNode[0][node.name];
        if (!tmp)
          tmp = {};
        var child = Object.keys(node.attrs).length !== 0 ? mergeProps({
          props: node.attrs
        }, tmp) : tmp;
        var isElement3 = react.isValidElement(child);
        var isValidTranslationWithChildren = isElement3 && hasChildren(node, true) && !node.voidElement;
        var isEmptyTransWithHTML = emptyChildrenButNeedsHandling && _typeof(child) === "object" && child.dummy && !isElement3;
        var isKnownComponent = _typeof(children2) === "object" && children2 !== null && Object.hasOwnProperty.call(children2, node.name);
        if (typeof child === "string") {
          var value = i18n.services.interpolator.interpolate(child, opts, i18n.language);
          mem.push(value);
        } else if (hasChildren(child) || isValidTranslationWithChildren) {
          var inner = renderInner(child, node, rootReactNode);
          pushTranslatedJSX(child, inner, mem, i3);
        } else if (isEmptyTransWithHTML) {
          var _inner = mapAST(reactNodes, node.children, rootReactNode);
          mem.push(react.cloneElement(child, _objectSpread$1(_objectSpread$1({}, child.props), {}, {
            key: i3
          }), _inner));
        } else if (Number.isNaN(parseFloat(node.name))) {
          if (isKnownComponent) {
            var _inner2 = renderInner(child, node, rootReactNode);
            pushTranslatedJSX(child, _inner2, mem, i3, node.voidElement);
          } else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {
            if (node.voidElement) {
              mem.push(react.createElement(node.name, {
                key: "".concat(node.name, "-").concat(i3)
              }));
            } else {
              var _inner3 = mapAST(reactNodes, node.children, rootReactNode);
              mem.push(react.createElement(node.name, {
                key: "".concat(node.name, "-").concat(i3)
              }, _inner3));
            }
          } else if (node.voidElement) {
            mem.push("<".concat(node.name, " />"));
          } else {
            var _inner4 = mapAST(reactNodes, node.children, rootReactNode);
            mem.push("<".concat(node.name, ">").concat(_inner4, "</").concat(node.name, ">"));
          }
        } else if (_typeof(child) === "object" && !isElement3) {
          var content2 = node.children[0] ? translationContent : null;
          if (content2)
            mem.push(content2);
        } else if (node.children.length === 1 && translationContent) {
          mem.push(react.cloneElement(child, _objectSpread$1(_objectSpread$1({}, child.props), {}, {
            key: i3
          }), translationContent));
        } else {
          mem.push(react.cloneElement(child, _objectSpread$1(_objectSpread$1({}, child.props), {}, {
            key: i3
          })));
        }
      } else if (node.type === "text") {
        var wrapTextNodes = i18nOptions.transWrapTextNodes;
        var _content = shouldUnescape ? unescape2(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language);
        if (wrapTextNodes) {
          mem.push(react.createElement(wrapTextNodes, {
            key: "".concat(node.name, "-").concat(i3)
          }, _content));
        } else {
          mem.push(_content);
        }
      }
      return mem;
    }, []);
  }
  var result = mapAST([{
    dummy: true,
    children: children2 || []
  }], ast, getAsArray(children2 || []));
  return getChildren(result[0]);
}
function Trans(_ref) {
  var children2 = _ref.children, count = _ref.count, parent = _ref.parent, i18nKey = _ref.i18nKey, _ref$tOptions = _ref.tOptions, tOptions = _ref$tOptions === void 0 ? {} : _ref$tOptions, values2 = _ref.values, defaults3 = _ref.defaults, components3 = _ref.components, ns = _ref.ns, i18nFromProps = _ref.i18n, tFromProps = _ref.t, shouldUnescape = _ref.shouldUnescape, additionalProps = _objectWithoutProperties2(_ref, _excluded2);
  var _ref2 = react.useContext(I18nContext) || {}, i18nFromContext = _ref2.i18n, defaultNSFromContext = _ref2.defaultNS;
  var i18n = i18nFromProps || i18nFromContext || getI18n();
  if (!i18n) {
    warnOnce("You will need to pass in an i18next instance by using i18nextReactModule");
    return children2;
  }
  var t5 = tFromProps || i18n.t.bind(i18n) || function(k2) {
    return k2;
  };
  var reactI18nextOptions = _objectSpread$1(_objectSpread$1({}, getDefaults()), i18n.options && i18n.options.react);
  var namespaces2 = ns || t5.ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
  namespaces2 = typeof namespaces2 === "string" ? [namespaces2] : namespaces2 || ["translation"];
  var defaultValue = defaults3 || nodesToString(children2, reactI18nextOptions) || reactI18nextOptions.transEmptyNodeValue || i18nKey;
  var hashTransKey = reactI18nextOptions.hashTransKey;
  var key = i18nKey || (hashTransKey ? hashTransKey(defaultValue) : defaultValue);
  var interpolationOverride = values2 ? tOptions.interpolation : {
    interpolation: _objectSpread$1(_objectSpread$1({}, tOptions.interpolation), {}, {
      prefix: "#$?",
      suffix: "?$#"
    })
  };
  var combinedTOpts = _objectSpread$1(_objectSpread$1(_objectSpread$1(_objectSpread$1({}, tOptions), {}, {
    count
  }, values2), interpolationOverride), {}, {
    defaultValue,
    ns: namespaces2
  });
  var translation = key ? t5(key, combinedTOpts) : defaultValue;
  var content2 = renderNodes(components3 || children2, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape);
  var useAsParent = parent !== void 0 ? parent : reactI18nextOptions.defaultTransParent;
  return useAsParent ? react.createElement(useAsParent, additionalProps, content2) : content2;
}
var arrayWithHoles = createCommonjsModule(function(module2) {
  function _arrayWithHoles3(arr) {
    if (Array.isArray(arr))
      return arr;
  }
  module2.exports = _arrayWithHoles3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var iterableToArrayLimit = createCommonjsModule(function(module2) {
  function _iterableToArrayLimit3(arr, i3) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null)
      return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
      for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);
        if (i3 && _arr.length === i3)
          break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"] != null)
          _i["return"]();
      } finally {
        if (_d)
          throw _e;
      }
    }
    return _arr;
  }
  module2.exports = _iterableToArrayLimit3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var nonIterableRest = createCommonjsModule(function(module2) {
  function _nonIterableRest3() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  module2.exports = _nonIterableRest3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var slicedToArray = createCommonjsModule(function(module2) {
  function _slicedToArray4(arr, i3) {
    return arrayWithHoles(arr) || iterableToArrayLimit(arr, i3) || unsupportedIterableToArray(arr, i3) || nonIterableRest();
  }
  module2.exports = _slicedToArray4;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var _slicedToArray = /* @__PURE__ */ getDefaultExportFromCjs(slicedToArray);
function ownKeys$2(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$2(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$2(Object(source2), true).forEach(function(key) {
        _defineProperty3(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$2(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
function useTranslation(ns) {
  var props = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
  var i18nFromProps = props.i18n;
  var _ref = react.useContext(I18nContext) || {}, i18nFromContext = _ref.i18n, defaultNSFromContext = _ref.defaultNS;
  var i18n = i18nFromProps || i18nFromContext || getI18n();
  if (i18n && !i18n.reportNamespaces)
    i18n.reportNamespaces = new ReportNamespaces();
  if (!i18n) {
    warnOnce("You will need to pass in an i18next instance by using initReactI18next");
    var notReadyT = function notReadyT2(k2) {
      return Array.isArray(k2) ? k2[k2.length - 1] : k2;
    };
    var retNotReady = [notReadyT, {}, false];
    retNotReady.t = notReadyT;
    retNotReady.i18n = {};
    retNotReady.ready = false;
    return retNotReady;
  }
  if (i18n.options.react && i18n.options.react.wait !== void 0)
    warnOnce("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");
  var i18nOptions = _objectSpread$2(_objectSpread$2(_objectSpread$2({}, getDefaults()), i18n.options.react), props);
  var useSuspense = i18nOptions.useSuspense, keyPrefix = i18nOptions.keyPrefix;
  var namespaces2 = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
  namespaces2 = typeof namespaces2 === "string" ? [namespaces2] : namespaces2 || ["translation"];
  if (i18n.reportNamespaces.addUsedNamespaces)
    i18n.reportNamespaces.addUsedNamespaces(namespaces2);
  var ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces2.every(function(n3) {
    return hasLoadedNamespace(n3, i18n, i18nOptions);
  });
  function getT() {
    return i18n.getFixedT(null, i18nOptions.nsMode === "fallback" ? namespaces2 : namespaces2[0], keyPrefix);
  }
  var _useState = react.useState(getT), _useState2 = _slicedToArray(_useState, 2), t5 = _useState2[0], setT = _useState2[1];
  var isMounted = react.useRef(true);
  react.useEffect(function() {
    var bindI18n = i18nOptions.bindI18n, bindI18nStore = i18nOptions.bindI18nStore;
    isMounted.current = true;
    if (!ready && !useSuspense) {
      loadNamespaces(i18n, namespaces2, function() {
        if (isMounted.current)
          setT(getT);
      });
    }
    function boundReset() {
      if (isMounted.current)
        setT(getT);
    }
    if (bindI18n && i18n)
      i18n.on(bindI18n, boundReset);
    if (bindI18nStore && i18n)
      i18n.store.on(bindI18nStore, boundReset);
    return function() {
      isMounted.current = false;
      if (bindI18n && i18n)
        bindI18n.split(" ").forEach(function(e2) {
          return i18n.off(e2, boundReset);
        });
      if (bindI18nStore && i18n)
        bindI18nStore.split(" ").forEach(function(e2) {
          return i18n.store.off(e2, boundReset);
        });
    };
  }, [i18n, namespaces2.join()]);
  var isInitial = react.useRef(true);
  react.useEffect(function() {
    if (isMounted.current && !isInitial.current) {
      setT(getT);
    }
    isInitial.current = false;
  }, [i18n]);
  var ret = [t5, i18n, ready];
  ret.t = t5;
  ret.i18n = i18n;
  ret.ready = ready;
  if (ready)
    return ret;
  if (!ready && !useSuspense)
    return ret;
  throw new Promise(function(resolve2) {
    loadNamespaces(i18n, namespaces2, function() {
      resolve2();
    });
  });
}

// build/utils/useRequiredContext.js
function useRequiredContext(context2) {
  const resolved = useContext(context2);
  if (resolved !== void 0 && resolved !== null) {
    return resolved;
  }
  throw new Error(`No provider found for ${context2.displayName ? `the '${context2.displayName}'` : "an unknown"} context, make sure it is included in your component hierarchy.`);
}

// build/components/help-enabler/HelpHeader.js
var HelpContext = createContext(void 0);
var useHelp = () => useRequiredContext(HelpContext);
var Help = ({children: children2}) => {
  const [enabled, setHelp] = useState(true);
  function toggleHelp() {
    setHelp((help) => !help);
  }
  return /* @__PURE__ */ react.createElement(HelpContext.Provider, {
    value: {enabled, toggleHelp}
  }, children2);
};
var HelpHeader = () => {
  const [open2, setOpen] = useState(false);
  const help = useHelp();
  const {t: t5} = useTranslation();
  const dropdownItems = [
    /* @__PURE__ */ react.createElement(DropdownItem, {
      key: "link",
      id: "link"
    }, /* @__PURE__ */ react.createElement(Split, null, /* @__PURE__ */ react.createElement(SplitItem, {
      isFilled: true
    }, t5("documentation")), /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(ExternalLinkAltIcon, null)))),
    /* @__PURE__ */ react.createElement(Divider, {
      key: "divide"
    }),
    /* @__PURE__ */ react.createElement(DropdownItem, {
      key: "enable",
      id: "enable"
    }, /* @__PURE__ */ react.createElement(Split, null, /* @__PURE__ */ react.createElement(SplitItem, {
      isFilled: true
    }, t5("enableHelpMode")), /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(Switch, {
      id: "enableHelp",
      "aria-label": "Help is enabled",
      isChecked: help.enabled,
      label: "",
      className: "keycloak_help-header-switch",
      onChange: () => help.toggleHelp()
    }))), /* @__PURE__ */ react.createElement(TextContent, {
      className: "keycloak_help-header-description"
    }, t5("common-help:helpToggleInfo")))
  ];
  return /* @__PURE__ */ react.createElement(Dropdown, {
    position: "right",
    isPlain: true,
    isOpen: open2,
    toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
      toggleIndicator: null,
      onToggle: () => setOpen(!open2),
      "aria-label": "Help",
      id: "help"
    }, /* @__PURE__ */ react.createElement(HelpIcon, null)),
    dropdownItems
  });
};

// build/_snowpack/pkg/common/process-2545f00a.js
function defaultSetTimout() {
  throw new Error("setTimeout has not been defined");
}
function defaultClearTimeout() {
  throw new Error("clearTimeout has not been defined");
}
var cachedSetTimeout = defaultSetTimout;
var cachedClearTimeout = defaultClearTimeout;
var globalContext;
if (typeof window !== "undefined") {
  globalContext = window;
} else if (typeof self !== "undefined") {
  globalContext = self;
} else {
  globalContext = {};
}
if (typeof globalContext.setTimeout === "function") {
  cachedSetTimeout = setTimeout;
}
if (typeof globalContext.clearTimeout === "function") {
  cachedClearTimeout = clearTimeout;
}
function runTimeout(fun) {
  if (cachedSetTimeout === setTimeout) {
    return setTimeout(fun, 0);
  }
  if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
    cachedSetTimeout = setTimeout;
    return setTimeout(fun, 0);
  }
  try {
    return cachedSetTimeout(fun, 0);
  } catch (e2) {
    try {
      return cachedSetTimeout.call(null, fun, 0);
    } catch (e3) {
      return cachedSetTimeout.call(this, fun, 0);
    }
  }
}
function runClearTimeout(marker) {
  if (cachedClearTimeout === clearTimeout) {
    return clearTimeout(marker);
  }
  if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
    cachedClearTimeout = clearTimeout;
    return clearTimeout(marker);
  }
  try {
    return cachedClearTimeout(marker);
  } catch (e2) {
    try {
      return cachedClearTimeout.call(null, marker);
    } catch (e3) {
      return cachedClearTimeout.call(this, marker);
    }
  }
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
  if (!draining || !currentQueue) {
    return;
  }
  draining = false;
  if (currentQueue.length) {
    queue = currentQueue.concat(queue);
  } else {
    queueIndex = -1;
  }
  if (queue.length) {
    drainQueue();
  }
}
function drainQueue() {
  if (draining) {
    return;
  }
  var timeout3 = runTimeout(cleanUpNextTick);
  draining = true;
  var len2 = queue.length;
  while (len2) {
    currentQueue = queue;
    queue = [];
    while (++queueIndex < len2) {
      if (currentQueue) {
        currentQueue[queueIndex].run();
      }
    }
    queueIndex = -1;
    len2 = queue.length;
  }
  currentQueue = null;
  draining = false;
  runClearTimeout(timeout3);
}
function nextTick(fun) {
  var args = new Array(arguments.length - 1);
  if (arguments.length > 1) {
    for (var i3 = 1; i3 < arguments.length; i3++) {
      args[i3 - 1] = arguments[i3];
    }
  }
  queue.push(new Item(fun, args));
  if (queue.length === 1 && !draining) {
    runTimeout(drainQueue);
  }
}
function Item(fun, array2) {
  this.fun = fun;
  this.array = array2;
}
Item.prototype.run = function() {
  this.fun.apply(null, this.array);
};
var title2 = "browser";
var platform = "browser";
var browser = true;
var argv = [];
var version2 = "";
var versions = {};
var release = {};
var config = {};
function noop2() {
}
var on = noop2;
var addListener = noop2;
var once = noop2;
var off = noop2;
var removeListener = noop2;
var removeAllListeners = noop2;
var emit = noop2;
function binding(name) {
  throw new Error("process.binding is not supported");
}
function cwd() {
  return "/";
}
function chdir(dir) {
  throw new Error("process.chdir is not supported");
}
function umask() {
  return 0;
}
var performance2 = globalContext.performance || {};
var performanceNow = performance2.now || performance2.mozNow || performance2.msNow || performance2.oNow || performance2.webkitNow || function() {
  return new Date().getTime();
};
function hrtime(previousTimestamp) {
  var clocktime = performanceNow.call(performance2) * 1e-3;
  var seconds = Math.floor(clocktime);
  var nanoseconds = Math.floor(clocktime % 1 * 1e9);
  if (previousTimestamp) {
    seconds = seconds - previousTimestamp[0];
    nanoseconds = nanoseconds - previousTimestamp[1];
    if (nanoseconds < 0) {
      seconds--;
      nanoseconds += 1e9;
    }
  }
  return [seconds, nanoseconds];
}
var startTime = new Date();
function uptime() {
  var currentTime = new Date();
  var dif = currentTime - startTime;
  return dif / 1e3;
}
var process = {
  nextTick,
  title: title2,
  browser,
  env: {NODE_ENV: "production"},
  argv,
  version: version2,
  versions,
  on,
  addListener,
  once,
  off,
  removeListener,
  removeAllListeners,
  emit,
  binding,
  cwd,
  chdir,
  umask,
  hrtime,
  platform,
  release,
  config,
  uptime
};

// build/_snowpack/pkg/common/index-6c6617bd.js
var bind = function bind2(fn, thisArg) {
  return function wrap() {
    var args = new Array(arguments.length);
    for (var i3 = 0; i3 < args.length; i3++) {
      args[i3] = arguments[i3];
    }
    return fn.apply(thisArg, args);
  };
};
var toString2 = Object.prototype.toString;
function isArray(val) {
  return toString2.call(val) === "[object Array]";
}
function isUndefined(val) {
  return typeof val === "undefined";
}
function isBuffer(val) {
  return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === "function" && val.constructor.isBuffer(val);
}
function isArrayBuffer(val) {
  return toString2.call(val) === "[object ArrayBuffer]";
}
function isFormData(val) {
  return typeof FormData !== "undefined" && val instanceof FormData;
}
function isArrayBufferView(val) {
  var result;
  if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
    result = ArrayBuffer.isView(val);
  } else {
    result = val && val.buffer && val.buffer instanceof ArrayBuffer;
  }
  return result;
}
function isString(val) {
  return typeof val === "string";
}
function isNumber(val) {
  return typeof val === "number";
}
function isObject(val) {
  return val !== null && typeof val === "object";
}
function isPlainObject(val) {
  if (toString2.call(val) !== "[object Object]") {
    return false;
  }
  var prototype = Object.getPrototypeOf(val);
  return prototype === null || prototype === Object.prototype;
}
function isDate(val) {
  return toString2.call(val) === "[object Date]";
}
function isFile(val) {
  return toString2.call(val) === "[object File]";
}
function isBlob(val) {
  return toString2.call(val) === "[object Blob]";
}
function isFunction(val) {
  return toString2.call(val) === "[object Function]";
}
function isStream(val) {
  return isObject(val) && isFunction(val.pipe);
}
function isURLSearchParams(val) {
  return typeof URLSearchParams !== "undefined" && val instanceof URLSearchParams;
}
function trim(str) {
  return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, "");
}
function isStandardBrowserEnv() {
  if (typeof navigator !== "undefined" && (navigator.product === "ReactNative" || navigator.product === "NativeScript" || navigator.product === "NS")) {
    return false;
  }
  return typeof window !== "undefined" && typeof document !== "undefined";
}
function forEach(obj, fn) {
  if (obj === null || typeof obj === "undefined") {
    return;
  }
  if (typeof obj !== "object") {
    obj = [obj];
  }
  if (isArray(obj)) {
    for (var i3 = 0, l2 = obj.length; i3 < l2; i3++) {
      fn.call(null, obj[i3], i3, obj);
    }
  } else {
    for (var key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        fn.call(null, obj[key], key, obj);
      }
    }
  }
}
function merge() {
  var result = {};
  function assignValue2(val, key) {
    if (isPlainObject(result[key]) && isPlainObject(val)) {
      result[key] = merge(result[key], val);
    } else if (isPlainObject(val)) {
      result[key] = merge({}, val);
    } else if (isArray(val)) {
      result[key] = val.slice();
    } else {
      result[key] = val;
    }
  }
  for (var i3 = 0, l2 = arguments.length; i3 < l2; i3++) {
    forEach(arguments[i3], assignValue2);
  }
  return result;
}
function extend(a2, b2, thisArg) {
  forEach(b2, function assignValue2(val, key) {
    if (thisArg && typeof val === "function") {
      a2[key] = bind(val, thisArg);
    } else {
      a2[key] = val;
    }
  });
  return a2;
}
function stripBOM(content2) {
  if (content2.charCodeAt(0) === 65279) {
    content2 = content2.slice(1);
  }
  return content2;
}
var utils = {
  isArray,
  isArrayBuffer,
  isBuffer,
  isFormData,
  isArrayBufferView,
  isString,
  isNumber,
  isObject,
  isPlainObject,
  isUndefined,
  isDate,
  isFile,
  isBlob,
  isFunction,
  isStream,
  isURLSearchParams,
  isStandardBrowserEnv,
  forEach,
  merge,
  extend,
  trim,
  stripBOM
};
function encode(val) {
  return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
}
var buildURL = function buildURL2(url, params, paramsSerializer) {
  if (!params) {
    return url;
  }
  var serializedParams;
  if (paramsSerializer) {
    serializedParams = paramsSerializer(params);
  } else if (utils.isURLSearchParams(params)) {
    serializedParams = params.toString();
  } else {
    var parts = [];
    utils.forEach(params, function serialize(val, key) {
      if (val === null || typeof val === "undefined") {
        return;
      }
      if (utils.isArray(val)) {
        key = key + "[]";
      } else {
        val = [val];
      }
      utils.forEach(val, function parseValue(v2) {
        if (utils.isDate(v2)) {
          v2 = v2.toISOString();
        } else if (utils.isObject(v2)) {
          v2 = JSON.stringify(v2);
        }
        parts.push(encode(key) + "=" + encode(v2));
      });
    });
    serializedParams = parts.join("&");
  }
  if (serializedParams) {
    var hashmarkIndex = url.indexOf("#");
    if (hashmarkIndex !== -1) {
      url = url.slice(0, hashmarkIndex);
    }
    url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
  }
  return url;
};
function InterceptorManager() {
  this.handlers = [];
}
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
  this.handlers.push({
    fulfilled,
    rejected,
    synchronous: options ? options.synchronous : false,
    runWhen: options ? options.runWhen : null
  });
  return this.handlers.length - 1;
};
InterceptorManager.prototype.eject = function eject(id3) {
  if (this.handlers[id3]) {
    this.handlers[id3] = null;
  }
};
InterceptorManager.prototype.forEach = function forEach2(fn) {
  utils.forEach(this.handlers, function forEachHandler(h2) {
    if (h2 !== null) {
      fn(h2);
    }
  });
};
var InterceptorManager_1 = InterceptorManager;
var normalizeHeaderName = function normalizeHeaderName2(headers, normalizedName) {
  utils.forEach(headers, function processHeader(value, name) {
    if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
      headers[normalizedName] = value;
      delete headers[name];
    }
  });
};
var enhanceError = function enhanceError2(error2, config2, code2, request2, response) {
  error2.config = config2;
  if (code2) {
    error2.code = code2;
  }
  error2.request = request2;
  error2.response = response;
  error2.isAxiosError = true;
  error2.toJSON = function toJSON() {
    return {
      message: this.message,
      name: this.name,
      description: this.description,
      number: this.number,
      fileName: this.fileName,
      lineNumber: this.lineNumber,
      columnNumber: this.columnNumber,
      stack: this.stack,
      config: this.config,
      code: this.code,
      status: this.response && this.response.status ? this.response.status : null
    };
  };
  return error2;
};
var createError = function createError2(message, config2, code2, request2, response) {
  var error2 = new Error(message);
  return enhanceError(error2, config2, code2, request2, response);
};
var settle = function settle2(resolve2, reject, response) {
  var validateStatus2 = response.config.validateStatus;
  if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
    resolve2(response);
  } else {
    reject(createError("Request failed with status code " + response.status, response.config, null, response.request, response));
  }
};
var cookies = utils.isStandardBrowserEnv() ? function standardBrowserEnv() {
  return {
    write: function write3(name, value, expires2, path, domain, secure) {
      var cookie = [];
      cookie.push(name + "=" + encodeURIComponent(value));
      if (utils.isNumber(expires2)) {
        cookie.push("expires=" + new Date(expires2).toGMTString());
      }
      if (utils.isString(path)) {
        cookie.push("path=" + path);
      }
      if (utils.isString(domain)) {
        cookie.push("domain=" + domain);
      }
      if (secure === true) {
        cookie.push("secure");
      }
      document.cookie = cookie.join("; ");
    },
    read: function read3(name) {
      var match2 = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
      return match2 ? decodeURIComponent(match2[3]) : null;
    },
    remove: function remove3(name) {
      this.write(name, "", Date.now() - 864e5);
    }
  };
}() : function nonStandardBrowserEnv() {
  return {
    write: function write3() {
    },
    read: function read3() {
      return null;
    },
    remove: function remove3() {
    }
  };
}();
var isAbsoluteURL = function isAbsoluteURL2(url) {
  return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
var combineURLs = function combineURLs2(baseURL, relativeURL) {
  return relativeURL ? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
};
var buildFullPath = function buildFullPath2(baseURL, requestedURL) {
  if (baseURL && !isAbsoluteURL(requestedURL)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
};
var ignoreDuplicateOf = [
  "age",
  "authorization",
  "content-length",
  "content-type",
  "etag",
  "expires",
  "from",
  "host",
  "if-modified-since",
  "if-unmodified-since",
  "last-modified",
  "location",
  "max-forwards",
  "proxy-authorization",
  "referer",
  "retry-after",
  "user-agent"
];
var parseHeaders = function parseHeaders2(headers) {
  var parsed = {};
  var key;
  var val;
  var i3;
  if (!headers) {
    return parsed;
  }
  utils.forEach(headers.split("\n"), function parser(line) {
    i3 = line.indexOf(":");
    key = utils.trim(line.substr(0, i3)).toLowerCase();
    val = utils.trim(line.substr(i3 + 1));
    if (key) {
      if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
        return;
      }
      if (key === "set-cookie") {
        parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
      } else {
        parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
      }
    }
  });
  return parsed;
};
var isURLSameOrigin = utils.isStandardBrowserEnv() ? function standardBrowserEnv2() {
  var msie = /(msie|trident)/i.test(navigator.userAgent);
  var urlParsingNode = document.createElement("a");
  var originURL;
  function resolveURL(url) {
    var href = url;
    if (msie) {
      urlParsingNode.setAttribute("href", href);
      href = urlParsingNode.href;
    }
    urlParsingNode.setAttribute("href", href);
    return {
      href: urlParsingNode.href,
      protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "",
      host: urlParsingNode.host,
      search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "",
      hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "",
      hostname: urlParsingNode.hostname,
      port: urlParsingNode.port,
      pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname
    };
  }
  originURL = resolveURL(window.location.href);
  return function isURLSameOrigin2(requestURL) {
    var parsed = utils.isString(requestURL) ? resolveURL(requestURL) : requestURL;
    return parsed.protocol === originURL.protocol && parsed.host === originURL.host;
  };
}() : function nonStandardBrowserEnv2() {
  return function isURLSameOrigin2() {
    return true;
  };
}();
function Cancel(message) {
  this.message = message;
}
Cancel.prototype.toString = function toString3() {
  return "Cancel" + (this.message ? ": " + this.message : "");
};
Cancel.prototype.__CANCEL__ = true;
var Cancel_1 = Cancel;
var xhr = function xhrAdapter(config2) {
  return new Promise(function dispatchXhrRequest(resolve2, reject) {
    var requestData = config2.data;
    var requestHeaders = config2.headers;
    var responseType = config2.responseType;
    var onCanceled;
    function done() {
      if (config2.cancelToken) {
        config2.cancelToken.unsubscribe(onCanceled);
      }
      if (config2.signal) {
        config2.signal.removeEventListener("abort", onCanceled);
      }
    }
    if (utils.isFormData(requestData)) {
      delete requestHeaders["Content-Type"];
    }
    var request2 = new XMLHttpRequest();
    if (config2.auth) {
      var username = config2.auth.username || "";
      var password = config2.auth.password ? unescape(encodeURIComponent(config2.auth.password)) : "";
      requestHeaders.Authorization = "Basic " + btoa(username + ":" + password);
    }
    var fullPath = buildFullPath(config2.baseURL, config2.url);
    request2.open(config2.method.toUpperCase(), buildURL(fullPath, config2.params, config2.paramsSerializer), true);
    request2.timeout = config2.timeout;
    function onloadend() {
      if (!request2) {
        return;
      }
      var responseHeaders = "getAllResponseHeaders" in request2 ? parseHeaders(request2.getAllResponseHeaders()) : null;
      var responseData = !responseType || responseType === "text" || responseType === "json" ? request2.responseText : request2.response;
      var response = {
        data: responseData,
        status: request2.status,
        statusText: request2.statusText,
        headers: responseHeaders,
        config: config2,
        request: request2
      };
      settle(function _resolve(value) {
        resolve2(value);
        done();
      }, function _reject(err) {
        reject(err);
        done();
      }, response);
      request2 = null;
    }
    if ("onloadend" in request2) {
      request2.onloadend = onloadend;
    } else {
      request2.onreadystatechange = function handleLoad() {
        if (!request2 || request2.readyState !== 4) {
          return;
        }
        if (request2.status === 0 && !(request2.responseURL && request2.responseURL.indexOf("file:") === 0)) {
          return;
        }
        setTimeout(onloadend);
      };
    }
    request2.onabort = function handleAbort() {
      if (!request2) {
        return;
      }
      reject(createError("Request aborted", config2, "ECONNABORTED", request2));
      request2 = null;
    };
    request2.onerror = function handleError() {
      reject(createError("Network Error", config2, null, request2));
      request2 = null;
    };
    request2.ontimeout = function handleTimeout() {
      var timeoutErrorMessage = config2.timeout ? "timeout of " + config2.timeout + "ms exceeded" : "timeout exceeded";
      var transitional2 = config2.transitional || defaults_1.transitional;
      if (config2.timeoutErrorMessage) {
        timeoutErrorMessage = config2.timeoutErrorMessage;
      }
      reject(createError(timeoutErrorMessage, config2, transitional2.clarifyTimeoutError ? "ETIMEDOUT" : "ECONNABORTED", request2));
      request2 = null;
    };
    if (utils.isStandardBrowserEnv()) {
      var xsrfValue = (config2.withCredentials || isURLSameOrigin(fullPath)) && config2.xsrfCookieName ? cookies.read(config2.xsrfCookieName) : void 0;
      if (xsrfValue) {
        requestHeaders[config2.xsrfHeaderName] = xsrfValue;
      }
    }
    if ("setRequestHeader" in request2) {
      utils.forEach(requestHeaders, function setRequestHeader(val, key) {
        if (typeof requestData === "undefined" && key.toLowerCase() === "content-type") {
          delete requestHeaders[key];
        } else {
          request2.setRequestHeader(key, val);
        }
      });
    }
    if (!utils.isUndefined(config2.withCredentials)) {
      request2.withCredentials = !!config2.withCredentials;
    }
    if (responseType && responseType !== "json") {
      request2.responseType = config2.responseType;
    }
    if (typeof config2.onDownloadProgress === "function") {
      request2.addEventListener("progress", config2.onDownloadProgress);
    }
    if (typeof config2.onUploadProgress === "function" && request2.upload) {
      request2.upload.addEventListener("progress", config2.onUploadProgress);
    }
    if (config2.cancelToken || config2.signal) {
      onCanceled = function(cancel) {
        if (!request2) {
          return;
        }
        reject(!cancel || cancel && cancel.type ? new Cancel_1("canceled") : cancel);
        request2.abort();
        request2 = null;
      };
      config2.cancelToken && config2.cancelToken.subscribe(onCanceled);
      if (config2.signal) {
        config2.signal.aborted ? onCanceled() : config2.signal.addEventListener("abort", onCanceled);
      }
    }
    if (!requestData) {
      requestData = null;
    }
    request2.send(requestData);
  });
};
var DEFAULT_CONTENT_TYPE = {
  "Content-Type": "application/x-www-form-urlencoded"
};
function setContentTypeIfUnset(headers, value) {
  if (!utils.isUndefined(headers) && utils.isUndefined(headers["Content-Type"])) {
    headers["Content-Type"] = value;
  }
}
function getDefaultAdapter() {
  var adapter;
  if (typeof XMLHttpRequest !== "undefined") {
    adapter = xhr;
  } else if (typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]") {
    adapter = xhr;
  }
  return adapter;
}
function stringifySafely(rawValue, parser, encoder) {
  if (utils.isString(rawValue)) {
    try {
      (parser || JSON.parse)(rawValue);
      return utils.trim(rawValue);
    } catch (e2) {
      if (e2.name !== "SyntaxError") {
        throw e2;
      }
    }
  }
  return (encoder || JSON.stringify)(rawValue);
}
var defaults = {
  transitional: {
    silentJSONParsing: true,
    forcedJSONParsing: true,
    clarifyTimeoutError: false
  },
  adapter: getDefaultAdapter(),
  transformRequest: [function transformRequest(data2, headers) {
    normalizeHeaderName(headers, "Accept");
    normalizeHeaderName(headers, "Content-Type");
    if (utils.isFormData(data2) || utils.isArrayBuffer(data2) || utils.isBuffer(data2) || utils.isStream(data2) || utils.isFile(data2) || utils.isBlob(data2)) {
      return data2;
    }
    if (utils.isArrayBufferView(data2)) {
      return data2.buffer;
    }
    if (utils.isURLSearchParams(data2)) {
      setContentTypeIfUnset(headers, "application/x-www-form-urlencoded;charset=utf-8");
      return data2.toString();
    }
    if (utils.isObject(data2) || headers && headers["Content-Type"] === "application/json") {
      setContentTypeIfUnset(headers, "application/json");
      return stringifySafely(data2);
    }
    return data2;
  }],
  transformResponse: [function transformResponse(data2) {
    var transitional2 = this.transitional || defaults.transitional;
    var silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
    var forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
    var strictJSONParsing = !silentJSONParsing && this.responseType === "json";
    if (strictJSONParsing || forcedJSONParsing && utils.isString(data2) && data2.length) {
      try {
        return JSON.parse(data2);
      } catch (e2) {
        if (strictJSONParsing) {
          if (e2.name === "SyntaxError") {
            throw enhanceError(e2, this, "E_JSON_PARSE");
          }
          throw e2;
        }
      }
    }
    return data2;
  }],
  timeout: 0,
  xsrfCookieName: "XSRF-TOKEN",
  xsrfHeaderName: "X-XSRF-TOKEN",
  maxContentLength: -1,
  maxBodyLength: -1,
  validateStatus: function validateStatus(status) {
    return status >= 200 && status < 300;
  },
  headers: {
    common: {
      Accept: "application/json, text/plain, */*"
    }
  }
};
utils.forEach(["delete", "get", "head"], function forEachMethodNoData(method) {
  defaults.headers[method] = {};
});
utils.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
  defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
var defaults_1 = defaults;
var transformData = function transformData2(data2, headers, fns) {
  var context2 = this || defaults_1;
  utils.forEach(fns, function transform3(fn) {
    data2 = fn.call(context2, data2, headers);
  });
  return data2;
};
var isCancel = function isCancel2(value) {
  return !!(value && value.__CANCEL__);
};
function throwIfCancellationRequested(config2) {
  if (config2.cancelToken) {
    config2.cancelToken.throwIfRequested();
  }
  if (config2.signal && config2.signal.aborted) {
    throw new Cancel_1("canceled");
  }
}
var dispatchRequest = function dispatchRequest2(config2) {
  throwIfCancellationRequested(config2);
  config2.headers = config2.headers || {};
  config2.data = transformData.call(config2, config2.data, config2.headers, config2.transformRequest);
  config2.headers = utils.merge(config2.headers.common || {}, config2.headers[config2.method] || {}, config2.headers);
  utils.forEach(["delete", "get", "head", "post", "put", "patch", "common"], function cleanHeaderConfig(method) {
    delete config2.headers[method];
  });
  var adapter = config2.adapter || defaults_1.adapter;
  return adapter(config2).then(function onAdapterResolution(response) {
    throwIfCancellationRequested(config2);
    response.data = transformData.call(config2, response.data, response.headers, config2.transformResponse);
    return response;
  }, function onAdapterRejection(reason) {
    if (!isCancel(reason)) {
      throwIfCancellationRequested(config2);
      if (reason && reason.response) {
        reason.response.data = transformData.call(config2, reason.response.data, reason.response.headers, config2.transformResponse);
      }
    }
    return Promise.reject(reason);
  });
};
var mergeConfig = function mergeConfig2(config1, config2) {
  config2 = config2 || {};
  var config3 = {};
  function getMergedValue(target, source2) {
    if (utils.isPlainObject(target) && utils.isPlainObject(source2)) {
      return utils.merge(target, source2);
    } else if (utils.isPlainObject(source2)) {
      return utils.merge({}, source2);
    } else if (utils.isArray(source2)) {
      return source2.slice();
    }
    return source2;
  }
  function mergeDeepProperties(prop) {
    if (!utils.isUndefined(config2[prop])) {
      return getMergedValue(config1[prop], config2[prop]);
    } else if (!utils.isUndefined(config1[prop])) {
      return getMergedValue(void 0, config1[prop]);
    }
  }
  function valueFromConfig2(prop) {
    if (!utils.isUndefined(config2[prop])) {
      return getMergedValue(void 0, config2[prop]);
    }
  }
  function defaultToConfig2(prop) {
    if (!utils.isUndefined(config2[prop])) {
      return getMergedValue(void 0, config2[prop]);
    } else if (!utils.isUndefined(config1[prop])) {
      return getMergedValue(void 0, config1[prop]);
    }
  }
  function mergeDirectKeys(prop) {
    if (prop in config2) {
      return getMergedValue(config1[prop], config2[prop]);
    } else if (prop in config1) {
      return getMergedValue(void 0, config1[prop]);
    }
  }
  var mergeMap = {
    url: valueFromConfig2,
    method: valueFromConfig2,
    data: valueFromConfig2,
    baseURL: defaultToConfig2,
    transformRequest: defaultToConfig2,
    transformResponse: defaultToConfig2,
    paramsSerializer: defaultToConfig2,
    timeout: defaultToConfig2,
    timeoutMessage: defaultToConfig2,
    withCredentials: defaultToConfig2,
    adapter: defaultToConfig2,
    responseType: defaultToConfig2,
    xsrfCookieName: defaultToConfig2,
    xsrfHeaderName: defaultToConfig2,
    onUploadProgress: defaultToConfig2,
    onDownloadProgress: defaultToConfig2,
    decompress: defaultToConfig2,
    maxContentLength: defaultToConfig2,
    maxBodyLength: defaultToConfig2,
    transport: defaultToConfig2,
    httpAgent: defaultToConfig2,
    httpsAgent: defaultToConfig2,
    cancelToken: defaultToConfig2,
    socketPath: defaultToConfig2,
    responseEncoding: defaultToConfig2,
    validateStatus: mergeDirectKeys
  };
  utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
    var merge3 = mergeMap[prop] || mergeDeepProperties;
    var configValue = merge3(prop);
    utils.isUndefined(configValue) && merge3 !== mergeDirectKeys || (config3[prop] = configValue);
  });
  return config3;
};
var data = {
  version: "0.24.0"
};
var VERSION = data.version;
var validators = {};
["object", "boolean", "number", "function", "string", "symbol"].forEach(function(type, i3) {
  validators[type] = function validator2(thing) {
    return typeof thing === type || "a" + (i3 < 1 ? "n " : " ") + type;
  };
});
var deprecatedWarnings = {};
validators.transitional = function transitional(validator2, version4, message) {
  function formatMessage(opt, desc) {
    return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
  }
  return function(value, opt, opts) {
    if (validator2 === false) {
      throw new Error(formatMessage(opt, " has been removed" + (version4 ? " in " + version4 : "")));
    }
    if (version4 && !deprecatedWarnings[opt]) {
      deprecatedWarnings[opt] = true;
      console.warn(formatMessage(opt, " has been deprecated since v" + version4 + " and will be removed in the near future"));
    }
    return validator2 ? validator2(value, opt, opts) : true;
  };
};
function assertOptions(options, schema, allowUnknown) {
  if (typeof options !== "object") {
    throw new TypeError("options must be an object");
  }
  var keys2 = Object.keys(options);
  var i3 = keys2.length;
  while (i3-- > 0) {
    var opt = keys2[i3];
    var validator2 = schema[opt];
    if (validator2) {
      var value = options[opt];
      var result = value === void 0 || validator2(value, opt, options);
      if (result !== true) {
        throw new TypeError("option " + opt + " must be " + result);
      }
      continue;
    }
    if (allowUnknown !== true) {
      throw Error("Unknown option " + opt);
    }
  }
}
var validator = {
  assertOptions,
  validators
};
var validators$1 = validator.validators;
function Axios(instanceConfig) {
  this.defaults = instanceConfig;
  this.interceptors = {
    request: new InterceptorManager_1(),
    response: new InterceptorManager_1()
  };
}
Axios.prototype.request = function request(config2) {
  if (typeof config2 === "string") {
    config2 = arguments[1] || {};
    config2.url = arguments[0];
  } else {
    config2 = config2 || {};
  }
  config2 = mergeConfig(this.defaults, config2);
  if (config2.method) {
    config2.method = config2.method.toLowerCase();
  } else if (this.defaults.method) {
    config2.method = this.defaults.method.toLowerCase();
  } else {
    config2.method = "get";
  }
  var transitional2 = config2.transitional;
  if (transitional2 !== void 0) {
    validator.assertOptions(transitional2, {
      silentJSONParsing: validators$1.transitional(validators$1.boolean),
      forcedJSONParsing: validators$1.transitional(validators$1.boolean),
      clarifyTimeoutError: validators$1.transitional(validators$1.boolean)
    }, false);
  }
  var requestInterceptorChain = [];
  var synchronousRequestInterceptors = true;
  this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
    if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config2) === false) {
      return;
    }
    synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
    requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  });
  var responseInterceptorChain = [];
  this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
    responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  });
  var promise;
  if (!synchronousRequestInterceptors) {
    var chain = [dispatchRequest, void 0];
    Array.prototype.unshift.apply(chain, requestInterceptorChain);
    chain = chain.concat(responseInterceptorChain);
    promise = Promise.resolve(config2);
    while (chain.length) {
      promise = promise.then(chain.shift(), chain.shift());
    }
    return promise;
  }
  var newConfig = config2;
  while (requestInterceptorChain.length) {
    var onFulfilled = requestInterceptorChain.shift();
    var onRejected = requestInterceptorChain.shift();
    try {
      newConfig = onFulfilled(newConfig);
    } catch (error2) {
      onRejected(error2);
      break;
    }
  }
  try {
    promise = dispatchRequest(newConfig);
  } catch (error2) {
    return Promise.reject(error2);
  }
  while (responseInterceptorChain.length) {
    promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
  }
  return promise;
};
Axios.prototype.getUri = function getUri(config2) {
  config2 = mergeConfig(this.defaults, config2);
  return buildURL(config2.url, config2.params, config2.paramsSerializer).replace(/^\?/, "");
};
utils.forEach(["delete", "get", "head", "options"], function forEachMethodNoData2(method) {
  Axios.prototype[method] = function(url, config2) {
    return this.request(mergeConfig(config2 || {}, {
      method,
      url,
      data: (config2 || {}).data
    }));
  };
});
utils.forEach(["post", "put", "patch"], function forEachMethodWithData2(method) {
  Axios.prototype[method] = function(url, data2, config2) {
    return this.request(mergeConfig(config2 || {}, {
      method,
      url,
      data: data2
    }));
  };
});
var Axios_1 = Axios;
function CancelToken(executor) {
  if (typeof executor !== "function") {
    throw new TypeError("executor must be a function.");
  }
  var resolvePromise;
  this.promise = new Promise(function promiseExecutor(resolve2) {
    resolvePromise = resolve2;
  });
  var token2 = this;
  this.promise.then(function(cancel) {
    if (!token2._listeners)
      return;
    var i3;
    var l2 = token2._listeners.length;
    for (i3 = 0; i3 < l2; i3++) {
      token2._listeners[i3](cancel);
    }
    token2._listeners = null;
  });
  this.promise.then = function(onfulfilled) {
    var _resolve;
    var promise = new Promise(function(resolve2) {
      token2.subscribe(resolve2);
      _resolve = resolve2;
    }).then(onfulfilled);
    promise.cancel = function reject() {
      token2.unsubscribe(_resolve);
    };
    return promise;
  };
  executor(function cancel(message) {
    if (token2.reason) {
      return;
    }
    token2.reason = new Cancel_1(message);
    resolvePromise(token2.reason);
  });
}
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  if (this.reason) {
    throw this.reason;
  }
};
CancelToken.prototype.subscribe = function subscribe(listener) {
  if (this.reason) {
    listener(this.reason);
    return;
  }
  if (this._listeners) {
    this._listeners.push(listener);
  } else {
    this._listeners = [listener];
  }
};
CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
  if (!this._listeners) {
    return;
  }
  var index3 = this._listeners.indexOf(listener);
  if (index3 !== -1) {
    this._listeners.splice(index3, 1);
  }
};
CancelToken.source = function source() {
  var cancel;
  var token2 = new CancelToken(function executor(c3) {
    cancel = c3;
  });
  return {
    token: token2,
    cancel
  };
};
var CancelToken_1 = CancelToken;
var spread = function spread2(callback) {
  return function wrap(arr) {
    return callback.apply(null, arr);
  };
};
var isAxiosError = function isAxiosError2(payload) {
  return typeof payload === "object" && payload.isAxiosError === true;
};
function createInstance(defaultConfig) {
  var context2 = new Axios_1(defaultConfig);
  var instance2 = bind(Axios_1.prototype.request, context2);
  utils.extend(instance2, Axios_1.prototype, context2);
  utils.extend(instance2, context2);
  instance2.create = function create3(instanceConfig) {
    return createInstance(mergeConfig(defaultConfig, instanceConfig));
  };
  return instance2;
}
var axios = createInstance(defaults_1);
axios.Axios = Axios_1;
axios.Cancel = Cancel_1;
axios.CancelToken = CancelToken_1;
axios.isCancel = isCancel;
axios.VERSION = data.version;
axios.all = function all(promises) {
  return Promise.all(promises);
};
axios.spread = spread;
axios.isAxiosError = isAxiosError;
var axios_1 = axios;
var _default = axios;
axios_1.default = _default;
var axios$1 = axios_1;

// build/context/auth/AdminClient.js
var AdminClient = createContext(void 0);
var useAdminClient = () => useRequiredContext(AdminClient);
function useFetch(adminClientCall, callback, deps) {
  const adminClient = useAdminClient();
  const onError = useErrorHandler();
  useEffect(() => {
    const source2 = axios$1.CancelToken.source();
    adminClient.setConfig({
      requestConfig: {cancelToken: source2.token}
    });
    adminClientCall().then((result) => {
      if (!source2.token.reason) {
        callback(result);
      }
    }).catch((error2) => {
      if (!axios$1.isCancel(error2)) {
        onError(error2);
      }
    });
    adminClient.setConfig({
      requestConfig: {cancelToken: void 0}
    });
    return () => {
      source2.cancel();
    };
  }, deps);
}

// build/components/realm-selector/recent-used.js
var RecentUsed = class {
  constructor() {
    this.MAX_NUM = 4;
    this.KEY = "recent-used-realms";
    this.recentUsedRealms = JSON.parse(localStorage.getItem(this.KEY) || "[]");
  }
  save() {
    this.recentUsedRealms = this.recentUsedRealms.slice(0, this.MAX_NUM);
    localStorage.setItem(this.KEY, JSON.stringify(this.recentUsedRealms));
  }
  clean(existingRealms) {
    this.recentUsedRealms = this.recentUsedRealms.filter((realm2) => existingRealms.includes(realm2));
    this.save();
  }
  get used() {
    return this.recentUsedRealms;
  }
  setRecentUsed(realm2) {
    if (!this.recentUsedRealms.includes(realm2)) {
      this.recentUsedRealms.unshift(realm2);
      this.save();
    }
  }
};

// build/_snowpack/pkg/common/lodash-63f0b2ce.js
var lodash = createCommonjsModule(function(module2, exports2) {
  (function() {
    var undefined$1;
    var VERSION2 = "4.17.21";
    var LARGE_ARRAY_SIZE3 = 200;
    var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://npms.io/search?q=ponyfill.", FUNC_ERROR_TEXT2 = "Expected a function", INVALID_TEMPL_VAR_ERROR_TEXT = "Invalid `variable` option passed into `_.template`";
    var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
    var MAX_MEMOIZE_SIZE2 = 500;
    var PLACEHOLDER = "__lodash_placeholder__";
    var CLONE_DEEP_FLAG2 = 1, CLONE_FLAT_FLAG2 = 2, CLONE_SYMBOLS_FLAG2 = 4;
    var COMPARE_PARTIAL_FLAG3 = 1, COMPARE_UNORDERED_FLAG3 = 2;
    var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512;
    var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "...";
    var HOT_COUNT2 = 800, HOT_SPAN2 = 16;
    var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3;
    var INFINITY3 = 1 / 0, MAX_SAFE_INTEGER2 = 9007199254740991, MAX_INTEGER2 = 17976931348623157e292, NAN2 = 0 / 0;
    var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
    var wrapFlags = [
      ["ary", WRAP_ARY_FLAG],
      ["bind", WRAP_BIND_FLAG],
      ["bindKey", WRAP_BIND_KEY_FLAG],
      ["curry", WRAP_CURRY_FLAG],
      ["curryRight", WRAP_CURRY_RIGHT_FLAG],
      ["flip", WRAP_FLIP_FLAG],
      ["partial", WRAP_PARTIAL_FLAG],
      ["partialRight", WRAP_PARTIAL_RIGHT_FLAG],
      ["rearg", WRAP_REARG_FLAG]
    ];
    var argsTag3 = "[object Arguments]", arrayTag3 = "[object Array]", asyncTag2 = "[object AsyncFunction]", boolTag3 = "[object Boolean]", dateTag3 = "[object Date]", domExcTag = "[object DOMException]", errorTag3 = "[object Error]", funcTag3 = "[object Function]", genTag3 = "[object GeneratorFunction]", mapTag3 = "[object Map]", numberTag3 = "[object Number]", nullTag2 = "[object Null]", objectTag3 = "[object Object]", promiseTag2 = "[object Promise]", proxyTag2 = "[object Proxy]", regexpTag3 = "[object RegExp]", setTag3 = "[object Set]", stringTag3 = "[object String]", symbolTag4 = "[object Symbol]", undefinedTag2 = "[object Undefined]", weakMapTag3 = "[object WeakMap]", weakSetTag = "[object WeakSet]";
    var arrayBufferTag3 = "[object ArrayBuffer]", dataViewTag3 = "[object DataView]", float32Tag3 = "[object Float32Array]", float64Tag3 = "[object Float64Array]", int8Tag3 = "[object Int8Array]", int16Tag3 = "[object Int16Array]", int32Tag3 = "[object Int32Array]", uint8Tag3 = "[object Uint8Array]", uint8ClampedTag3 = "[object Uint8ClampedArray]", uint16Tag3 = "[object Uint16Array]", uint32Tag3 = "[object Uint32Array]";
    var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
    var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
    var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g;
    var reIsDeepProp2 = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp2 = /^\w*$/, rePropName2 = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
    var reRegExpChar2 = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar2.source);
    var reTrimStart2 = /^\s+/;
    var reWhitespace2 = /\s/;
    var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /;
    var reAsciiWord2 = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
    var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
    var reEscapeChar2 = /\\(\\)?/g;
    var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
    var reFlags2 = /\w*$/;
    var reIsBadHex2 = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary2 = /^0b[01]+$/i;
    var reIsHostCtor2 = /^\[object .+?Constructor\]$/;
    var reIsOctal2 = /^0o[0-7]+$/i;
    var reIsUint2 = /^(?:0|[1-9]\d*)$/;
    var reLatin2 = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
    var reNoMatch = /($^)/;
    var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
    var rsAstralRange3 = "\\ud800-\\udfff", rsComboMarksRange3 = "\\u0300-\\u036f", reComboHalfMarksRange2 = "\\ufe20-\\ufe2f", rsComboSymbolsRange3 = "\\u20d0-\\u20ff", rsComboRange2 = rsComboMarksRange3 + reComboHalfMarksRange2 + rsComboSymbolsRange3, rsDingbatRange2 = "\\u2700-\\u27bf", rsLowerRange2 = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange2 = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange2 = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange2 = "\\u2000-\\u206f", rsSpaceRange2 = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange2 = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange3 = "\\ufe0e\\ufe0f", rsBreakRange2 = rsMathOpRange2 + rsNonCharRange2 + rsPunctuationRange2 + rsSpaceRange2;
    var rsApos2 = "['’]", rsAstral3 = "[" + rsAstralRange3 + "]", rsBreak2 = "[" + rsBreakRange2 + "]", rsCombo3 = "[" + rsComboRange2 + "]", rsDigits2 = "\\d+", rsDingbat2 = "[" + rsDingbatRange2 + "]", rsLower2 = "[" + rsLowerRange2 + "]", rsMisc2 = "[^" + rsAstralRange3 + rsBreakRange2 + rsDigits2 + rsDingbatRange2 + rsLowerRange2 + rsUpperRange2 + "]", rsFitz3 = "\\ud83c[\\udffb-\\udfff]", rsModifier3 = "(?:" + rsCombo3 + "|" + rsFitz3 + ")", rsNonAstral3 = "[^" + rsAstralRange3 + "]", rsRegional3 = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair3 = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper2 = "[" + rsUpperRange2 + "]", rsZWJ3 = "\\u200d";
    var rsMiscLower = "(?:" + rsLower2 + "|" + rsMisc2 + ")", rsMiscUpper = "(?:" + rsUpper2 + "|" + rsMisc2 + ")", rsOptContrLower = "(?:" + rsApos2 + "(?:d|ll|m|re|s|t|ve))?", rsOptContrUpper = "(?:" + rsApos2 + "(?:D|LL|M|RE|S|T|VE))?", reOptMod3 = rsModifier3 + "?", rsOptVar3 = "[" + rsVarRange3 + "]?", rsOptJoin3 = "(?:" + rsZWJ3 + "(?:" + [rsNonAstral3, rsRegional3, rsSurrPair3].join("|") + ")" + rsOptVar3 + reOptMod3 + ")*", rsOrdLower = "\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])", rsOrdUpper = "\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])", rsSeq3 = rsOptVar3 + reOptMod3 + rsOptJoin3, rsEmoji2 = "(?:" + [rsDingbat2, rsRegional3, rsSurrPair3].join("|") + ")" + rsSeq3, rsSymbol3 = "(?:" + [rsNonAstral3 + rsCombo3 + "?", rsCombo3, rsRegional3, rsSurrPair3, rsAstral3].join("|") + ")";
    var reApos2 = RegExp(rsApos2, "g");
    var reComboMark2 = RegExp(rsCombo3, "g");
    var reUnicode3 = RegExp(rsFitz3 + "(?=" + rsFitz3 + ")|" + rsSymbol3 + rsSeq3, "g");
    var reUnicodeWord2 = RegExp([
      rsUpper2 + "?" + rsLower2 + "+" + rsOptContrLower + "(?=" + [rsBreak2, rsUpper2, "$"].join("|") + ")",
      rsMiscUpper + "+" + rsOptContrUpper + "(?=" + [rsBreak2, rsUpper2 + rsMiscLower, "$"].join("|") + ")",
      rsUpper2 + "?" + rsMiscLower + "+" + rsOptContrLower,
      rsUpper2 + "+" + rsOptContrUpper,
      rsOrdUpper,
      rsOrdLower,
      rsDigits2,
      rsEmoji2
    ].join("|"), "g");
    var reHasUnicode3 = RegExp("[" + rsZWJ3 + rsAstralRange3 + rsComboRange2 + rsVarRange3 + "]");
    var reHasUnicodeWord2 = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
    var contextProps = [
      "Array",
      "Buffer",
      "DataView",
      "Date",
      "Error",
      "Float32Array",
      "Float64Array",
      "Function",
      "Int8Array",
      "Int16Array",
      "Int32Array",
      "Map",
      "Math",
      "Object",
      "Promise",
      "RegExp",
      "Set",
      "String",
      "Symbol",
      "TypeError",
      "Uint8Array",
      "Uint8ClampedArray",
      "Uint16Array",
      "Uint32Array",
      "WeakMap",
      "_",
      "clearTimeout",
      "isFinite",
      "parseInt",
      "setTimeout"
    ];
    var templateCounter = -1;
    var typedArrayTags2 = {};
    typedArrayTags2[float32Tag3] = typedArrayTags2[float64Tag3] = typedArrayTags2[int8Tag3] = typedArrayTags2[int16Tag3] = typedArrayTags2[int32Tag3] = typedArrayTags2[uint8Tag3] = typedArrayTags2[uint8ClampedTag3] = typedArrayTags2[uint16Tag3] = typedArrayTags2[uint32Tag3] = true;
    typedArrayTags2[argsTag3] = typedArrayTags2[arrayTag3] = typedArrayTags2[arrayBufferTag3] = typedArrayTags2[boolTag3] = typedArrayTags2[dataViewTag3] = typedArrayTags2[dateTag3] = typedArrayTags2[errorTag3] = typedArrayTags2[funcTag3] = typedArrayTags2[mapTag3] = typedArrayTags2[numberTag3] = typedArrayTags2[objectTag3] = typedArrayTags2[regexpTag3] = typedArrayTags2[setTag3] = typedArrayTags2[stringTag3] = typedArrayTags2[weakMapTag3] = false;
    var cloneableTags2 = {};
    cloneableTags2[argsTag3] = cloneableTags2[arrayTag3] = cloneableTags2[arrayBufferTag3] = cloneableTags2[dataViewTag3] = cloneableTags2[boolTag3] = cloneableTags2[dateTag3] = cloneableTags2[float32Tag3] = cloneableTags2[float64Tag3] = cloneableTags2[int8Tag3] = cloneableTags2[int16Tag3] = cloneableTags2[int32Tag3] = cloneableTags2[mapTag3] = cloneableTags2[numberTag3] = cloneableTags2[objectTag3] = cloneableTags2[regexpTag3] = cloneableTags2[setTag3] = cloneableTags2[stringTag3] = cloneableTags2[symbolTag4] = cloneableTags2[uint8Tag3] = cloneableTags2[uint8ClampedTag3] = cloneableTags2[uint16Tag3] = cloneableTags2[uint32Tag3] = true;
    cloneableTags2[errorTag3] = cloneableTags2[funcTag3] = cloneableTags2[weakMapTag3] = false;
    var deburredLetters2 = {
      À: "A",
      Á: "A",
      Â: "A",
      Ã: "A",
      Ä: "A",
      Å: "A",
      à: "a",
      á: "a",
      â: "a",
      ã: "a",
      ä: "a",
      å: "a",
      Ç: "C",
      ç: "c",
      Ð: "D",
      ð: "d",
      È: "E",
      É: "E",
      Ê: "E",
      Ë: "E",
      è: "e",
      é: "e",
      ê: "e",
      ë: "e",
      Ì: "I",
      Í: "I",
      Î: "I",
      Ï: "I",
      ì: "i",
      í: "i",
      î: "i",
      ï: "i",
      Ñ: "N",
      ñ: "n",
      Ò: "O",
      Ó: "O",
      Ô: "O",
      Õ: "O",
      Ö: "O",
      Ø: "O",
      ò: "o",
      ó: "o",
      ô: "o",
      õ: "o",
      ö: "o",
      ø: "o",
      Ù: "U",
      Ú: "U",
      Û: "U",
      Ü: "U",
      ù: "u",
      ú: "u",
      û: "u",
      ü: "u",
      Ý: "Y",
      ý: "y",
      ÿ: "y",
      Æ: "Ae",
      æ: "ae",
      Þ: "Th",
      þ: "th",
      ß: "ss",
      Ā: "A",
      Ă: "A",
      Ą: "A",
      ā: "a",
      ă: "a",
      ą: "a",
      Ć: "C",
      Ĉ: "C",
      Ċ: "C",
      Č: "C",
      ć: "c",
      ĉ: "c",
      ċ: "c",
      č: "c",
      Ď: "D",
      Đ: "D",
      ď: "d",
      đ: "d",
      Ē: "E",
      Ĕ: "E",
      Ė: "E",
      Ę: "E",
      Ě: "E",
      ē: "e",
      ĕ: "e",
      ė: "e",
      ę: "e",
      ě: "e",
      Ĝ: "G",
      Ğ: "G",
      Ġ: "G",
      Ģ: "G",
      ĝ: "g",
      ğ: "g",
      ġ: "g",
      ģ: "g",
      Ĥ: "H",
      Ħ: "H",
      ĥ: "h",
      ħ: "h",
      Ĩ: "I",
      Ī: "I",
      Ĭ: "I",
      Į: "I",
      İ: "I",
      ĩ: "i",
      ī: "i",
      ĭ: "i",
      į: "i",
      ı: "i",
      Ĵ: "J",
      ĵ: "j",
      Ķ: "K",
      ķ: "k",
      ĸ: "k",
      Ĺ: "L",
      Ļ: "L",
      Ľ: "L",
      Ŀ: "L",
      Ł: "L",
      ĺ: "l",
      ļ: "l",
      ľ: "l",
      ŀ: "l",
      ł: "l",
      Ń: "N",
      Ņ: "N",
      Ň: "N",
      Ŋ: "N",
      ń: "n",
      ņ: "n",
      ň: "n",
      ŋ: "n",
      Ō: "O",
      Ŏ: "O",
      Ő: "O",
      ō: "o",
      ŏ: "o",
      ő: "o",
      Ŕ: "R",
      Ŗ: "R",
      Ř: "R",
      ŕ: "r",
      ŗ: "r",
      ř: "r",
      Ś: "S",
      Ŝ: "S",
      Ş: "S",
      Š: "S",
      ś: "s",
      ŝ: "s",
      ş: "s",
      š: "s",
      Ţ: "T",
      Ť: "T",
      Ŧ: "T",
      ţ: "t",
      ť: "t",
      ŧ: "t",
      Ũ: "U",
      Ū: "U",
      Ŭ: "U",
      Ů: "U",
      Ű: "U",
      Ų: "U",
      ũ: "u",
      ū: "u",
      ŭ: "u",
      ů: "u",
      ű: "u",
      ų: "u",
      Ŵ: "W",
      ŵ: "w",
      Ŷ: "Y",
      ŷ: "y",
      Ÿ: "Y",
      Ź: "Z",
      Ż: "Z",
      Ž: "Z",
      ź: "z",
      ż: "z",
      ž: "z",
      Ĳ: "IJ",
      ĳ: "ij",
      Œ: "Oe",
      œ: "oe",
      ŉ: "'n",
      ſ: "s"
    };
    var htmlEscapes = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#39;"
    };
    var htmlUnescapes = {
      "&amp;": "&",
      "&lt;": "<",
      "&gt;": ">",
      "&quot;": '"',
      "&#39;": "'"
    };
    var stringEscapes = {
      "\\": "\\",
      "'": "'",
      "\n": "n",
      "\r": "r",
      "\u2028": "u2028",
      "\u2029": "u2029"
    };
    var freeParseFloat = parseFloat, freeParseInt2 = parseInt;
    var freeGlobal3 = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
    var freeSelf3 = typeof self == "object" && self && self.Object === Object && self;
    var root4 = freeGlobal3 || freeSelf3 || Function("return this")();
    var freeExports = exports2 && !exports2.nodeType && exports2;
    var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var freeProcess = moduleExports && freeGlobal3.process;
    var nodeUtil = function() {
      try {
        var types2 = freeModule && freeModule.require && freeModule.require("util").types;
        if (types2) {
          return types2;
        }
        return freeProcess && freeProcess.binding && freeProcess.binding("util");
      } catch (e2) {
      }
    }();
    var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap2 = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet2 = nodeUtil && nodeUtil.isSet, nodeIsTypedArray2 = nodeUtil && nodeUtil.isTypedArray;
    function apply2(func, thisArg, args) {
      switch (args.length) {
        case 0:
          return func.call(thisArg);
        case 1:
          return func.call(thisArg, args[0]);
        case 2:
          return func.call(thisArg, args[0], args[1]);
        case 3:
          return func.call(thisArg, args[0], args[1], args[2]);
      }
      return func.apply(thisArg, args);
    }
    function arrayAggregator(array2, setter, iteratee, accumulator) {
      var index3 = -1, length = array2 == null ? 0 : array2.length;
      while (++index3 < length) {
        var value = array2[index3];
        setter(accumulator, value, iteratee(value), array2);
      }
      return accumulator;
    }
    function arrayEach2(array2, iteratee) {
      var index3 = -1, length = array2 == null ? 0 : array2.length;
      while (++index3 < length) {
        if (iteratee(array2[index3], index3, array2) === false) {
          break;
        }
      }
      return array2;
    }
    function arrayEachRight(array2, iteratee) {
      var length = array2 == null ? 0 : array2.length;
      while (length--) {
        if (iteratee(array2[length], length, array2) === false) {
          break;
        }
      }
      return array2;
    }
    function arrayEvery(array2, predicate) {
      var index3 = -1, length = array2 == null ? 0 : array2.length;
      while (++index3 < length) {
        if (!predicate(array2[index3], index3, array2)) {
          return false;
        }
      }
      return true;
    }
    function arrayFilter2(array2, predicate) {
      var index3 = -1, length = array2 == null ? 0 : array2.length, resIndex = 0, result = [];
      while (++index3 < length) {
        var value = array2[index3];
        if (predicate(value, index3, array2)) {
          result[resIndex++] = value;
        }
      }
      return result;
    }
    function arrayIncludes2(array2, value) {
      var length = array2 == null ? 0 : array2.length;
      return !!length && baseIndexOf2(array2, value, 0) > -1;
    }
    function arrayIncludesWith2(array2, value, comparator) {
      var index3 = -1, length = array2 == null ? 0 : array2.length;
      while (++index3 < length) {
        if (comparator(value, array2[index3])) {
          return true;
        }
      }
      return false;
    }
    function arrayMap2(array2, iteratee) {
      var index3 = -1, length = array2 == null ? 0 : array2.length, result = Array(length);
      while (++index3 < length) {
        result[index3] = iteratee(array2[index3], index3, array2);
      }
      return result;
    }
    function arrayPush2(array2, values2) {
      var index3 = -1, length = values2.length, offset2 = array2.length;
      while (++index3 < length) {
        array2[offset2 + index3] = values2[index3];
      }
      return array2;
    }
    function arrayReduce3(array2, iteratee, accumulator, initAccum) {
      var index3 = -1, length = array2 == null ? 0 : array2.length;
      if (initAccum && length) {
        accumulator = array2[++index3];
      }
      while (++index3 < length) {
        accumulator = iteratee(accumulator, array2[index3], index3, array2);
      }
      return accumulator;
    }
    function arrayReduceRight(array2, iteratee, accumulator, initAccum) {
      var length = array2 == null ? 0 : array2.length;
      if (initAccum && length) {
        accumulator = array2[--length];
      }
      while (length--) {
        accumulator = iteratee(accumulator, array2[length], length, array2);
      }
      return accumulator;
    }
    function arraySome2(array2, predicate) {
      var index3 = -1, length = array2 == null ? 0 : array2.length;
      while (++index3 < length) {
        if (predicate(array2[index3], index3, array2)) {
          return true;
        }
      }
      return false;
    }
    var asciiSize2 = baseProperty2("length");
    function asciiToArray2(string2) {
      return string2.split("");
    }
    function asciiWords2(string2) {
      return string2.match(reAsciiWord2) || [];
    }
    function baseFindKey(collection, predicate, eachFunc) {
      var result;
      eachFunc(collection, function(value, key, collection2) {
        if (predicate(value, key, collection2)) {
          result = key;
          return false;
        }
      });
      return result;
    }
    function baseFindIndex2(array2, predicate, fromIndex, fromRight) {
      var length = array2.length, index3 = fromIndex + (fromRight ? 1 : -1);
      while (fromRight ? index3-- : ++index3 < length) {
        if (predicate(array2[index3], index3, array2)) {
          return index3;
        }
      }
      return -1;
    }
    function baseIndexOf2(array2, value, fromIndex) {
      return value === value ? strictIndexOf2(array2, value, fromIndex) : baseFindIndex2(array2, baseIsNaN2, fromIndex);
    }
    function baseIndexOfWith(array2, value, fromIndex, comparator) {
      var index3 = fromIndex - 1, length = array2.length;
      while (++index3 < length) {
        if (comparator(array2[index3], value)) {
          return index3;
        }
      }
      return -1;
    }
    function baseIsNaN2(value) {
      return value !== value;
    }
    function baseMean(array2, iteratee) {
      var length = array2 == null ? 0 : array2.length;
      return length ? baseSum(array2, iteratee) / length : NAN2;
    }
    function baseProperty2(key) {
      return function(object) {
        return object == null ? undefined$1 : object[key];
      };
    }
    function basePropertyOf2(object) {
      return function(key) {
        return object == null ? undefined$1 : object[key];
      };
    }
    function baseReduce2(collection, iteratee, accumulator, initAccum, eachFunc) {
      eachFunc(collection, function(value, index3, collection2) {
        accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index3, collection2);
      });
      return accumulator;
    }
    function baseSortBy2(array2, comparer) {
      var length = array2.length;
      array2.sort(comparer);
      while (length--) {
        array2[length] = array2[length].value;
      }
      return array2;
    }
    function baseSum(array2, iteratee) {
      var result, index3 = -1, length = array2.length;
      while (++index3 < length) {
        var current = iteratee(array2[index3]);
        if (current !== undefined$1) {
          result = result === undefined$1 ? current : result + current;
        }
      }
      return result;
    }
    function baseTimes2(n3, iteratee) {
      var index3 = -1, result = Array(n3);
      while (++index3 < n3) {
        result[index3] = iteratee(index3);
      }
      return result;
    }
    function baseToPairs(object, props) {
      return arrayMap2(props, function(key) {
        return [key, object[key]];
      });
    }
    function baseTrim2(string2) {
      return string2 ? string2.slice(0, trimmedEndIndex2(string2) + 1).replace(reTrimStart2, "") : string2;
    }
    function baseUnary2(func) {
      return function(value) {
        return func(value);
      };
    }
    function baseValues2(object, props) {
      return arrayMap2(props, function(key) {
        return object[key];
      });
    }
    function cacheHas2(cache3, key) {
      return cache3.has(key);
    }
    function charsStartIndex(strSymbols, chrSymbols) {
      var index3 = -1, length = strSymbols.length;
      while (++index3 < length && baseIndexOf2(chrSymbols, strSymbols[index3], 0) > -1) {
      }
      return index3;
    }
    function charsEndIndex(strSymbols, chrSymbols) {
      var index3 = strSymbols.length;
      while (index3-- && baseIndexOf2(chrSymbols, strSymbols[index3], 0) > -1) {
      }
      return index3;
    }
    function countHolders(array2, placeholder) {
      var length = array2.length, result = 0;
      while (length--) {
        if (array2[length] === placeholder) {
          ++result;
        }
      }
      return result;
    }
    var deburrLetter2 = basePropertyOf2(deburredLetters2);
    var escapeHtmlChar = basePropertyOf2(htmlEscapes);
    function escapeStringChar(chr) {
      return "\\" + stringEscapes[chr];
    }
    function getValue2(object, key) {
      return object == null ? undefined$1 : object[key];
    }
    function hasUnicode3(string2) {
      return reHasUnicode3.test(string2);
    }
    function hasUnicodeWord2(string2) {
      return reHasUnicodeWord2.test(string2);
    }
    function iteratorToArray(iterator) {
      var data2, result = [];
      while (!(data2 = iterator.next()).done) {
        result.push(data2.value);
      }
      return result;
    }
    function mapToArray2(map2) {
      var index3 = -1, result = Array(map2.size);
      map2.forEach(function(value, key) {
        result[++index3] = [key, value];
      });
      return result;
    }
    function overArg2(func, transform3) {
      return function(arg) {
        return func(transform3(arg));
      };
    }
    function replaceHolders(array2, placeholder) {
      var index3 = -1, length = array2.length, resIndex = 0, result = [];
      while (++index3 < length) {
        var value = array2[index3];
        if (value === placeholder || value === PLACEHOLDER) {
          array2[index3] = PLACEHOLDER;
          result[resIndex++] = index3;
        }
      }
      return result;
    }
    function setToArray2(set3) {
      var index3 = -1, result = Array(set3.size);
      set3.forEach(function(value) {
        result[++index3] = value;
      });
      return result;
    }
    function setToPairs(set3) {
      var index3 = -1, result = Array(set3.size);
      set3.forEach(function(value) {
        result[++index3] = [value, value];
      });
      return result;
    }
    function strictIndexOf2(array2, value, fromIndex) {
      var index3 = fromIndex - 1, length = array2.length;
      while (++index3 < length) {
        if (array2[index3] === value) {
          return index3;
        }
      }
      return -1;
    }
    function strictLastIndexOf(array2, value, fromIndex) {
      var index3 = fromIndex + 1;
      while (index3--) {
        if (array2[index3] === value) {
          return index3;
        }
      }
      return index3;
    }
    function stringSize2(string2) {
      return hasUnicode3(string2) ? unicodeSize2(string2) : asciiSize2(string2);
    }
    function stringToArray2(string2) {
      return hasUnicode3(string2) ? unicodeToArray2(string2) : asciiToArray2(string2);
    }
    function trimmedEndIndex2(string2) {
      var index3 = string2.length;
      while (index3-- && reWhitespace2.test(string2.charAt(index3))) {
      }
      return index3;
    }
    var unescapeHtmlChar = basePropertyOf2(htmlUnescapes);
    function unicodeSize2(string2) {
      var result = reUnicode3.lastIndex = 0;
      while (reUnicode3.test(string2)) {
        ++result;
      }
      return result;
    }
    function unicodeToArray2(string2) {
      return string2.match(reUnicode3) || [];
    }
    function unicodeWords2(string2) {
      return string2.match(reUnicodeWord2) || [];
    }
    var runInContext = function runInContext2(context2) {
      context2 = context2 == null ? root4 : _23.defaults(root4.Object(), context2, _23.pick(root4, contextProps));
      var Array2 = context2.Array, Date2 = context2.Date, Error2 = context2.Error, Function2 = context2.Function, Math2 = context2.Math, Object2 = context2.Object, RegExp2 = context2.RegExp, String2 = context2.String, TypeError2 = context2.TypeError;
      var arrayProto2 = Array2.prototype, funcProto2 = Function2.prototype, objectProto4 = Object2.prototype;
      var coreJsData2 = context2["__core-js_shared__"];
      var funcToString2 = funcProto2.toString;
      var hasOwnProperty6 = objectProto4.hasOwnProperty;
      var idCounter2 = 0;
      var maskSrcKey2 = function() {
        var uid2 = /[^.]+$/.exec(coreJsData2 && coreJsData2.keys && coreJsData2.keys.IE_PROTO || "");
        return uid2 ? "Symbol(src)_1." + uid2 : "";
      }();
      var nativeObjectToString2 = objectProto4.toString;
      var objectCtorString2 = funcToString2.call(Object2);
      var oldDash = root4._;
      var reIsNative2 = RegExp2("^" + funcToString2.call(hasOwnProperty6).replace(reRegExpChar2, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
      var Buffer2 = moduleExports ? context2.Buffer : undefined$1, Symbol3 = context2.Symbol, Uint8Array3 = context2.Uint8Array, allocUnsafe = Buffer2 ? Buffer2.allocUnsafe : undefined$1, getPrototype2 = overArg2(Object2.getPrototypeOf, Object2), objectCreate2 = Object2.create, propertyIsEnumerable2 = objectProto4.propertyIsEnumerable, splice3 = arrayProto2.splice, spreadableSymbol2 = Symbol3 ? Symbol3.isConcatSpreadable : undefined$1, symIterator = Symbol3 ? Symbol3.iterator : undefined$1, symToStringTag2 = Symbol3 ? Symbol3.toStringTag : undefined$1;
      var defineProperty3 = function() {
        try {
          var func = getNative2(Object2, "defineProperty");
          func({}, "", {});
          return func;
        } catch (e2) {
        }
      }();
      var ctxClearTimeout = context2.clearTimeout !== root4.clearTimeout && context2.clearTimeout, ctxNow = Date2 && Date2.now !== root4.Date.now && Date2.now, ctxSetTimeout = context2.setTimeout !== root4.setTimeout && context2.setTimeout;
      var nativeCeil2 = Math2.ceil, nativeFloor = Math2.floor, nativeGetSymbols3 = Object2.getOwnPropertySymbols, nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : undefined$1, nativeIsFinite = context2.isFinite, nativeJoin = arrayProto2.join, nativeKeys2 = overArg2(Object2.keys, Object2), nativeMax3 = Math2.max, nativeMin = Math2.min, nativeNow2 = Date2.now, nativeParseInt = context2.parseInt, nativeRandom = Math2.random, nativeReverse = arrayProto2.reverse;
      var DataView3 = getNative2(context2, "DataView"), Map3 = getNative2(context2, "Map"), Promise3 = getNative2(context2, "Promise"), Set3 = getNative2(context2, "Set"), WeakMap3 = getNative2(context2, "WeakMap"), nativeCreate2 = getNative2(Object2, "create");
      var metaMap = WeakMap3 && new WeakMap3();
      var realNames = {};
      var dataViewCtorString2 = toSource2(DataView3), mapCtorString2 = toSource2(Map3), promiseCtorString2 = toSource2(Promise3), setCtorString2 = toSource2(Set3), weakMapCtorString2 = toSource2(WeakMap3);
      var symbolProto4 = Symbol3 ? Symbol3.prototype : undefined$1, symbolValueOf3 = symbolProto4 ? symbolProto4.valueOf : undefined$1, symbolToString3 = symbolProto4 ? symbolProto4.toString : undefined$1;
      function lodash3(value) {
        if (isObjectLike3(value) && !isArray3(value) && !(value instanceof LazyWrapper)) {
          if (value instanceof LodashWrapper) {
            return value;
          }
          if (hasOwnProperty6.call(value, "__wrapped__")) {
            return wrapperClone(value);
          }
        }
        return new LodashWrapper(value);
      }
      var baseCreate2 = function() {
        function object() {
        }
        return function(proto) {
          if (!isObject5(proto)) {
            return {};
          }
          if (objectCreate2) {
            return objectCreate2(proto);
          }
          object.prototype = proto;
          var result2 = new object();
          object.prototype = undefined$1;
          return result2;
        };
      }();
      function baseLodash() {
      }
      function LodashWrapper(value, chainAll) {
        this.__wrapped__ = value;
        this.__actions__ = [];
        this.__chain__ = !!chainAll;
        this.__index__ = 0;
        this.__values__ = undefined$1;
      }
      lodash3.templateSettings = {
        escape: reEscape,
        evaluate: reEvaluate,
        interpolate: reInterpolate,
        variable: "",
        imports: {
          _: lodash3
        }
      };
      lodash3.prototype = baseLodash.prototype;
      lodash3.prototype.constructor = lodash3;
      LodashWrapper.prototype = baseCreate2(baseLodash.prototype);
      LodashWrapper.prototype.constructor = LodashWrapper;
      function LazyWrapper(value) {
        this.__wrapped__ = value;
        this.__actions__ = [];
        this.__dir__ = 1;
        this.__filtered__ = false;
        this.__iteratees__ = [];
        this.__takeCount__ = MAX_ARRAY_LENGTH;
        this.__views__ = [];
      }
      function lazyClone() {
        var result2 = new LazyWrapper(this.__wrapped__);
        result2.__actions__ = copyArray2(this.__actions__);
        result2.__dir__ = this.__dir__;
        result2.__filtered__ = this.__filtered__;
        result2.__iteratees__ = copyArray2(this.__iteratees__);
        result2.__takeCount__ = this.__takeCount__;
        result2.__views__ = copyArray2(this.__views__);
        return result2;
      }
      function lazyReverse() {
        if (this.__filtered__) {
          var result2 = new LazyWrapper(this);
          result2.__dir__ = -1;
          result2.__filtered__ = true;
        } else {
          result2 = this.clone();
          result2.__dir__ *= -1;
        }
        return result2;
      }
      function lazyValue() {
        var array2 = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray3(array2), isRight = dir < 0, arrLength = isArr ? array2.length : 0, view = getView(0, arrLength, this.__views__), start3 = view.start, end2 = view.end, length = end2 - start3, index3 = isRight ? end2 : start3 - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__);
        if (!isArr || !isRight && arrLength == length && takeCount == length) {
          return baseWrapperValue(array2, this.__actions__);
        }
        var result2 = [];
        outer:
          while (length-- && resIndex < takeCount) {
            index3 += dir;
            var iterIndex = -1, value = array2[index3];
            while (++iterIndex < iterLength) {
              var data2 = iteratees[iterIndex], iteratee2 = data2.iteratee, type = data2.type, computed = iteratee2(value);
              if (type == LAZY_MAP_FLAG) {
                value = computed;
              } else if (!computed) {
                if (type == LAZY_FILTER_FLAG) {
                  continue outer;
                } else {
                  break outer;
                }
              }
            }
            result2[resIndex++] = value;
          }
        return result2;
      }
      LazyWrapper.prototype = baseCreate2(baseLodash.prototype);
      LazyWrapper.prototype.constructor = LazyWrapper;
      function Hash2(entries) {
        var index3 = -1, length = entries == null ? 0 : entries.length;
        this.clear();
        while (++index3 < length) {
          var entry = entries[index3];
          this.set(entry[0], entry[1]);
        }
      }
      function hashClear2() {
        this.__data__ = nativeCreate2 ? nativeCreate2(null) : {};
        this.size = 0;
      }
      function hashDelete2(key) {
        var result2 = this.has(key) && delete this.__data__[key];
        this.size -= result2 ? 1 : 0;
        return result2;
      }
      function hashGet2(key) {
        var data2 = this.__data__;
        if (nativeCreate2) {
          var result2 = data2[key];
          return result2 === HASH_UNDEFINED2 ? undefined$1 : result2;
        }
        return hasOwnProperty6.call(data2, key) ? data2[key] : undefined$1;
      }
      function hashHas2(key) {
        var data2 = this.__data__;
        return nativeCreate2 ? data2[key] !== undefined$1 : hasOwnProperty6.call(data2, key);
      }
      function hashSet2(key, value) {
        var data2 = this.__data__;
        this.size += this.has(key) ? 0 : 1;
        data2[key] = nativeCreate2 && value === undefined$1 ? HASH_UNDEFINED2 : value;
        return this;
      }
      Hash2.prototype.clear = hashClear2;
      Hash2.prototype["delete"] = hashDelete2;
      Hash2.prototype.get = hashGet2;
      Hash2.prototype.has = hashHas2;
      Hash2.prototype.set = hashSet2;
      function ListCache2(entries) {
        var index3 = -1, length = entries == null ? 0 : entries.length;
        this.clear();
        while (++index3 < length) {
          var entry = entries[index3];
          this.set(entry[0], entry[1]);
        }
      }
      function listCacheClear2() {
        this.__data__ = [];
        this.size = 0;
      }
      function listCacheDelete2(key) {
        var data2 = this.__data__, index3 = assocIndexOf2(data2, key);
        if (index3 < 0) {
          return false;
        }
        var lastIndex = data2.length - 1;
        if (index3 == lastIndex) {
          data2.pop();
        } else {
          splice3.call(data2, index3, 1);
        }
        --this.size;
        return true;
      }
      function listCacheGet2(key) {
        var data2 = this.__data__, index3 = assocIndexOf2(data2, key);
        return index3 < 0 ? undefined$1 : data2[index3][1];
      }
      function listCacheHas2(key) {
        return assocIndexOf2(this.__data__, key) > -1;
      }
      function listCacheSet2(key, value) {
        var data2 = this.__data__, index3 = assocIndexOf2(data2, key);
        if (index3 < 0) {
          ++this.size;
          data2.push([key, value]);
        } else {
          data2[index3][1] = value;
        }
        return this;
      }
      ListCache2.prototype.clear = listCacheClear2;
      ListCache2.prototype["delete"] = listCacheDelete2;
      ListCache2.prototype.get = listCacheGet2;
      ListCache2.prototype.has = listCacheHas2;
      ListCache2.prototype.set = listCacheSet2;
      function MapCache2(entries) {
        var index3 = -1, length = entries == null ? 0 : entries.length;
        this.clear();
        while (++index3 < length) {
          var entry = entries[index3];
          this.set(entry[0], entry[1]);
        }
      }
      function mapCacheClear2() {
        this.size = 0;
        this.__data__ = {
          hash: new Hash2(),
          map: new (Map3 || ListCache2)(),
          string: new Hash2()
        };
      }
      function mapCacheDelete2(key) {
        var result2 = getMapData2(this, key)["delete"](key);
        this.size -= result2 ? 1 : 0;
        return result2;
      }
      function mapCacheGet2(key) {
        return getMapData2(this, key).get(key);
      }
      function mapCacheHas2(key) {
        return getMapData2(this, key).has(key);
      }
      function mapCacheSet2(key, value) {
        var data2 = getMapData2(this, key), size3 = data2.size;
        data2.set(key, value);
        this.size += data2.size == size3 ? 0 : 1;
        return this;
      }
      MapCache2.prototype.clear = mapCacheClear2;
      MapCache2.prototype["delete"] = mapCacheDelete2;
      MapCache2.prototype.get = mapCacheGet2;
      MapCache2.prototype.has = mapCacheHas2;
      MapCache2.prototype.set = mapCacheSet2;
      function SetCache2(values3) {
        var index3 = -1, length = values3 == null ? 0 : values3.length;
        this.__data__ = new MapCache2();
        while (++index3 < length) {
          this.add(values3[index3]);
        }
      }
      function setCacheAdd2(value) {
        this.__data__.set(value, HASH_UNDEFINED2);
        return this;
      }
      function setCacheHas2(value) {
        return this.__data__.has(value);
      }
      SetCache2.prototype.add = SetCache2.prototype.push = setCacheAdd2;
      SetCache2.prototype.has = setCacheHas2;
      function Stack4(entries) {
        var data2 = this.__data__ = new ListCache2(entries);
        this.size = data2.size;
      }
      function stackClear2() {
        this.__data__ = new ListCache2();
        this.size = 0;
      }
      function stackDelete2(key) {
        var data2 = this.__data__, result2 = data2["delete"](key);
        this.size = data2.size;
        return result2;
      }
      function stackGet2(key) {
        return this.__data__.get(key);
      }
      function stackHas2(key) {
        return this.__data__.has(key);
      }
      function stackSet2(key, value) {
        var data2 = this.__data__;
        if (data2 instanceof ListCache2) {
          var pairs = data2.__data__;
          if (!Map3 || pairs.length < LARGE_ARRAY_SIZE3 - 1) {
            pairs.push([key, value]);
            this.size = ++data2.size;
            return this;
          }
          data2 = this.__data__ = new MapCache2(pairs);
        }
        data2.set(key, value);
        this.size = data2.size;
        return this;
      }
      Stack4.prototype.clear = stackClear2;
      Stack4.prototype["delete"] = stackDelete2;
      Stack4.prototype.get = stackGet2;
      Stack4.prototype.has = stackHas2;
      Stack4.prototype.set = stackSet2;
      function arrayLikeKeys2(value, inherited) {
        var isArr = isArray3(value), isArg = !isArr && isArguments2(value), isBuff = !isArr && !isArg && isBuffer3(value), isType = !isArr && !isArg && !isBuff && isTypedArray2(value), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes2(value.length, String2) : [], length = result2.length;
        for (var key in value) {
          if ((inherited || hasOwnProperty6.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || isIndex2(key, length)))) {
            result2.push(key);
          }
        }
        return result2;
      }
      function arraySample(array2) {
        var length = array2.length;
        return length ? array2[baseRandom(0, length - 1)] : undefined$1;
      }
      function arraySampleSize(array2, n3) {
        return shuffleSelf(copyArray2(array2), baseClamp(n3, 0, array2.length));
      }
      function arrayShuffle(array2) {
        return shuffleSelf(copyArray2(array2));
      }
      function assignMergeValue2(object, key, value) {
        if (value !== undefined$1 && !eq2(object[key], value) || value === undefined$1 && !(key in object)) {
          baseAssignValue2(object, key, value);
        }
      }
      function assignValue2(object, key, value) {
        var objValue = object[key];
        if (!(hasOwnProperty6.call(object, key) && eq2(objValue, value)) || value === undefined$1 && !(key in object)) {
          baseAssignValue2(object, key, value);
        }
      }
      function assocIndexOf2(array2, key) {
        var length = array2.length;
        while (length--) {
          if (eq2(array2[length][0], key)) {
            return length;
          }
        }
        return -1;
      }
      function baseAggregator(collection, setter, iteratee2, accumulator) {
        baseEach2(collection, function(value, key, collection2) {
          setter(accumulator, value, iteratee2(value), collection2);
        });
        return accumulator;
      }
      function baseAssign2(object, source2) {
        return object && copyObject2(source2, keys2(source2), object);
      }
      function baseAssignIn2(object, source2) {
        return object && copyObject2(source2, keysIn2(source2), object);
      }
      function baseAssignValue2(object, key, value) {
        if (key == "__proto__" && defineProperty3) {
          defineProperty3(object, key, {
            configurable: true,
            enumerable: true,
            value,
            writable: true
          });
        } else {
          object[key] = value;
        }
      }
      function baseAt(object, paths) {
        var index3 = -1, length = paths.length, result2 = Array2(length), skip = object == null;
        while (++index3 < length) {
          result2[index3] = skip ? undefined$1 : get7(object, paths[index3]);
        }
        return result2;
      }
      function baseClamp(number, lower2, upper) {
        if (number === number) {
          if (upper !== undefined$1) {
            number = number <= upper ? number : upper;
          }
          if (lower2 !== undefined$1) {
            number = number >= lower2 ? number : lower2;
          }
        }
        return number;
      }
      function baseClone2(value, bitmask, customizer, key, object, stack2) {
        var result2, isDeep = bitmask & CLONE_DEEP_FLAG2, isFlat = bitmask & CLONE_FLAT_FLAG2, isFull = bitmask & CLONE_SYMBOLS_FLAG2;
        if (customizer) {
          result2 = object ? customizer(value, key, object, stack2) : customizer(value);
        }
        if (result2 !== undefined$1) {
          return result2;
        }
        if (!isObject5(value)) {
          return value;
        }
        var isArr = isArray3(value);
        if (isArr) {
          result2 = initCloneArray2(value);
          if (!isDeep) {
            return copyArray2(value, result2);
          }
        } else {
          var tag = getTag2(value), isFunc = tag == funcTag3 || tag == genTag3;
          if (isBuffer3(value)) {
            return cloneBuffer(value, isDeep);
          }
          if (tag == objectTag3 || tag == argsTag3 || isFunc && !object) {
            result2 = isFlat || isFunc ? {} : initCloneObject2(value);
            if (!isDeep) {
              return isFlat ? copySymbolsIn2(value, baseAssignIn2(result2, value)) : copySymbols2(value, baseAssign2(result2, value));
            }
          } else {
            if (!cloneableTags2[tag]) {
              return object ? value : {};
            }
            result2 = initCloneByTag2(value, tag, isDeep);
          }
        }
        stack2 || (stack2 = new Stack4());
        var stacked = stack2.get(value);
        if (stacked) {
          return stacked;
        }
        stack2.set(value, result2);
        if (isSet2(value)) {
          value.forEach(function(subValue) {
            result2.add(baseClone2(subValue, bitmask, customizer, subValue, value, stack2));
          });
        } else if (isMap2(value)) {
          value.forEach(function(subValue, key2) {
            result2.set(key2, baseClone2(subValue, bitmask, customizer, key2, value, stack2));
          });
        }
        var keysFunc = isFull ? isFlat ? getAllKeysIn2 : getAllKeys2 : isFlat ? keysIn2 : keys2;
        var props = isArr ? undefined$1 : keysFunc(value);
        arrayEach2(props || value, function(subValue, key2) {
          if (props) {
            key2 = subValue;
            subValue = value[key2];
          }
          assignValue2(result2, key2, baseClone2(subValue, bitmask, customizer, key2, value, stack2));
        });
        return result2;
      }
      function baseConforms(source2) {
        var props = keys2(source2);
        return function(object) {
          return baseConformsTo(object, source2, props);
        };
      }
      function baseConformsTo(object, source2, props) {
        var length = props.length;
        if (object == null) {
          return !length;
        }
        object = Object2(object);
        while (length--) {
          var key = props[length], predicate = source2[key], value = object[key];
          if (value === undefined$1 && !(key in object) || !predicate(value)) {
            return false;
          }
        }
        return true;
      }
      function baseDelay(func, wait, args) {
        if (typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT2);
        }
        return setTimeout2(function() {
          func.apply(undefined$1, args);
        }, wait);
      }
      function baseDifference(array2, values3, iteratee2, comparator) {
        var index3 = -1, includes2 = arrayIncludes2, isCommon = true, length = array2.length, result2 = [], valuesLength = values3.length;
        if (!length) {
          return result2;
        }
        if (iteratee2) {
          values3 = arrayMap2(values3, baseUnary2(iteratee2));
        }
        if (comparator) {
          includes2 = arrayIncludesWith2;
          isCommon = false;
        } else if (values3.length >= LARGE_ARRAY_SIZE3) {
          includes2 = cacheHas2;
          isCommon = false;
          values3 = new SetCache2(values3);
        }
        outer:
          while (++index3 < length) {
            var value = array2[index3], computed = iteratee2 == null ? value : iteratee2(value);
            value = comparator || value !== 0 ? value : 0;
            if (isCommon && computed === computed) {
              var valuesIndex = valuesLength;
              while (valuesIndex--) {
                if (values3[valuesIndex] === computed) {
                  continue outer;
                }
              }
              result2.push(value);
            } else if (!includes2(values3, computed, comparator)) {
              result2.push(value);
            }
          }
        return result2;
      }
      var baseEach2 = createBaseEach2(baseForOwn2);
      var baseEachRight = createBaseEach2(baseForOwnRight, true);
      function baseEvery(collection, predicate) {
        var result2 = true;
        baseEach2(collection, function(value, index3, collection2) {
          result2 = !!predicate(value, index3, collection2);
          return result2;
        });
        return result2;
      }
      function baseExtremum2(array2, iteratee2, comparator) {
        var index3 = -1, length = array2.length;
        while (++index3 < length) {
          var value = array2[index3], current = iteratee2(value);
          if (current != null && (computed === undefined$1 ? current === current && !isSymbol3(current) : comparator(current, computed))) {
            var computed = current, result2 = value;
          }
        }
        return result2;
      }
      function baseFill(array2, value, start3, end2) {
        var length = array2.length;
        start3 = toInteger2(start3);
        if (start3 < 0) {
          start3 = -start3 > length ? 0 : length + start3;
        }
        end2 = end2 === undefined$1 || end2 > length ? length : toInteger2(end2);
        if (end2 < 0) {
          end2 += length;
        }
        end2 = start3 > end2 ? 0 : toLength(end2);
        while (start3 < end2) {
          array2[start3++] = value;
        }
        return array2;
      }
      function baseFilter2(collection, predicate) {
        var result2 = [];
        baseEach2(collection, function(value, index3, collection2) {
          if (predicate(value, index3, collection2)) {
            result2.push(value);
          }
        });
        return result2;
      }
      function baseFlatten2(array2, depth, predicate, isStrict, result2) {
        var index3 = -1, length = array2.length;
        predicate || (predicate = isFlattenable2);
        result2 || (result2 = []);
        while (++index3 < length) {
          var value = array2[index3];
          if (depth > 0 && predicate(value)) {
            if (depth > 1) {
              baseFlatten2(value, depth - 1, predicate, isStrict, result2);
            } else {
              arrayPush2(result2, value);
            }
          } else if (!isStrict) {
            result2[result2.length] = value;
          }
        }
        return result2;
      }
      var baseFor2 = createBaseFor2();
      var baseForRight = createBaseFor2(true);
      function baseForOwn2(object, iteratee2) {
        return object && baseFor2(object, iteratee2, keys2);
      }
      function baseForOwnRight(object, iteratee2) {
        return object && baseForRight(object, iteratee2, keys2);
      }
      function baseFunctions(object, props) {
        return arrayFilter2(props, function(key) {
          return isFunction6(object[key]);
        });
      }
      function baseGet3(object, path) {
        path = castPath2(path, object);
        var index3 = 0, length = path.length;
        while (object != null && index3 < length) {
          object = object[toKey2(path[index3++])];
        }
        return index3 && index3 == length ? object : undefined$1;
      }
      function baseGetAllKeys2(object, keysFunc, symbolsFunc) {
        var result2 = keysFunc(object);
        return isArray3(object) ? result2 : arrayPush2(result2, symbolsFunc(object));
      }
      function baseGetTag2(value) {
        if (value == null) {
          return value === undefined$1 ? undefinedTag2 : nullTag2;
        }
        return symToStringTag2 && symToStringTag2 in Object2(value) ? getRawTag2(value) : objectToString3(value);
      }
      function baseGt2(value, other) {
        return value > other;
      }
      function baseHas2(object, key) {
        return object != null && hasOwnProperty6.call(object, key);
      }
      function baseHasIn2(object, key) {
        return object != null && key in Object2(object);
      }
      function baseInRange(number, start3, end2) {
        return number >= nativeMin(start3, end2) && number < nativeMax3(start3, end2);
      }
      function baseIntersection(arrays, iteratee2, comparator) {
        var includes2 = comparator ? arrayIncludesWith2 : arrayIncludes2, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array2(othLength), maxLength = Infinity, result2 = [];
        while (othIndex--) {
          var array2 = arrays[othIndex];
          if (othIndex && iteratee2) {
            array2 = arrayMap2(array2, baseUnary2(iteratee2));
          }
          maxLength = nativeMin(array2.length, maxLength);
          caches[othIndex] = !comparator && (iteratee2 || length >= 120 && array2.length >= 120) ? new SetCache2(othIndex && array2) : undefined$1;
        }
        array2 = arrays[0];
        var index3 = -1, seen = caches[0];
        outer:
          while (++index3 < length && result2.length < maxLength) {
            var value = array2[index3], computed = iteratee2 ? iteratee2(value) : value;
            value = comparator || value !== 0 ? value : 0;
            if (!(seen ? cacheHas2(seen, computed) : includes2(result2, computed, comparator))) {
              othIndex = othLength;
              while (--othIndex) {
                var cache3 = caches[othIndex];
                if (!(cache3 ? cacheHas2(cache3, computed) : includes2(arrays[othIndex], computed, comparator))) {
                  continue outer;
                }
              }
              if (seen) {
                seen.push(computed);
              }
              result2.push(value);
            }
          }
        return result2;
      }
      function baseInverter(object, setter, iteratee2, accumulator) {
        baseForOwn2(object, function(value, key, object2) {
          setter(accumulator, iteratee2(value), key, object2);
        });
        return accumulator;
      }
      function baseInvoke(object, path, args) {
        path = castPath2(path, object);
        object = parent(object, path);
        var func = object == null ? object : object[toKey2(last2(path))];
        return func == null ? undefined$1 : apply2(func, object, args);
      }
      function baseIsArguments2(value) {
        return isObjectLike3(value) && baseGetTag2(value) == argsTag3;
      }
      function baseIsArrayBuffer(value) {
        return isObjectLike3(value) && baseGetTag2(value) == arrayBufferTag3;
      }
      function baseIsDate(value) {
        return isObjectLike3(value) && baseGetTag2(value) == dateTag3;
      }
      function baseIsEqual2(value, other, bitmask, customizer, stack2) {
        if (value === other) {
          return true;
        }
        if (value == null || other == null || !isObjectLike3(value) && !isObjectLike3(other)) {
          return value !== value && other !== other;
        }
        return baseIsEqualDeep2(value, other, bitmask, customizer, baseIsEqual2, stack2);
      }
      function baseIsEqualDeep2(object, other, bitmask, customizer, equalFunc, stack2) {
        var objIsArr = isArray3(object), othIsArr = isArray3(other), objTag = objIsArr ? arrayTag3 : getTag2(object), othTag = othIsArr ? arrayTag3 : getTag2(other);
        objTag = objTag == argsTag3 ? objectTag3 : objTag;
        othTag = othTag == argsTag3 ? objectTag3 : othTag;
        var objIsObj = objTag == objectTag3, othIsObj = othTag == objectTag3, isSameTag = objTag == othTag;
        if (isSameTag && isBuffer3(object)) {
          if (!isBuffer3(other)) {
            return false;
          }
          objIsArr = true;
          objIsObj = false;
        }
        if (isSameTag && !objIsObj) {
          stack2 || (stack2 = new Stack4());
          return objIsArr || isTypedArray2(object) ? equalArrays2(object, other, bitmask, customizer, equalFunc, stack2) : equalByTag2(object, other, objTag, bitmask, customizer, equalFunc, stack2);
        }
        if (!(bitmask & COMPARE_PARTIAL_FLAG3)) {
          var objIsWrapped = objIsObj && hasOwnProperty6.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty6.call(other, "__wrapped__");
          if (objIsWrapped || othIsWrapped) {
            var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
            stack2 || (stack2 = new Stack4());
            return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack2);
          }
        }
        if (!isSameTag) {
          return false;
        }
        stack2 || (stack2 = new Stack4());
        return equalObjects2(object, other, bitmask, customizer, equalFunc, stack2);
      }
      function baseIsMap2(value) {
        return isObjectLike3(value) && getTag2(value) == mapTag3;
      }
      function baseIsMatch2(object, source2, matchData, customizer) {
        var index3 = matchData.length, length = index3, noCustomizer = !customizer;
        if (object == null) {
          return !length;
        }
        object = Object2(object);
        while (index3--) {
          var data2 = matchData[index3];
          if (noCustomizer && data2[2] ? data2[1] !== object[data2[0]] : !(data2[0] in object)) {
            return false;
          }
        }
        while (++index3 < length) {
          data2 = matchData[index3];
          var key = data2[0], objValue = object[key], srcValue = data2[1];
          if (noCustomizer && data2[2]) {
            if (objValue === undefined$1 && !(key in object)) {
              return false;
            }
          } else {
            var stack2 = new Stack4();
            if (customizer) {
              var result2 = customizer(objValue, srcValue, key, object, source2, stack2);
            }
            if (!(result2 === undefined$1 ? baseIsEqual2(srcValue, objValue, COMPARE_PARTIAL_FLAG3 | COMPARE_UNORDERED_FLAG3, customizer, stack2) : result2)) {
              return false;
            }
          }
        }
        return true;
      }
      function baseIsNative2(value) {
        if (!isObject5(value) || isMasked2(value)) {
          return false;
        }
        var pattern = isFunction6(value) ? reIsNative2 : reIsHostCtor2;
        return pattern.test(toSource2(value));
      }
      function baseIsRegExp(value) {
        return isObjectLike3(value) && baseGetTag2(value) == regexpTag3;
      }
      function baseIsSet2(value) {
        return isObjectLike3(value) && getTag2(value) == setTag3;
      }
      function baseIsTypedArray2(value) {
        return isObjectLike3(value) && isLength2(value.length) && !!typedArrayTags2[baseGetTag2(value)];
      }
      function baseIteratee2(value) {
        if (typeof value == "function") {
          return value;
        }
        if (value == null) {
          return identity3;
        }
        if (typeof value == "object") {
          return isArray3(value) ? baseMatchesProperty2(value[0], value[1]) : baseMatches2(value);
        }
        return property2(value);
      }
      function baseKeys2(object) {
        if (!isPrototype2(object)) {
          return nativeKeys2(object);
        }
        var result2 = [];
        for (var key in Object2(object)) {
          if (hasOwnProperty6.call(object, key) && key != "constructor") {
            result2.push(key);
          }
        }
        return result2;
      }
      function baseKeysIn2(object) {
        if (!isObject5(object)) {
          return nativeKeysIn2(object);
        }
        var isProto = isPrototype2(object), result2 = [];
        for (var key in object) {
          if (!(key == "constructor" && (isProto || !hasOwnProperty6.call(object, key)))) {
            result2.push(key);
          }
        }
        return result2;
      }
      function baseLt2(value, other) {
        return value < other;
      }
      function baseMap2(collection, iteratee2) {
        var index3 = -1, result2 = isArrayLike2(collection) ? Array2(collection.length) : [];
        baseEach2(collection, function(value, key, collection2) {
          result2[++index3] = iteratee2(value, key, collection2);
        });
        return result2;
      }
      function baseMatches2(source2) {
        var matchData = getMatchData2(source2);
        if (matchData.length == 1 && matchData[0][2]) {
          return matchesStrictComparable2(matchData[0][0], matchData[0][1]);
        }
        return function(object) {
          return object === source2 || baseIsMatch2(object, source2, matchData);
        };
      }
      function baseMatchesProperty2(path, srcValue) {
        if (isKey3(path) && isStrictComparable2(srcValue)) {
          return matchesStrictComparable2(toKey2(path), srcValue);
        }
        return function(object) {
          var objValue = get7(object, path);
          return objValue === undefined$1 && objValue === srcValue ? hasIn2(object, path) : baseIsEqual2(srcValue, objValue, COMPARE_PARTIAL_FLAG3 | COMPARE_UNORDERED_FLAG3);
        };
      }
      function baseMerge2(object, source2, srcIndex, customizer, stack2) {
        if (object === source2) {
          return;
        }
        baseFor2(source2, function(srcValue, key) {
          stack2 || (stack2 = new Stack4());
          if (isObject5(srcValue)) {
            baseMergeDeep2(object, source2, key, srcIndex, baseMerge2, customizer, stack2);
          } else {
            var newValue = customizer ? customizer(safeGet2(object, key), srcValue, key + "", object, source2, stack2) : undefined$1;
            if (newValue === undefined$1) {
              newValue = srcValue;
            }
            assignMergeValue2(object, key, newValue);
          }
        }, keysIn2);
      }
      function baseMergeDeep2(object, source2, key, srcIndex, mergeFunc, customizer, stack2) {
        var objValue = safeGet2(object, key), srcValue = safeGet2(source2, key), stacked = stack2.get(srcValue);
        if (stacked) {
          assignMergeValue2(object, key, stacked);
          return;
        }
        var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source2, stack2) : undefined$1;
        var isCommon = newValue === undefined$1;
        if (isCommon) {
          var isArr = isArray3(srcValue), isBuff = !isArr && isBuffer3(srcValue), isTyped = !isArr && !isBuff && isTypedArray2(srcValue);
          newValue = srcValue;
          if (isArr || isBuff || isTyped) {
            if (isArray3(objValue)) {
              newValue = objValue;
            } else if (isArrayLikeObject2(objValue)) {
              newValue = copyArray2(objValue);
            } else if (isBuff) {
              isCommon = false;
              newValue = cloneBuffer(srcValue, true);
            } else if (isTyped) {
              isCommon = false;
              newValue = cloneTypedArray2(srcValue, true);
            } else {
              newValue = [];
            }
          } else if (isPlainObject4(srcValue) || isArguments2(srcValue)) {
            newValue = objValue;
            if (isArguments2(objValue)) {
              newValue = toPlainObject2(objValue);
            } else if (!isObject5(objValue) || isFunction6(objValue)) {
              newValue = initCloneObject2(srcValue);
            }
          } else {
            isCommon = false;
          }
        }
        if (isCommon) {
          stack2.set(srcValue, newValue);
          mergeFunc(newValue, srcValue, srcIndex, customizer, stack2);
          stack2["delete"](srcValue);
        }
        assignMergeValue2(object, key, newValue);
      }
      function baseNth(array2, n3) {
        var length = array2.length;
        if (!length) {
          return;
        }
        n3 += n3 < 0 ? length : 0;
        return isIndex2(n3, length) ? array2[n3] : undefined$1;
      }
      function baseOrderBy2(collection, iteratees, orders) {
        if (iteratees.length) {
          iteratees = arrayMap2(iteratees, function(iteratee2) {
            if (isArray3(iteratee2)) {
              return function(value) {
                return baseGet3(value, iteratee2.length === 1 ? iteratee2[0] : iteratee2);
              };
            }
            return iteratee2;
          });
        } else {
          iteratees = [identity3];
        }
        var index3 = -1;
        iteratees = arrayMap2(iteratees, baseUnary2(getIteratee()));
        var result2 = baseMap2(collection, function(value, key, collection2) {
          var criteria = arrayMap2(iteratees, function(iteratee2) {
            return iteratee2(value);
          });
          return {criteria, index: ++index3, value};
        });
        return baseSortBy2(result2, function(object, other) {
          return compareMultiple2(object, other, orders);
        });
      }
      function basePick2(object, paths) {
        return basePickBy2(object, paths, function(value, path) {
          return hasIn2(object, path);
        });
      }
      function basePickBy2(object, paths, predicate) {
        var index3 = -1, length = paths.length, result2 = {};
        while (++index3 < length) {
          var path = paths[index3], value = baseGet3(object, path);
          if (predicate(value, path)) {
            baseSet2(result2, castPath2(path, object), value);
          }
        }
        return result2;
      }
      function basePropertyDeep2(path) {
        return function(object) {
          return baseGet3(object, path);
        };
      }
      function basePullAll(array2, values3, iteratee2, comparator) {
        var indexOf2 = comparator ? baseIndexOfWith : baseIndexOf2, index3 = -1, length = values3.length, seen = array2;
        if (array2 === values3) {
          values3 = copyArray2(values3);
        }
        if (iteratee2) {
          seen = arrayMap2(array2, baseUnary2(iteratee2));
        }
        while (++index3 < length) {
          var fromIndex = 0, value = values3[index3], computed = iteratee2 ? iteratee2(value) : value;
          while ((fromIndex = indexOf2(seen, computed, fromIndex, comparator)) > -1) {
            if (seen !== array2) {
              splice3.call(seen, fromIndex, 1);
            }
            splice3.call(array2, fromIndex, 1);
          }
        }
        return array2;
      }
      function basePullAt(array2, indexes) {
        var length = array2 ? indexes.length : 0, lastIndex = length - 1;
        while (length--) {
          var index3 = indexes[length];
          if (length == lastIndex || index3 !== previous) {
            var previous = index3;
            if (isIndex2(index3)) {
              splice3.call(array2, index3, 1);
            } else {
              baseUnset(array2, index3);
            }
          }
        }
        return array2;
      }
      function baseRandom(lower2, upper) {
        return lower2 + nativeFloor(nativeRandom() * (upper - lower2 + 1));
      }
      function baseRange2(start3, end2, step, fromRight) {
        var index3 = -1, length = nativeMax3(nativeCeil2((end2 - start3) / (step || 1)), 0), result2 = Array2(length);
        while (length--) {
          result2[fromRight ? length : ++index3] = start3;
          start3 += step;
        }
        return result2;
      }
      function baseRepeat(string2, n3) {
        var result2 = "";
        if (!string2 || n3 < 1 || n3 > MAX_SAFE_INTEGER2) {
          return result2;
        }
        do {
          if (n3 % 2) {
            result2 += string2;
          }
          n3 = nativeFloor(n3 / 2);
          if (n3) {
            string2 += string2;
          }
        } while (n3);
        return result2;
      }
      function baseRest2(func, start3) {
        return setToString2(overRest2(func, start3, identity3), func + "");
      }
      function baseSample(collection) {
        return arraySample(values2(collection));
      }
      function baseSampleSize(collection, n3) {
        var array2 = values2(collection);
        return shuffleSelf(array2, baseClamp(n3, 0, array2.length));
      }
      function baseSet2(object, path, value, customizer) {
        if (!isObject5(object)) {
          return object;
        }
        path = castPath2(path, object);
        var index3 = -1, length = path.length, lastIndex = length - 1, nested = object;
        while (nested != null && ++index3 < length) {
          var key = toKey2(path[index3]), newValue = value;
          if (key === "__proto__" || key === "constructor" || key === "prototype") {
            return object;
          }
          if (index3 != lastIndex) {
            var objValue = nested[key];
            newValue = customizer ? customizer(objValue, key, nested) : undefined$1;
            if (newValue === undefined$1) {
              newValue = isObject5(objValue) ? objValue : isIndex2(path[index3 + 1]) ? [] : {};
            }
          }
          assignValue2(nested, key, newValue);
          nested = nested[key];
        }
        return object;
      }
      var baseSetData = !metaMap ? identity3 : function(func, data2) {
        metaMap.set(func, data2);
        return func;
      };
      var baseSetToString2 = !defineProperty3 ? identity3 : function(func, string2) {
        return defineProperty3(func, "toString", {
          configurable: true,
          enumerable: false,
          value: constant3(string2),
          writable: true
        });
      };
      function baseShuffle(collection) {
        return shuffleSelf(values2(collection));
      }
      function baseSlice2(array2, start3, end2) {
        var index3 = -1, length = array2.length;
        if (start3 < 0) {
          start3 = -start3 > length ? 0 : length + start3;
        }
        end2 = end2 > length ? length : end2;
        if (end2 < 0) {
          end2 += length;
        }
        length = start3 > end2 ? 0 : end2 - start3 >>> 0;
        start3 >>>= 0;
        var result2 = Array2(length);
        while (++index3 < length) {
          result2[index3] = array2[index3 + start3];
        }
        return result2;
      }
      function baseSome(collection, predicate) {
        var result2;
        baseEach2(collection, function(value, index3, collection2) {
          result2 = predicate(value, index3, collection2);
          return !result2;
        });
        return !!result2;
      }
      function baseSortedIndex(array2, value, retHighest) {
        var low = 0, high = array2 == null ? low : array2.length;
        if (typeof value == "number" && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
          while (low < high) {
            var mid = low + high >>> 1, computed = array2[mid];
            if (computed !== null && !isSymbol3(computed) && (retHighest ? computed <= value : computed < value)) {
              low = mid + 1;
            } else {
              high = mid;
            }
          }
          return high;
        }
        return baseSortedIndexBy(array2, value, identity3, retHighest);
      }
      function baseSortedIndexBy(array2, value, iteratee2, retHighest) {
        var low = 0, high = array2 == null ? 0 : array2.length;
        if (high === 0) {
          return 0;
        }
        value = iteratee2(value);
        var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol3(value), valIsUndefined = value === undefined$1;
        while (low < high) {
          var mid = nativeFloor((low + high) / 2), computed = iteratee2(array2[mid]), othIsDefined = computed !== undefined$1, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol3(computed);
          if (valIsNaN) {
            var setLow = retHighest || othIsReflexive;
          } else if (valIsUndefined) {
            setLow = othIsReflexive && (retHighest || othIsDefined);
          } else if (valIsNull) {
            setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
          } else if (valIsSymbol) {
            setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
          } else if (othIsNull || othIsSymbol) {
            setLow = false;
          } else {
            setLow = retHighest ? computed <= value : computed < value;
          }
          if (setLow) {
            low = mid + 1;
          } else {
            high = mid;
          }
        }
        return nativeMin(high, MAX_ARRAY_INDEX);
      }
      function baseSortedUniq(array2, iteratee2) {
        var index3 = -1, length = array2.length, resIndex = 0, result2 = [];
        while (++index3 < length) {
          var value = array2[index3], computed = iteratee2 ? iteratee2(value) : value;
          if (!index3 || !eq2(computed, seen)) {
            var seen = computed;
            result2[resIndex++] = value === 0 ? 0 : value;
          }
        }
        return result2;
      }
      function baseToNumber(value) {
        if (typeof value == "number") {
          return value;
        }
        if (isSymbol3(value)) {
          return NAN2;
        }
        return +value;
      }
      function baseToString3(value) {
        if (typeof value == "string") {
          return value;
        }
        if (isArray3(value)) {
          return arrayMap2(value, baseToString3) + "";
        }
        if (isSymbol3(value)) {
          return symbolToString3 ? symbolToString3.call(value) : "";
        }
        var result2 = value + "";
        return result2 == "0" && 1 / value == -INFINITY3 ? "-0" : result2;
      }
      function baseUniq2(array2, iteratee2, comparator) {
        var index3 = -1, includes2 = arrayIncludes2, length = array2.length, isCommon = true, result2 = [], seen = result2;
        if (comparator) {
          isCommon = false;
          includes2 = arrayIncludesWith2;
        } else if (length >= LARGE_ARRAY_SIZE3) {
          var set4 = iteratee2 ? null : createSet2(array2);
          if (set4) {
            return setToArray2(set4);
          }
          isCommon = false;
          includes2 = cacheHas2;
          seen = new SetCache2();
        } else {
          seen = iteratee2 ? [] : result2;
        }
        outer:
          while (++index3 < length) {
            var value = array2[index3], computed = iteratee2 ? iteratee2(value) : value;
            value = comparator || value !== 0 ? value : 0;
            if (isCommon && computed === computed) {
              var seenIndex = seen.length;
              while (seenIndex--) {
                if (seen[seenIndex] === computed) {
                  continue outer;
                }
              }
              if (iteratee2) {
                seen.push(computed);
              }
              result2.push(value);
            } else if (!includes2(seen, computed, comparator)) {
              if (seen !== result2) {
                seen.push(computed);
              }
              result2.push(value);
            }
          }
        return result2;
      }
      function baseUnset(object, path) {
        path = castPath2(path, object);
        object = parent(object, path);
        return object == null || delete object[toKey2(last2(path))];
      }
      function baseUpdate(object, path, updater, customizer) {
        return baseSet2(object, path, updater(baseGet3(object, path)), customizer);
      }
      function baseWhile(array2, predicate, isDrop, fromRight) {
        var length = array2.length, index3 = fromRight ? length : -1;
        while ((fromRight ? index3-- : ++index3 < length) && predicate(array2[index3], index3, array2)) {
        }
        return isDrop ? baseSlice2(array2, fromRight ? 0 : index3, fromRight ? index3 + 1 : length) : baseSlice2(array2, fromRight ? index3 + 1 : 0, fromRight ? length : index3);
      }
      function baseWrapperValue(value, actions2) {
        var result2 = value;
        if (result2 instanceof LazyWrapper) {
          result2 = result2.value();
        }
        return arrayReduce3(actions2, function(result3, action) {
          return action.func.apply(action.thisArg, arrayPush2([result3], action.args));
        }, result2);
      }
      function baseXor(arrays, iteratee2, comparator) {
        var length = arrays.length;
        if (length < 2) {
          return length ? baseUniq2(arrays[0]) : [];
        }
        var index3 = -1, result2 = Array2(length);
        while (++index3 < length) {
          var array2 = arrays[index3], othIndex = -1;
          while (++othIndex < length) {
            if (othIndex != index3) {
              result2[index3] = baseDifference(result2[index3] || array2, arrays[othIndex], iteratee2, comparator);
            }
          }
        }
        return baseUniq2(baseFlatten2(result2, 1), iteratee2, comparator);
      }
      function baseZipObject2(props, values3, assignFunc) {
        var index3 = -1, length = props.length, valsLength = values3.length, result2 = {};
        while (++index3 < length) {
          var value = index3 < valsLength ? values3[index3] : undefined$1;
          assignFunc(result2, props[index3], value);
        }
        return result2;
      }
      function castArrayLikeObject(value) {
        return isArrayLikeObject2(value) ? value : [];
      }
      function castFunction2(value) {
        return typeof value == "function" ? value : identity3;
      }
      function castPath2(value, object) {
        if (isArray3(value)) {
          return value;
        }
        return isKey3(value, object) ? [value] : stringToPath3(toString5(value));
      }
      var castRest = baseRest2;
      function castSlice2(array2, start3, end2) {
        var length = array2.length;
        end2 = end2 === undefined$1 ? length : end2;
        return !start3 && end2 >= length ? array2 : baseSlice2(array2, start3, end2);
      }
      var clearTimeout2 = ctxClearTimeout || function(id3) {
        return root4.clearTimeout(id3);
      };
      function cloneBuffer(buffer, isDeep) {
        if (isDeep) {
          return buffer.slice();
        }
        var length = buffer.length, result2 = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
        buffer.copy(result2);
        return result2;
      }
      function cloneArrayBuffer2(arrayBuffer) {
        var result2 = new arrayBuffer.constructor(arrayBuffer.byteLength);
        new Uint8Array3(result2).set(new Uint8Array3(arrayBuffer));
        return result2;
      }
      function cloneDataView2(dataView, isDeep) {
        var buffer = isDeep ? cloneArrayBuffer2(dataView.buffer) : dataView.buffer;
        return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
      }
      function cloneRegExp2(regexp) {
        var result2 = new regexp.constructor(regexp.source, reFlags2.exec(regexp));
        result2.lastIndex = regexp.lastIndex;
        return result2;
      }
      function cloneSymbol2(symbol) {
        return symbolValueOf3 ? Object2(symbolValueOf3.call(symbol)) : {};
      }
      function cloneTypedArray2(typedArray, isDeep) {
        var buffer = isDeep ? cloneArrayBuffer2(typedArray.buffer) : typedArray.buffer;
        return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
      }
      function compareAscending2(value, other) {
        if (value !== other) {
          var valIsDefined = value !== undefined$1, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol3(value);
          var othIsDefined = other !== undefined$1, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol3(other);
          if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) {
            return 1;
          }
          if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) {
            return -1;
          }
        }
        return 0;
      }
      function compareMultiple2(object, other, orders) {
        var index3 = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length;
        while (++index3 < length) {
          var result2 = compareAscending2(objCriteria[index3], othCriteria[index3]);
          if (result2) {
            if (index3 >= ordersLength) {
              return result2;
            }
            var order3 = orders[index3];
            return result2 * (order3 == "desc" ? -1 : 1);
          }
        }
        return object.index - other.index;
      }
      function composeArgs(args, partials, holders, isCurried) {
        var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax3(argsLength - holdersLength, 0), result2 = Array2(leftLength + rangeLength), isUncurried = !isCurried;
        while (++leftIndex < leftLength) {
          result2[leftIndex] = partials[leftIndex];
        }
        while (++argsIndex < holdersLength) {
          if (isUncurried || argsIndex < argsLength) {
            result2[holders[argsIndex]] = args[argsIndex];
          }
        }
        while (rangeLength--) {
          result2[leftIndex++] = args[argsIndex++];
        }
        return result2;
      }
      function composeArgsRight(args, partials, holders, isCurried) {
        var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax3(argsLength - holdersLength, 0), result2 = Array2(rangeLength + rightLength), isUncurried = !isCurried;
        while (++argsIndex < rangeLength) {
          result2[argsIndex] = args[argsIndex];
        }
        var offset2 = argsIndex;
        while (++rightIndex < rightLength) {
          result2[offset2 + rightIndex] = partials[rightIndex];
        }
        while (++holdersIndex < holdersLength) {
          if (isUncurried || argsIndex < argsLength) {
            result2[offset2 + holders[holdersIndex]] = args[argsIndex++];
          }
        }
        return result2;
      }
      function copyArray2(source2, array2) {
        var index3 = -1, length = source2.length;
        array2 || (array2 = Array2(length));
        while (++index3 < length) {
          array2[index3] = source2[index3];
        }
        return array2;
      }
      function copyObject2(source2, props, object, customizer) {
        var isNew = !object;
        object || (object = {});
        var index3 = -1, length = props.length;
        while (++index3 < length) {
          var key = props[index3];
          var newValue = customizer ? customizer(object[key], source2[key], key, object, source2) : undefined$1;
          if (newValue === undefined$1) {
            newValue = source2[key];
          }
          if (isNew) {
            baseAssignValue2(object, key, newValue);
          } else {
            assignValue2(object, key, newValue);
          }
        }
        return object;
      }
      function copySymbols2(source2, object) {
        return copyObject2(source2, getSymbols2(source2), object);
      }
      function copySymbolsIn2(source2, object) {
        return copyObject2(source2, getSymbolsIn2(source2), object);
      }
      function createAggregator(setter, initializer) {
        return function(collection, iteratee2) {
          var func = isArray3(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {};
          return func(collection, setter, getIteratee(iteratee2, 2), accumulator);
        };
      }
      function createAssigner2(assigner) {
        return baseRest2(function(object, sources) {
          var index3 = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined$1, guard = length > 2 ? sources[2] : undefined$1;
          customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined$1;
          if (guard && isIterateeCall2(sources[0], sources[1], guard)) {
            customizer = length < 3 ? undefined$1 : customizer;
            length = 1;
          }
          object = Object2(object);
          while (++index3 < length) {
            var source2 = sources[index3];
            if (source2) {
              assigner(object, source2, index3, customizer);
            }
          }
          return object;
        });
      }
      function createBaseEach2(eachFunc, fromRight) {
        return function(collection, iteratee2) {
          if (collection == null) {
            return collection;
          }
          if (!isArrayLike2(collection)) {
            return eachFunc(collection, iteratee2);
          }
          var length = collection.length, index3 = fromRight ? length : -1, iterable = Object2(collection);
          while (fromRight ? index3-- : ++index3 < length) {
            if (iteratee2(iterable[index3], index3, iterable) === false) {
              break;
            }
          }
          return collection;
        };
      }
      function createBaseFor2(fromRight) {
        return function(object, iteratee2, keysFunc) {
          var index3 = -1, iterable = Object2(object), props = keysFunc(object), length = props.length;
          while (length--) {
            var key = props[fromRight ? length : ++index3];
            if (iteratee2(iterable[key], key, iterable) === false) {
              break;
            }
          }
          return object;
        };
      }
      function createBind(func, bitmask, thisArg) {
        var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func);
        function wrapper() {
          var fn = this && this !== root4 && this instanceof wrapper ? Ctor : func;
          return fn.apply(isBind ? thisArg : this, arguments);
        }
        return wrapper;
      }
      function createCaseFirst2(methodName) {
        return function(string2) {
          string2 = toString5(string2);
          var strSymbols = hasUnicode3(string2) ? stringToArray2(string2) : undefined$1;
          var chr = strSymbols ? strSymbols[0] : string2.charAt(0);
          var trailing = strSymbols ? castSlice2(strSymbols, 1).join("") : string2.slice(1);
          return chr[methodName]() + trailing;
        };
      }
      function createCompounder2(callback) {
        return function(string2) {
          return arrayReduce3(words2(deburr2(string2).replace(reApos2, "")), callback, "");
        };
      }
      function createCtor(Ctor) {
        return function() {
          var args = arguments;
          switch (args.length) {
            case 0:
              return new Ctor();
            case 1:
              return new Ctor(args[0]);
            case 2:
              return new Ctor(args[0], args[1]);
            case 3:
              return new Ctor(args[0], args[1], args[2]);
            case 4:
              return new Ctor(args[0], args[1], args[2], args[3]);
            case 5:
              return new Ctor(args[0], args[1], args[2], args[3], args[4]);
            case 6:
              return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
            case 7:
              return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
          }
          var thisBinding = baseCreate2(Ctor.prototype), result2 = Ctor.apply(thisBinding, args);
          return isObject5(result2) ? result2 : thisBinding;
        };
      }
      function createCurry(func, bitmask, arity) {
        var Ctor = createCtor(func);
        function wrapper() {
          var length = arguments.length, args = Array2(length), index3 = length, placeholder = getHolder(wrapper);
          while (index3--) {
            args[index3] = arguments[index3];
          }
          var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder);
          length -= holders.length;
          if (length < arity) {
            return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, undefined$1, args, holders, undefined$1, undefined$1, arity - length);
          }
          var fn = this && this !== root4 && this instanceof wrapper ? Ctor : func;
          return apply2(fn, this, args);
        }
        return wrapper;
      }
      function createFind2(findIndexFunc) {
        return function(collection, predicate, fromIndex) {
          var iterable = Object2(collection);
          if (!isArrayLike2(collection)) {
            var iteratee2 = getIteratee(predicate, 3);
            collection = keys2(collection);
            predicate = function(key) {
              return iteratee2(iterable[key], key, iterable);
            };
          }
          var index3 = findIndexFunc(collection, predicate, fromIndex);
          return index3 > -1 ? iterable[iteratee2 ? collection[index3] : index3] : undefined$1;
        };
      }
      function createFlow(fromRight) {
        return flatRest2(function(funcs) {
          var length = funcs.length, index3 = length, prereq = LodashWrapper.prototype.thru;
          if (fromRight) {
            funcs.reverse();
          }
          while (index3--) {
            var func = funcs[index3];
            if (typeof func != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT2);
            }
            if (prereq && !wrapper && getFuncName(func) == "wrapper") {
              var wrapper = new LodashWrapper([], true);
            }
          }
          index3 = wrapper ? index3 : length;
          while (++index3 < length) {
            func = funcs[index3];
            var funcName = getFuncName(func), data2 = funcName == "wrapper" ? getData(func) : undefined$1;
            if (data2 && isLaziable(data2[0]) && data2[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data2[4].length && data2[9] == 1) {
              wrapper = wrapper[getFuncName(data2[0])].apply(wrapper, data2[3]);
            } else {
              wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func);
            }
          }
          return function() {
            var args = arguments, value = args[0];
            if (wrapper && args.length == 1 && isArray3(value)) {
              return wrapper.plant(value).value();
            }
            var index4 = 0, result2 = length ? funcs[index4].apply(this, args) : value;
            while (++index4 < length) {
              result2 = funcs[index4].call(this, result2);
            }
            return result2;
          };
        });
      }
      function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary2, arity) {
        var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined$1 : createCtor(func);
        function wrapper() {
          var length = arguments.length, args = Array2(length), index3 = length;
          while (index3--) {
            args[index3] = arguments[index3];
          }
          if (isCurried) {
            var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder);
          }
          if (partials) {
            args = composeArgs(args, partials, holders, isCurried);
          }
          if (partialsRight) {
            args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
          }
          length -= holdersCount;
          if (isCurried && length < arity) {
            var newHolders = replaceHolders(args, placeholder);
            return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary2, arity - length);
          }
          var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func;
          length = args.length;
          if (argPos) {
            args = reorder(args, argPos);
          } else if (isFlip && length > 1) {
            args.reverse();
          }
          if (isAry && ary2 < length) {
            args.length = ary2;
          }
          if (this && this !== root4 && this instanceof wrapper) {
            fn = Ctor || createCtor(fn);
          }
          return fn.apply(thisBinding, args);
        }
        return wrapper;
      }
      function createInverter(setter, toIteratee) {
        return function(object, iteratee2) {
          return baseInverter(object, setter, toIteratee(iteratee2), {});
        };
      }
      function createMathOperation(operator, defaultValue) {
        return function(value, other) {
          var result2;
          if (value === undefined$1 && other === undefined$1) {
            return defaultValue;
          }
          if (value !== undefined$1) {
            result2 = value;
          }
          if (other !== undefined$1) {
            if (result2 === undefined$1) {
              return other;
            }
            if (typeof value == "string" || typeof other == "string") {
              value = baseToString3(value);
              other = baseToString3(other);
            } else {
              value = baseToNumber(value);
              other = baseToNumber(other);
            }
            result2 = operator(value, other);
          }
          return result2;
        };
      }
      function createOver(arrayFunc) {
        return flatRest2(function(iteratees) {
          iteratees = arrayMap2(iteratees, baseUnary2(getIteratee()));
          return baseRest2(function(args) {
            var thisArg = this;
            return arrayFunc(iteratees, function(iteratee2) {
              return apply2(iteratee2, thisArg, args);
            });
          });
        });
      }
      function createPadding(length, chars2) {
        chars2 = chars2 === undefined$1 ? " " : baseToString3(chars2);
        var charsLength = chars2.length;
        if (charsLength < 2) {
          return charsLength ? baseRepeat(chars2, length) : chars2;
        }
        var result2 = baseRepeat(chars2, nativeCeil2(length / stringSize2(chars2)));
        return hasUnicode3(chars2) ? castSlice2(stringToArray2(result2), 0, length).join("") : result2.slice(0, length);
      }
      function createPartial(func, bitmask, thisArg, partials) {
        var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func);
        function wrapper() {
          var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array2(leftLength + argsLength), fn = this && this !== root4 && this instanceof wrapper ? Ctor : func;
          while (++leftIndex < leftLength) {
            args[leftIndex] = partials[leftIndex];
          }
          while (argsLength--) {
            args[leftIndex++] = arguments[++argsIndex];
          }
          return apply2(fn, isBind ? thisArg : this, args);
        }
        return wrapper;
      }
      function createRange2(fromRight) {
        return function(start3, end2, step) {
          if (step && typeof step != "number" && isIterateeCall2(start3, end2, step)) {
            end2 = step = undefined$1;
          }
          start3 = toFinite2(start3);
          if (end2 === undefined$1) {
            end2 = start3;
            start3 = 0;
          } else {
            end2 = toFinite2(end2);
          }
          step = step === undefined$1 ? start3 < end2 ? 1 : -1 : toFinite2(step);
          return baseRange2(start3, end2, step, fromRight);
        };
      }
      function createRelationalOperation(operator) {
        return function(value, other) {
          if (!(typeof value == "string" && typeof other == "string")) {
            value = toNumber2(value);
            other = toNumber2(other);
          }
          return operator(value, other);
        };
      }
      function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary2, arity) {
        var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined$1, newHoldersRight = isCurry ? undefined$1 : holders, newPartials = isCurry ? partials : undefined$1, newPartialsRight = isCurry ? undefined$1 : partials;
        bitmask |= isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG;
        bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
        if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
          bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
        }
        var newData = [
          func,
          bitmask,
          thisArg,
          newPartials,
          newHolders,
          newPartialsRight,
          newHoldersRight,
          argPos,
          ary2,
          arity
        ];
        var result2 = wrapFunc.apply(undefined$1, newData);
        if (isLaziable(func)) {
          setData(result2, newData);
        }
        result2.placeholder = placeholder;
        return setWrapToString(result2, func, bitmask);
      }
      function createRound(methodName) {
        var func = Math2[methodName];
        return function(number, precision) {
          number = toNumber2(number);
          precision = precision == null ? 0 : nativeMin(toInteger2(precision), 292);
          if (precision && nativeIsFinite(number)) {
            var pair = (toString5(number) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision));
            pair = (toString5(value) + "e").split("e");
            return +(pair[0] + "e" + (+pair[1] - precision));
          }
          return func(number);
        };
      }
      var createSet2 = !(Set3 && 1 / setToArray2(new Set3([, -0]))[1] == INFINITY3) ? noop7 : function(values3) {
        return new Set3(values3);
      };
      function createToPairs(keysFunc) {
        return function(object) {
          var tag = getTag2(object);
          if (tag == mapTag3) {
            return mapToArray2(object);
          }
          if (tag == setTag3) {
            return setToPairs(object);
          }
          return baseToPairs(object, keysFunc(object));
        };
      }
      function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary2, arity) {
        var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
        if (!isBindKey && typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT2);
        }
        var length = partials ? partials.length : 0;
        if (!length) {
          bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
          partials = holders = undefined$1;
        }
        ary2 = ary2 === undefined$1 ? ary2 : nativeMax3(toInteger2(ary2), 0);
        arity = arity === undefined$1 ? arity : toInteger2(arity);
        length -= holders ? holders.length : 0;
        if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
          var partialsRight = partials, holdersRight = holders;
          partials = holders = undefined$1;
        }
        var data2 = isBindKey ? undefined$1 : getData(func);
        var newData = [
          func,
          bitmask,
          thisArg,
          partials,
          holders,
          partialsRight,
          holdersRight,
          argPos,
          ary2,
          arity
        ];
        if (data2) {
          mergeData(newData, data2);
        }
        func = newData[0];
        bitmask = newData[1];
        thisArg = newData[2];
        partials = newData[3];
        holders = newData[4];
        arity = newData[9] = newData[9] === undefined$1 ? isBindKey ? 0 : func.length : nativeMax3(newData[9] - length, 0);
        if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
          bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
        }
        if (!bitmask || bitmask == WRAP_BIND_FLAG) {
          var result2 = createBind(func, bitmask, thisArg);
        } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
          result2 = createCurry(func, bitmask, arity);
        } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
          result2 = createPartial(func, bitmask, thisArg, partials);
        } else {
          result2 = createHybrid.apply(undefined$1, newData);
        }
        var setter = data2 ? baseSetData : setData;
        return setWrapToString(setter(result2, newData), func, bitmask);
      }
      function customDefaultsAssignIn(objValue, srcValue, key, object) {
        if (objValue === undefined$1 || eq2(objValue, objectProto4[key]) && !hasOwnProperty6.call(object, key)) {
          return srcValue;
        }
        return objValue;
      }
      function customDefaultsMerge(objValue, srcValue, key, object, source2, stack2) {
        if (isObject5(objValue) && isObject5(srcValue)) {
          stack2.set(srcValue, objValue);
          baseMerge2(objValue, srcValue, undefined$1, customDefaultsMerge, stack2);
          stack2["delete"](srcValue);
        }
        return objValue;
      }
      function customOmitClone(value) {
        return isPlainObject4(value) ? undefined$1 : value;
      }
      function equalArrays2(array2, other, bitmask, customizer, equalFunc, stack2) {
        var isPartial = bitmask & COMPARE_PARTIAL_FLAG3, arrLength = array2.length, othLength = other.length;
        if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
          return false;
        }
        var arrStacked = stack2.get(array2);
        var othStacked = stack2.get(other);
        if (arrStacked && othStacked) {
          return arrStacked == other && othStacked == array2;
        }
        var index3 = -1, result2 = true, seen = bitmask & COMPARE_UNORDERED_FLAG3 ? new SetCache2() : undefined$1;
        stack2.set(array2, other);
        stack2.set(other, array2);
        while (++index3 < arrLength) {
          var arrValue = array2[index3], othValue = other[index3];
          if (customizer) {
            var compared = isPartial ? customizer(othValue, arrValue, index3, other, array2, stack2) : customizer(arrValue, othValue, index3, array2, other, stack2);
          }
          if (compared !== undefined$1) {
            if (compared) {
              continue;
            }
            result2 = false;
            break;
          }
          if (seen) {
            if (!arraySome2(other, function(othValue2, othIndex) {
              if (!cacheHas2(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack2))) {
                return seen.push(othIndex);
              }
            })) {
              result2 = false;
              break;
            }
          } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack2))) {
            result2 = false;
            break;
          }
        }
        stack2["delete"](array2);
        stack2["delete"](other);
        return result2;
      }
      function equalByTag2(object, other, tag, bitmask, customizer, equalFunc, stack2) {
        switch (tag) {
          case dataViewTag3:
            if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
              return false;
            }
            object = object.buffer;
            other = other.buffer;
          case arrayBufferTag3:
            if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array3(object), new Uint8Array3(other))) {
              return false;
            }
            return true;
          case boolTag3:
          case dateTag3:
          case numberTag3:
            return eq2(+object, +other);
          case errorTag3:
            return object.name == other.name && object.message == other.message;
          case regexpTag3:
          case stringTag3:
            return object == other + "";
          case mapTag3:
            var convert = mapToArray2;
          case setTag3:
            var isPartial = bitmask & COMPARE_PARTIAL_FLAG3;
            convert || (convert = setToArray2);
            if (object.size != other.size && !isPartial) {
              return false;
            }
            var stacked = stack2.get(object);
            if (stacked) {
              return stacked == other;
            }
            bitmask |= COMPARE_UNORDERED_FLAG3;
            stack2.set(object, other);
            var result2 = equalArrays2(convert(object), convert(other), bitmask, customizer, equalFunc, stack2);
            stack2["delete"](object);
            return result2;
          case symbolTag4:
            if (symbolValueOf3) {
              return symbolValueOf3.call(object) == symbolValueOf3.call(other);
            }
        }
        return false;
      }
      function equalObjects2(object, other, bitmask, customizer, equalFunc, stack2) {
        var isPartial = bitmask & COMPARE_PARTIAL_FLAG3, objProps = getAllKeys2(object), objLength = objProps.length, othProps = getAllKeys2(other), othLength = othProps.length;
        if (objLength != othLength && !isPartial) {
          return false;
        }
        var index3 = objLength;
        while (index3--) {
          var key = objProps[index3];
          if (!(isPartial ? key in other : hasOwnProperty6.call(other, key))) {
            return false;
          }
        }
        var objStacked = stack2.get(object);
        var othStacked = stack2.get(other);
        if (objStacked && othStacked) {
          return objStacked == other && othStacked == object;
        }
        var result2 = true;
        stack2.set(object, other);
        stack2.set(other, object);
        var skipCtor = isPartial;
        while (++index3 < objLength) {
          key = objProps[index3];
          var objValue = object[key], othValue = other[key];
          if (customizer) {
            var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack2) : customizer(objValue, othValue, key, object, other, stack2);
          }
          if (!(compared === undefined$1 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack2) : compared)) {
            result2 = false;
            break;
          }
          skipCtor || (skipCtor = key == "constructor");
        }
        if (result2 && !skipCtor) {
          var objCtor = object.constructor, othCtor = other.constructor;
          if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
            result2 = false;
          }
        }
        stack2["delete"](object);
        stack2["delete"](other);
        return result2;
      }
      function flatRest2(func) {
        return setToString2(overRest2(func, undefined$1, flatten4), func + "");
      }
      function getAllKeys2(object) {
        return baseGetAllKeys2(object, keys2, getSymbols2);
      }
      function getAllKeysIn2(object) {
        return baseGetAllKeys2(object, keysIn2, getSymbolsIn2);
      }
      var getData = !metaMap ? noop7 : function(func) {
        return metaMap.get(func);
      };
      function getFuncName(func) {
        var result2 = func.name + "", array2 = realNames[result2], length = hasOwnProperty6.call(realNames, result2) ? array2.length : 0;
        while (length--) {
          var data2 = array2[length], otherFunc = data2.func;
          if (otherFunc == null || otherFunc == func) {
            return data2.name;
          }
        }
        return result2;
      }
      function getHolder(func) {
        var object = hasOwnProperty6.call(lodash3, "placeholder") ? lodash3 : func;
        return object.placeholder;
      }
      function getIteratee() {
        var result2 = lodash3.iteratee || iteratee;
        result2 = result2 === iteratee ? baseIteratee2 : result2;
        return arguments.length ? result2(arguments[0], arguments[1]) : result2;
      }
      function getMapData2(map3, key) {
        var data2 = map3.__data__;
        return isKeyable2(key) ? data2[typeof key == "string" ? "string" : "hash"] : data2.map;
      }
      function getMatchData2(object) {
        var result2 = keys2(object), length = result2.length;
        while (length--) {
          var key = result2[length], value = object[key];
          result2[length] = [key, value, isStrictComparable2(value)];
        }
        return result2;
      }
      function getNative2(object, key) {
        var value = getValue2(object, key);
        return baseIsNative2(value) ? value : undefined$1;
      }
      function getRawTag2(value) {
        var isOwn = hasOwnProperty6.call(value, symToStringTag2), tag = value[symToStringTag2];
        try {
          value[symToStringTag2] = undefined$1;
          var unmasked = true;
        } catch (e2) {
        }
        var result2 = nativeObjectToString2.call(value);
        if (unmasked) {
          if (isOwn) {
            value[symToStringTag2] = tag;
          } else {
            delete value[symToStringTag2];
          }
        }
        return result2;
      }
      var getSymbols2 = !nativeGetSymbols3 ? stubArray2 : function(object) {
        if (object == null) {
          return [];
        }
        object = Object2(object);
        return arrayFilter2(nativeGetSymbols3(object), function(symbol) {
          return propertyIsEnumerable2.call(object, symbol);
        });
      };
      var getSymbolsIn2 = !nativeGetSymbols3 ? stubArray2 : function(object) {
        var result2 = [];
        while (object) {
          arrayPush2(result2, getSymbols2(object));
          object = getPrototype2(object);
        }
        return result2;
      };
      var getTag2 = baseGetTag2;
      if (DataView3 && getTag2(new DataView3(new ArrayBuffer(1))) != dataViewTag3 || Map3 && getTag2(new Map3()) != mapTag3 || Promise3 && getTag2(Promise3.resolve()) != promiseTag2 || Set3 && getTag2(new Set3()) != setTag3 || WeakMap3 && getTag2(new WeakMap3()) != weakMapTag3) {
        getTag2 = function(value) {
          var result2 = baseGetTag2(value), Ctor = result2 == objectTag3 ? value.constructor : undefined$1, ctorString = Ctor ? toSource2(Ctor) : "";
          if (ctorString) {
            switch (ctorString) {
              case dataViewCtorString2:
                return dataViewTag3;
              case mapCtorString2:
                return mapTag3;
              case promiseCtorString2:
                return promiseTag2;
              case setCtorString2:
                return setTag3;
              case weakMapCtorString2:
                return weakMapTag3;
            }
          }
          return result2;
        };
      }
      function getView(start3, end2, transforms) {
        var index3 = -1, length = transforms.length;
        while (++index3 < length) {
          var data2 = transforms[index3], size3 = data2.size;
          switch (data2.type) {
            case "drop":
              start3 += size3;
              break;
            case "dropRight":
              end2 -= size3;
              break;
            case "take":
              end2 = nativeMin(end2, start3 + size3);
              break;
            case "takeRight":
              start3 = nativeMax3(start3, end2 - size3);
              break;
          }
        }
        return {start: start3, end: end2};
      }
      function getWrapDetails(source2) {
        var match2 = source2.match(reWrapDetails);
        return match2 ? match2[1].split(reSplitDetails) : [];
      }
      function hasPath2(object, path, hasFunc) {
        path = castPath2(path, object);
        var index3 = -1, length = path.length, result2 = false;
        while (++index3 < length) {
          var key = toKey2(path[index3]);
          if (!(result2 = object != null && hasFunc(object, key))) {
            break;
          }
          object = object[key];
        }
        if (result2 || ++index3 != length) {
          return result2;
        }
        length = object == null ? 0 : object.length;
        return !!length && isLength2(length) && isIndex2(key, length) && (isArray3(object) || isArguments2(object));
      }
      function initCloneArray2(array2) {
        var length = array2.length, result2 = new array2.constructor(length);
        if (length && typeof array2[0] == "string" && hasOwnProperty6.call(array2, "index")) {
          result2.index = array2.index;
          result2.input = array2.input;
        }
        return result2;
      }
      function initCloneObject2(object) {
        return typeof object.constructor == "function" && !isPrototype2(object) ? baseCreate2(getPrototype2(object)) : {};
      }
      function initCloneByTag2(object, tag, isDeep) {
        var Ctor = object.constructor;
        switch (tag) {
          case arrayBufferTag3:
            return cloneArrayBuffer2(object);
          case boolTag3:
          case dateTag3:
            return new Ctor(+object);
          case dataViewTag3:
            return cloneDataView2(object, isDeep);
          case float32Tag3:
          case float64Tag3:
          case int8Tag3:
          case int16Tag3:
          case int32Tag3:
          case uint8Tag3:
          case uint8ClampedTag3:
          case uint16Tag3:
          case uint32Tag3:
            return cloneTypedArray2(object, isDeep);
          case mapTag3:
            return new Ctor();
          case numberTag3:
          case stringTag3:
            return new Ctor(object);
          case regexpTag3:
            return cloneRegExp2(object);
          case setTag3:
            return new Ctor();
          case symbolTag4:
            return cloneSymbol2(object);
        }
      }
      function insertWrapDetails(source2, details) {
        var length = details.length;
        if (!length) {
          return source2;
        }
        var lastIndex = length - 1;
        details[lastIndex] = (length > 1 ? "& " : "") + details[lastIndex];
        details = details.join(length > 2 ? ", " : " ");
        return source2.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n");
      }
      function isFlattenable2(value) {
        return isArray3(value) || isArguments2(value) || !!(spreadableSymbol2 && value && value[spreadableSymbol2]);
      }
      function isIndex2(value, length) {
        var type = typeof value;
        length = length == null ? MAX_SAFE_INTEGER2 : length;
        return !!length && (type == "number" || type != "symbol" && reIsUint2.test(value)) && (value > -1 && value % 1 == 0 && value < length);
      }
      function isIterateeCall2(value, index3, object) {
        if (!isObject5(object)) {
          return false;
        }
        var type = typeof index3;
        if (type == "number" ? isArrayLike2(object) && isIndex2(index3, object.length) : type == "string" && index3 in object) {
          return eq2(object[index3], value);
        }
        return false;
      }
      function isKey3(value, object) {
        if (isArray3(value)) {
          return false;
        }
        var type = typeof value;
        if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol3(value)) {
          return true;
        }
        return reIsPlainProp2.test(value) || !reIsDeepProp2.test(value) || object != null && value in Object2(object);
      }
      function isKeyable2(value) {
        var type = typeof value;
        return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
      }
      function isLaziable(func) {
        var funcName = getFuncName(func), other = lodash3[funcName];
        if (typeof other != "function" || !(funcName in LazyWrapper.prototype)) {
          return false;
        }
        if (func === other) {
          return true;
        }
        var data2 = getData(other);
        return !!data2 && func === data2[0];
      }
      function isMasked2(func) {
        return !!maskSrcKey2 && maskSrcKey2 in func;
      }
      var isMaskable = coreJsData2 ? isFunction6 : stubFalse2;
      function isPrototype2(value) {
        var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto4;
        return value === proto;
      }
      function isStrictComparable2(value) {
        return value === value && !isObject5(value);
      }
      function matchesStrictComparable2(key, srcValue) {
        return function(object) {
          if (object == null) {
            return false;
          }
          return object[key] === srcValue && (srcValue !== undefined$1 || key in Object2(object));
        };
      }
      function memoizeCapped2(func) {
        var result2 = memoize3(func, function(key) {
          if (cache3.size === MAX_MEMOIZE_SIZE2) {
            cache3.clear();
          }
          return key;
        });
        var cache3 = result2.cache;
        return result2;
      }
      function mergeData(data2, source2) {
        var bitmask = data2[1], srcBitmask = source2[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
        var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data2[7].length <= source2[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source2[7].length <= source2[8] && bitmask == WRAP_CURRY_FLAG;
        if (!(isCommon || isCombo)) {
          return data2;
        }
        if (srcBitmask & WRAP_BIND_FLAG) {
          data2[2] = source2[2];
          newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
        }
        var value = source2[3];
        if (value) {
          var partials = data2[3];
          data2[3] = partials ? composeArgs(partials, value, source2[4]) : value;
          data2[4] = partials ? replaceHolders(data2[3], PLACEHOLDER) : source2[4];
        }
        value = source2[5];
        if (value) {
          partials = data2[5];
          data2[5] = partials ? composeArgsRight(partials, value, source2[6]) : value;
          data2[6] = partials ? replaceHolders(data2[5], PLACEHOLDER) : source2[6];
        }
        value = source2[7];
        if (value) {
          data2[7] = value;
        }
        if (srcBitmask & WRAP_ARY_FLAG) {
          data2[8] = data2[8] == null ? source2[8] : nativeMin(data2[8], source2[8]);
        }
        if (data2[9] == null) {
          data2[9] = source2[9];
        }
        data2[0] = source2[0];
        data2[1] = newBitmask;
        return data2;
      }
      function nativeKeysIn2(object) {
        var result2 = [];
        if (object != null) {
          for (var key in Object2(object)) {
            result2.push(key);
          }
        }
        return result2;
      }
      function objectToString3(value) {
        return nativeObjectToString2.call(value);
      }
      function overRest2(func, start3, transform4) {
        start3 = nativeMax3(start3 === undefined$1 ? func.length - 1 : start3, 0);
        return function() {
          var args = arguments, index3 = -1, length = nativeMax3(args.length - start3, 0), array2 = Array2(length);
          while (++index3 < length) {
            array2[index3] = args[start3 + index3];
          }
          index3 = -1;
          var otherArgs = Array2(start3 + 1);
          while (++index3 < start3) {
            otherArgs[index3] = args[index3];
          }
          otherArgs[start3] = transform4(array2);
          return apply2(func, this, otherArgs);
        };
      }
      function parent(object, path) {
        return path.length < 2 ? object : baseGet3(object, baseSlice2(path, 0, -1));
      }
      function reorder(array2, indexes) {
        var arrLength = array2.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray2(array2);
        while (length--) {
          var index3 = indexes[length];
          array2[length] = isIndex2(index3, arrLength) ? oldArray[index3] : undefined$1;
        }
        return array2;
      }
      function safeGet2(object, key) {
        if (key === "constructor" && typeof object[key] === "function") {
          return;
        }
        if (key == "__proto__") {
          return;
        }
        return object[key];
      }
      var setData = shortOut2(baseSetData);
      var setTimeout2 = ctxSetTimeout || function(func, wait) {
        return root4.setTimeout(func, wait);
      };
      var setToString2 = shortOut2(baseSetToString2);
      function setWrapToString(wrapper, reference2, bitmask) {
        var source2 = reference2 + "";
        return setToString2(wrapper, insertWrapDetails(source2, updateWrapDetails(getWrapDetails(source2), bitmask)));
      }
      function shortOut2(func) {
        var count = 0, lastCalled = 0;
        return function() {
          var stamp = nativeNow2(), remaining = HOT_SPAN2 - (stamp - lastCalled);
          lastCalled = stamp;
          if (remaining > 0) {
            if (++count >= HOT_COUNT2) {
              return arguments[0];
            }
          } else {
            count = 0;
          }
          return func.apply(undefined$1, arguments);
        };
      }
      function shuffleSelf(array2, size3) {
        var index3 = -1, length = array2.length, lastIndex = length - 1;
        size3 = size3 === undefined$1 ? length : size3;
        while (++index3 < size3) {
          var rand = baseRandom(index3, lastIndex), value = array2[rand];
          array2[rand] = array2[index3];
          array2[index3] = value;
        }
        array2.length = size3;
        return array2;
      }
      var stringToPath3 = memoizeCapped2(function(string2) {
        var result2 = [];
        if (string2.charCodeAt(0) === 46) {
          result2.push("");
        }
        string2.replace(rePropName2, function(match2, number, quote, subString) {
          result2.push(quote ? subString.replace(reEscapeChar2, "$1") : number || match2);
        });
        return result2;
      });
      function toKey2(value) {
        if (typeof value == "string" || isSymbol3(value)) {
          return value;
        }
        var result2 = value + "";
        return result2 == "0" && 1 / value == -INFINITY3 ? "-0" : result2;
      }
      function toSource2(func) {
        if (func != null) {
          try {
            return funcToString2.call(func);
          } catch (e2) {
          }
          try {
            return func + "";
          } catch (e2) {
          }
        }
        return "";
      }
      function updateWrapDetails(details, bitmask) {
        arrayEach2(wrapFlags, function(pair) {
          var value = "_." + pair[0];
          if (bitmask & pair[1] && !arrayIncludes2(details, value)) {
            details.push(value);
          }
        });
        return details.sort();
      }
      function wrapperClone(wrapper) {
        if (wrapper instanceof LazyWrapper) {
          return wrapper.clone();
        }
        var result2 = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
        result2.__actions__ = copyArray2(wrapper.__actions__);
        result2.__index__ = wrapper.__index__;
        result2.__values__ = wrapper.__values__;
        return result2;
      }
      function chunk(array2, size3, guard) {
        if (guard ? isIterateeCall2(array2, size3, guard) : size3 === undefined$1) {
          size3 = 1;
        } else {
          size3 = nativeMax3(toInteger2(size3), 0);
        }
        var length = array2 == null ? 0 : array2.length;
        if (!length || size3 < 1) {
          return [];
        }
        var index3 = 0, resIndex = 0, result2 = Array2(nativeCeil2(length / size3));
        while (index3 < length) {
          result2[resIndex++] = baseSlice2(array2, index3, index3 += size3);
        }
        return result2;
      }
      function compact2(array2) {
        var index3 = -1, length = array2 == null ? 0 : array2.length, resIndex = 0, result2 = [];
        while (++index3 < length) {
          var value = array2[index3];
          if (value) {
            result2[resIndex++] = value;
          }
        }
        return result2;
      }
      function concat2() {
        var length = arguments.length;
        if (!length) {
          return [];
        }
        var args = Array2(length - 1), array2 = arguments[0], index3 = length;
        while (index3--) {
          args[index3 - 1] = arguments[index3];
        }
        return arrayPush2(isArray3(array2) ? copyArray2(array2) : [array2], baseFlatten2(args, 1));
      }
      var difference = baseRest2(function(array2, values3) {
        return isArrayLikeObject2(array2) ? baseDifference(array2, baseFlatten2(values3, 1, isArrayLikeObject2, true)) : [];
      });
      var differenceBy = baseRest2(function(array2, values3) {
        var iteratee2 = last2(values3);
        if (isArrayLikeObject2(iteratee2)) {
          iteratee2 = undefined$1;
        }
        return isArrayLikeObject2(array2) ? baseDifference(array2, baseFlatten2(values3, 1, isArrayLikeObject2, true), getIteratee(iteratee2, 2)) : [];
      });
      var differenceWith = baseRest2(function(array2, values3) {
        var comparator = last2(values3);
        if (isArrayLikeObject2(comparator)) {
          comparator = undefined$1;
        }
        return isArrayLikeObject2(array2) ? baseDifference(array2, baseFlatten2(values3, 1, isArrayLikeObject2, true), undefined$1, comparator) : [];
      });
      function drop(array2, n3, guard) {
        var length = array2 == null ? 0 : array2.length;
        if (!length) {
          return [];
        }
        n3 = guard || n3 === undefined$1 ? 1 : toInteger2(n3);
        return baseSlice2(array2, n3 < 0 ? 0 : n3, length);
      }
      function dropRight(array2, n3, guard) {
        var length = array2 == null ? 0 : array2.length;
        if (!length) {
          return [];
        }
        n3 = guard || n3 === undefined$1 ? 1 : toInteger2(n3);
        n3 = length - n3;
        return baseSlice2(array2, 0, n3 < 0 ? 0 : n3);
      }
      function dropRightWhile(array2, predicate) {
        return array2 && array2.length ? baseWhile(array2, getIteratee(predicate, 3), true, true) : [];
      }
      function dropWhile(array2, predicate) {
        return array2 && array2.length ? baseWhile(array2, getIteratee(predicate, 3), true) : [];
      }
      function fill2(array2, value, start3, end2) {
        var length = array2 == null ? 0 : array2.length;
        if (!length) {
          return [];
        }
        if (start3 && typeof start3 != "number" && isIterateeCall2(array2, value, start3)) {
          start3 = 0;
          end2 = length;
        }
        return baseFill(array2, value, start3, end2);
      }
      function findIndex2(array2, predicate, fromIndex) {
        var length = array2 == null ? 0 : array2.length;
        if (!length) {
          return -1;
        }
        var index3 = fromIndex == null ? 0 : toInteger2(fromIndex);
        if (index3 < 0) {
          index3 = nativeMax3(length + index3, 0);
        }
        return baseFindIndex2(array2, getIteratee(predicate, 3), index3);
      }
      function findLastIndex(array2, predicate, fromIndex) {
        var length = array2 == null ? 0 : array2.length;
        if (!length) {
          return -1;
        }
        var index3 = length - 1;
        if (fromIndex !== undefined$1) {
          index3 = toInteger2(fromIndex);
          index3 = fromIndex < 0 ? nativeMax3(length + index3, 0) : nativeMin(index3, length - 1);
        }
        return baseFindIndex2(array2, getIteratee(predicate, 3), index3, true);
      }
      function flatten4(array2) {
        var length = array2 == null ? 0 : array2.length;
        return length ? baseFlatten2(array2, 1) : [];
      }
      function flattenDeep(array2) {
        var length = array2 == null ? 0 : array2.length;
        return length ? baseFlatten2(array2, INFINITY3) : [];
      }
      function flattenDepth(array2, depth) {
        var length = array2 == null ? 0 : array2.length;
        if (!length) {
          return [];
        }
        depth = depth === undefined$1 ? 1 : toInteger2(depth);
        return baseFlatten2(array2, depth);
      }
      function fromPairs(pairs) {
        var index3 = -1, length = pairs == null ? 0 : pairs.length, result2 = {};
        while (++index3 < length) {
          var pair = pairs[index3];
          result2[pair[0]] = pair[1];
        }
        return result2;
      }
      function head(array2) {
        return array2 && array2.length ? array2[0] : undefined$1;
      }
      function indexOf(array2, value, fromIndex) {
        var length = array2 == null ? 0 : array2.length;
        if (!length) {
          return -1;
        }
        var index3 = fromIndex == null ? 0 : toInteger2(fromIndex);
        if (index3 < 0) {
          index3 = nativeMax3(length + index3, 0);
        }
        return baseIndexOf2(array2, value, index3);
      }
      function initial(array2) {
        var length = array2 == null ? 0 : array2.length;
        return length ? baseSlice2(array2, 0, -1) : [];
      }
      var intersection = baseRest2(function(arrays) {
        var mapped = arrayMap2(arrays, castArrayLikeObject);
        return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : [];
      });
      var intersectionBy2 = baseRest2(function(arrays) {
        var iteratee2 = last2(arrays), mapped = arrayMap2(arrays, castArrayLikeObject);
        if (iteratee2 === last2(mapped)) {
          iteratee2 = undefined$1;
        } else {
          mapped.pop();
        }
        return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee2, 2)) : [];
      });
      var intersectionWith = baseRest2(function(arrays) {
        var comparator = last2(arrays), mapped = arrayMap2(arrays, castArrayLikeObject);
        comparator = typeof comparator == "function" ? comparator : undefined$1;
        if (comparator) {
          mapped.pop();
        }
        return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined$1, comparator) : [];
      });
      function join2(array2, separator) {
        return array2 == null ? "" : nativeJoin.call(array2, separator);
      }
      function last2(array2) {
        var length = array2 == null ? 0 : array2.length;
        return length ? array2[length - 1] : undefined$1;
      }
      function lastIndexOf(array2, value, fromIndex) {
        var length = array2 == null ? 0 : array2.length;
        if (!length) {
          return -1;
        }
        var index3 = length;
        if (fromIndex !== undefined$1) {
          index3 = toInteger2(fromIndex);
          index3 = index3 < 0 ? nativeMax3(length + index3, 0) : nativeMin(index3, length - 1);
        }
        return value === value ? strictLastIndexOf(array2, value, index3) : baseFindIndex2(array2, baseIsNaN2, index3, true);
      }
      function nth(array2, n3) {
        return array2 && array2.length ? baseNth(array2, toInteger2(n3)) : undefined$1;
      }
      var pull = baseRest2(pullAll);
      function pullAll(array2, values3) {
        return array2 && array2.length && values3 && values3.length ? basePullAll(array2, values3) : array2;
      }
      function pullAllBy(array2, values3, iteratee2) {
        return array2 && array2.length && values3 && values3.length ? basePullAll(array2, values3, getIteratee(iteratee2, 2)) : array2;
      }
      function pullAllWith(array2, values3, comparator) {
        return array2 && array2.length && values3 && values3.length ? basePullAll(array2, values3, undefined$1, comparator) : array2;
      }
      var pullAt = flatRest2(function(array2, indexes) {
        var length = array2 == null ? 0 : array2.length, result2 = baseAt(array2, indexes);
        basePullAt(array2, arrayMap2(indexes, function(index3) {
          return isIndex2(index3, length) ? +index3 : index3;
        }).sort(compareAscending2));
        return result2;
      });
      function remove3(array2, predicate) {
        var result2 = [];
        if (!(array2 && array2.length)) {
          return result2;
        }
        var index3 = -1, indexes = [], length = array2.length;
        predicate = getIteratee(predicate, 3);
        while (++index3 < length) {
          var value = array2[index3];
          if (predicate(value, index3, array2)) {
            result2.push(value);
            indexes.push(index3);
          }
        }
        basePullAt(array2, indexes);
        return result2;
      }
      function reverse(array2) {
        return array2 == null ? array2 : nativeReverse.call(array2);
      }
      function slice(array2, start3, end2) {
        var length = array2 == null ? 0 : array2.length;
        if (!length) {
          return [];
        }
        if (end2 && typeof end2 != "number" && isIterateeCall2(array2, start3, end2)) {
          start3 = 0;
          end2 = length;
        } else {
          start3 = start3 == null ? 0 : toInteger2(start3);
          end2 = end2 === undefined$1 ? length : toInteger2(end2);
        }
        return baseSlice2(array2, start3, end2);
      }
      function sortedIndex(array2, value) {
        return baseSortedIndex(array2, value);
      }
      function sortedIndexBy(array2, value, iteratee2) {
        return baseSortedIndexBy(array2, value, getIteratee(iteratee2, 2));
      }
      function sortedIndexOf(array2, value) {
        var length = array2 == null ? 0 : array2.length;
        if (length) {
          var index3 = baseSortedIndex(array2, value);
          if (index3 < length && eq2(array2[index3], value)) {
            return index3;
          }
        }
        return -1;
      }
      function sortedLastIndex(array2, value) {
        return baseSortedIndex(array2, value, true);
      }
      function sortedLastIndexBy(array2, value, iteratee2) {
        return baseSortedIndexBy(array2, value, getIteratee(iteratee2, 2), true);
      }
      function sortedLastIndexOf(array2, value) {
        var length = array2 == null ? 0 : array2.length;
        if (length) {
          var index3 = baseSortedIndex(array2, value, true) - 1;
          if (eq2(array2[index3], value)) {
            return index3;
          }
        }
        return -1;
      }
      function sortedUniq2(array2) {
        return array2 && array2.length ? baseSortedUniq(array2) : [];
      }
      function sortedUniqBy(array2, iteratee2) {
        return array2 && array2.length ? baseSortedUniq(array2, getIteratee(iteratee2, 2)) : [];
      }
      function tail3(array2) {
        var length = array2 == null ? 0 : array2.length;
        return length ? baseSlice2(array2, 1, length) : [];
      }
      function take(array2, n3, guard) {
        if (!(array2 && array2.length)) {
          return [];
        }
        n3 = guard || n3 === undefined$1 ? 1 : toInteger2(n3);
        return baseSlice2(array2, 0, n3 < 0 ? 0 : n3);
      }
      function takeRight(array2, n3, guard) {
        var length = array2 == null ? 0 : array2.length;
        if (!length) {
          return [];
        }
        n3 = guard || n3 === undefined$1 ? 1 : toInteger2(n3);
        n3 = length - n3;
        return baseSlice2(array2, n3 < 0 ? 0 : n3, length);
      }
      function takeRightWhile(array2, predicate) {
        return array2 && array2.length ? baseWhile(array2, getIteratee(predicate, 3), false, true) : [];
      }
      function takeWhile(array2, predicate) {
        return array2 && array2.length ? baseWhile(array2, getIteratee(predicate, 3)) : [];
      }
      var union2 = baseRest2(function(arrays) {
        return baseUniq2(baseFlatten2(arrays, 1, isArrayLikeObject2, true));
      });
      var unionBy = baseRest2(function(arrays) {
        var iteratee2 = last2(arrays);
        if (isArrayLikeObject2(iteratee2)) {
          iteratee2 = undefined$1;
        }
        return baseUniq2(baseFlatten2(arrays, 1, isArrayLikeObject2, true), getIteratee(iteratee2, 2));
      });
      var unionWith = baseRest2(function(arrays) {
        var comparator = last2(arrays);
        comparator = typeof comparator == "function" ? comparator : undefined$1;
        return baseUniq2(baseFlatten2(arrays, 1, isArrayLikeObject2, true), undefined$1, comparator);
      });
      function uniq(array2) {
        return array2 && array2.length ? baseUniq2(array2) : [];
      }
      function uniqBy(array2, iteratee2) {
        return array2 && array2.length ? baseUniq2(array2, getIteratee(iteratee2, 2)) : [];
      }
      function uniqWith(array2, comparator) {
        comparator = typeof comparator == "function" ? comparator : undefined$1;
        return array2 && array2.length ? baseUniq2(array2, undefined$1, comparator) : [];
      }
      function unzip(array2) {
        if (!(array2 && array2.length)) {
          return [];
        }
        var length = 0;
        array2 = arrayFilter2(array2, function(group) {
          if (isArrayLikeObject2(group)) {
            length = nativeMax3(group.length, length);
            return true;
          }
        });
        return baseTimes2(length, function(index3) {
          return arrayMap2(array2, baseProperty2(index3));
        });
      }
      function unzipWith(array2, iteratee2) {
        if (!(array2 && array2.length)) {
          return [];
        }
        var result2 = unzip(array2);
        if (iteratee2 == null) {
          return result2;
        }
        return arrayMap2(result2, function(group) {
          return apply2(iteratee2, undefined$1, group);
        });
      }
      var without = baseRest2(function(array2, values3) {
        return isArrayLikeObject2(array2) ? baseDifference(array2, values3) : [];
      });
      var xor2 = baseRest2(function(arrays) {
        return baseXor(arrayFilter2(arrays, isArrayLikeObject2));
      });
      var xorBy = baseRest2(function(arrays) {
        var iteratee2 = last2(arrays);
        if (isArrayLikeObject2(iteratee2)) {
          iteratee2 = undefined$1;
        }
        return baseXor(arrayFilter2(arrays, isArrayLikeObject2), getIteratee(iteratee2, 2));
      });
      var xorWith = baseRest2(function(arrays) {
        var comparator = last2(arrays);
        comparator = typeof comparator == "function" ? comparator : undefined$1;
        return baseXor(arrayFilter2(arrays, isArrayLikeObject2), undefined$1, comparator);
      });
      var zip = baseRest2(unzip);
      function zipObject2(props, values3) {
        return baseZipObject2(props || [], values3 || [], assignValue2);
      }
      function zipObjectDeep(props, values3) {
        return baseZipObject2(props || [], values3 || [], baseSet2);
      }
      var zipWith = baseRest2(function(arrays) {
        var length = arrays.length, iteratee2 = length > 1 ? arrays[length - 1] : undefined$1;
        iteratee2 = typeof iteratee2 == "function" ? (arrays.pop(), iteratee2) : undefined$1;
        return unzipWith(arrays, iteratee2);
      });
      function chain(value) {
        var result2 = lodash3(value);
        result2.__chain__ = true;
        return result2;
      }
      function tap(value, interceptor) {
        interceptor(value);
        return value;
      }
      function thru(value, interceptor) {
        return interceptor(value);
      }
      var wrapperAt = flatRest2(function(paths) {
        var length = paths.length, start3 = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) {
          return baseAt(object, paths);
        };
        if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex2(start3)) {
          return this.thru(interceptor);
        }
        value = value.slice(start3, +start3 + (length ? 1 : 0));
        value.__actions__.push({
          func: thru,
          args: [interceptor],
          thisArg: undefined$1
        });
        return new LodashWrapper(value, this.__chain__).thru(function(array2) {
          if (length && !array2.length) {
            array2.push(undefined$1);
          }
          return array2;
        });
      });
      function wrapperChain() {
        return chain(this);
      }
      function wrapperCommit() {
        return new LodashWrapper(this.value(), this.__chain__);
      }
      function wrapperNext() {
        if (this.__values__ === undefined$1) {
          this.__values__ = toArray(this.value());
        }
        var done = this.__index__ >= this.__values__.length, value = done ? undefined$1 : this.__values__[this.__index__++];
        return {done, value};
      }
      function wrapperToIterator() {
        return this;
      }
      function wrapperPlant(value) {
        var result2, parent2 = this;
        while (parent2 instanceof baseLodash) {
          var clone3 = wrapperClone(parent2);
          clone3.__index__ = 0;
          clone3.__values__ = undefined$1;
          if (result2) {
            previous.__wrapped__ = clone3;
          } else {
            result2 = clone3;
          }
          var previous = clone3;
          parent2 = parent2.__wrapped__;
        }
        previous.__wrapped__ = value;
        return result2;
      }
      function wrapperReverse() {
        var value = this.__wrapped__;
        if (value instanceof LazyWrapper) {
          var wrapped = value;
          if (this.__actions__.length) {
            wrapped = new LazyWrapper(this);
          }
          wrapped = wrapped.reverse();
          wrapped.__actions__.push({
            func: thru,
            args: [reverse],
            thisArg: undefined$1
          });
          return new LodashWrapper(wrapped, this.__chain__);
        }
        return this.thru(reverse);
      }
      function wrapperValue() {
        return baseWrapperValue(this.__wrapped__, this.__actions__);
      }
      var countBy = createAggregator(function(result2, value, key) {
        if (hasOwnProperty6.call(result2, key)) {
          ++result2[key];
        } else {
          baseAssignValue2(result2, key, 1);
        }
      });
      function every(collection, predicate, guard) {
        var func = isArray3(collection) ? arrayEvery : baseEvery;
        if (guard && isIterateeCall2(collection, predicate, guard)) {
          predicate = undefined$1;
        }
        return func(collection, getIteratee(predicate, 3));
      }
      function filter3(collection, predicate) {
        var func = isArray3(collection) ? arrayFilter2 : baseFilter2;
        return func(collection, getIteratee(predicate, 3));
      }
      var find3 = createFind2(findIndex2);
      var findLast = createFind2(findLastIndex);
      function flatMap(collection, iteratee2) {
        return baseFlatten2(map2(collection, iteratee2), 1);
      }
      function flatMapDeep(collection, iteratee2) {
        return baseFlatten2(map2(collection, iteratee2), INFINITY3);
      }
      function flatMapDepth(collection, iteratee2, depth) {
        depth = depth === undefined$1 ? 1 : toInteger2(depth);
        return baseFlatten2(map2(collection, iteratee2), depth);
      }
      function forEach5(collection, iteratee2) {
        var func = isArray3(collection) ? arrayEach2 : baseEach2;
        return func(collection, getIteratee(iteratee2, 3));
      }
      function forEachRight(collection, iteratee2) {
        var func = isArray3(collection) ? arrayEachRight : baseEachRight;
        return func(collection, getIteratee(iteratee2, 3));
      }
      var groupBy = createAggregator(function(result2, value, key) {
        if (hasOwnProperty6.call(result2, key)) {
          result2[key].push(value);
        } else {
          baseAssignValue2(result2, key, [value]);
        }
      });
      function includes(collection, value, fromIndex, guard) {
        collection = isArrayLike2(collection) ? collection : values2(collection);
        fromIndex = fromIndex && !guard ? toInteger2(fromIndex) : 0;
        var length = collection.length;
        if (fromIndex < 0) {
          fromIndex = nativeMax3(length + fromIndex, 0);
        }
        return isString5(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf2(collection, value, fromIndex) > -1;
      }
      var invokeMap = baseRest2(function(collection, path, args) {
        var index3 = -1, isFunc = typeof path == "function", result2 = isArrayLike2(collection) ? Array2(collection.length) : [];
        baseEach2(collection, function(value) {
          result2[++index3] = isFunc ? apply2(path, value, args) : baseInvoke(value, path, args);
        });
        return result2;
      });
      var keyBy = createAggregator(function(result2, value, key) {
        baseAssignValue2(result2, key, value);
      });
      function map2(collection, iteratee2) {
        var func = isArray3(collection) ? arrayMap2 : baseMap2;
        return func(collection, getIteratee(iteratee2, 3));
      }
      function orderBy(collection, iteratees, orders, guard) {
        if (collection == null) {
          return [];
        }
        if (!isArray3(iteratees)) {
          iteratees = iteratees == null ? [] : [iteratees];
        }
        orders = guard ? undefined$1 : orders;
        if (!isArray3(orders)) {
          orders = orders == null ? [] : [orders];
        }
        return baseOrderBy2(collection, iteratees, orders);
      }
      var partition2 = createAggregator(function(result2, value, key) {
        result2[key ? 0 : 1].push(value);
      }, function() {
        return [[], []];
      });
      function reduce2(collection, iteratee2, accumulator) {
        var func = isArray3(collection) ? arrayReduce3 : baseReduce2, initAccum = arguments.length < 3;
        return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEach2);
      }
      function reduceRight(collection, iteratee2, accumulator) {
        var func = isArray3(collection) ? arrayReduceRight : baseReduce2, initAccum = arguments.length < 3;
        return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEachRight);
      }
      function reject(collection, predicate) {
        var func = isArray3(collection) ? arrayFilter2 : baseFilter2;
        return func(collection, negate(getIteratee(predicate, 3)));
      }
      function sample(collection) {
        var func = isArray3(collection) ? arraySample : baseSample;
        return func(collection);
      }
      function sampleSize(collection, n3, guard) {
        if (guard ? isIterateeCall2(collection, n3, guard) : n3 === undefined$1) {
          n3 = 1;
        } else {
          n3 = toInteger2(n3);
        }
        var func = isArray3(collection) ? arraySampleSize : baseSampleSize;
        return func(collection, n3);
      }
      function shuffle(collection) {
        var func = isArray3(collection) ? arrayShuffle : baseShuffle;
        return func(collection);
      }
      function size2(collection) {
        if (collection == null) {
          return 0;
        }
        if (isArrayLike2(collection)) {
          return isString5(collection) ? stringSize2(collection) : collection.length;
        }
        var tag = getTag2(collection);
        if (tag == mapTag3 || tag == setTag3) {
          return collection.size;
        }
        return baseKeys2(collection).length;
      }
      function some(collection, predicate, guard) {
        var func = isArray3(collection) ? arraySome2 : baseSome;
        if (guard && isIterateeCall2(collection, predicate, guard)) {
          predicate = undefined$1;
        }
        return func(collection, getIteratee(predicate, 3));
      }
      var sortBy3 = baseRest2(function(collection, iteratees) {
        if (collection == null) {
          return [];
        }
        var length = iteratees.length;
        if (length > 1 && isIterateeCall2(collection, iteratees[0], iteratees[1])) {
          iteratees = [];
        } else if (length > 2 && isIterateeCall2(iteratees[0], iteratees[1], iteratees[2])) {
          iteratees = [iteratees[0]];
        }
        return baseOrderBy2(collection, baseFlatten2(iteratees, 1), []);
      });
      var now3 = ctxNow || function() {
        return root4.Date.now();
      };
      function after(n3, func) {
        if (typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT2);
        }
        n3 = toInteger2(n3);
        return function() {
          if (--n3 < 1) {
            return func.apply(this, arguments);
          }
        };
      }
      function ary(func, n3, guard) {
        n3 = guard ? undefined$1 : n3;
        n3 = func && n3 == null ? func.length : n3;
        return createWrap(func, WRAP_ARY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, n3);
      }
      function before(n3, func) {
        var result2;
        if (typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT2);
        }
        n3 = toInteger2(n3);
        return function() {
          if (--n3 > 0) {
            result2 = func.apply(this, arguments);
          }
          if (n3 <= 1) {
            func = undefined$1;
          }
          return result2;
        };
      }
      var bind3 = baseRest2(function(func, thisArg, partials) {
        var bitmask = WRAP_BIND_FLAG;
        if (partials.length) {
          var holders = replaceHolders(partials, getHolder(bind3));
          bitmask |= WRAP_PARTIAL_FLAG;
        }
        return createWrap(func, bitmask, thisArg, partials, holders);
      });
      var bindKey2 = baseRest2(function(object, key, partials) {
        var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
        if (partials.length) {
          var holders = replaceHolders(partials, getHolder(bindKey2));
          bitmask |= WRAP_PARTIAL_FLAG;
        }
        return createWrap(key, bitmask, object, partials, holders);
      });
      function curry(func, arity, guard) {
        arity = guard ? undefined$1 : arity;
        var result2 = createWrap(func, WRAP_CURRY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity);
        result2.placeholder = curry.placeholder;
        return result2;
      }
      function curryRight(func, arity, guard) {
        arity = guard ? undefined$1 : arity;
        var result2 = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity);
        result2.placeholder = curryRight.placeholder;
        return result2;
      }
      function debounce2(func, wait, options) {
        var lastArgs, lastThis, maxWait, result2, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
        if (typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT2);
        }
        wait = toNumber2(wait) || 0;
        if (isObject5(options)) {
          leading = !!options.leading;
          maxing = "maxWait" in options;
          maxWait = maxing ? nativeMax3(toNumber2(options.maxWait) || 0, wait) : maxWait;
          trailing = "trailing" in options ? !!options.trailing : trailing;
        }
        function invokeFunc(time2) {
          var args = lastArgs, thisArg = lastThis;
          lastArgs = lastThis = undefined$1;
          lastInvokeTime = time2;
          result2 = func.apply(thisArg, args);
          return result2;
        }
        function leadingEdge(time2) {
          lastInvokeTime = time2;
          timerId = setTimeout2(timerExpired, wait);
          return leading ? invokeFunc(time2) : result2;
        }
        function remainingWait(time2) {
          var timeSinceLastCall = time2 - lastCallTime, timeSinceLastInvoke = time2 - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
          return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
        }
        function shouldInvoke(time2) {
          var timeSinceLastCall = time2 - lastCallTime, timeSinceLastInvoke = time2 - lastInvokeTime;
          return lastCallTime === undefined$1 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
        }
        function timerExpired() {
          var time2 = now3();
          if (shouldInvoke(time2)) {
            return trailingEdge(time2);
          }
          timerId = setTimeout2(timerExpired, remainingWait(time2));
        }
        function trailingEdge(time2) {
          timerId = undefined$1;
          if (trailing && lastArgs) {
            return invokeFunc(time2);
          }
          lastArgs = lastThis = undefined$1;
          return result2;
        }
        function cancel() {
          if (timerId !== undefined$1) {
            clearTimeout2(timerId);
          }
          lastInvokeTime = 0;
          lastArgs = lastCallTime = lastThis = timerId = undefined$1;
        }
        function flush() {
          return timerId === undefined$1 ? result2 : trailingEdge(now3());
        }
        function debounced() {
          var time2 = now3(), isInvoking = shouldInvoke(time2);
          lastArgs = arguments;
          lastThis = this;
          lastCallTime = time2;
          if (isInvoking) {
            if (timerId === undefined$1) {
              return leadingEdge(lastCallTime);
            }
            if (maxing) {
              clearTimeout2(timerId);
              timerId = setTimeout2(timerExpired, wait);
              return invokeFunc(lastCallTime);
            }
          }
          if (timerId === undefined$1) {
            timerId = setTimeout2(timerExpired, wait);
          }
          return result2;
        }
        debounced.cancel = cancel;
        debounced.flush = flush;
        return debounced;
      }
      var defer2 = baseRest2(function(func, args) {
        return baseDelay(func, 1, args);
      });
      var delay3 = baseRest2(function(func, wait, args) {
        return baseDelay(func, toNumber2(wait) || 0, args);
      });
      function flip2(func) {
        return createWrap(func, WRAP_FLIP_FLAG);
      }
      function memoize3(func, resolver) {
        if (typeof func != "function" || resolver != null && typeof resolver != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT2);
        }
        var memoized = function() {
          var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache3 = memoized.cache;
          if (cache3.has(key)) {
            return cache3.get(key);
          }
          var result2 = func.apply(this, args);
          memoized.cache = cache3.set(key, result2) || cache3;
          return result2;
        };
        memoized.cache = new (memoize3.Cache || MapCache2)();
        return memoized;
      }
      memoize3.Cache = MapCache2;
      function negate(predicate) {
        if (typeof predicate != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT2);
        }
        return function() {
          var args = arguments;
          switch (args.length) {
            case 0:
              return !predicate.call(this);
            case 1:
              return !predicate.call(this, args[0]);
            case 2:
              return !predicate.call(this, args[0], args[1]);
            case 3:
              return !predicate.call(this, args[0], args[1], args[2]);
          }
          return !predicate.apply(this, args);
        };
      }
      function once3(func) {
        return before(2, func);
      }
      var overArgs = castRest(function(func, transforms) {
        transforms = transforms.length == 1 && isArray3(transforms[0]) ? arrayMap2(transforms[0], baseUnary2(getIteratee())) : arrayMap2(baseFlatten2(transforms, 1), baseUnary2(getIteratee()));
        var funcsLength = transforms.length;
        return baseRest2(function(args) {
          var index3 = -1, length = nativeMin(args.length, funcsLength);
          while (++index3 < length) {
            args[index3] = transforms[index3].call(this, args[index3]);
          }
          return apply2(func, this, args);
        });
      });
      var partial = baseRest2(function(func, partials) {
        var holders = replaceHolders(partials, getHolder(partial));
        return createWrap(func, WRAP_PARTIAL_FLAG, undefined$1, partials, holders);
      });
      var partialRight = baseRest2(function(func, partials) {
        var holders = replaceHolders(partials, getHolder(partialRight));
        return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined$1, partials, holders);
      });
      var rearg = flatRest2(function(func, indexes) {
        return createWrap(func, WRAP_REARG_FLAG, undefined$1, undefined$1, undefined$1, indexes);
      });
      function rest(func, start3) {
        if (typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT2);
        }
        start3 = start3 === undefined$1 ? start3 : toInteger2(start3);
        return baseRest2(func, start3);
      }
      function spread3(func, start3) {
        if (typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT2);
        }
        start3 = start3 == null ? 0 : nativeMax3(toInteger2(start3), 0);
        return baseRest2(function(args) {
          var array2 = args[start3], otherArgs = castSlice2(args, 0, start3);
          if (array2) {
            arrayPush2(otherArgs, array2);
          }
          return apply2(func, this, otherArgs);
        });
      }
      function throttle(func, wait, options) {
        var leading = true, trailing = true;
        if (typeof func != "function") {
          throw new TypeError2(FUNC_ERROR_TEXT2);
        }
        if (isObject5(options)) {
          leading = "leading" in options ? !!options.leading : leading;
          trailing = "trailing" in options ? !!options.trailing : trailing;
        }
        return debounce2(func, wait, {
          leading,
          maxWait: wait,
          trailing
        });
      }
      function unary(func) {
        return ary(func, 1);
      }
      function wrap(value, wrapper) {
        return partial(castFunction2(wrapper), value);
      }
      function castArray() {
        if (!arguments.length) {
          return [];
        }
        var value = arguments[0];
        return isArray3(value) ? value : [value];
      }
      function clone2(value) {
        return baseClone2(value, CLONE_SYMBOLS_FLAG2);
      }
      function cloneWith(value, customizer) {
        customizer = typeof customizer == "function" ? customizer : undefined$1;
        return baseClone2(value, CLONE_SYMBOLS_FLAG2, customizer);
      }
      function cloneDeep3(value) {
        return baseClone2(value, CLONE_DEEP_FLAG2 | CLONE_SYMBOLS_FLAG2);
      }
      function cloneDeepWith(value, customizer) {
        customizer = typeof customizer == "function" ? customizer : undefined$1;
        return baseClone2(value, CLONE_DEEP_FLAG2 | CLONE_SYMBOLS_FLAG2, customizer);
      }
      function conformsTo(object, source2) {
        return source2 == null || baseConformsTo(object, source2, keys2(source2));
      }
      function eq2(value, other) {
        return value === other || value !== value && other !== other;
      }
      var gt = createRelationalOperation(baseGt2);
      var gte = createRelationalOperation(function(value, other) {
        return value >= other;
      });
      var isArguments2 = baseIsArguments2(function() {
        return arguments;
      }()) ? baseIsArguments2 : function(value) {
        return isObjectLike3(value) && hasOwnProperty6.call(value, "callee") && !propertyIsEnumerable2.call(value, "callee");
      };
      var isArray3 = Array2.isArray;
      var isArrayBuffer2 = nodeIsArrayBuffer ? baseUnary2(nodeIsArrayBuffer) : baseIsArrayBuffer;
      function isArrayLike2(value) {
        return value != null && isLength2(value.length) && !isFunction6(value);
      }
      function isArrayLikeObject2(value) {
        return isObjectLike3(value) && isArrayLike2(value);
      }
      function isBoolean3(value) {
        return value === true || value === false || isObjectLike3(value) && baseGetTag2(value) == boolTag3;
      }
      var isBuffer3 = nativeIsBuffer || stubFalse2;
      var isDate2 = nodeIsDate ? baseUnary2(nodeIsDate) : baseIsDate;
      function isElement3(value) {
        return isObjectLike3(value) && value.nodeType === 1 && !isPlainObject4(value);
      }
      function isEmpty3(value) {
        if (value == null) {
          return true;
        }
        if (isArrayLike2(value) && (isArray3(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer3(value) || isTypedArray2(value) || isArguments2(value))) {
          return !value.length;
        }
        var tag = getTag2(value);
        if (tag == mapTag3 || tag == setTag3) {
          return !value.size;
        }
        if (isPrototype2(value)) {
          return !baseKeys2(value).length;
        }
        for (var key in value) {
          if (hasOwnProperty6.call(value, key)) {
            return false;
          }
        }
        return true;
      }
      function isEqual4(value, other) {
        return baseIsEqual2(value, other);
      }
      function isEqualWith2(value, other, customizer) {
        customizer = typeof customizer == "function" ? customizer : undefined$1;
        var result2 = customizer ? customizer(value, other) : undefined$1;
        return result2 === undefined$1 ? baseIsEqual2(value, other, undefined$1, customizer) : !!result2;
      }
      function isError(value) {
        if (!isObjectLike3(value)) {
          return false;
        }
        var tag = baseGetTag2(value);
        return tag == errorTag3 || tag == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject4(value);
      }
      function isFinite2(value) {
        return typeof value == "number" && nativeIsFinite(value);
      }
      function isFunction6(value) {
        if (!isObject5(value)) {
          return false;
        }
        var tag = baseGetTag2(value);
        return tag == funcTag3 || tag == genTag3 || tag == asyncTag2 || tag == proxyTag2;
      }
      function isInteger(value) {
        return typeof value == "number" && value == toInteger2(value);
      }
      function isLength2(value) {
        return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
      }
      function isObject5(value) {
        var type = typeof value;
        return value != null && (type == "object" || type == "function");
      }
      function isObjectLike3(value) {
        return value != null && typeof value == "object";
      }
      var isMap2 = nodeIsMap2 ? baseUnary2(nodeIsMap2) : baseIsMap2;
      function isMatch(object, source2) {
        return object === source2 || baseIsMatch2(object, source2, getMatchData2(source2));
      }
      function isMatchWith(object, source2, customizer) {
        customizer = typeof customizer == "function" ? customizer : undefined$1;
        return baseIsMatch2(object, source2, getMatchData2(source2), customizer);
      }
      function isNaN2(value) {
        return isNumber3(value) && value != +value;
      }
      function isNative2(value) {
        if (isMaskable(value)) {
          throw new Error2(CORE_ERROR_TEXT);
        }
        return baseIsNative2(value);
      }
      function isNull(value) {
        return value === null;
      }
      function isNil(value) {
        return value == null;
      }
      function isNumber3(value) {
        return typeof value == "number" || isObjectLike3(value) && baseGetTag2(value) == numberTag3;
      }
      function isPlainObject4(value) {
        if (!isObjectLike3(value) || baseGetTag2(value) != objectTag3) {
          return false;
        }
        var proto = getPrototype2(value);
        if (proto === null) {
          return true;
        }
        var Ctor = hasOwnProperty6.call(proto, "constructor") && proto.constructor;
        return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString2.call(Ctor) == objectCtorString2;
      }
      var isRegExp = nodeIsRegExp ? baseUnary2(nodeIsRegExp) : baseIsRegExp;
      function isSafeInteger(value) {
        return isInteger(value) && value >= -MAX_SAFE_INTEGER2 && value <= MAX_SAFE_INTEGER2;
      }
      var isSet2 = nodeIsSet2 ? baseUnary2(nodeIsSet2) : baseIsSet2;
      function isString5(value) {
        return typeof value == "string" || !isArray3(value) && isObjectLike3(value) && baseGetTag2(value) == stringTag3;
      }
      function isSymbol3(value) {
        return typeof value == "symbol" || isObjectLike3(value) && baseGetTag2(value) == symbolTag4;
      }
      var isTypedArray2 = nodeIsTypedArray2 ? baseUnary2(nodeIsTypedArray2) : baseIsTypedArray2;
      function isUndefined5(value) {
        return value === undefined$1;
      }
      function isWeakMap(value) {
        return isObjectLike3(value) && getTag2(value) == weakMapTag3;
      }
      function isWeakSet(value) {
        return isObjectLike3(value) && baseGetTag2(value) == weakSetTag;
      }
      var lt = createRelationalOperation(baseLt2);
      var lte = createRelationalOperation(function(value, other) {
        return value <= other;
      });
      function toArray(value) {
        if (!value) {
          return [];
        }
        if (isArrayLike2(value)) {
          return isString5(value) ? stringToArray2(value) : copyArray2(value);
        }
        if (symIterator && value[symIterator]) {
          return iteratorToArray(value[symIterator]());
        }
        var tag = getTag2(value), func = tag == mapTag3 ? mapToArray2 : tag == setTag3 ? setToArray2 : values2;
        return func(value);
      }
      function toFinite2(value) {
        if (!value) {
          return value === 0 ? value : 0;
        }
        value = toNumber2(value);
        if (value === INFINITY3 || value === -INFINITY3) {
          var sign = value < 0 ? -1 : 1;
          return sign * MAX_INTEGER2;
        }
        return value === value ? value : 0;
      }
      function toInteger2(value) {
        var result2 = toFinite2(value), remainder = result2 % 1;
        return result2 === result2 ? remainder ? result2 - remainder : result2 : 0;
      }
      function toLength(value) {
        return value ? baseClamp(toInteger2(value), 0, MAX_ARRAY_LENGTH) : 0;
      }
      function toNumber2(value) {
        if (typeof value == "number") {
          return value;
        }
        if (isSymbol3(value)) {
          return NAN2;
        }
        if (isObject5(value)) {
          var other = typeof value.valueOf == "function" ? value.valueOf() : value;
          value = isObject5(other) ? other + "" : other;
        }
        if (typeof value != "string") {
          return value === 0 ? value : +value;
        }
        value = baseTrim2(value);
        var isBinary = reIsBinary2.test(value);
        return isBinary || reIsOctal2.test(value) ? freeParseInt2(value.slice(2), isBinary ? 2 : 8) : reIsBadHex2.test(value) ? NAN2 : +value;
      }
      function toPlainObject2(value) {
        return copyObject2(value, keysIn2(value));
      }
      function toSafeInteger(value) {
        return value ? baseClamp(toInteger2(value), -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2) : value === 0 ? value : 0;
      }
      function toString5(value) {
        return value == null ? "" : baseToString3(value);
      }
      var assign2 = createAssigner2(function(object, source2) {
        if (isPrototype2(source2) || isArrayLike2(source2)) {
          copyObject2(source2, keys2(source2), object);
          return;
        }
        for (var key in source2) {
          if (hasOwnProperty6.call(source2, key)) {
            assignValue2(object, key, source2[key]);
          }
        }
      });
      var assignIn = createAssigner2(function(object, source2) {
        copyObject2(source2, keysIn2(source2), object);
      });
      var assignInWith = createAssigner2(function(object, source2, srcIndex, customizer) {
        copyObject2(source2, keysIn2(source2), object, customizer);
      });
      var assignWith = createAssigner2(function(object, source2, srcIndex, customizer) {
        copyObject2(source2, keys2(source2), object, customizer);
      });
      var at = flatRest2(baseAt);
      function create3(prototype, properties) {
        var result2 = baseCreate2(prototype);
        return properties == null ? result2 : baseAssign2(result2, properties);
      }
      var defaults3 = baseRest2(function(object, sources) {
        object = Object2(object);
        var index3 = -1;
        var length = sources.length;
        var guard = length > 2 ? sources[2] : undefined$1;
        if (guard && isIterateeCall2(sources[0], sources[1], guard)) {
          length = 1;
        }
        while (++index3 < length) {
          var source2 = sources[index3];
          var props = keysIn2(source2);
          var propsIndex = -1;
          var propsLength = props.length;
          while (++propsIndex < propsLength) {
            var key = props[propsIndex];
            var value = object[key];
            if (value === undefined$1 || eq2(value, objectProto4[key]) && !hasOwnProperty6.call(object, key)) {
              object[key] = source2[key];
            }
          }
        }
        return object;
      });
      var defaultsDeep = baseRest2(function(args) {
        args.push(undefined$1, customDefaultsMerge);
        return apply2(mergeWith2, undefined$1, args);
      });
      function findKey(object, predicate) {
        return baseFindKey(object, getIteratee(predicate, 3), baseForOwn2);
      }
      function findLastKey(object, predicate) {
        return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
      }
      function forIn2(object, iteratee2) {
        return object == null ? object : baseFor2(object, getIteratee(iteratee2, 3), keysIn2);
      }
      function forInRight(object, iteratee2) {
        return object == null ? object : baseForRight(object, getIteratee(iteratee2, 3), keysIn2);
      }
      function forOwn(object, iteratee2) {
        return object && baseForOwn2(object, getIteratee(iteratee2, 3));
      }
      function forOwnRight(object, iteratee2) {
        return object && baseForOwnRight(object, getIteratee(iteratee2, 3));
      }
      function functions(object) {
        return object == null ? [] : baseFunctions(object, keys2(object));
      }
      function functionsIn(object) {
        return object == null ? [] : baseFunctions(object, keysIn2(object));
      }
      function get7(object, path, defaultValue) {
        var result2 = object == null ? undefined$1 : baseGet3(object, path);
        return result2 === undefined$1 ? defaultValue : result2;
      }
      function has3(object, path) {
        return object != null && hasPath2(object, path, baseHas2);
      }
      function hasIn2(object, path) {
        return object != null && hasPath2(object, path, baseHasIn2);
      }
      var invert = createInverter(function(result2, value, key) {
        if (value != null && typeof value.toString != "function") {
          value = nativeObjectToString2.call(value);
        }
        result2[value] = key;
      }, constant3(identity3));
      var invertBy = createInverter(function(result2, value, key) {
        if (value != null && typeof value.toString != "function") {
          value = nativeObjectToString2.call(value);
        }
        if (hasOwnProperty6.call(result2, value)) {
          result2[value].push(key);
        } else {
          result2[value] = [key];
        }
      }, getIteratee);
      var invoke = baseRest2(baseInvoke);
      function keys2(object) {
        return isArrayLike2(object) ? arrayLikeKeys2(object) : baseKeys2(object);
      }
      function keysIn2(object) {
        return isArrayLike2(object) ? arrayLikeKeys2(object, true) : baseKeysIn2(object);
      }
      function mapKeys(object, iteratee2) {
        var result2 = {};
        iteratee2 = getIteratee(iteratee2, 3);
        baseForOwn2(object, function(value, key, object2) {
          baseAssignValue2(result2, iteratee2(value, key, object2), value);
        });
        return result2;
      }
      function mapValues2(object, iteratee2) {
        var result2 = {};
        iteratee2 = getIteratee(iteratee2, 3);
        baseForOwn2(object, function(value, key, object2) {
          baseAssignValue2(result2, key, iteratee2(value, key, object2));
        });
        return result2;
      }
      var merge3 = createAssigner2(function(object, source2, srcIndex) {
        baseMerge2(object, source2, srcIndex);
      });
      var mergeWith2 = createAssigner2(function(object, source2, srcIndex, customizer) {
        baseMerge2(object, source2, srcIndex, customizer);
      });
      var omit2 = flatRest2(function(object, paths) {
        var result2 = {};
        if (object == null) {
          return result2;
        }
        var isDeep = false;
        paths = arrayMap2(paths, function(path) {
          path = castPath2(path, object);
          isDeep || (isDeep = path.length > 1);
          return path;
        });
        copyObject2(object, getAllKeysIn2(object), result2);
        if (isDeep) {
          result2 = baseClone2(result2, CLONE_DEEP_FLAG2 | CLONE_FLAT_FLAG2 | CLONE_SYMBOLS_FLAG2, customOmitClone);
        }
        var length = paths.length;
        while (length--) {
          baseUnset(result2, paths[length]);
        }
        return result2;
      });
      function omitBy(object, predicate) {
        return pickBy2(object, negate(getIteratee(predicate)));
      }
      var pick2 = flatRest2(function(object, paths) {
        return object == null ? {} : basePick2(object, paths);
      });
      function pickBy2(object, predicate) {
        if (object == null) {
          return {};
        }
        var props = arrayMap2(getAllKeysIn2(object), function(prop) {
          return [prop];
        });
        predicate = getIteratee(predicate);
        return basePickBy2(object, props, function(value, path) {
          return predicate(value, path[0]);
        });
      }
      function result(object, path, defaultValue) {
        path = castPath2(path, object);
        var index3 = -1, length = path.length;
        if (!length) {
          length = 1;
          object = undefined$1;
        }
        while (++index3 < length) {
          var value = object == null ? undefined$1 : object[toKey2(path[index3])];
          if (value === undefined$1) {
            index3 = length;
            value = defaultValue;
          }
          object = isFunction6(value) ? value.call(object) : value;
        }
        return object;
      }
      function set3(object, path, value) {
        return object == null ? object : baseSet2(object, path, value);
      }
      function setWith(object, path, value, customizer) {
        customizer = typeof customizer == "function" ? customizer : undefined$1;
        return object == null ? object : baseSet2(object, path, value, customizer);
      }
      var toPairs = createToPairs(keys2);
      var toPairsIn = createToPairs(keysIn2);
      function transform3(object, iteratee2, accumulator) {
        var isArr = isArray3(object), isArrLike = isArr || isBuffer3(object) || isTypedArray2(object);
        iteratee2 = getIteratee(iteratee2, 4);
        if (accumulator == null) {
          var Ctor = object && object.constructor;
          if (isArrLike) {
            accumulator = isArr ? new Ctor() : [];
          } else if (isObject5(object)) {
            accumulator = isFunction6(Ctor) ? baseCreate2(getPrototype2(object)) : {};
          } else {
            accumulator = {};
          }
        }
        (isArrLike ? arrayEach2 : baseForOwn2)(object, function(value, index3, object2) {
          return iteratee2(accumulator, value, index3, object2);
        });
        return accumulator;
      }
      function unset2(object, path) {
        return object == null ? true : baseUnset(object, path);
      }
      function update(object, path, updater) {
        return object == null ? object : baseUpdate(object, path, castFunction2(updater));
      }
      function updateWith(object, path, updater, customizer) {
        customizer = typeof customizer == "function" ? customizer : undefined$1;
        return object == null ? object : baseUpdate(object, path, castFunction2(updater), customizer);
      }
      function values2(object) {
        return object == null ? [] : baseValues2(object, keys2(object));
      }
      function valuesIn(object) {
        return object == null ? [] : baseValues2(object, keysIn2(object));
      }
      function clamp5(number, lower2, upper) {
        if (upper === undefined$1) {
          upper = lower2;
          lower2 = undefined$1;
        }
        if (upper !== undefined$1) {
          upper = toNumber2(upper);
          upper = upper === upper ? upper : 0;
        }
        if (lower2 !== undefined$1) {
          lower2 = toNumber2(lower2);
          lower2 = lower2 === lower2 ? lower2 : 0;
        }
        return baseClamp(toNumber2(number), lower2, upper);
      }
      function inRange(number, start3, end2) {
        start3 = toFinite2(start3);
        if (end2 === undefined$1) {
          end2 = start3;
          start3 = 0;
        } else {
          end2 = toFinite2(end2);
        }
        number = toNumber2(number);
        return baseInRange(number, start3, end2);
      }
      function random(lower2, upper, floating) {
        if (floating && typeof floating != "boolean" && isIterateeCall2(lower2, upper, floating)) {
          upper = floating = undefined$1;
        }
        if (floating === undefined$1) {
          if (typeof upper == "boolean") {
            floating = upper;
            upper = undefined$1;
          } else if (typeof lower2 == "boolean") {
            floating = lower2;
            lower2 = undefined$1;
          }
        }
        if (lower2 === undefined$1 && upper === undefined$1) {
          lower2 = 0;
          upper = 1;
        } else {
          lower2 = toFinite2(lower2);
          if (upper === undefined$1) {
            upper = lower2;
            lower2 = 0;
          } else {
            upper = toFinite2(upper);
          }
        }
        if (lower2 > upper) {
          var temp = lower2;
          lower2 = upper;
          upper = temp;
        }
        if (floating || lower2 % 1 || upper % 1) {
          var rand = nativeRandom();
          return nativeMin(lower2 + rand * (upper - lower2 + freeParseFloat("1e-" + ((rand + "").length - 1))), upper);
        }
        return baseRandom(lower2, upper);
      }
      var camelCase3 = createCompounder2(function(result2, word, index3) {
        word = word.toLowerCase();
        return result2 + (index3 ? capitalize5(word) : word);
      });
      function capitalize5(string2) {
        return upperFirst2(toString5(string2).toLowerCase());
      }
      function deburr2(string2) {
        string2 = toString5(string2);
        return string2 && string2.replace(reLatin2, deburrLetter2).replace(reComboMark2, "");
      }
      function endsWith2(string2, target, position2) {
        string2 = toString5(string2);
        target = baseToString3(target);
        var length = string2.length;
        position2 = position2 === undefined$1 ? length : baseClamp(toInteger2(position2), 0, length);
        var end2 = position2;
        position2 -= target.length;
        return position2 >= 0 && string2.slice(position2, end2) == target;
      }
      function escape4(string2) {
        string2 = toString5(string2);
        return string2 && reHasUnescapedHtml.test(string2) ? string2.replace(reUnescapedHtml, escapeHtmlChar) : string2;
      }
      function escapeRegExp(string2) {
        string2 = toString5(string2);
        return string2 && reHasRegExpChar.test(string2) ? string2.replace(reRegExpChar2, "\\$&") : string2;
      }
      var kebabCase = createCompounder2(function(result2, word, index3) {
        return result2 + (index3 ? "-" : "") + word.toLowerCase();
      });
      var lowerCase = createCompounder2(function(result2, word, index3) {
        return result2 + (index3 ? " " : "") + word.toLowerCase();
      });
      var lowerFirst = createCaseFirst2("toLowerCase");
      function pad(string2, length, chars2) {
        string2 = toString5(string2);
        length = toInteger2(length);
        var strLength = length ? stringSize2(string2) : 0;
        if (!length || strLength >= length) {
          return string2;
        }
        var mid = (length - strLength) / 2;
        return createPadding(nativeFloor(mid), chars2) + string2 + createPadding(nativeCeil2(mid), chars2);
      }
      function padEnd(string2, length, chars2) {
        string2 = toString5(string2);
        length = toInteger2(length);
        var strLength = length ? stringSize2(string2) : 0;
        return length && strLength < length ? string2 + createPadding(length - strLength, chars2) : string2;
      }
      function padStart(string2, length, chars2) {
        string2 = toString5(string2);
        length = toInteger2(length);
        var strLength = length ? stringSize2(string2) : 0;
        return length && strLength < length ? createPadding(length - strLength, chars2) + string2 : string2;
      }
      function parseInt2(string2, radix, guard) {
        if (guard || radix == null) {
          radix = 0;
        } else if (radix) {
          radix = +radix;
        }
        return nativeParseInt(toString5(string2).replace(reTrimStart2, ""), radix || 0);
      }
      function repeat(string2, n3, guard) {
        if (guard ? isIterateeCall2(string2, n3, guard) : n3 === undefined$1) {
          n3 = 1;
        } else {
          n3 = toInteger2(n3);
        }
        return baseRepeat(toString5(string2), n3);
      }
      function replace2() {
        var args = arguments, string2 = toString5(args[0]);
        return args.length < 3 ? string2 : string2.replace(args[1], args[2]);
      }
      var snakeCase = createCompounder2(function(result2, word, index3) {
        return result2 + (index3 ? "_" : "") + word.toLowerCase();
      });
      function split2(string2, separator, limit) {
        if (limit && typeof limit != "number" && isIterateeCall2(string2, separator, limit)) {
          separator = limit = undefined$1;
        }
        limit = limit === undefined$1 ? MAX_ARRAY_LENGTH : limit >>> 0;
        if (!limit) {
          return [];
        }
        string2 = toString5(string2);
        if (string2 && (typeof separator == "string" || separator != null && !isRegExp(separator))) {
          separator = baseToString3(separator);
          if (!separator && hasUnicode3(string2)) {
            return castSlice2(stringToArray2(string2), 0, limit);
          }
        }
        return string2.split(separator, limit);
      }
      var startCase = createCompounder2(function(result2, word, index3) {
        return result2 + (index3 ? " " : "") + upperFirst2(word);
      });
      function startsWith2(string2, target, position2) {
        string2 = toString5(string2);
        position2 = position2 == null ? 0 : baseClamp(toInteger2(position2), 0, string2.length);
        target = baseToString3(target);
        return string2.slice(position2, position2 + target.length) == target;
      }
      function template(string2, options, guard) {
        var settings = lodash3.templateSettings;
        if (guard && isIterateeCall2(string2, options, guard)) {
          options = undefined$1;
        }
        string2 = toString5(string2);
        options = assignInWith({}, options, settings, customDefaultsAssignIn);
        var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys2(imports), importsValues = baseValues2(imports, importsKeys);
        var isEscaping, isEvaluating, index3 = 0, interpolate2 = options.interpolate || reNoMatch, source2 = "__p += '";
        var reDelimiters = RegExp2((options.escape || reNoMatch).source + "|" + interpolate2.source + "|" + (interpolate2 === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g");
        var sourceURL = "//# sourceURL=" + (hasOwnProperty6.call(options, "sourceURL") ? (options.sourceURL + "").replace(/\s/g, " ") : "lodash.templateSources[" + ++templateCounter + "]") + "\n";
        string2.replace(reDelimiters, function(match2, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset2) {
          interpolateValue || (interpolateValue = esTemplateValue);
          source2 += string2.slice(index3, offset2).replace(reUnescapedString, escapeStringChar);
          if (escapeValue) {
            isEscaping = true;
            source2 += "' +\n__e(" + escapeValue + ") +\n'";
          }
          if (evaluateValue) {
            isEvaluating = true;
            source2 += "';\n" + evaluateValue + ";\n__p += '";
          }
          if (interpolateValue) {
            source2 += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
          }
          index3 = offset2 + match2.length;
          return match2;
        });
        source2 += "';\n";
        var variable = hasOwnProperty6.call(options, "variable") && options.variable;
        if (!variable) {
          source2 = "with (obj) {\n" + source2 + "\n}\n";
        } else if (reForbiddenIdentifierChars.test(variable)) {
          throw new Error2(INVALID_TEMPL_VAR_ERROR_TEXT);
        }
        source2 = (isEvaluating ? source2.replace(reEmptyStringLeading, "") : source2).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;");
        source2 = "function(" + (variable || "obj") + ") {\n" + (variable ? "" : "obj || (obj = {});\n") + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n" : ";\n") + source2 + "return __p\n}";
        var result2 = attempt(function() {
          return Function2(importsKeys, sourceURL + "return " + source2).apply(undefined$1, importsValues);
        });
        result2.source = source2;
        if (isError(result2)) {
          throw result2;
        }
        return result2;
      }
      function toLower(value) {
        return toString5(value).toLowerCase();
      }
      function toUpper(value) {
        return toString5(value).toUpperCase();
      }
      function trim2(string2, chars2, guard) {
        string2 = toString5(string2);
        if (string2 && (guard || chars2 === undefined$1)) {
          return baseTrim2(string2);
        }
        if (!string2 || !(chars2 = baseToString3(chars2))) {
          return string2;
        }
        var strSymbols = stringToArray2(string2), chrSymbols = stringToArray2(chars2), start3 = charsStartIndex(strSymbols, chrSymbols), end2 = charsEndIndex(strSymbols, chrSymbols) + 1;
        return castSlice2(strSymbols, start3, end2).join("");
      }
      function trimEnd(string2, chars2, guard) {
        string2 = toString5(string2);
        if (string2 && (guard || chars2 === undefined$1)) {
          return string2.slice(0, trimmedEndIndex2(string2) + 1);
        }
        if (!string2 || !(chars2 = baseToString3(chars2))) {
          return string2;
        }
        var strSymbols = stringToArray2(string2), end2 = charsEndIndex(strSymbols, stringToArray2(chars2)) + 1;
        return castSlice2(strSymbols, 0, end2).join("");
      }
      function trimStart(string2, chars2, guard) {
        string2 = toString5(string2);
        if (string2 && (guard || chars2 === undefined$1)) {
          return string2.replace(reTrimStart2, "");
        }
        if (!string2 || !(chars2 = baseToString3(chars2))) {
          return string2;
        }
        var strSymbols = stringToArray2(string2), start3 = charsStartIndex(strSymbols, stringToArray2(chars2));
        return castSlice2(strSymbols, start3).join("");
      }
      function truncate(string2, options) {
        var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION;
        if (isObject5(options)) {
          var separator = "separator" in options ? options.separator : separator;
          length = "length" in options ? toInteger2(options.length) : length;
          omission = "omission" in options ? baseToString3(options.omission) : omission;
        }
        string2 = toString5(string2);
        var strLength = string2.length;
        if (hasUnicode3(string2)) {
          var strSymbols = stringToArray2(string2);
          strLength = strSymbols.length;
        }
        if (length >= strLength) {
          return string2;
        }
        var end2 = length - stringSize2(omission);
        if (end2 < 1) {
          return omission;
        }
        var result2 = strSymbols ? castSlice2(strSymbols, 0, end2).join("") : string2.slice(0, end2);
        if (separator === undefined$1) {
          return result2 + omission;
        }
        if (strSymbols) {
          end2 += result2.length - end2;
        }
        if (isRegExp(separator)) {
          if (string2.slice(end2).search(separator)) {
            var match2, substring = result2;
            if (!separator.global) {
              separator = RegExp2(separator.source, toString5(reFlags2.exec(separator)) + "g");
            }
            separator.lastIndex = 0;
            while (match2 = separator.exec(substring)) {
              var newEnd = match2.index;
            }
            result2 = result2.slice(0, newEnd === undefined$1 ? end2 : newEnd);
          }
        } else if (string2.indexOf(baseToString3(separator), end2) != end2) {
          var index3 = result2.lastIndexOf(separator);
          if (index3 > -1) {
            result2 = result2.slice(0, index3);
          }
        }
        return result2 + omission;
      }
      function unescape3(string2) {
        string2 = toString5(string2);
        return string2 && reHasEscapedHtml.test(string2) ? string2.replace(reEscapedHtml, unescapeHtmlChar) : string2;
      }
      var upperCase = createCompounder2(function(result2, word, index3) {
        return result2 + (index3 ? " " : "") + word.toUpperCase();
      });
      var upperFirst2 = createCaseFirst2("toUpperCase");
      function words2(string2, pattern, guard) {
        string2 = toString5(string2);
        pattern = guard ? undefined$1 : pattern;
        if (pattern === undefined$1) {
          return hasUnicodeWord2(string2) ? unicodeWords2(string2) : asciiWords2(string2);
        }
        return string2.match(pattern) || [];
      }
      var attempt = baseRest2(function(func, args) {
        try {
          return apply2(func, undefined$1, args);
        } catch (e2) {
          return isError(e2) ? e2 : new Error2(e2);
        }
      });
      var bindAll = flatRest2(function(object, methodNames) {
        arrayEach2(methodNames, function(key) {
          key = toKey2(key);
          baseAssignValue2(object, key, bind3(object[key], object));
        });
        return object;
      });
      function cond(pairs) {
        var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee();
        pairs = !length ? [] : arrayMap2(pairs, function(pair) {
          if (typeof pair[1] != "function") {
            throw new TypeError2(FUNC_ERROR_TEXT2);
          }
          return [toIteratee(pair[0]), pair[1]];
        });
        return baseRest2(function(args) {
          var index3 = -1;
          while (++index3 < length) {
            var pair = pairs[index3];
            if (apply2(pair[0], this, args)) {
              return apply2(pair[1], this, args);
            }
          }
        });
      }
      function conforms(source2) {
        return baseConforms(baseClone2(source2, CLONE_DEEP_FLAG2));
      }
      function constant3(value) {
        return function() {
          return value;
        };
      }
      function defaultTo(value, defaultValue) {
        return value == null || value !== value ? defaultValue : value;
      }
      var flow = createFlow();
      var flowRight = createFlow(true);
      function identity3(value) {
        return value;
      }
      function iteratee(func) {
        return baseIteratee2(typeof func == "function" ? func : baseClone2(func, CLONE_DEEP_FLAG2));
      }
      function matches2(source2) {
        return baseMatches2(baseClone2(source2, CLONE_DEEP_FLAG2));
      }
      function matchesProperty(path, srcValue) {
        return baseMatchesProperty2(path, baseClone2(srcValue, CLONE_DEEP_FLAG2));
      }
      var method = baseRest2(function(path, args) {
        return function(object) {
          return baseInvoke(object, path, args);
        };
      });
      var methodOf = baseRest2(function(object, args) {
        return function(path) {
          return baseInvoke(object, path, args);
        };
      });
      function mixin2(object, source2, options) {
        var props = keys2(source2), methodNames = baseFunctions(source2, props);
        if (options == null && !(isObject5(source2) && (methodNames.length || !props.length))) {
          options = source2;
          source2 = object;
          object = this;
          methodNames = baseFunctions(source2, keys2(source2));
        }
        var chain2 = !(isObject5(options) && "chain" in options) || !!options.chain, isFunc = isFunction6(object);
        arrayEach2(methodNames, function(methodName) {
          var func = source2[methodName];
          object[methodName] = func;
          if (isFunc) {
            object.prototype[methodName] = function() {
              var chainAll = this.__chain__;
              if (chain2 || chainAll) {
                var result2 = object(this.__wrapped__), actions2 = result2.__actions__ = copyArray2(this.__actions__);
                actions2.push({func, args: arguments, thisArg: object});
                result2.__chain__ = chainAll;
                return result2;
              }
              return func.apply(object, arrayPush2([this.value()], arguments));
            };
          }
        });
        return object;
      }
      function noConflict() {
        if (root4._ === this) {
          root4._ = oldDash;
        }
        return this;
      }
      function noop7() {
      }
      function nthArg(n3) {
        n3 = toInteger2(n3);
        return baseRest2(function(args) {
          return baseNth(args, n3);
        });
      }
      var over = createOver(arrayMap2);
      var overEvery = createOver(arrayEvery);
      var overSome = createOver(arraySome2);
      function property2(path) {
        return isKey3(path) ? baseProperty2(toKey2(path)) : basePropertyDeep2(path);
      }
      function propertyOf(object) {
        return function(path) {
          return object == null ? undefined$1 : baseGet3(object, path);
        };
      }
      var range3 = createRange2();
      var rangeRight = createRange2(true);
      function stubArray2() {
        return [];
      }
      function stubFalse2() {
        return false;
      }
      function stubObject() {
        return {};
      }
      function stubString() {
        return "";
      }
      function stubTrue() {
        return true;
      }
      function times(n3, iteratee2) {
        n3 = toInteger2(n3);
        if (n3 < 1 || n3 > MAX_SAFE_INTEGER2) {
          return [];
        }
        var index3 = MAX_ARRAY_LENGTH, length = nativeMin(n3, MAX_ARRAY_LENGTH);
        iteratee2 = getIteratee(iteratee2);
        n3 -= MAX_ARRAY_LENGTH;
        var result2 = baseTimes2(length, iteratee2);
        while (++index3 < n3) {
          iteratee2(index3);
        }
        return result2;
      }
      function toPath(value) {
        if (isArray3(value)) {
          return arrayMap2(value, toKey2);
        }
        return isSymbol3(value) ? [value] : copyArray2(stringToPath3(toString5(value)));
      }
      function uniqueId2(prefix2) {
        var id3 = ++idCounter2;
        return toString5(prefix2) + id3;
      }
      var add = createMathOperation(function(augend, addend) {
        return augend + addend;
      }, 0);
      var ceil = createRound("ceil");
      var divide = createMathOperation(function(dividend, divisor) {
        return dividend / divisor;
      }, 1);
      var floor = createRound("floor");
      function max2(array2) {
        return array2 && array2.length ? baseExtremum2(array2, identity3, baseGt2) : undefined$1;
      }
      function maxBy(array2, iteratee2) {
        return array2 && array2.length ? baseExtremum2(array2, getIteratee(iteratee2, 2), baseGt2) : undefined$1;
      }
      function mean(array2) {
        return baseMean(array2, identity3);
      }
      function meanBy(array2, iteratee2) {
        return baseMean(array2, getIteratee(iteratee2, 2));
      }
      function min2(array2) {
        return array2 && array2.length ? baseExtremum2(array2, identity3, baseLt2) : undefined$1;
      }
      function minBy2(array2, iteratee2) {
        return array2 && array2.length ? baseExtremum2(array2, getIteratee(iteratee2, 2), baseLt2) : undefined$1;
      }
      var multiply = createMathOperation(function(multiplier, multiplicand) {
        return multiplier * multiplicand;
      }, 1);
      var round = createRound("round");
      var subtract = createMathOperation(function(minuend, subtrahend) {
        return minuend - subtrahend;
      }, 0);
      function sum(array2) {
        return array2 && array2.length ? baseSum(array2, identity3) : 0;
      }
      function sumBy(array2, iteratee2) {
        return array2 && array2.length ? baseSum(array2, getIteratee(iteratee2, 2)) : 0;
      }
      lodash3.after = after;
      lodash3.ary = ary;
      lodash3.assign = assign2;
      lodash3.assignIn = assignIn;
      lodash3.assignInWith = assignInWith;
      lodash3.assignWith = assignWith;
      lodash3.at = at;
      lodash3.before = before;
      lodash3.bind = bind3;
      lodash3.bindAll = bindAll;
      lodash3.bindKey = bindKey2;
      lodash3.castArray = castArray;
      lodash3.chain = chain;
      lodash3.chunk = chunk;
      lodash3.compact = compact2;
      lodash3.concat = concat2;
      lodash3.cond = cond;
      lodash3.conforms = conforms;
      lodash3.constant = constant3;
      lodash3.countBy = countBy;
      lodash3.create = create3;
      lodash3.curry = curry;
      lodash3.curryRight = curryRight;
      lodash3.debounce = debounce2;
      lodash3.defaults = defaults3;
      lodash3.defaultsDeep = defaultsDeep;
      lodash3.defer = defer2;
      lodash3.delay = delay3;
      lodash3.difference = difference;
      lodash3.differenceBy = differenceBy;
      lodash3.differenceWith = differenceWith;
      lodash3.drop = drop;
      lodash3.dropRight = dropRight;
      lodash3.dropRightWhile = dropRightWhile;
      lodash3.dropWhile = dropWhile;
      lodash3.fill = fill2;
      lodash3.filter = filter3;
      lodash3.flatMap = flatMap;
      lodash3.flatMapDeep = flatMapDeep;
      lodash3.flatMapDepth = flatMapDepth;
      lodash3.flatten = flatten4;
      lodash3.flattenDeep = flattenDeep;
      lodash3.flattenDepth = flattenDepth;
      lodash3.flip = flip2;
      lodash3.flow = flow;
      lodash3.flowRight = flowRight;
      lodash3.fromPairs = fromPairs;
      lodash3.functions = functions;
      lodash3.functionsIn = functionsIn;
      lodash3.groupBy = groupBy;
      lodash3.initial = initial;
      lodash3.intersection = intersection;
      lodash3.intersectionBy = intersectionBy2;
      lodash3.intersectionWith = intersectionWith;
      lodash3.invert = invert;
      lodash3.invertBy = invertBy;
      lodash3.invokeMap = invokeMap;
      lodash3.iteratee = iteratee;
      lodash3.keyBy = keyBy;
      lodash3.keys = keys2;
      lodash3.keysIn = keysIn2;
      lodash3.map = map2;
      lodash3.mapKeys = mapKeys;
      lodash3.mapValues = mapValues2;
      lodash3.matches = matches2;
      lodash3.matchesProperty = matchesProperty;
      lodash3.memoize = memoize3;
      lodash3.merge = merge3;
      lodash3.mergeWith = mergeWith2;
      lodash3.method = method;
      lodash3.methodOf = methodOf;
      lodash3.mixin = mixin2;
      lodash3.negate = negate;
      lodash3.nthArg = nthArg;
      lodash3.omit = omit2;
      lodash3.omitBy = omitBy;
      lodash3.once = once3;
      lodash3.orderBy = orderBy;
      lodash3.over = over;
      lodash3.overArgs = overArgs;
      lodash3.overEvery = overEvery;
      lodash3.overSome = overSome;
      lodash3.partial = partial;
      lodash3.partialRight = partialRight;
      lodash3.partition = partition2;
      lodash3.pick = pick2;
      lodash3.pickBy = pickBy2;
      lodash3.property = property2;
      lodash3.propertyOf = propertyOf;
      lodash3.pull = pull;
      lodash3.pullAll = pullAll;
      lodash3.pullAllBy = pullAllBy;
      lodash3.pullAllWith = pullAllWith;
      lodash3.pullAt = pullAt;
      lodash3.range = range3;
      lodash3.rangeRight = rangeRight;
      lodash3.rearg = rearg;
      lodash3.reject = reject;
      lodash3.remove = remove3;
      lodash3.rest = rest;
      lodash3.reverse = reverse;
      lodash3.sampleSize = sampleSize;
      lodash3.set = set3;
      lodash3.setWith = setWith;
      lodash3.shuffle = shuffle;
      lodash3.slice = slice;
      lodash3.sortBy = sortBy3;
      lodash3.sortedUniq = sortedUniq2;
      lodash3.sortedUniqBy = sortedUniqBy;
      lodash3.split = split2;
      lodash3.spread = spread3;
      lodash3.tail = tail3;
      lodash3.take = take;
      lodash3.takeRight = takeRight;
      lodash3.takeRightWhile = takeRightWhile;
      lodash3.takeWhile = takeWhile;
      lodash3.tap = tap;
      lodash3.throttle = throttle;
      lodash3.thru = thru;
      lodash3.toArray = toArray;
      lodash3.toPairs = toPairs;
      lodash3.toPairsIn = toPairsIn;
      lodash3.toPath = toPath;
      lodash3.toPlainObject = toPlainObject2;
      lodash3.transform = transform3;
      lodash3.unary = unary;
      lodash3.union = union2;
      lodash3.unionBy = unionBy;
      lodash3.unionWith = unionWith;
      lodash3.uniq = uniq;
      lodash3.uniqBy = uniqBy;
      lodash3.uniqWith = uniqWith;
      lodash3.unset = unset2;
      lodash3.unzip = unzip;
      lodash3.unzipWith = unzipWith;
      lodash3.update = update;
      lodash3.updateWith = updateWith;
      lodash3.values = values2;
      lodash3.valuesIn = valuesIn;
      lodash3.without = without;
      lodash3.words = words2;
      lodash3.wrap = wrap;
      lodash3.xor = xor2;
      lodash3.xorBy = xorBy;
      lodash3.xorWith = xorWith;
      lodash3.zip = zip;
      lodash3.zipObject = zipObject2;
      lodash3.zipObjectDeep = zipObjectDeep;
      lodash3.zipWith = zipWith;
      lodash3.entries = toPairs;
      lodash3.entriesIn = toPairsIn;
      lodash3.extend = assignIn;
      lodash3.extendWith = assignInWith;
      mixin2(lodash3, lodash3);
      lodash3.add = add;
      lodash3.attempt = attempt;
      lodash3.camelCase = camelCase3;
      lodash3.capitalize = capitalize5;
      lodash3.ceil = ceil;
      lodash3.clamp = clamp5;
      lodash3.clone = clone2;
      lodash3.cloneDeep = cloneDeep3;
      lodash3.cloneDeepWith = cloneDeepWith;
      lodash3.cloneWith = cloneWith;
      lodash3.conformsTo = conformsTo;
      lodash3.deburr = deburr2;
      lodash3.defaultTo = defaultTo;
      lodash3.divide = divide;
      lodash3.endsWith = endsWith2;
      lodash3.eq = eq2;
      lodash3.escape = escape4;
      lodash3.escapeRegExp = escapeRegExp;
      lodash3.every = every;
      lodash3.find = find3;
      lodash3.findIndex = findIndex2;
      lodash3.findKey = findKey;
      lodash3.findLast = findLast;
      lodash3.findLastIndex = findLastIndex;
      lodash3.findLastKey = findLastKey;
      lodash3.floor = floor;
      lodash3.forEach = forEach5;
      lodash3.forEachRight = forEachRight;
      lodash3.forIn = forIn2;
      lodash3.forInRight = forInRight;
      lodash3.forOwn = forOwn;
      lodash3.forOwnRight = forOwnRight;
      lodash3.get = get7;
      lodash3.gt = gt;
      lodash3.gte = gte;
      lodash3.has = has3;
      lodash3.hasIn = hasIn2;
      lodash3.head = head;
      lodash3.identity = identity3;
      lodash3.includes = includes;
      lodash3.indexOf = indexOf;
      lodash3.inRange = inRange;
      lodash3.invoke = invoke;
      lodash3.isArguments = isArguments2;
      lodash3.isArray = isArray3;
      lodash3.isArrayBuffer = isArrayBuffer2;
      lodash3.isArrayLike = isArrayLike2;
      lodash3.isArrayLikeObject = isArrayLikeObject2;
      lodash3.isBoolean = isBoolean3;
      lodash3.isBuffer = isBuffer3;
      lodash3.isDate = isDate2;
      lodash3.isElement = isElement3;
      lodash3.isEmpty = isEmpty3;
      lodash3.isEqual = isEqual4;
      lodash3.isEqualWith = isEqualWith2;
      lodash3.isError = isError;
      lodash3.isFinite = isFinite2;
      lodash3.isFunction = isFunction6;
      lodash3.isInteger = isInteger;
      lodash3.isLength = isLength2;
      lodash3.isMap = isMap2;
      lodash3.isMatch = isMatch;
      lodash3.isMatchWith = isMatchWith;
      lodash3.isNaN = isNaN2;
      lodash3.isNative = isNative2;
      lodash3.isNil = isNil;
      lodash3.isNull = isNull;
      lodash3.isNumber = isNumber3;
      lodash3.isObject = isObject5;
      lodash3.isObjectLike = isObjectLike3;
      lodash3.isPlainObject = isPlainObject4;
      lodash3.isRegExp = isRegExp;
      lodash3.isSafeInteger = isSafeInteger;
      lodash3.isSet = isSet2;
      lodash3.isString = isString5;
      lodash3.isSymbol = isSymbol3;
      lodash3.isTypedArray = isTypedArray2;
      lodash3.isUndefined = isUndefined5;
      lodash3.isWeakMap = isWeakMap;
      lodash3.isWeakSet = isWeakSet;
      lodash3.join = join2;
      lodash3.kebabCase = kebabCase;
      lodash3.last = last2;
      lodash3.lastIndexOf = lastIndexOf;
      lodash3.lowerCase = lowerCase;
      lodash3.lowerFirst = lowerFirst;
      lodash3.lt = lt;
      lodash3.lte = lte;
      lodash3.max = max2;
      lodash3.maxBy = maxBy;
      lodash3.mean = mean;
      lodash3.meanBy = meanBy;
      lodash3.min = min2;
      lodash3.minBy = minBy2;
      lodash3.stubArray = stubArray2;
      lodash3.stubFalse = stubFalse2;
      lodash3.stubObject = stubObject;
      lodash3.stubString = stubString;
      lodash3.stubTrue = stubTrue;
      lodash3.multiply = multiply;
      lodash3.nth = nth;
      lodash3.noConflict = noConflict;
      lodash3.noop = noop7;
      lodash3.now = now3;
      lodash3.pad = pad;
      lodash3.padEnd = padEnd;
      lodash3.padStart = padStart;
      lodash3.parseInt = parseInt2;
      lodash3.random = random;
      lodash3.reduce = reduce2;
      lodash3.reduceRight = reduceRight;
      lodash3.repeat = repeat;
      lodash3.replace = replace2;
      lodash3.result = result;
      lodash3.round = round;
      lodash3.runInContext = runInContext2;
      lodash3.sample = sample;
      lodash3.size = size2;
      lodash3.snakeCase = snakeCase;
      lodash3.some = some;
      lodash3.sortedIndex = sortedIndex;
      lodash3.sortedIndexBy = sortedIndexBy;
      lodash3.sortedIndexOf = sortedIndexOf;
      lodash3.sortedLastIndex = sortedLastIndex;
      lodash3.sortedLastIndexBy = sortedLastIndexBy;
      lodash3.sortedLastIndexOf = sortedLastIndexOf;
      lodash3.startCase = startCase;
      lodash3.startsWith = startsWith2;
      lodash3.subtract = subtract;
      lodash3.sum = sum;
      lodash3.sumBy = sumBy;
      lodash3.template = template;
      lodash3.times = times;
      lodash3.toFinite = toFinite2;
      lodash3.toInteger = toInteger2;
      lodash3.toLength = toLength;
      lodash3.toLower = toLower;
      lodash3.toNumber = toNumber2;
      lodash3.toSafeInteger = toSafeInteger;
      lodash3.toString = toString5;
      lodash3.toUpper = toUpper;
      lodash3.trim = trim2;
      lodash3.trimEnd = trimEnd;
      lodash3.trimStart = trimStart;
      lodash3.truncate = truncate;
      lodash3.unescape = unescape3;
      lodash3.uniqueId = uniqueId2;
      lodash3.upperCase = upperCase;
      lodash3.upperFirst = upperFirst2;
      lodash3.each = forEach5;
      lodash3.eachRight = forEachRight;
      lodash3.first = head;
      mixin2(lodash3, function() {
        var source2 = {};
        baseForOwn2(lodash3, function(func, methodName) {
          if (!hasOwnProperty6.call(lodash3.prototype, methodName)) {
            source2[methodName] = func;
          }
        });
        return source2;
      }(), {chain: false});
      lodash3.VERSION = VERSION2;
      arrayEach2(["bind", "bindKey", "curry", "curryRight", "partial", "partialRight"], function(methodName) {
        lodash3[methodName].placeholder = lodash3;
      });
      arrayEach2(["drop", "take"], function(methodName, index3) {
        LazyWrapper.prototype[methodName] = function(n3) {
          n3 = n3 === undefined$1 ? 1 : nativeMax3(toInteger2(n3), 0);
          var result2 = this.__filtered__ && !index3 ? new LazyWrapper(this) : this.clone();
          if (result2.__filtered__) {
            result2.__takeCount__ = nativeMin(n3, result2.__takeCount__);
          } else {
            result2.__views__.push({
              size: nativeMin(n3, MAX_ARRAY_LENGTH),
              type: methodName + (result2.__dir__ < 0 ? "Right" : "")
            });
          }
          return result2;
        };
        LazyWrapper.prototype[methodName + "Right"] = function(n3) {
          return this.reverse()[methodName](n3).reverse();
        };
      });
      arrayEach2(["filter", "map", "takeWhile"], function(methodName, index3) {
        var type = index3 + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
        LazyWrapper.prototype[methodName] = function(iteratee2) {
          var result2 = this.clone();
          result2.__iteratees__.push({
            iteratee: getIteratee(iteratee2, 3),
            type
          });
          result2.__filtered__ = result2.__filtered__ || isFilter;
          return result2;
        };
      });
      arrayEach2(["head", "last"], function(methodName, index3) {
        var takeName = "take" + (index3 ? "Right" : "");
        LazyWrapper.prototype[methodName] = function() {
          return this[takeName](1).value()[0];
        };
      });
      arrayEach2(["initial", "tail"], function(methodName, index3) {
        var dropName = "drop" + (index3 ? "" : "Right");
        LazyWrapper.prototype[methodName] = function() {
          return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
        };
      });
      LazyWrapper.prototype.compact = function() {
        return this.filter(identity3);
      };
      LazyWrapper.prototype.find = function(predicate) {
        return this.filter(predicate).head();
      };
      LazyWrapper.prototype.findLast = function(predicate) {
        return this.reverse().find(predicate);
      };
      LazyWrapper.prototype.invokeMap = baseRest2(function(path, args) {
        if (typeof path == "function") {
          return new LazyWrapper(this);
        }
        return this.map(function(value) {
          return baseInvoke(value, path, args);
        });
      });
      LazyWrapper.prototype.reject = function(predicate) {
        return this.filter(negate(getIteratee(predicate)));
      };
      LazyWrapper.prototype.slice = function(start3, end2) {
        start3 = toInteger2(start3);
        var result2 = this;
        if (result2.__filtered__ && (start3 > 0 || end2 < 0)) {
          return new LazyWrapper(result2);
        }
        if (start3 < 0) {
          result2 = result2.takeRight(-start3);
        } else if (start3) {
          result2 = result2.drop(start3);
        }
        if (end2 !== undefined$1) {
          end2 = toInteger2(end2);
          result2 = end2 < 0 ? result2.dropRight(-end2) : result2.take(end2 - start3);
        }
        return result2;
      };
      LazyWrapper.prototype.takeRightWhile = function(predicate) {
        return this.reverse().takeWhile(predicate).reverse();
      };
      LazyWrapper.prototype.toArray = function() {
        return this.take(MAX_ARRAY_LENGTH);
      };
      baseForOwn2(LazyWrapper.prototype, function(func, methodName) {
        var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash3[isTaker ? "take" + (methodName == "last" ? "Right" : "") : methodName], retUnwrapped = isTaker || /^find/.test(methodName);
        if (!lodashFunc) {
          return;
        }
        lodash3.prototype[methodName] = function() {
          var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy2 = value instanceof LazyWrapper, iteratee2 = args[0], useLazy = isLazy2 || isArray3(value);
          var interceptor = function(value2) {
            var result3 = lodashFunc.apply(lodash3, arrayPush2([value2], args));
            return isTaker && chainAll ? result3[0] : result3;
          };
          if (useLazy && checkIteratee && typeof iteratee2 == "function" && iteratee2.length != 1) {
            isLazy2 = useLazy = false;
          }
          var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy2 && !isHybrid;
          if (!retUnwrapped && useLazy) {
            value = onlyLazy ? value : new LazyWrapper(this);
            var result2 = func.apply(value, args);
            result2.__actions__.push({func: thru, args: [interceptor], thisArg: undefined$1});
            return new LodashWrapper(result2, chainAll);
          }
          if (isUnwrapped && onlyLazy) {
            return func.apply(this, args);
          }
          result2 = this.thru(interceptor);
          return isUnwrapped ? isTaker ? result2.value()[0] : result2.value() : result2;
        };
      });
      arrayEach2(["pop", "push", "shift", "sort", "splice", "unshift"], function(methodName) {
        var func = arrayProto2[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? "tap" : "thru", retUnwrapped = /^(?:pop|shift)$/.test(methodName);
        lodash3.prototype[methodName] = function() {
          var args = arguments;
          if (retUnwrapped && !this.__chain__) {
            var value = this.value();
            return func.apply(isArray3(value) ? value : [], args);
          }
          return this[chainName](function(value2) {
            return func.apply(isArray3(value2) ? value2 : [], args);
          });
        };
      });
      baseForOwn2(LazyWrapper.prototype, function(func, methodName) {
        var lodashFunc = lodash3[methodName];
        if (lodashFunc) {
          var key = lodashFunc.name + "";
          if (!hasOwnProperty6.call(realNames, key)) {
            realNames[key] = [];
          }
          realNames[key].push({name: methodName, func: lodashFunc});
        }
      });
      realNames[createHybrid(undefined$1, WRAP_BIND_KEY_FLAG).name] = [{
        name: "wrapper",
        func: undefined$1
      }];
      LazyWrapper.prototype.clone = lazyClone;
      LazyWrapper.prototype.reverse = lazyReverse;
      LazyWrapper.prototype.value = lazyValue;
      lodash3.prototype.at = wrapperAt;
      lodash3.prototype.chain = wrapperChain;
      lodash3.prototype.commit = wrapperCommit;
      lodash3.prototype.next = wrapperNext;
      lodash3.prototype.plant = wrapperPlant;
      lodash3.prototype.reverse = wrapperReverse;
      lodash3.prototype.toJSON = lodash3.prototype.valueOf = lodash3.prototype.value = wrapperValue;
      lodash3.prototype.first = lodash3.prototype.head;
      if (symIterator) {
        lodash3.prototype[symIterator] = wrapperToIterator;
      }
      return lodash3;
    };
    var _23 = runInContext();
    if (freeModule) {
      (freeModule.exports = _23)._ = _23;
      freeExports._ = _23;
    } else {
      root4._ = _23;
    }
  }).call(commonjsGlobal);
});

// build/_snowpack/pkg/lodash.js
var camelCase2 = lodash.camelCase;
var cloneDeep = lodash.cloneDeep;
var get = lodash.get;
var intersectionBy = lodash.intersectionBy;
var omit = lodash.omit;
var pickBy = lodash.pickBy;
var sortBy = lodash.sortBy;
var sortedUniq = lodash.sortedUniq;
var xor = lodash.xor;

// build/components/keycloak-spinner/KeycloakSpinner.js
var KeycloakSpinner = () => /* @__PURE__ */ react.createElement("div", {
  className: "pf-u-text-align-center"
}, /* @__PURE__ */ react.createElement(Spinner, null));

// build/components/data-loader/DataLoader.js
function DataLoader(props) {
  const [data2, setData] = useState();
  useFetch(() => props.loader(), (result) => setData(result), props.deps || []);
  if (data2) {
    if (props.children instanceof Function) {
      return props.children(data2);
    }
    return props.children;
  }
  return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
}

// build/_snowpack/pkg/file-saver.js
var FileSaver_min = createCommonjsModule(function(module2, exports2) {
  (function(a2, b2) {
    b2();
  })(commonjsGlobal, function() {
    function b2(a3, b3) {
      return typeof b3 == "undefined" ? b3 = {autoBom: false} : typeof b3 != "object" && (console.warn("Deprecated: Expected third argument to be a object"), b3 = {autoBom: !b3}), b3.autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a3.type) ? new Blob(["\uFEFF", a3], {type: a3.type}) : a3;
    }
    function c3(a3, b3, c4) {
      var d3 = new XMLHttpRequest();
      d3.open("GET", a3), d3.responseType = "blob", d3.onload = function() {
        g2(d3.response, b3, c4);
      }, d3.onerror = function() {
        console.error("could not download file");
      }, d3.send();
    }
    function d2(a3) {
      var b3 = new XMLHttpRequest();
      b3.open("HEAD", a3, false);
      try {
        b3.send();
      } catch (a4) {
      }
      return 200 <= b3.status && 299 >= b3.status;
    }
    function e2(a3) {
      try {
        a3.dispatchEvent(new MouseEvent("click"));
      } catch (c4) {
        var b3 = document.createEvent("MouseEvents");
        b3.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null), a3.dispatchEvent(b3);
      }
    }
    var f2 = typeof window == "object" && window.window === window ? window : typeof self == "object" && self.self === self ? self : typeof commonjsGlobal == "object" && commonjsGlobal.global === commonjsGlobal ? commonjsGlobal : void 0, a2 = f2.navigator && /Macintosh/.test(navigator.userAgent) && /AppleWebKit/.test(navigator.userAgent) && !/Safari/.test(navigator.userAgent), g2 = f2.saveAs || (typeof window != "object" || window !== f2 ? function() {
    } : "download" in HTMLAnchorElement.prototype && !a2 ? function(b3, g3, h2) {
      var i3 = f2.URL || f2.webkitURL, j = document.createElement("a");
      g3 = g3 || b3.name || "download", j.download = g3, j.rel = "noopener", typeof b3 == "string" ? (j.href = b3, j.origin === location.origin ? e2(j) : d2(j.href) ? c3(b3, g3, h2) : e2(j, j.target = "_blank")) : (j.href = i3.createObjectURL(b3), setTimeout(function() {
        i3.revokeObjectURL(j.href);
      }, 4e4), setTimeout(function() {
        e2(j);
      }, 0));
    } : "msSaveOrOpenBlob" in navigator ? function(f3, g3, h2) {
      if (g3 = g3 || f3.name || "download", typeof f3 != "string")
        navigator.msSaveOrOpenBlob(b2(f3, h2), g3);
      else if (d2(f3))
        c3(f3, g3, h2);
      else {
        var i3 = document.createElement("a");
        i3.href = f3, i3.target = "_blank", setTimeout(function() {
          e2(i3);
        });
      }
    } : function(b3, d3, e3, g3) {
      if (g3 = g3 || open("", "_blank"), g3 && (g3.document.title = g3.document.body.innerText = "downloading..."), typeof b3 == "string")
        return c3(b3, d3, e3);
      var h2 = b3.type === "application/octet-stream", i3 = /constructor/i.test(f2.HTMLElement) || f2.safari, j = /CriOS\/[\d]+/.test(navigator.userAgent);
      if ((j || h2 && i3 || a2) && typeof FileReader != "undefined") {
        var k2 = new FileReader();
        k2.onloadend = function() {
          var a3 = k2.result;
          a3 = j ? a3 : a3.replace(/^data:[^;]*;/, "data:attachment/file;"), g3 ? g3.location.href = a3 : location = a3, g3 = null;
        }, k2.readAsDataURL(b3);
      } else {
        var l2 = f2.URL || f2.webkitURL, m2 = l2.createObjectURL(b3);
        g3 ? g3.location = m2 : location.href = m2, g3 = null, setTimeout(function() {
          l2.revokeObjectURL(m2);
        }, 4e4);
      }
    });
    f2.saveAs = g2.saveAs = g2, module2.exports = g2;
  });
});
var file_saver_default = FileSaver_min;

// build/_snowpack/pkg/flat.js
var flat = flatten2;
flatten2.flatten = flatten2;
flatten2.unflatten = unflatten;
function isBuffer2(obj) {
  return obj && obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
}
function keyIdentity(key) {
  return key;
}
function flatten2(target, opts) {
  opts = opts || {};
  const delimiter = opts.delimiter || ".";
  const maxDepth = opts.maxDepth;
  const transformKey = opts.transformKey || keyIdentity;
  const output2 = {};
  function step(object, prev, currentDepth) {
    currentDepth = currentDepth || 1;
    Object.keys(object).forEach(function(key) {
      const value = object[key];
      const isarray2 = opts.safe && Array.isArray(value);
      const type = Object.prototype.toString.call(value);
      const isbuffer = isBuffer2(value);
      const isobject = type === "[object Object]" || type === "[object Array]";
      const newKey = prev ? prev + delimiter + transformKey(key) : transformKey(key);
      if (!isarray2 && !isbuffer && isobject && Object.keys(value).length && (!opts.maxDepth || currentDepth < maxDepth)) {
        return step(value, newKey, currentDepth + 1);
      }
      output2[newKey] = value;
    });
  }
  step(target);
  return output2;
}
function unflatten(target, opts) {
  opts = opts || {};
  const delimiter = opts.delimiter || ".";
  const overwrite = opts.overwrite || false;
  const transformKey = opts.transformKey || keyIdentity;
  const result = {};
  const isbuffer = isBuffer2(target);
  if (isbuffer || Object.prototype.toString.call(target) !== "[object Object]") {
    return target;
  }
  function getkey(key) {
    const parsedKey = Number(key);
    return isNaN(parsedKey) || key.indexOf(".") !== -1 || opts.object ? key : parsedKey;
  }
  function addKeys(keyPrefix, recipient, target2) {
    return Object.keys(target2).reduce(function(result2, key) {
      result2[keyPrefix + delimiter + key] = target2[key];
      return result2;
    }, recipient);
  }
  function isEmpty3(val) {
    const type = Object.prototype.toString.call(val);
    const isArray3 = type === "[object Array]";
    const isObject5 = type === "[object Object]";
    if (!val) {
      return true;
    } else if (isArray3) {
      return !val.length;
    } else if (isObject5) {
      return !Object.keys(val).length;
    }
  }
  target = Object.keys(target).reduce(function(result2, key) {
    const type = Object.prototype.toString.call(target[key]);
    const isObject5 = type === "[object Object]" || type === "[object Array]";
    if (!isObject5 || isEmpty3(target[key])) {
      result2[key] = target[key];
      return result2;
    } else {
      return addKeys(key, result2, flatten2(target[key], opts));
    }
  }, {});
  Object.keys(target).forEach(function(key) {
    const split2 = key.split(delimiter).map(transformKey);
    let key1 = getkey(split2.shift());
    let key2 = getkey(split2[0]);
    let recipient = result;
    while (key2 !== void 0) {
      if (key1 === "__proto__") {
        return;
      }
      const type = Object.prototype.toString.call(recipient[key1]);
      const isobject = type === "[object Object]" || type === "[object Array]";
      if (!overwrite && !isobject && typeof recipient[key1] !== "undefined") {
        return;
      }
      if (overwrite && !isobject || !overwrite && recipient[key1] == null) {
        recipient[key1] = typeof key2 === "number" && !opts.object ? [] : {};
      }
      recipient = recipient[key1];
      if (split2.length > 0) {
        key1 = getkey(split2.shift());
        key2 = getkey(split2[0]);
      }
    }
    recipient[key1] = unflatten(target[key], opts);
  });
  return result;
}
var flatten$1 = flat.flatten;
var unflatten$1 = flat.unflatten;

// build/components/attribute-form/attribute-convert.js
var arrayToAttributes = (attributeArray = []) => Object.fromEntries(attributeArray.filter(({key}) => key !== "").map(({key, value}) => [key, [value]]));
var attributesToArray = (attributes = {}) => {
  const result = Object.entries(attributes).flatMap(([key, value]) => value.map((value2) => ({key, value: value2})));
  return result.concat({key: "", value: ""});
};

// build/components/multi-line-input/multi-line-convert.js
function convertToMultiline(fields) {
  return (fields.length > 0 ? fields : [""]).map((field) => {
    return {value: field};
  });
}
function toValue(formValue) {
  return formValue.map((field) => field.value);
}

// build/util.js
var sortProviders = (providers) => {
  return [...new Map(Object.entries(providers).sort(sortProvider)).keys()];
};
var sortProvider = (a2, b2) => {
  let s1, s2;
  if (a2[1].order !== b2[1].order) {
    s1 = b2[1].order;
    s2 = a2[1].order;
  } else {
    s1 = a2[0];
    s2 = b2[0];
  }
  if (s1 < s2) {
    return -1;
  } else if (s1 > s2) {
    return 1;
  } else {
    return 0;
  }
};
var exportClient = (client2) => {
  const clientCopy = cloneDeep(client2);
  delete clientCopy.id;
  if (clientCopy.protocolMappers) {
    for (let i3 = 0; i3 < clientCopy.protocolMappers.length; i3++) {
      delete clientCopy.protocolMappers[i3].id;
    }
  }
  file_saver_default.saveAs(new Blob([prettyPrintJSON(clientCopy)], {
    type: "application/json"
  }), clientCopy.clientId + ".json");
};
var toUpperCase = (name) => name.charAt(0).toUpperCase() + name.slice(1);
var isAttributesObject = (value) => {
  return Object.values(value).filter((value2) => Array.isArray(value2) && value2.length === 1).length !== 0;
};
var isAttributeArray = (value) => {
  if (!Array.isArray(value)) {
    return false;
  }
  return value.filter((e2) => e2.key && e2.value).length !== 0;
};
var isEmpty = (obj) => Object.keys(obj).length === 0;
var convertToFormValues = (obj, setValue, multiline) => {
  Object.entries(obj).map(([key, value]) => {
    if (key === "attributes" && isAttributesObject(value)) {
      setValue(key, attributesToArray(value));
    } else if (key === "config" || key === "attributes") {
      setValue(key, !isEmpty(value) ? unflatten$1(value) : void 0);
    } else if (multiline?.includes(key)) {
      setValue(key, convertToMultiline(value));
    } else {
      setValue(key, value);
    }
  });
};
function convertFormValuesToObject(obj, multiline = []) {
  const result = {};
  Object.entries(obj).map(([key, value]) => {
    if (isAttributeArray(value)) {
      result[key] = arrayToAttributes(value);
    } else if (multiline.includes(key)) {
      result[key] = toValue(value);
    } else if (key === "config" || key === "attributes") {
      result[key] = flatten$1(value, {safe: true});
    } else {
      result[key] = value;
    }
  });
  return result;
}
var emptyFormatter = () => (data2) => {
  return data2 ? data2 : "—";
};
var upperCaseFormatter = () => (data2) => {
  const value = data2?.toString();
  return value ? toUpperCase(value) : void 0;
};
var getBaseUrl = (adminClient) => {
  return (adminClient.keycloak ? adminClient.keycloak.authServerUrl : adminClient.baseUrl) + "/";
};
var emailRegexPattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var forHumans = (seconds) => {
  const {t: t5} = useTranslation();
  const levels = [
    [Math.floor(seconds / 31536e3), t5("common:times.years")],
    [Math.floor(seconds % 31536e3 / 86400), t5("common:times.days")],
    [
      Math.floor(seconds % 31536e3 % 86400 / 3600),
      t5("common:times.hours")
    ],
    [
      Math.floor(seconds % 31536e3 % 86400 % 3600 / 60),
      t5("common:times.minutes")
    ],
    [seconds % 31536e3 % 86400 % 3600 % 60, t5("common:times.seconds")]
  ];
  let returntext = "";
  for (let i3 = 0, max2 = levels.length; i3 < max2; i3++) {
    if (levels[i3][0] === 0)
      continue;
    returntext += " " + levels[i3][0] + " " + (levels[i3][0] === 1 ? levels[i3][1].substr(0, levels[i3][1].length - 1) : levels[i3][1]);
  }
  return returntext.trim();
};
var interpolateTimespan = (forHumans2) => {
  const {t: t5} = useTranslation();
  const timespan = forHumans2.split(" ");
  if (timespan[1] === "Years") {
    return t5(`realm-settings:convertedToYearsValue`, {
      convertedToYears: forHumans2
    });
  }
  if (timespan[1] === "Days") {
    return t5(`realm-settings:convertedToDaysValue`, {
      convertedToYears: forHumans2
    });
  }
  if (timespan[1] === "Hours") {
    return t5(`realm-settings:convertedToHoursValue`, {
      convertedToHours: forHumans2
    });
  }
  if (timespan[1] === "Minutes") {
    return t5(`realm-settings:convertedToMinutesValue`, {
      convertedToMinutes: forHumans2
    });
  }
  if (timespan[1] === "Seconds") {
    return t5(`realm-settings:convertedToSecondsValue`, {
      convertedToSeconds: forHumans2
    });
  }
};
var KEY_PROVIDER_TYPE = "org.keycloak.keys.KeyProvider";
var prettyPrintJSON = (value) => JSON.stringify(value, null, 2);

// build/context/server-info/ServerInfoProvider.js
var ServerInfoContext = createContext(void 0);
var useServerInfo = () => useRequiredContext(ServerInfoContext);
var useLoginProviders = () => {
  return sortProviders(useServerInfo().providers["login-protocol"].providers);
};
var ServerInfoProvider = ({children: children2}) => {
  const adminClient = useAdminClient();
  const loader = async () => {
    return await adminClient.serverInfo.find();
  };
  return /* @__PURE__ */ react.createElement(DataLoader, {
    loader
  }, (serverInfo2) => /* @__PURE__ */ react.createElement(ServerInfoContext.Provider, {
    value: serverInfo2
  }, children2));
};

// build/components/help-enabler/HelpItem.js
var HelpItem = ({
  helpText,
  fieldLabelId,
  noVerticalAlign = true,
  unWrap = false
}) => {
  const {t: t5} = useTranslation();
  const {enabled} = useHelp();
  return enabled ? /* @__PURE__ */ react.createElement(Popover, {
    bodyContent: isValidElement(helpText) ? helpText : t5(helpText)
  }, /* @__PURE__ */ react.createElement(react.Fragment, null, !unWrap && /* @__PURE__ */ react.createElement("button", {
    "data-testid": `help-label-${t5(fieldLabelId).toLowerCase().replace(/\s/g, "-")}`,
    "aria-label": t5("helpLabel", {label: t5(fieldLabelId)}),
    onClick: (e2) => e2.preventDefault(),
    className: "pf-c-form__group-label-help"
  }, /* @__PURE__ */ react.createElement(HelpIcon, {
    noVerticalAlign
  })), unWrap && /* @__PURE__ */ react.createElement(HelpIcon, {
    noVerticalAlign
  }))) : null;
};

// build/environment.js
var realm = new URLSearchParams(window.location.search).get("realm") ?? "master";
var defaultEnvironment = {
  loginRealm: realm,
  authServerUrl: "http://localhost:8180/auth",
  authUrl: "http://localhost:8180/auth",
  consoleBaseUrl: "/auth/admin/master/console/",
  resourceUrl: ".",
  masterRealm: "master",
  resourceVersion: "unknown",
  commitHash: "unknown",
  isRunningAsTheme: false
};
var environment = {
  ...defaultEnvironment,
  ...getInjectedEnvironment()
};
var environment_default = environment;
function getInjectedEnvironment() {
  const element = document.getElementById("environment");
  if (!element?.textContent) {
    return {};
  }
  try {
    return JSON.parse(element.textContent);
  } catch (error2) {
    console.error("Unable to parse environment variables.");
  }
  return {};
}

// build/dashboard/routes/Dashboard.js
var DashboardRoute = {
  path: "/:realm?",
  component: lazy(() => Promise.resolve().then(() => require_Dashboard())),
  breadcrumb: (t5) => t5("common:home"),
  access: "anyone"
};
var toDashboard = (params) => ({
  pathname: generatePath(DashboardRoute.path, params)
});

// build/context/realm-context/RealmContext.js
var RealmContext = react.createContext(void 0);
var RealmContextProvider = ({children: children2}) => {
  const adminClient = useAdminClient();
  const recentUsed = useMemo(() => new RecentUsed(), []);
  const routeMatch = useRouteMatch(DashboardRoute.path);
  const realmParam = routeMatch?.params.realm;
  const realm2 = useMemo(() => realmParam ?? environment_default.loginRealm, [realmParam]);
  useEffect(() => adminClient.setConfig({realmName: realm2}), [realm2]);
  useEffect(() => recentUsed.setRecentUsed(realm2), [realm2]);
  const value = useMemo(() => ({realm: realm2}), [realm2]);
  return /* @__PURE__ */ react.createElement(RealmContext.Provider, {
    value
  }, children2);
};
var useRealm = () => useRequiredContext(RealmContext);

// build/_snowpack/pkg/i18next.js
function _typeof2(obj) {
  "@babel/helpers - typeof";
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof2 = function _typeof4(obj2) {
      return typeof obj2;
    };
  } else {
    _typeof2 = function _typeof4(obj2) {
      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
    };
  }
  return _typeof2(obj);
}
function _classCallCheck3(instance2, Constructor) {
  if (!(instance2 instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties(target, props) {
  for (var i3 = 0; i3 < props.length; i3++) {
    var descriptor = props[i3];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor)
      descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}
function _createClass3(Constructor, protoProps, staticProps) {
  if (protoProps)
    _defineProperties(Constructor.prototype, protoProps);
  if (staticProps)
    _defineProperties(Constructor, staticProps);
  return Constructor;
}
function _assertThisInitialized(self2) {
  if (self2 === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self2;
}
function _inherits2(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      writable: true,
      configurable: true
    }
  });
  if (superClass)
    _setPrototypeOf(subClass, superClass);
}
function _possibleConstructorReturn2(self2, call) {
  if (call && (_typeof(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized(self2);
}
function _getPrototypeOf(o) {
  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf3(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf(o);
}
function _defineProperty4(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _arrayWithHoles(arr) {
  if (Array.isArray(arr))
    return arr;
}
function _iterableToArrayLimit(arr, i3) {
  var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
  if (_i == null)
    return;
  var _arr = [];
  var _n = true;
  var _d = false;
  var _s, _e;
  try {
    for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);
      if (i3 && _arr.length === i3)
        break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null)
        _i["return"]();
    } finally {
      if (_d)
        throw _e;
    }
  }
  return _arr;
}
function _arrayLikeToArray(arr, len2) {
  if (len2 == null || len2 > arr.length)
    len2 = arr.length;
  for (var i3 = 0, arr2 = new Array(len2); i3 < len2; i3++) {
    arr2[i3] = arr[i3];
  }
  return arr2;
}
function _unsupportedIterableToArray(o, minLen) {
  if (!o)
    return;
  if (typeof o === "string")
    return _arrayLikeToArray(o, minLen);
  var n3 = Object.prototype.toString.call(o).slice(8, -1);
  if (n3 === "Object" && o.constructor)
    n3 = o.constructor.name;
  if (n3 === "Map" || n3 === "Set")
    return Array.from(o);
  if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3))
    return _arrayLikeToArray(o, minLen);
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _slicedToArray2(arr, i3) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i3) || _unsupportedIterableToArray(arr, i3) || _nonIterableRest();
}
function ownKeys3(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread3(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys3(Object(source2), true).forEach(function(key) {
        _defineProperty4(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys3(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var consoleLogger = {
  type: "logger",
  log: function log(args) {
    this.output("log", args);
  },
  warn: function warn2(args) {
    this.output("warn", args);
  },
  error: function error(args) {
    this.output("error", args);
  },
  output: function output(type, args) {
    if (console && console[type])
      console[type].apply(console, args);
  }
};
var Logger = function() {
  function Logger2(concreteLogger) {
    var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    _classCallCheck3(this, Logger2);
    this.init(concreteLogger, options);
  }
  _createClass3(Logger2, [{
    key: "init",
    value: function init4(concreteLogger) {
      var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      this.prefix = options.prefix || "i18next:";
      this.logger = concreteLogger || consoleLogger;
      this.options = options;
      this.debug = options.debug;
    }
  }, {
    key: "setDebug",
    value: function setDebug(bool2) {
      this.debug = bool2;
    }
  }, {
    key: "log",
    value: function log4() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      return this.forward(args, "log", "", true);
    }
  }, {
    key: "warn",
    value: function warn3() {
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }
      return this.forward(args, "warn", "", true);
    }
  }, {
    key: "error",
    value: function error2() {
      for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
        args[_key3] = arguments[_key3];
      }
      return this.forward(args, "error", "");
    }
  }, {
    key: "deprecate",
    value: function deprecate() {
      for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
        args[_key4] = arguments[_key4];
      }
      return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
    }
  }, {
    key: "forward",
    value: function forward(args, lvl, prefix2, debugOnly) {
      if (debugOnly && !this.debug)
        return null;
      if (typeof args[0] === "string")
        args[0] = "".concat(prefix2).concat(this.prefix, " ").concat(args[0]);
      return this.logger[lvl](args);
    }
  }, {
    key: "create",
    value: function create3(moduleName) {
      return new Logger2(this.logger, _objectSpread3(_objectSpread3({}, {
        prefix: "".concat(this.prefix, ":").concat(moduleName, ":")
      }), this.options));
    }
  }]);
  return Logger2;
}();
var baseLogger = new Logger();
var EventEmitter = function() {
  function EventEmitter2() {
    _classCallCheck3(this, EventEmitter2);
    this.observers = {};
  }
  _createClass3(EventEmitter2, [{
    key: "on",
    value: function on2(events, listener) {
      var _this = this;
      events.split(" ").forEach(function(event) {
        _this.observers[event] = _this.observers[event] || [];
        _this.observers[event].push(listener);
      });
      return this;
    }
  }, {
    key: "off",
    value: function off2(event, listener) {
      if (!this.observers[event])
        return;
      if (!listener) {
        delete this.observers[event];
        return;
      }
      this.observers[event] = this.observers[event].filter(function(l2) {
        return l2 !== listener;
      });
    }
  }, {
    key: "emit",
    value: function emit2(event) {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }
      if (this.observers[event]) {
        var cloned = [].concat(this.observers[event]);
        cloned.forEach(function(observer) {
          observer.apply(void 0, args);
        });
      }
      if (this.observers["*"]) {
        var _cloned = [].concat(this.observers["*"]);
        _cloned.forEach(function(observer) {
          observer.apply(observer, [event].concat(args));
        });
      }
    }
  }]);
  return EventEmitter2;
}();
function defer() {
  var res;
  var rej;
  var promise = new Promise(function(resolve2, reject) {
    res = resolve2;
    rej = reject;
  });
  promise.resolve = res;
  promise.reject = rej;
  return promise;
}
function makeString(object) {
  if (object == null)
    return "";
  return "" + object;
}
function copy(a2, s2, t5) {
  a2.forEach(function(m2) {
    if (s2[m2])
      t5[m2] = s2[m2];
  });
}
function getLastOfPath(object, path, Empty) {
  function cleanKey(key2) {
    return key2 && key2.indexOf("###") > -1 ? key2.replace(/###/g, ".") : key2;
  }
  function canNotTraverseDeeper() {
    return !object || typeof object === "string";
  }
  var stack2 = typeof path !== "string" ? [].concat(path) : path.split(".");
  while (stack2.length > 1) {
    if (canNotTraverseDeeper())
      return {};
    var key = cleanKey(stack2.shift());
    if (!object[key] && Empty)
      object[key] = new Empty();
    if (Object.prototype.hasOwnProperty.call(object, key)) {
      object = object[key];
    } else {
      object = {};
    }
  }
  if (canNotTraverseDeeper())
    return {};
  return {
    obj: object,
    k: cleanKey(stack2.shift())
  };
}
function setPath(object, path, newValue) {
  var _getLastOfPath = getLastOfPath(object, path, Object), obj = _getLastOfPath.obj, k2 = _getLastOfPath.k;
  obj[k2] = newValue;
}
function pushPath(object, path, newValue, concat2) {
  var _getLastOfPath2 = getLastOfPath(object, path, Object), obj = _getLastOfPath2.obj, k2 = _getLastOfPath2.k;
  obj[k2] = obj[k2] || [];
  if (concat2)
    obj[k2] = obj[k2].concat(newValue);
  if (!concat2)
    obj[k2].push(newValue);
}
function getPath(object, path) {
  var _getLastOfPath3 = getLastOfPath(object, path), obj = _getLastOfPath3.obj, k2 = _getLastOfPath3.k;
  if (!obj)
    return void 0;
  return obj[k2];
}
function getPathWithDefaults(data2, defaultData, key) {
  var value = getPath(data2, key);
  if (value !== void 0) {
    return value;
  }
  return getPath(defaultData, key);
}
function deepExtend(target, source2, overwrite) {
  for (var prop in source2) {
    if (prop !== "__proto__" && prop !== "constructor") {
      if (prop in target) {
        if (typeof target[prop] === "string" || target[prop] instanceof String || typeof source2[prop] === "string" || source2[prop] instanceof String) {
          if (overwrite)
            target[prop] = source2[prop];
        } else {
          deepExtend(target[prop], source2[prop], overwrite);
        }
      } else {
        target[prop] = source2[prop];
      }
    }
  }
  return target;
}
function regexEscape(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
var _entityMap = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;",
  "/": "&#x2F;"
};
function escape2(data2) {
  if (typeof data2 === "string") {
    return data2.replace(/[&<>"'\/]/g, function(s2) {
      return _entityMap[s2];
    });
  }
  return data2;
}
var isIE10 = typeof window !== "undefined" && window.navigator && window.navigator.userAgent && window.navigator.userAgent.indexOf("MSIE") > -1;
var chars = [" ", ",", "?", "!", ";"];
function looksLikeObjectPath(key, nsSeparator, keySeparator) {
  nsSeparator = nsSeparator || "";
  keySeparator = keySeparator || "";
  var possibleChars = chars.filter(function(c3) {
    return nsSeparator.indexOf(c3) < 0 && keySeparator.indexOf(c3) < 0;
  });
  if (possibleChars.length === 0)
    return true;
  var r3 = new RegExp("(".concat(possibleChars.map(function(c3) {
    return c3 === "?" ? "\\?" : c3;
  }).join("|"), ")"));
  var matched = !r3.test(key);
  if (!matched) {
    var ki2 = key.indexOf(keySeparator);
    if (ki2 > 0 && !r3.test(key.substring(0, ki2))) {
      matched = true;
    }
  }
  return matched;
}
function ownKeys$12(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$12(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$12(Object(source2), true).forEach(function(key) {
        _defineProperty4(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$12(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
function _createSuper(Derived) {
  var hasNativeReflectConstruct = _isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = _getPrototypeOf(Derived), result;
    if (hasNativeReflectConstruct) {
      var NewTarget = _getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return _possibleConstructorReturn2(this, result);
  };
}
function _isNativeReflectConstruct() {
  if (typeof Reflect === "undefined" || !Reflect.construct)
    return false;
  if (Reflect.construct.sham)
    return false;
  if (typeof Proxy === "function")
    return true;
  try {
    Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
    return true;
  } catch (e2) {
    return false;
  }
}
function deepFind(obj, path) {
  var keySeparator = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : ".";
  if (!obj)
    return void 0;
  if (obj[path])
    return obj[path];
  var paths = path.split(keySeparator);
  var current = obj;
  for (var i3 = 0; i3 < paths.length; ++i3) {
    if (!current)
      return void 0;
    if (typeof current[paths[i3]] === "string" && i3 + 1 < paths.length) {
      return void 0;
    }
    if (current[paths[i3]] === void 0) {
      var j = 2;
      var p2 = paths.slice(i3, i3 + j).join(keySeparator);
      var mix = current[p2];
      while (mix === void 0 && paths.length > i3 + j) {
        j++;
        p2 = paths.slice(i3, i3 + j).join(keySeparator);
        mix = current[p2];
      }
      if (mix === void 0)
        return void 0;
      if (typeof mix === "string")
        return mix;
      if (p2 && typeof mix[p2] === "string")
        return mix[p2];
      var joinedPath = paths.slice(i3 + j).join(keySeparator);
      if (joinedPath)
        return deepFind(mix, joinedPath, keySeparator);
      return void 0;
    }
    current = current[paths[i3]];
  }
  return current;
}
var ResourceStore = function(_EventEmitter) {
  _inherits2(ResourceStore2, _EventEmitter);
  var _super = _createSuper(ResourceStore2);
  function ResourceStore2(data2) {
    var _this;
    var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
      ns: ["translation"],
      defaultNS: "translation"
    };
    _classCallCheck3(this, ResourceStore2);
    _this = _super.call(this);
    if (isIE10) {
      EventEmitter.call(_assertThisInitialized(_this));
    }
    _this.data = data2 || {};
    _this.options = options;
    if (_this.options.keySeparator === void 0) {
      _this.options.keySeparator = ".";
    }
    if (_this.options.ignoreJSONStructure === void 0) {
      _this.options.ignoreJSONStructure = true;
    }
    return _this;
  }
  _createClass3(ResourceStore2, [{
    key: "addNamespaces",
    value: function addNamespaces(ns) {
      if (this.options.ns.indexOf(ns) < 0) {
        this.options.ns.push(ns);
      }
    }
  }, {
    key: "removeNamespaces",
    value: function removeNamespaces(ns) {
      var index3 = this.options.ns.indexOf(ns);
      if (index3 > -1) {
        this.options.ns.splice(index3, 1);
      }
    }
  }, {
    key: "getResource",
    value: function getResource(lng, ns, key) {
      var options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
      var keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
      var ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
      var path = [lng, ns];
      if (key && typeof key !== "string")
        path = path.concat(key);
      if (key && typeof key === "string")
        path = path.concat(keySeparator ? key.split(keySeparator) : key);
      if (lng.indexOf(".") > -1) {
        path = lng.split(".");
      }
      var result = getPath(this.data, path);
      if (result || !ignoreJSONStructure || typeof key !== "string")
        return result;
      return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
    }
  }, {
    key: "addResource",
    value: function addResource(lng, ns, key, value) {
      var options = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : {
        silent: false
      };
      var keySeparator = this.options.keySeparator;
      if (keySeparator === void 0)
        keySeparator = ".";
      var path = [lng, ns];
      if (key)
        path = path.concat(keySeparator ? key.split(keySeparator) : key);
      if (lng.indexOf(".") > -1) {
        path = lng.split(".");
        value = ns;
        ns = path[1];
      }
      this.addNamespaces(ns);
      setPath(this.data, path, value);
      if (!options.silent)
        this.emit("added", lng, ns, key, value);
    }
  }, {
    key: "addResources",
    value: function addResources(lng, ns, resources) {
      var options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {
        silent: false
      };
      for (var m2 in resources) {
        if (typeof resources[m2] === "string" || Object.prototype.toString.apply(resources[m2]) === "[object Array]")
          this.addResource(lng, ns, m2, resources[m2], {
            silent: true
          });
      }
      if (!options.silent)
        this.emit("added", lng, ns, resources);
    }
  }, {
    key: "addResourceBundle",
    value: function addResourceBundle(lng, ns, resources, deep, overwrite) {
      var options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {
        silent: false
      };
      var path = [lng, ns];
      if (lng.indexOf(".") > -1) {
        path = lng.split(".");
        deep = resources;
        resources = ns;
        ns = path[1];
      }
      this.addNamespaces(ns);
      var pack = getPath(this.data, path) || {};
      if (deep) {
        deepExtend(pack, resources, overwrite);
      } else {
        pack = _objectSpread$12(_objectSpread$12({}, pack), resources);
      }
      setPath(this.data, path, pack);
      if (!options.silent)
        this.emit("added", lng, ns, resources);
    }
  }, {
    key: "removeResourceBundle",
    value: function removeResourceBundle(lng, ns) {
      if (this.hasResourceBundle(lng, ns)) {
        delete this.data[lng][ns];
      }
      this.removeNamespaces(ns);
      this.emit("removed", lng, ns);
    }
  }, {
    key: "hasResourceBundle",
    value: function hasResourceBundle(lng, ns) {
      return this.getResource(lng, ns) !== void 0;
    }
  }, {
    key: "getResourceBundle",
    value: function getResourceBundle(lng, ns) {
      if (!ns)
        ns = this.options.defaultNS;
      if (this.options.compatibilityAPI === "v1")
        return _objectSpread$12(_objectSpread$12({}, {}), this.getResource(lng, ns));
      return this.getResource(lng, ns);
    }
  }, {
    key: "getDataByLanguage",
    value: function getDataByLanguage(lng) {
      return this.data[lng];
    }
  }, {
    key: "hasLanguageSomeTranslations",
    value: function hasLanguageSomeTranslations(lng) {
      var data2 = this.getDataByLanguage(lng);
      var n3 = data2 && Object.keys(data2) || [];
      return !!n3.find(function(v2) {
        return data2[v2] && Object.keys(data2[v2]).length > 0;
      });
    }
  }, {
    key: "toJSON",
    value: function toJSON() {
      return this.data;
    }
  }]);
  return ResourceStore2;
}(EventEmitter);
var postProcessor = {
  processors: {},
  addPostProcessor: function addPostProcessor(module2) {
    this.processors[module2.name] = module2;
  },
  handle: function handle(processors, value, key, options, translator) {
    var _this = this;
    processors.forEach(function(processor) {
      if (_this.processors[processor])
        value = _this.processors[processor].process(value, key, options, translator);
    });
    return value;
  }
};
function ownKeys$22(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$22(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$22(Object(source2), true).forEach(function(key) {
        _defineProperty4(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$22(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
function _createSuper$1(Derived) {
  var hasNativeReflectConstruct = _isNativeReflectConstruct$1();
  return function _createSuperInternal() {
    var Super = _getPrototypeOf(Derived), result;
    if (hasNativeReflectConstruct) {
      var NewTarget = _getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return _possibleConstructorReturn2(this, result);
  };
}
function _isNativeReflectConstruct$1() {
  if (typeof Reflect === "undefined" || !Reflect.construct)
    return false;
  if (Reflect.construct.sham)
    return false;
  if (typeof Proxy === "function")
    return true;
  try {
    Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
    return true;
  } catch (e2) {
    return false;
  }
}
var checkedLoadedFor = {};
var Translator = function(_EventEmitter) {
  _inherits2(Translator2, _EventEmitter);
  var _super = _createSuper$1(Translator2);
  function Translator2(services) {
    var _this;
    var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    _classCallCheck3(this, Translator2);
    _this = _super.call(this);
    if (isIE10) {
      EventEmitter.call(_assertThisInitialized(_this));
    }
    copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, _assertThisInitialized(_this));
    _this.options = options;
    if (_this.options.keySeparator === void 0) {
      _this.options.keySeparator = ".";
    }
    _this.logger = baseLogger.create("translator");
    return _this;
  }
  _createClass3(Translator2, [{
    key: "changeLanguage",
    value: function changeLanguage2(lng) {
      if (lng)
        this.language = lng;
    }
  }, {
    key: "exists",
    value: function exists2(key) {
      var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
        interpolation: {}
      };
      if (key === void 0 || key === null) {
        return false;
      }
      var resolved = this.resolve(key, options);
      return resolved && resolved.res !== void 0;
    }
  }, {
    key: "extractFromKey",
    value: function extractFromKey(key, options) {
      var nsSeparator = options.nsSeparator !== void 0 ? options.nsSeparator : this.options.nsSeparator;
      if (nsSeparator === void 0)
        nsSeparator = ":";
      var keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
      var namespaces2 = options.ns || this.options.defaultNS;
      var wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
      var seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
      if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
        var m2 = key.match(this.interpolator.nestingRegexp);
        if (m2 && m2.length > 0) {
          return {
            key,
            namespaces: namespaces2
          };
        }
        var parts = key.split(nsSeparator);
        if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1)
          namespaces2 = parts.shift();
        key = parts.join(keySeparator);
      }
      if (typeof namespaces2 === "string")
        namespaces2 = [namespaces2];
      return {
        key,
        namespaces: namespaces2
      };
    }
  }, {
    key: "translate",
    value: function translate(keys2, options, lastKey) {
      var _this2 = this;
      if (_typeof2(options) !== "object" && this.options.overloadTranslationOptionHandler) {
        options = this.options.overloadTranslationOptionHandler(arguments);
      }
      if (!options)
        options = {};
      if (keys2 === void 0 || keys2 === null)
        return "";
      if (!Array.isArray(keys2))
        keys2 = [String(keys2)];
      var keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
      var _this$extractFromKey = this.extractFromKey(keys2[keys2.length - 1], options), key = _this$extractFromKey.key, namespaces2 = _this$extractFromKey.namespaces;
      var namespace2 = namespaces2[namespaces2.length - 1];
      var lng = options.lng || this.language;
      var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
      if (lng && lng.toLowerCase() === "cimode") {
        if (appendNamespaceToCIMode) {
          var nsSeparator = options.nsSeparator || this.options.nsSeparator;
          return namespace2 + nsSeparator + key;
        }
        return key;
      }
      var resolved = this.resolve(keys2, options);
      var res = resolved && resolved.res;
      var resUsedKey = resolved && resolved.usedKey || key;
      var resExactUsedKey = resolved && resolved.exactUsedKey || key;
      var resType = Object.prototype.toString.apply(res);
      var noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
      var joinArrays = options.joinArrays !== void 0 ? options.joinArrays : this.options.joinArrays;
      var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
      var handleAsObject = typeof res !== "string" && typeof res !== "boolean" && typeof res !== "number";
      if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === "string" && resType === "[object Array]")) {
        if (!options.returnObjects && !this.options.returnObjects) {
          if (!this.options.returnedObjectHandler) {
            this.logger.warn("accessing an object - but returnObjects options is not enabled!");
          }
          return this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, _objectSpread$22(_objectSpread$22({}, options), {}, {
            ns: namespaces2
          })) : "key '".concat(key, " (").concat(this.language, ")' returned an object instead of string.");
        }
        if (keySeparator) {
          var resTypeIsArray = resType === "[object Array]";
          var copy2 = resTypeIsArray ? [] : {};
          var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
          for (var m2 in res) {
            if (Object.prototype.hasOwnProperty.call(res, m2)) {
              var deepKey = "".concat(newKeyToUse).concat(keySeparator).concat(m2);
              copy2[m2] = this.translate(deepKey, _objectSpread$22(_objectSpread$22({}, options), {
                joinArrays: false,
                ns: namespaces2
              }));
              if (copy2[m2] === deepKey)
                copy2[m2] = res[m2];
            }
          }
          res = copy2;
        }
      } else if (handleAsObjectInI18nFormat && typeof joinArrays === "string" && resType === "[object Array]") {
        res = res.join(joinArrays);
        if (res)
          res = this.extendTranslation(res, keys2, options, lastKey);
      } else {
        var usedDefault = false;
        var usedKey = false;
        var needsPluralHandling = options.count !== void 0 && typeof options.count !== "string";
        var hasDefaultValue = Translator2.hasDefaultValue(options);
        var defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : "";
        var defaultValue = options["defaultValue".concat(defaultValueSuffix)] || options.defaultValue;
        if (!this.isValidLookup(res) && hasDefaultValue) {
          usedDefault = true;
          res = defaultValue;
        }
        if (!this.isValidLookup(res)) {
          usedKey = true;
          res = key;
        }
        var missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
        var resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
        var updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
        if (usedKey || usedDefault || updateMissing) {
          this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace2, key, updateMissing ? defaultValue : res);
          if (keySeparator) {
            var fk2 = this.resolve(key, _objectSpread$22(_objectSpread$22({}, options), {}, {
              keySeparator: false
            }));
            if (fk2 && fk2.res)
              this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.");
          }
          var lngs = [];
          var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
          if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
            for (var i3 = 0; i3 < fallbackLngs.length; i3++) {
              lngs.push(fallbackLngs[i3]);
            }
          } else if (this.options.saveMissingTo === "all") {
            lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
          } else {
            lngs.push(options.lng || this.language);
          }
          var send = function send2(l2, k2, specificDefaultValue) {
            var defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
            if (_this2.options.missingKeyHandler) {
              _this2.options.missingKeyHandler(l2, namespace2, k2, defaultForMissing, updateMissing, options);
            } else if (_this2.backendConnector && _this2.backendConnector.saveMissing) {
              _this2.backendConnector.saveMissing(l2, namespace2, k2, defaultForMissing, updateMissing, options);
            }
            _this2.emit("missingKey", l2, namespace2, k2, res);
          };
          if (this.options.saveMissing) {
            if (this.options.saveMissingPlurals && needsPluralHandling) {
              lngs.forEach(function(language) {
                _this2.pluralResolver.getSuffixes(language).forEach(function(suffix) {
                  send([language], key + suffix, options["defaultValue".concat(suffix)] || defaultValue);
                });
              });
            } else {
              send(lngs, key, defaultValue);
            }
          }
        }
        res = this.extendTranslation(res, keys2, options, resolved, lastKey);
        if (usedKey && res === key && this.options.appendNamespaceToMissingKey)
          res = "".concat(namespace2, ":").concat(key);
        if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler)
          res = this.options.parseMissingKeyHandler(res);
      }
      return res;
    }
  }, {
    key: "extendTranslation",
    value: function extendTranslation(res, key, options, resolved, lastKey) {
      var _this3 = this;
      if (this.i18nFormat && this.i18nFormat.parse) {
        res = this.i18nFormat.parse(res, options, resolved.usedLng, resolved.usedNS, resolved.usedKey, {
          resolved
        });
      } else if (!options.skipInterpolation) {
        if (options.interpolation)
          this.interpolator.init(_objectSpread$22(_objectSpread$22({}, options), {
            interpolation: _objectSpread$22(_objectSpread$22({}, this.options.interpolation), options.interpolation)
          }));
        var skipOnVariables = typeof res === "string" && (options.interpolation && options.interpolation.skipOnVariables || this.options.interpolation.skipOnVariables);
        var nestBef;
        if (skipOnVariables) {
          var nb2 = res.match(this.interpolator.nestingRegexp);
          nestBef = nb2 && nb2.length;
        }
        var data2 = options.replace && typeof options.replace !== "string" ? options.replace : options;
        if (this.options.interpolation.defaultVariables)
          data2 = _objectSpread$22(_objectSpread$22({}, this.options.interpolation.defaultVariables), data2);
        res = this.interpolator.interpolate(res, data2, options.lng || this.language, options);
        if (skipOnVariables) {
          var na2 = res.match(this.interpolator.nestingRegexp);
          var nestAft = na2 && na2.length;
          if (nestBef < nestAft)
            options.nest = false;
        }
        if (options.nest !== false)
          res = this.interpolator.nest(res, function() {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = arguments[_key];
            }
            if (lastKey && lastKey[0] === args[0] && !options.context) {
              _this3.logger.warn("It seems you are nesting recursively key: ".concat(args[0], " in key: ").concat(key[0]));
              return null;
            }
            return _this3.translate.apply(_this3, args.concat([key]));
          }, options);
        if (options.interpolation)
          this.interpolator.reset();
      }
      var postProcess = options.postProcess || this.options.postProcess;
      var postProcessorNames = typeof postProcess === "string" ? [postProcess] : postProcess;
      if (res !== void 0 && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
        res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread$22({
          i18nResolved: resolved
        }, options) : options, this);
      }
      return res;
    }
  }, {
    key: "resolve",
    value: function resolve2(keys2) {
      var _this4 = this;
      var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      var found;
      var usedKey;
      var exactUsedKey;
      var usedLng;
      var usedNS;
      if (typeof keys2 === "string")
        keys2 = [keys2];
      keys2.forEach(function(k2) {
        if (_this4.isValidLookup(found))
          return;
        var extracted = _this4.extractFromKey(k2, options);
        var key = extracted.key;
        usedKey = key;
        var namespaces2 = extracted.namespaces;
        if (_this4.options.fallbackNS)
          namespaces2 = namespaces2.concat(_this4.options.fallbackNS);
        var needsPluralHandling = options.count !== void 0 && typeof options.count !== "string";
        var needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && _this4.pluralResolver.shouldUseIntlApi();
        var needsContextHandling = options.context !== void 0 && (typeof options.context === "string" || typeof options.context === "number") && options.context !== "";
        var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng);
        namespaces2.forEach(function(ns) {
          if (_this4.isValidLookup(found))
            return;
          usedNS = ns;
          if (!checkedLoadedFor["".concat(codes[0], "-").concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) {
            checkedLoadedFor["".concat(codes[0], "-").concat(ns)] = true;
            _this4.logger.warn('key "'.concat(usedKey, '" for languages "').concat(codes.join(", "), `" won't get resolved as namespace "`).concat(usedNS, '" was not yet loaded'), "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
          }
          codes.forEach(function(code2) {
            if (_this4.isValidLookup(found))
              return;
            usedLng = code2;
            var finalKeys = [key];
            if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) {
              _this4.i18nFormat.addLookupKeys(finalKeys, key, code2, ns, options);
            } else {
              var pluralSuffix;
              if (needsPluralHandling)
                pluralSuffix = _this4.pluralResolver.getSuffix(code2, options.count, options);
              var zeroSuffix = "_zero";
              if (needsPluralHandling) {
                finalKeys.push(key + pluralSuffix);
                if (needsZeroSuffixLookup) {
                  finalKeys.push(key + zeroSuffix);
                }
              }
              if (needsContextHandling) {
                var contextKey = "".concat(key).concat(_this4.options.contextSeparator).concat(options.context);
                finalKeys.push(contextKey);
                if (needsPluralHandling) {
                  finalKeys.push(contextKey + pluralSuffix);
                  if (needsZeroSuffixLookup) {
                    finalKeys.push(contextKey + zeroSuffix);
                  }
                }
              }
            }
            var possibleKey;
            while (possibleKey = finalKeys.pop()) {
              if (!_this4.isValidLookup(found)) {
                exactUsedKey = possibleKey;
                found = _this4.getResource(code2, ns, possibleKey, options);
              }
            }
          });
        });
      });
      return {
        res: found,
        usedKey,
        exactUsedKey,
        usedLng,
        usedNS
      };
    }
  }, {
    key: "isValidLookup",
    value: function isValidLookup(res) {
      return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
    }
  }, {
    key: "getResource",
    value: function getResource(code2, ns, key) {
      var options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
      if (this.i18nFormat && this.i18nFormat.getResource)
        return this.i18nFormat.getResource(code2, ns, key, options);
      return this.resourceStore.getResource(code2, ns, key, options);
    }
  }], [{
    key: "hasDefaultValue",
    value: function hasDefaultValue(options) {
      var prefix2 = "defaultValue";
      for (var option in options) {
        if (Object.prototype.hasOwnProperty.call(options, option) && prefix2 === option.substring(0, prefix2.length) && options[option] !== void 0) {
          return true;
        }
      }
      return false;
    }
  }]);
  return Translator2;
}(EventEmitter);
function capitalize3(string2) {
  return string2.charAt(0).toUpperCase() + string2.slice(1);
}
var LanguageUtil = function() {
  function LanguageUtil2(options) {
    _classCallCheck3(this, LanguageUtil2);
    this.options = options;
    this.supportedLngs = this.options.supportedLngs || false;
    this.logger = baseLogger.create("languageUtils");
  }
  _createClass3(LanguageUtil2, [{
    key: "getScriptPartFromCode",
    value: function getScriptPartFromCode(code2) {
      if (!code2 || code2.indexOf("-") < 0)
        return null;
      var p2 = code2.split("-");
      if (p2.length === 2)
        return null;
      p2.pop();
      if (p2[p2.length - 1].toLowerCase() === "x")
        return null;
      return this.formatLanguageCode(p2.join("-"));
    }
  }, {
    key: "getLanguagePartFromCode",
    value: function getLanguagePartFromCode(code2) {
      if (!code2 || code2.indexOf("-") < 0)
        return code2;
      var p2 = code2.split("-");
      return this.formatLanguageCode(p2[0]);
    }
  }, {
    key: "formatLanguageCode",
    value: function formatLanguageCode(code2) {
      if (typeof code2 === "string" && code2.indexOf("-") > -1) {
        var specialCases = ["hans", "hant", "latn", "cyrl", "cans", "mong", "arab"];
        var p2 = code2.split("-");
        if (this.options.lowerCaseLng) {
          p2 = p2.map(function(part) {
            return part.toLowerCase();
          });
        } else if (p2.length === 2) {
          p2[0] = p2[0].toLowerCase();
          p2[1] = p2[1].toUpperCase();
          if (specialCases.indexOf(p2[1].toLowerCase()) > -1)
            p2[1] = capitalize3(p2[1].toLowerCase());
        } else if (p2.length === 3) {
          p2[0] = p2[0].toLowerCase();
          if (p2[1].length === 2)
            p2[1] = p2[1].toUpperCase();
          if (p2[0] !== "sgn" && p2[2].length === 2)
            p2[2] = p2[2].toUpperCase();
          if (specialCases.indexOf(p2[1].toLowerCase()) > -1)
            p2[1] = capitalize3(p2[1].toLowerCase());
          if (specialCases.indexOf(p2[2].toLowerCase()) > -1)
            p2[2] = capitalize3(p2[2].toLowerCase());
        }
        return p2.join("-");
      }
      return this.options.cleanCode || this.options.lowerCaseLng ? code2.toLowerCase() : code2;
    }
  }, {
    key: "isSupportedCode",
    value: function isSupportedCode(code2) {
      if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
        code2 = this.getLanguagePartFromCode(code2);
      }
      return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code2) > -1;
    }
  }, {
    key: "getBestMatchFromCodes",
    value: function getBestMatchFromCodes(codes) {
      var _this = this;
      if (!codes)
        return null;
      var found;
      codes.forEach(function(code2) {
        if (found)
          return;
        var cleanedLng = _this.formatLanguageCode(code2);
        if (!_this.options.supportedLngs || _this.isSupportedCode(cleanedLng))
          found = cleanedLng;
      });
      if (!found && this.options.supportedLngs) {
        codes.forEach(function(code2) {
          if (found)
            return;
          var lngOnly = _this.getLanguagePartFromCode(code2);
          if (_this.isSupportedCode(lngOnly))
            return found = lngOnly;
          found = _this.options.supportedLngs.find(function(supportedLng) {
            if (supportedLng.indexOf(lngOnly) === 0)
              return supportedLng;
          });
        });
      }
      if (!found)
        found = this.getFallbackCodes(this.options.fallbackLng)[0];
      return found;
    }
  }, {
    key: "getFallbackCodes",
    value: function getFallbackCodes(fallbacks, code2) {
      if (!fallbacks)
        return [];
      if (typeof fallbacks === "function")
        fallbacks = fallbacks(code2);
      if (typeof fallbacks === "string")
        fallbacks = [fallbacks];
      if (Object.prototype.toString.apply(fallbacks) === "[object Array]")
        return fallbacks;
      if (!code2)
        return fallbacks["default"] || [];
      var found = fallbacks[code2];
      if (!found)
        found = fallbacks[this.getScriptPartFromCode(code2)];
      if (!found)
        found = fallbacks[this.formatLanguageCode(code2)];
      if (!found)
        found = fallbacks[this.getLanguagePartFromCode(code2)];
      if (!found)
        found = fallbacks["default"];
      return found || [];
    }
  }, {
    key: "toResolveHierarchy",
    value: function toResolveHierarchy(code2, fallbackCode) {
      var _this2 = this;
      var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code2);
      var codes = [];
      var addCode = function addCode2(c3) {
        if (!c3)
          return;
        if (_this2.isSupportedCode(c3)) {
          codes.push(c3);
        } else {
          _this2.logger.warn("rejecting language code not found in supportedLngs: ".concat(c3));
        }
      };
      if (typeof code2 === "string" && code2.indexOf("-") > -1) {
        if (this.options.load !== "languageOnly")
          addCode(this.formatLanguageCode(code2));
        if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly")
          addCode(this.getScriptPartFromCode(code2));
        if (this.options.load !== "currentOnly")
          addCode(this.getLanguagePartFromCode(code2));
      } else if (typeof code2 === "string") {
        addCode(this.formatLanguageCode(code2));
      }
      fallbackCodes.forEach(function(fc2) {
        if (codes.indexOf(fc2) < 0)
          addCode(_this2.formatLanguageCode(fc2));
      });
      return codes;
    }
  }]);
  return LanguageUtil2;
}();
var sets = [{
  lngs: ["ach", "ak", "am", "arn", "br", "fil", "gun", "ln", "mfe", "mg", "mi", "oc", "pt", "pt-BR", "tg", "tl", "ti", "tr", "uz", "wa"],
  nr: [1, 2],
  fc: 1
}, {
  lngs: ["af", "an", "ast", "az", "bg", "bn", "ca", "da", "de", "dev", "el", "en", "eo", "es", "et", "eu", "fi", "fo", "fur", "fy", "gl", "gu", "ha", "hi", "hu", "hy", "ia", "it", "kk", "kn", "ku", "lb", "mai", "ml", "mn", "mr", "nah", "nap", "nb", "ne", "nl", "nn", "no", "nso", "pa", "pap", "pms", "ps", "pt-PT", "rm", "sco", "se", "si", "so", "son", "sq", "sv", "sw", "ta", "te", "tk", "ur", "yo"],
  nr: [1, 2],
  fc: 2
}, {
  lngs: ["ay", "bo", "cgg", "fa", "ht", "id", "ja", "jbo", "ka", "km", "ko", "ky", "lo", "ms", "sah", "su", "th", "tt", "ug", "vi", "wo", "zh"],
  nr: [1],
  fc: 3
}, {
  lngs: ["be", "bs", "cnr", "dz", "hr", "ru", "sr", "uk"],
  nr: [1, 2, 5],
  fc: 4
}, {
  lngs: ["ar"],
  nr: [0, 1, 2, 3, 11, 100],
  fc: 5
}, {
  lngs: ["cs", "sk"],
  nr: [1, 2, 5],
  fc: 6
}, {
  lngs: ["csb", "pl"],
  nr: [1, 2, 5],
  fc: 7
}, {
  lngs: ["cy"],
  nr: [1, 2, 3, 8],
  fc: 8
}, {
  lngs: ["fr"],
  nr: [1, 2],
  fc: 9
}, {
  lngs: ["ga"],
  nr: [1, 2, 3, 7, 11],
  fc: 10
}, {
  lngs: ["gd"],
  nr: [1, 2, 3, 20],
  fc: 11
}, {
  lngs: ["is"],
  nr: [1, 2],
  fc: 12
}, {
  lngs: ["jv"],
  nr: [0, 1],
  fc: 13
}, {
  lngs: ["kw"],
  nr: [1, 2, 3, 4],
  fc: 14
}, {
  lngs: ["lt"],
  nr: [1, 2, 10],
  fc: 15
}, {
  lngs: ["lv"],
  nr: [1, 2, 0],
  fc: 16
}, {
  lngs: ["mk"],
  nr: [1, 2],
  fc: 17
}, {
  lngs: ["mnk"],
  nr: [0, 1, 2],
  fc: 18
}, {
  lngs: ["mt"],
  nr: [1, 2, 11, 20],
  fc: 19
}, {
  lngs: ["or"],
  nr: [2, 1],
  fc: 2
}, {
  lngs: ["ro"],
  nr: [1, 2, 20],
  fc: 20
}, {
  lngs: ["sl"],
  nr: [5, 1, 2, 3],
  fc: 21
}, {
  lngs: ["he", "iw"],
  nr: [1, 2, 20, 21],
  fc: 22
}];
var _rulesPluralsTypes = {
  1: function _(n3) {
    return Number(n3 > 1);
  },
  2: function _2(n3) {
    return Number(n3 != 1);
  },
  3: function _3(n3) {
    return 0;
  },
  4: function _4(n3) {
    return Number(n3 % 10 == 1 && n3 % 100 != 11 ? 0 : n3 % 10 >= 2 && n3 % 10 <= 4 && (n3 % 100 < 10 || n3 % 100 >= 20) ? 1 : 2);
  },
  5: function _5(n3) {
    return Number(n3 == 0 ? 0 : n3 == 1 ? 1 : n3 == 2 ? 2 : n3 % 100 >= 3 && n3 % 100 <= 10 ? 3 : n3 % 100 >= 11 ? 4 : 5);
  },
  6: function _6(n3) {
    return Number(n3 == 1 ? 0 : n3 >= 2 && n3 <= 4 ? 1 : 2);
  },
  7: function _7(n3) {
    return Number(n3 == 1 ? 0 : n3 % 10 >= 2 && n3 % 10 <= 4 && (n3 % 100 < 10 || n3 % 100 >= 20) ? 1 : 2);
  },
  8: function _8(n3) {
    return Number(n3 == 1 ? 0 : n3 == 2 ? 1 : n3 != 8 && n3 != 11 ? 2 : 3);
  },
  9: function _9(n3) {
    return Number(n3 >= 2);
  },
  10: function _10(n3) {
    return Number(n3 == 1 ? 0 : n3 == 2 ? 1 : n3 < 7 ? 2 : n3 < 11 ? 3 : 4);
  },
  11: function _11(n3) {
    return Number(n3 == 1 || n3 == 11 ? 0 : n3 == 2 || n3 == 12 ? 1 : n3 > 2 && n3 < 20 ? 2 : 3);
  },
  12: function _12(n3) {
    return Number(n3 % 10 != 1 || n3 % 100 == 11);
  },
  13: function _13(n3) {
    return Number(n3 !== 0);
  },
  14: function _14(n3) {
    return Number(n3 == 1 ? 0 : n3 == 2 ? 1 : n3 == 3 ? 2 : 3);
  },
  15: function _15(n3) {
    return Number(n3 % 10 == 1 && n3 % 100 != 11 ? 0 : n3 % 10 >= 2 && (n3 % 100 < 10 || n3 % 100 >= 20) ? 1 : 2);
  },
  16: function _16(n3) {
    return Number(n3 % 10 == 1 && n3 % 100 != 11 ? 0 : n3 !== 0 ? 1 : 2);
  },
  17: function _17(n3) {
    return Number(n3 == 1 || n3 % 10 == 1 && n3 % 100 != 11 ? 0 : 1);
  },
  18: function _18(n3) {
    return Number(n3 == 0 ? 0 : n3 == 1 ? 1 : 2);
  },
  19: function _19(n3) {
    return Number(n3 == 1 ? 0 : n3 == 0 || n3 % 100 > 1 && n3 % 100 < 11 ? 1 : n3 % 100 > 10 && n3 % 100 < 20 ? 2 : 3);
  },
  20: function _20(n3) {
    return Number(n3 == 1 ? 0 : n3 == 0 || n3 % 100 > 0 && n3 % 100 < 20 ? 1 : 2);
  },
  21: function _21(n3) {
    return Number(n3 % 100 == 1 ? 1 : n3 % 100 == 2 ? 2 : n3 % 100 == 3 || n3 % 100 == 4 ? 3 : 0);
  },
  22: function _22(n3) {
    return Number(n3 == 1 ? 0 : n3 == 2 ? 1 : (n3 < 0 || n3 > 10) && n3 % 10 == 0 ? 2 : 3);
  }
};
var deprecatedJsonVersions = ["v1", "v2", "v3"];
var suffixesOrder = {
  zero: 0,
  one: 1,
  two: 2,
  few: 3,
  many: 4,
  other: 5
};
function createRules() {
  var rules = {};
  sets.forEach(function(set3) {
    set3.lngs.forEach(function(l2) {
      rules[l2] = {
        numbers: set3.nr,
        plurals: _rulesPluralsTypes[set3.fc]
      };
    });
  });
  return rules;
}
var PluralResolver = function() {
  function PluralResolver2(languageUtils) {
    var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    _classCallCheck3(this, PluralResolver2);
    this.languageUtils = languageUtils;
    this.options = options;
    this.logger = baseLogger.create("pluralResolver");
    if ((!this.options.compatibilityJSON || this.options.compatibilityJSON === "v4") && (typeof Intl === "undefined" || !Intl.PluralRules)) {
      this.options.compatibilityJSON = "v3";
      this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.");
    }
    this.rules = createRules();
  }
  _createClass3(PluralResolver2, [{
    key: "addRule",
    value: function addRule(lng, obj) {
      this.rules[lng] = obj;
    }
  }, {
    key: "getRule",
    value: function getRule(code2) {
      var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      if (this.shouldUseIntlApi()) {
        try {
          return new Intl.PluralRules(code2, {
            type: options.ordinal ? "ordinal" : "cardinal"
          });
        } catch (_unused) {
          return;
        }
      }
      return this.rules[code2] || this.rules[this.languageUtils.getLanguagePartFromCode(code2)];
    }
  }, {
    key: "needsPlural",
    value: function needsPlural(code2) {
      var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      var rule = this.getRule(code2, options);
      if (this.shouldUseIntlApi()) {
        return rule && rule.resolvedOptions().pluralCategories.length > 1;
      }
      return rule && rule.numbers.length > 1;
    }
  }, {
    key: "getPluralFormsOfKey",
    value: function getPluralFormsOfKey(code2, key) {
      var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      return this.getSuffixes(code2, options).map(function(suffix) {
        return "".concat(key).concat(suffix);
      });
    }
  }, {
    key: "getSuffixes",
    value: function getSuffixes(code2) {
      var _this = this;
      var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      var rule = this.getRule(code2, options);
      if (!rule) {
        return [];
      }
      if (this.shouldUseIntlApi()) {
        return rule.resolvedOptions().pluralCategories.sort(function(pluralCategory1, pluralCategory2) {
          return suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2];
        }).map(function(pluralCategory) {
          return "".concat(_this.options.prepend).concat(pluralCategory);
        });
      }
      return rule.numbers.map(function(number) {
        return _this.getSuffix(code2, number, options);
      });
    }
  }, {
    key: "getSuffix",
    value: function getSuffix(code2, count) {
      var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      var rule = this.getRule(code2, options);
      if (rule) {
        if (this.shouldUseIntlApi()) {
          return "".concat(this.options.prepend).concat(rule.select(count));
        }
        return this.getSuffixRetroCompatible(rule, count);
      }
      this.logger.warn("no plural rule found for: ".concat(code2));
      return "";
    }
  }, {
    key: "getSuffixRetroCompatible",
    value: function getSuffixRetroCompatible(rule, count) {
      var _this2 = this;
      var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
      var suffix = rule.numbers[idx];
      if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
        if (suffix === 2) {
          suffix = "plural";
        } else if (suffix === 1) {
          suffix = "";
        }
      }
      var returnSuffix = function returnSuffix2() {
        return _this2.options.prepend && suffix.toString() ? _this2.options.prepend + suffix.toString() : suffix.toString();
      };
      if (this.options.compatibilityJSON === "v1") {
        if (suffix === 1)
          return "";
        if (typeof suffix === "number")
          return "_plural_".concat(suffix.toString());
        return returnSuffix();
      } else if (this.options.compatibilityJSON === "v2") {
        return returnSuffix();
      } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
        return returnSuffix();
      }
      return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
    }
  }, {
    key: "shouldUseIntlApi",
    value: function shouldUseIntlApi() {
      return !deprecatedJsonVersions.includes(this.options.compatibilityJSON);
    }
  }]);
  return PluralResolver2;
}();
function ownKeys$3(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$3(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$3(Object(source2), true).forEach(function(key) {
        _defineProperty4(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$3(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var Interpolator = function() {
  function Interpolator2() {
    var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    _classCallCheck3(this, Interpolator2);
    this.logger = baseLogger.create("interpolator");
    this.options = options;
    this.format = options.interpolation && options.interpolation.format || function(value) {
      return value;
    };
    this.init(options);
  }
  _createClass3(Interpolator2, [{
    key: "init",
    value: function init4() {
      var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      if (!options.interpolation)
        options.interpolation = {
          escapeValue: true
        };
      var iOpts = options.interpolation;
      this.escape = iOpts.escape !== void 0 ? iOpts.escape : escape2;
      this.escapeValue = iOpts.escapeValue !== void 0 ? iOpts.escapeValue : true;
      this.useRawValueToEscape = iOpts.useRawValueToEscape !== void 0 ? iOpts.useRawValueToEscape : false;
      this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || "{{";
      this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || "}}";
      this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ",";
      this.unescapePrefix = iOpts.unescapeSuffix ? "" : iOpts.unescapePrefix || "-";
      this.unescapeSuffix = this.unescapePrefix ? "" : iOpts.unescapeSuffix || "";
      this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape("$t(");
      this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(")");
      this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ",";
      this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1e3;
      this.alwaysFormat = iOpts.alwaysFormat !== void 0 ? iOpts.alwaysFormat : false;
      this.resetRegExp();
    }
  }, {
    key: "reset",
    value: function reset2() {
      if (this.options)
        this.init(this.options);
    }
  }, {
    key: "resetRegExp",
    value: function resetRegExp() {
      var regexpStr = "".concat(this.prefix, "(.+?)").concat(this.suffix);
      this.regexp = new RegExp(regexpStr, "g");
      var regexpUnescapeStr = "".concat(this.prefix).concat(this.unescapePrefix, "(.+?)").concat(this.unescapeSuffix).concat(this.suffix);
      this.regexpUnescape = new RegExp(regexpUnescapeStr, "g");
      var nestingRegexpStr = "".concat(this.nestingPrefix, "(.+?)").concat(this.nestingSuffix);
      this.nestingRegexp = new RegExp(nestingRegexpStr, "g");
    }
  }, {
    key: "interpolate",
    value: function interpolate2(str, data2, lng, options) {
      var _this = this;
      var match2;
      var value;
      var replaces;
      var defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
      function regexSafe(val) {
        return val.replace(/\$/g, "$$$$");
      }
      var handleFormat = function handleFormat2(key) {
        if (key.indexOf(_this.formatSeparator) < 0) {
          var path = getPathWithDefaults(data2, defaultData, key);
          return _this.alwaysFormat ? _this.format(path, void 0, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data2), {}, {
            interpolationkey: key
          })) : path;
        }
        var p2 = key.split(_this.formatSeparator);
        var k2 = p2.shift().trim();
        var f2 = p2.join(_this.formatSeparator).trim();
        return _this.format(getPathWithDefaults(data2, defaultData, k2), f2, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data2), {}, {
          interpolationkey: k2
        }));
      };
      this.resetRegExp();
      var missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
      var skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables || this.options.interpolation.skipOnVariables;
      var todos = [{
        regex: this.regexpUnescape,
        safeValue: function safeValue(val) {
          return regexSafe(val);
        }
      }, {
        regex: this.regexp,
        safeValue: function safeValue(val) {
          return _this.escapeValue ? regexSafe(_this.escape(val)) : regexSafe(val);
        }
      }];
      todos.forEach(function(todo) {
        replaces = 0;
        while (match2 = todo.regex.exec(str)) {
          value = handleFormat(match2[1].trim());
          if (value === void 0) {
            if (typeof missingInterpolationHandler === "function") {
              var temp = missingInterpolationHandler(str, match2, options);
              value = typeof temp === "string" ? temp : "";
            } else if (skipOnVariables) {
              value = match2[0];
              continue;
            } else {
              _this.logger.warn("missed to pass in variable ".concat(match2[1], " for interpolating ").concat(str));
              value = "";
            }
          } else if (typeof value !== "string" && !_this.useRawValueToEscape) {
            value = makeString(value);
          }
          var safeValue = todo.safeValue(value);
          str = str.replace(match2[0], safeValue);
          if (skipOnVariables) {
            todo.regex.lastIndex += safeValue.length;
            todo.regex.lastIndex -= match2[0].length;
          } else {
            todo.regex.lastIndex = 0;
          }
          replaces++;
          if (replaces >= _this.maxReplaces) {
            break;
          }
        }
      });
      return str;
    }
  }, {
    key: "nest",
    value: function nest(str, fc2) {
      var _this2 = this;
      var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      var match2;
      var value;
      var clonedOptions = _objectSpread$3({}, options);
      clonedOptions.applyPostProcessor = false;
      delete clonedOptions.defaultValue;
      function handleHasOptions(key, inheritedOptions) {
        var sep3 = this.nestingOptionsSeparator;
        if (key.indexOf(sep3) < 0)
          return key;
        var c3 = key.split(new RegExp("".concat(sep3, "[ ]*{")));
        var optionsString = "{".concat(c3[1]);
        key = c3[0];
        optionsString = this.interpolate(optionsString, clonedOptions);
        optionsString = optionsString.replace(/'/g, '"');
        try {
          clonedOptions = JSON.parse(optionsString);
          if (inheritedOptions)
            clonedOptions = _objectSpread$3(_objectSpread$3({}, inheritedOptions), clonedOptions);
        } catch (e2) {
          this.logger.warn("failed parsing options string in nesting for key ".concat(key), e2);
          return "".concat(key).concat(sep3).concat(optionsString);
        }
        delete clonedOptions.defaultValue;
        return key;
      }
      while (match2 = this.nestingRegexp.exec(str)) {
        var formatters = [];
        var doReduce = false;
        if (match2[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match2[1])) {
          var r3 = match2[1].split(this.formatSeparator).map(function(elem) {
            return elem.trim();
          });
          match2[1] = r3.shift();
          formatters = r3;
          doReduce = true;
        }
        value = fc2(handleHasOptions.call(this, match2[1].trim(), clonedOptions), clonedOptions);
        if (value && match2[0] === str && typeof value !== "string")
          return value;
        if (typeof value !== "string")
          value = makeString(value);
        if (!value) {
          this.logger.warn("missed to resolve ".concat(match2[1], " for nesting ").concat(str));
          value = "";
        }
        if (doReduce) {
          value = formatters.reduce(function(v2, f2) {
            return _this2.format(v2, f2, options.lng, _objectSpread$3(_objectSpread$3({}, options), {}, {
              interpolationkey: match2[1].trim()
            }));
          }, value.trim());
        }
        str = str.replace(match2[0], value);
        this.regexp.lastIndex = 0;
      }
      return str;
    }
  }]);
  return Interpolator2;
}();
function ownKeys$4(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$4(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$4(Object(source2), true).forEach(function(key) {
        _defineProperty4(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$4(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
function parseFormatStr(formatStr) {
  var formatName = formatStr.toLowerCase().trim();
  var formatOptions = {};
  if (formatStr.indexOf("(") > -1) {
    var p2 = formatStr.split("(");
    formatName = p2[0].toLowerCase().trim();
    var optStr = p2[1].substring(0, p2[1].length - 1);
    if (formatName === "currency" && optStr.indexOf(":") < 0) {
      if (!formatOptions.currency)
        formatOptions.currency = optStr.trim();
    } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
      if (!formatOptions.range)
        formatOptions.range = optStr.trim();
    } else {
      var opts = optStr.split(";");
      opts.forEach(function(opt) {
        if (!opt)
          return;
        var _opt$split = opt.split(":"), _opt$split2 = _slicedToArray2(_opt$split, 2), key = _opt$split2[0], val = _opt$split2[1];
        if (val.trim() === "false")
          formatOptions[key.trim()] = false;
        if (val.trim() === "true")
          formatOptions[key.trim()] = true;
        if (!isNaN(val.trim()))
          formatOptions[key.trim()] = parseInt(val.trim(), 10);
        if (!formatOptions[key.trim()])
          formatOptions[key.trim()] = val.trim();
      });
    }
  }
  return {
    formatName,
    formatOptions
  };
}
var Formatter = function() {
  function Formatter2() {
    var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    _classCallCheck3(this, Formatter2);
    this.logger = baseLogger.create("formatter");
    this.options = options;
    this.formats = {
      number: function number(val, lng, options2) {
        return new Intl.NumberFormat(lng, options2).format(val);
      },
      currency: function currency(val, lng, options2) {
        return new Intl.NumberFormat(lng, _objectSpread$4(_objectSpread$4({}, options2), {}, {
          style: "currency"
        })).format(val);
      },
      datetime: function datetime(val, lng, options2) {
        return new Intl.DateTimeFormat(lng, _objectSpread$4({}, options2)).format(val);
      },
      relativetime: function relativetime(val, lng, options2) {
        return new Intl.RelativeTimeFormat(lng, _objectSpread$4({}, options2)).format(val, options2.range || "day");
      },
      list: function list3(val, lng, options2) {
        return new Intl.ListFormat(lng, _objectSpread$4({}, options2)).format(val);
      }
    };
    this.init(options);
  }
  _createClass3(Formatter2, [{
    key: "init",
    value: function init4(services) {
      var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
        interpolation: {}
      };
      var iOpts = options.interpolation;
      this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ",";
    }
  }, {
    key: "add",
    value: function add(name, fc2) {
      this.formats[name] = fc2;
    }
  }, {
    key: "format",
    value: function format2(value, _format2, lng, options) {
      var _this = this;
      var formats2 = _format2.split(this.formatSeparator);
      var result = formats2.reduce(function(mem, f2) {
        var _parseFormatStr = parseFormatStr(f2), formatName = _parseFormatStr.formatName, formatOptions = _parseFormatStr.formatOptions;
        if (_this.formats[formatName]) {
          var formatted = mem;
          try {
            var valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
            var l2 = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
            formatted = _this.formats[formatName](mem, l2, _objectSpread$4(_objectSpread$4(_objectSpread$4({}, formatOptions), options), valOptions));
          } catch (error2) {
            _this.logger.warn(error2);
          }
          return formatted;
        } else {
          _this.logger.warn("there was no format function for ".concat(formatName));
        }
        return mem;
      }, value);
      return result;
    }
  }]);
  return Formatter2;
}();
function ownKeys$5(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$5(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$5(Object(source2), true).forEach(function(key) {
        _defineProperty4(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$5(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
function _createSuper$2(Derived) {
  var hasNativeReflectConstruct = _isNativeReflectConstruct$2();
  return function _createSuperInternal() {
    var Super = _getPrototypeOf(Derived), result;
    if (hasNativeReflectConstruct) {
      var NewTarget = _getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return _possibleConstructorReturn2(this, result);
  };
}
function _isNativeReflectConstruct$2() {
  if (typeof Reflect === "undefined" || !Reflect.construct)
    return false;
  if (Reflect.construct.sham)
    return false;
  if (typeof Proxy === "function")
    return true;
  try {
    Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
    return true;
  } catch (e2) {
    return false;
  }
}
function remove(arr, what) {
  var found = arr.indexOf(what);
  while (found !== -1) {
    arr.splice(found, 1);
    found = arr.indexOf(what);
  }
}
var Connector = function(_EventEmitter) {
  _inherits2(Connector2, _EventEmitter);
  var _super = _createSuper$2(Connector2);
  function Connector2(backend, store2, services) {
    var _this;
    var options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
    _classCallCheck3(this, Connector2);
    _this = _super.call(this);
    if (isIE10) {
      EventEmitter.call(_assertThisInitialized(_this));
    }
    _this.backend = backend;
    _this.store = store2;
    _this.services = services;
    _this.languageUtils = services.languageUtils;
    _this.options = options;
    _this.logger = baseLogger.create("backendConnector");
    _this.state = {};
    _this.queue = [];
    if (_this.backend && _this.backend.init) {
      _this.backend.init(services, options.backend, options);
    }
    return _this;
  }
  _createClass3(Connector2, [{
    key: "queueLoad",
    value: function queueLoad(languages2, namespaces2, options, callback) {
      var _this2 = this;
      var toLoad = [];
      var pending = [];
      var toLoadLanguages = [];
      var toLoadNamespaces = [];
      languages2.forEach(function(lng) {
        var hasAllNamespaces = true;
        namespaces2.forEach(function(ns) {
          var name = "".concat(lng, "|").concat(ns);
          if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) {
            _this2.state[name] = 2;
          } else if (_this2.state[name] < 0)
            ;
          else if (_this2.state[name] === 1) {
            if (pending.indexOf(name) < 0)
              pending.push(name);
          } else {
            _this2.state[name] = 1;
            hasAllNamespaces = false;
            if (pending.indexOf(name) < 0)
              pending.push(name);
            if (toLoad.indexOf(name) < 0)
              toLoad.push(name);
            if (toLoadNamespaces.indexOf(ns) < 0)
              toLoadNamespaces.push(ns);
          }
        });
        if (!hasAllNamespaces)
          toLoadLanguages.push(lng);
      });
      if (toLoad.length || pending.length) {
        this.queue.push({
          pending,
          loaded: {},
          errors: [],
          callback
        });
      }
      return {
        toLoad,
        pending,
        toLoadLanguages,
        toLoadNamespaces
      };
    }
  }, {
    key: "loaded",
    value: function loaded(name, err, data2) {
      var s2 = name.split("|");
      var lng = s2[0];
      var ns = s2[1];
      if (err)
        this.emit("failedLoading", lng, ns, err);
      if (data2) {
        this.store.addResourceBundle(lng, ns, data2);
      }
      this.state[name] = err ? -1 : 2;
      var loaded2 = {};
      this.queue.forEach(function(q2) {
        pushPath(q2.loaded, [lng], ns);
        remove(q2.pending, name);
        if (err)
          q2.errors.push(err);
        if (q2.pending.length === 0 && !q2.done) {
          Object.keys(q2.loaded).forEach(function(l2) {
            if (!loaded2[l2])
              loaded2[l2] = [];
            if (q2.loaded[l2].length) {
              q2.loaded[l2].forEach(function(ns2) {
                if (loaded2[l2].indexOf(ns2) < 0)
                  loaded2[l2].push(ns2);
              });
            }
          });
          q2.done = true;
          if (q2.errors.length) {
            q2.callback(q2.errors);
          } else {
            q2.callback();
          }
        }
      });
      this.emit("loaded", loaded2);
      this.queue = this.queue.filter(function(q2) {
        return !q2.done;
      });
    }
  }, {
    key: "read",
    value: function read3(lng, ns, fcName) {
      var _this3 = this;
      var tried = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0;
      var wait = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : 350;
      var callback = arguments.length > 5 ? arguments[5] : void 0;
      if (!lng.length)
        return callback(null, {});
      return this.backend[fcName](lng, ns, function(err, data2) {
        if (err && data2 && tried < 5) {
          setTimeout(function() {
            _this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback);
          }, wait);
          return;
        }
        callback(err, data2);
      });
    }
  }, {
    key: "prepareLoading",
    value: function prepareLoading(languages2, namespaces2) {
      var _this4 = this;
      var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      var callback = arguments.length > 3 ? arguments[3] : void 0;
      if (!this.backend) {
        this.logger.warn("No backend was added via i18next.use. Will not load resources.");
        return callback && callback();
      }
      if (typeof languages2 === "string")
        languages2 = this.languageUtils.toResolveHierarchy(languages2);
      if (typeof namespaces2 === "string")
        namespaces2 = [namespaces2];
      var toLoad = this.queueLoad(languages2, namespaces2, options, callback);
      if (!toLoad.toLoad.length) {
        if (!toLoad.pending.length)
          callback();
        return null;
      }
      toLoad.toLoad.forEach(function(name) {
        _this4.loadOne(name);
      });
    }
  }, {
    key: "load",
    value: function load(languages2, namespaces2, callback) {
      this.prepareLoading(languages2, namespaces2, {}, callback);
    }
  }, {
    key: "reload",
    value: function reload(languages2, namespaces2, callback) {
      this.prepareLoading(languages2, namespaces2, {
        reload: true
      }, callback);
    }
  }, {
    key: "loadOne",
    value: function loadOne(name) {
      var _this5 = this;
      var prefix2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
      var s2 = name.split("|");
      var lng = s2[0];
      var ns = s2[1];
      this.read(lng, ns, "read", void 0, void 0, function(err, data2) {
        if (err)
          _this5.logger.warn("".concat(prefix2, "loading namespace ").concat(ns, " for language ").concat(lng, " failed"), err);
        if (!err && data2)
          _this5.logger.log("".concat(prefix2, "loaded namespace ").concat(ns, " for language ").concat(lng), data2);
        _this5.loaded(name, err, data2);
      });
    }
  }, {
    key: "saveMissing",
    value: function saveMissing(languages2, namespace2, key, fallbackValue, isUpdate) {
      var options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {};
      if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace2)) {
        this.logger.warn('did not save key "'.concat(key, '" as the namespace "').concat(namespace2, '" was not yet loaded'), "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
        return;
      }
      if (key === void 0 || key === null || key === "")
        return;
      if (this.backend && this.backend.create) {
        this.backend.create(languages2, namespace2, key, fallbackValue, null, _objectSpread$5(_objectSpread$5({}, options), {}, {
          isUpdate
        }));
      }
      if (!languages2 || !languages2[0])
        return;
      this.store.addResource(languages2[0], namespace2, key, fallbackValue);
    }
  }]);
  return Connector2;
}(EventEmitter);
function get2() {
  return {
    debug: false,
    initImmediate: true,
    ns: ["translation"],
    defaultNS: ["translation"],
    fallbackLng: ["dev"],
    fallbackNS: false,
    supportedLngs: false,
    nonExplicitSupportedLngs: false,
    load: "all",
    preload: false,
    simplifyPluralSuffix: true,
    keySeparator: ".",
    nsSeparator: ":",
    pluralSeparator: "_",
    contextSeparator: "_",
    partialBundledLanguages: false,
    saveMissing: false,
    updateMissing: false,
    saveMissingTo: "fallback",
    saveMissingPlurals: true,
    missingKeyHandler: false,
    missingInterpolationHandler: false,
    postProcess: false,
    postProcessPassResolved: false,
    returnNull: true,
    returnEmptyString: true,
    returnObjects: false,
    joinArrays: false,
    returnedObjectHandler: false,
    parseMissingKeyHandler: false,
    appendNamespaceToMissingKey: false,
    appendNamespaceToCIMode: false,
    overloadTranslationOptionHandler: function handle2(args) {
      var ret = {};
      if (_typeof2(args[1]) === "object")
        ret = args[1];
      if (typeof args[1] === "string")
        ret.defaultValue = args[1];
      if (typeof args[2] === "string")
        ret.tDescription = args[2];
      if (_typeof2(args[2]) === "object" || _typeof2(args[3]) === "object") {
        var options = args[3] || args[2];
        Object.keys(options).forEach(function(key) {
          ret[key] = options[key];
        });
      }
      return ret;
    },
    interpolation: {
      escapeValue: true,
      format: function format2(value, _format2, lng, options) {
        return value;
      },
      prefix: "{{",
      suffix: "}}",
      formatSeparator: ",",
      unescapePrefix: "-",
      nestingPrefix: "$t(",
      nestingSuffix: ")",
      nestingOptionsSeparator: ",",
      maxReplaces: 1e3,
      skipOnVariables: true
    }
  };
}
function transformOptions(options) {
  if (typeof options.ns === "string")
    options.ns = [options.ns];
  if (typeof options.fallbackLng === "string")
    options.fallbackLng = [options.fallbackLng];
  if (typeof options.fallbackNS === "string")
    options.fallbackNS = [options.fallbackNS];
  if (options.supportedLngs && options.supportedLngs.indexOf("cimode") < 0) {
    options.supportedLngs = options.supportedLngs.concat(["cimode"]);
  }
  return options;
}
function ownKeys$6(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$6(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$6(Object(source2), true).forEach(function(key) {
        _defineProperty4(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$6(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
function _createSuper$3(Derived) {
  var hasNativeReflectConstruct = _isNativeReflectConstruct$3();
  return function _createSuperInternal() {
    var Super = _getPrototypeOf(Derived), result;
    if (hasNativeReflectConstruct) {
      var NewTarget = _getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return _possibleConstructorReturn2(this, result);
  };
}
function _isNativeReflectConstruct$3() {
  if (typeof Reflect === "undefined" || !Reflect.construct)
    return false;
  if (Reflect.construct.sham)
    return false;
  if (typeof Proxy === "function")
    return true;
  try {
    Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
    return true;
  } catch (e2) {
    return false;
  }
}
function noop3() {
}
function bindMemberFunctions(inst) {
  var mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
  mems.forEach(function(mem) {
    if (typeof inst[mem] === "function") {
      inst[mem] = inst[mem].bind(inst);
    }
  });
}
var I18n = function(_EventEmitter) {
  _inherits2(I18n2, _EventEmitter);
  var _super = _createSuper$3(I18n2);
  function I18n2() {
    var _this;
    var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    var callback = arguments.length > 1 ? arguments[1] : void 0;
    _classCallCheck3(this, I18n2);
    _this = _super.call(this);
    if (isIE10) {
      EventEmitter.call(_assertThisInitialized(_this));
    }
    _this.options = transformOptions(options);
    _this.services = {};
    _this.logger = baseLogger;
    _this.modules = {
      external: []
    };
    bindMemberFunctions(_assertThisInitialized(_this));
    if (callback && !_this.isInitialized && !options.isClone) {
      if (!_this.options.initImmediate) {
        _this.init(options, callback);
        return _possibleConstructorReturn2(_this, _assertThisInitialized(_this));
      }
      setTimeout(function() {
        _this.init(options, callback);
      }, 0);
    }
    return _this;
  }
  _createClass3(I18n2, [{
    key: "init",
    value: function init4() {
      var _this2 = this;
      var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      var callback = arguments.length > 1 ? arguments[1] : void 0;
      if (typeof options === "function") {
        callback = options;
        options = {};
      }
      if (!options.defaultNS && options.ns) {
        if (typeof options.ns === "string") {
          options.defaultNS = options.ns;
        } else if (options.ns.indexOf("translation") < 0) {
          options.defaultNS = options.ns[0];
        }
      }
      var defOpts = get2();
      this.options = _objectSpread$6(_objectSpread$6(_objectSpread$6({}, defOpts), this.options), transformOptions(options));
      this.options.interpolation = _objectSpread$6({}, this.options.interpolation);
      if (options.keySeparator !== void 0) {
        this.options.userDefinedKeySeparator = options.keySeparator;
      }
      if (options.nsSeparator !== void 0) {
        this.options.userDefinedNsSeparator = options.nsSeparator;
      }
      function createClassOnDemand(ClassOrObject) {
        if (!ClassOrObject)
          return null;
        if (typeof ClassOrObject === "function")
          return new ClassOrObject();
        return ClassOrObject;
      }
      if (!this.options.isClone) {
        if (this.modules.logger) {
          baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
        } else {
          baseLogger.init(null, this.options);
        }
        var formatter;
        if (this.modules.formatter) {
          formatter = this.modules.formatter;
        } else if (typeof Intl !== "undefined") {
          formatter = Formatter;
        }
        var lu = new LanguageUtil(this.options);
        this.store = new ResourceStore(this.options.resources, this.options);
        var s2 = this.services;
        s2.logger = baseLogger;
        s2.resourceStore = this.store;
        s2.languageUtils = lu;
        s2.pluralResolver = new PluralResolver(lu, {
          prepend: this.options.pluralSeparator,
          compatibilityJSON: this.options.compatibilityJSON,
          simplifyPluralSuffix: this.options.simplifyPluralSuffix
        });
        if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
          s2.formatter = createClassOnDemand(formatter);
          s2.formatter.init(s2, this.options);
          this.options.interpolation.format = s2.formatter.format.bind(s2.formatter);
        }
        s2.interpolator = new Interpolator(this.options);
        s2.utils = {
          hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
        };
        s2.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s2.resourceStore, s2, this.options);
        s2.backendConnector.on("*", function(event) {
          for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            args[_key - 1] = arguments[_key];
          }
          _this2.emit.apply(_this2, [event].concat(args));
        });
        if (this.modules.languageDetector) {
          s2.languageDetector = createClassOnDemand(this.modules.languageDetector);
          s2.languageDetector.init(s2, this.options.detection, this.options);
        }
        if (this.modules.i18nFormat) {
          s2.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
          if (s2.i18nFormat.init)
            s2.i18nFormat.init(this);
        }
        this.translator = new Translator(this.services, this.options);
        this.translator.on("*", function(event) {
          for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
            args[_key2 - 1] = arguments[_key2];
          }
          _this2.emit.apply(_this2, [event].concat(args));
        });
        this.modules.external.forEach(function(m2) {
          if (m2.init)
            m2.init(_this2);
        });
      }
      this.format = this.options.interpolation.format;
      if (!callback)
        callback = noop3;
      if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
        var codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
        if (codes.length > 0 && codes[0] !== "dev")
          this.options.lng = codes[0];
      }
      if (!this.services.languageDetector && !this.options.lng) {
        this.logger.warn("init: no languageDetector is used and no lng is defined");
      }
      var storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
      storeApi.forEach(function(fcName) {
        _this2[fcName] = function() {
          var _this2$store;
          return (_this2$store = _this2.store)[fcName].apply(_this2$store, arguments);
        };
      });
      var storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
      storeApiChained.forEach(function(fcName) {
        _this2[fcName] = function() {
          var _this2$store2;
          (_this2$store2 = _this2.store)[fcName].apply(_this2$store2, arguments);
          return _this2;
        };
      });
      var deferred = defer();
      var load = function load2() {
        var finish = function finish2(err, t5) {
          if (_this2.isInitialized && !_this2.initializedStoreOnce)
            _this2.logger.warn("init: i18next is already initialized. You should call init just once!");
          _this2.isInitialized = true;
          if (!_this2.options.isClone)
            _this2.logger.log("initialized", _this2.options);
          _this2.emit("initialized", _this2.options);
          deferred.resolve(t5);
          callback(err, t5);
        };
        if (_this2.languages && _this2.options.compatibilityAPI !== "v1" && !_this2.isInitialized)
          return finish(null, _this2.t.bind(_this2));
        _this2.changeLanguage(_this2.options.lng, finish);
      };
      if (this.options.resources || !this.options.initImmediate) {
        load();
      } else {
        setTimeout(load, 0);
      }
      return deferred;
    }
  }, {
    key: "loadResources",
    value: function loadResources2(language) {
      var _this3 = this;
      var callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop3;
      var usedCallback = callback;
      var usedLng = typeof language === "string" ? language : this.language;
      if (typeof language === "function")
        usedCallback = language;
      if (!this.options.resources || this.options.partialBundledLanguages) {
        if (usedLng && usedLng.toLowerCase() === "cimode")
          return usedCallback();
        var toLoad = [];
        var append2 = function append3(lng) {
          if (!lng)
            return;
          var lngs = _this3.services.languageUtils.toResolveHierarchy(lng);
          lngs.forEach(function(l2) {
            if (toLoad.indexOf(l2) < 0)
              toLoad.push(l2);
          });
        };
        if (!usedLng) {
          var fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
          fallbacks.forEach(function(l2) {
            return append2(l2);
          });
        } else {
          append2(usedLng);
        }
        if (this.options.preload) {
          this.options.preload.forEach(function(l2) {
            return append2(l2);
          });
        }
        this.services.backendConnector.load(toLoad, this.options.ns, usedCallback);
      } else {
        usedCallback(null);
      }
    }
  }, {
    key: "reloadResources",
    value: function reloadResources2(lngs, ns, callback) {
      var deferred = defer();
      if (!lngs)
        lngs = this.languages;
      if (!ns)
        ns = this.options.ns;
      if (!callback)
        callback = noop3;
      this.services.backendConnector.reload(lngs, ns, function(err) {
        deferred.resolve();
        callback(err);
      });
      return deferred;
    }
  }, {
    key: "use",
    value: function use3(module2) {
      if (!module2)
        throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
      if (!module2.type)
        throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
      if (module2.type === "backend") {
        this.modules.backend = module2;
      }
      if (module2.type === "logger" || module2.log && module2.warn && module2.error) {
        this.modules.logger = module2;
      }
      if (module2.type === "languageDetector") {
        this.modules.languageDetector = module2;
      }
      if (module2.type === "i18nFormat") {
        this.modules.i18nFormat = module2;
      }
      if (module2.type === "postProcessor") {
        postProcessor.addPostProcessor(module2);
      }
      if (module2.type === "formatter") {
        this.modules.formatter = module2;
      }
      if (module2.type === "3rdParty") {
        this.modules.external.push(module2);
      }
      return this;
    }
  }, {
    key: "changeLanguage",
    value: function changeLanguage2(lng, callback) {
      var _this4 = this;
      this.isLanguageChangingTo = lng;
      var deferred = defer();
      this.emit("languageChanging", lng);
      var setLngProps = function setLngProps2(l2) {
        _this4.language = l2;
        _this4.languages = _this4.services.languageUtils.toResolveHierarchy(l2);
        _this4.resolvedLanguage = void 0;
        if (["cimode", "dev"].indexOf(l2) > -1)
          return;
        for (var li2 = 0; li2 < _this4.languages.length; li2++) {
          var lngInLngs = _this4.languages[li2];
          if (["cimode", "dev"].indexOf(lngInLngs) > -1)
            continue;
          if (_this4.store.hasLanguageSomeTranslations(lngInLngs)) {
            _this4.resolvedLanguage = lngInLngs;
            break;
          }
        }
      };
      var done = function done2(err, l2) {
        if (l2) {
          setLngProps(l2);
          _this4.translator.changeLanguage(l2);
          _this4.isLanguageChangingTo = void 0;
          _this4.emit("languageChanged", l2);
          _this4.logger.log("languageChanged", l2);
        } else {
          _this4.isLanguageChangingTo = void 0;
        }
        deferred.resolve(function() {
          return _this4.t.apply(_this4, arguments);
        });
        if (callback)
          callback(err, function() {
            return _this4.t.apply(_this4, arguments);
          });
      };
      var setLng = function setLng2(lngs) {
        if (!lng && !lngs && _this4.services.languageDetector)
          lngs = [];
        var l2 = typeof lngs === "string" ? lngs : _this4.services.languageUtils.getBestMatchFromCodes(lngs);
        if (l2) {
          if (!_this4.language) {
            setLngProps(l2);
          }
          if (!_this4.translator.language)
            _this4.translator.changeLanguage(l2);
          if (_this4.services.languageDetector)
            _this4.services.languageDetector.cacheUserLanguage(l2);
        }
        _this4.loadResources(l2, function(err) {
          done(err, l2);
        });
      };
      if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
        setLng(this.services.languageDetector.detect());
      } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
        this.services.languageDetector.detect(setLng);
      } else {
        setLng(lng);
      }
      return deferred;
    }
  }, {
    key: "getFixedT",
    value: function getFixedT2(lng, ns, keyPrefix) {
      var _this5 = this;
      var fixedT = function fixedT2(key, opts) {
        var options;
        if (_typeof2(opts) !== "object") {
          for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
            rest[_key3 - 2] = arguments[_key3];
          }
          options = _this5.options.overloadTranslationOptionHandler([key, opts].concat(rest));
        } else {
          options = _objectSpread$6({}, opts);
        }
        options.lng = options.lng || fixedT2.lng;
        options.lngs = options.lngs || fixedT2.lngs;
        options.ns = options.ns || fixedT2.ns;
        var keySeparator = _this5.options.keySeparator || ".";
        var resultKey = keyPrefix ? "".concat(keyPrefix).concat(keySeparator).concat(key) : key;
        return _this5.t(resultKey, options);
      };
      if (typeof lng === "string") {
        fixedT.lng = lng;
      } else {
        fixedT.lngs = lng;
      }
      fixedT.ns = ns;
      fixedT.keyPrefix = keyPrefix;
      return fixedT;
    }
  }, {
    key: "t",
    value: function t5() {
      var _this$translator;
      return this.translator && (_this$translator = this.translator).translate.apply(_this$translator, arguments);
    }
  }, {
    key: "exists",
    value: function exists2() {
      var _this$translator2;
      return this.translator && (_this$translator2 = this.translator).exists.apply(_this$translator2, arguments);
    }
  }, {
    key: "setDefaultNamespace",
    value: function setDefaultNamespace2(ns) {
      this.options.defaultNS = ns;
    }
  }, {
    key: "hasLoadedNamespace",
    value: function hasLoadedNamespace3(ns) {
      var _this6 = this;
      var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      if (!this.isInitialized) {
        this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
        return false;
      }
      if (!this.languages || !this.languages.length) {
        this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
        return false;
      }
      var lng = this.resolvedLanguage || this.languages[0];
      var fallbackLng = this.options ? this.options.fallbackLng : false;
      var lastLng = this.languages[this.languages.length - 1];
      if (lng.toLowerCase() === "cimode")
        return true;
      var loadNotPending = function loadNotPending2(l2, n3) {
        var loadState = _this6.services.backendConnector.state["".concat(l2, "|").concat(n3)];
        return loadState === -1 || loadState === 2;
      };
      if (options.precheck) {
        var preResult = options.precheck(this, loadNotPending);
        if (preResult !== void 0)
          return preResult;
      }
      if (this.hasResourceBundle(lng, ns))
        return true;
      if (!this.services.backendConnector.backend)
        return true;
      if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns)))
        return true;
      return false;
    }
  }, {
    key: "loadNamespaces",
    value: function loadNamespaces3(ns, callback) {
      var _this7 = this;
      var deferred = defer();
      if (!this.options.ns) {
        callback && callback();
        return Promise.resolve();
      }
      if (typeof ns === "string")
        ns = [ns];
      ns.forEach(function(n3) {
        if (_this7.options.ns.indexOf(n3) < 0)
          _this7.options.ns.push(n3);
      });
      this.loadResources(function(err) {
        deferred.resolve();
        if (callback)
          callback(err);
      });
      return deferred;
    }
  }, {
    key: "loadLanguages",
    value: function loadLanguages2(lngs, callback) {
      var deferred = defer();
      if (typeof lngs === "string")
        lngs = [lngs];
      var preloaded = this.options.preload || [];
      var newLngs = lngs.filter(function(lng) {
        return preloaded.indexOf(lng) < 0;
      });
      if (!newLngs.length) {
        if (callback)
          callback();
        return Promise.resolve();
      }
      this.options.preload = preloaded.concat(newLngs);
      this.loadResources(function(err) {
        deferred.resolve();
        if (callback)
          callback(err);
      });
      return deferred;
    }
  }, {
    key: "dir",
    value: function dir(lng) {
      if (!lng)
        lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
      if (!lng)
        return "rtl";
      var rtlLngs = ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"];
      return rtlLngs.indexOf(this.services.languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
    }
  }, {
    key: "cloneInstance",
    value: function cloneInstance() {
      var _this8 = this;
      var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      var callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop3;
      var mergedOptions = _objectSpread$6(_objectSpread$6(_objectSpread$6({}, this.options), options), {
        isClone: true
      });
      var clone2 = new I18n2(mergedOptions);
      var membersToCopy = ["store", "services", "language"];
      membersToCopy.forEach(function(m2) {
        clone2[m2] = _this8[m2];
      });
      clone2.services = _objectSpread$6({}, this.services);
      clone2.services.utils = {
        hasLoadedNamespace: clone2.hasLoadedNamespace.bind(clone2)
      };
      clone2.translator = new Translator(clone2.services, clone2.options);
      clone2.translator.on("*", function(event) {
        for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
          args[_key4 - 1] = arguments[_key4];
        }
        clone2.emit.apply(clone2, [event].concat(args));
      });
      clone2.init(mergedOptions, callback);
      clone2.translator.options = clone2.options;
      clone2.translator.backendConnector.services.utils = {
        hasLoadedNamespace: clone2.hasLoadedNamespace.bind(clone2)
      };
      return clone2;
    }
  }, {
    key: "toJSON",
    value: function toJSON() {
      return {
        options: this.options,
        store: this.store,
        language: this.language,
        languages: this.languages,
        resolvedLanguage: this.resolvedLanguage
      };
    }
  }]);
  return I18n2;
}(EventEmitter);
_defineProperty4(I18n, "createInstance", function() {
  var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
  var callback = arguments.length > 1 ? arguments[1] : void 0;
  return new I18n(options, callback);
});
var instance = I18n.createInstance();
instance.createInstance = I18n.createInstance;
var createInstance2 = instance.createInstance;
var init2 = instance.init;
var loadResources = instance.loadResources;
var reloadResources = instance.reloadResources;
var use2 = instance.use;
var changeLanguage = instance.changeLanguage;
var getFixedT = instance.getFixedT;
var t3 = instance.t;
var exists = instance.exists;
var setDefaultNamespace = instance.setDefaultNamespace;
var hasLoadedNamespace2 = instance.hasLoadedNamespace;
var loadNamespaces2 = instance.loadNamespaces;
var loadLanguages = instance.loadLanguages;
var i18next_default = instance;

// build/common-messages.js
var common_messages_default = {
  common: {
    fullName: "{{givenName}} {{familyName}}",
    unknownUser: "Anonymous",
    add: "Add",
    yes: "Yes",
    no: "No",
    create: "Create",
    save: "Save",
    revert: "Revert",
    cancel: "Cancel",
    reload: "Reload",
    continue: "Continue",
    close: "Close",
    delete: "Delete",
    remove: "Remove",
    search: "Search",
    key: "Key",
    value: "Value",
    noSearchResults: "No search results",
    noSearchResultsInstructions: "Click on the search bar above to search",
    next: "Next",
    back: "Back",
    finish: "Finish",
    skipCustomizationAndFinish: "Skip customization and finish",
    export: "Export",
    action: "Action",
    download: "Download",
    resourceFile: "Resource file",
    clear: "Clear",
    clearFile: "Clear this file",
    clearFileExplain: "Are you sure you want to clear this file?",
    on: "On",
    off: "Off",
    enabled: "Enabled",
    disabled: "Disabled",
    disable: "Disable",
    selectOne: "Select an option",
    select: "Select",
    choose: "Choose...",
    any: "Any",
    none: "None",
    signOut: "Sign out",
    manageAccount: "Manage account",
    serverInfo: "Server info",
    realmInfo: "Realm info",
    help: "Help",
    helpLabel: "More help for '{{label}}'",
    helpEnabled: "Help on",
    helpDisabled: "Help off",
    documentation: "Documentation",
    enableHelpMode: "Enable help mode",
    learnMore: "Learn more",
    show: "Show",
    hide: "Hide",
    showRemaining: "Show ${remaining}",
    more: "{{count}} more",
    test: "Test",
    testConnection: "Test connection",
    name: "Name",
    role: "Role",
    description: "Description",
    type: "Type",
    category: "Category",
    priority: "Priority",
    unexpectedError: "An unexpected error occurred: '{{error}}'",
    retry: "Press here to refresh and continue",
    plus: "Plus",
    minus: "Minus",
    clientScope: {
      default: "Default",
      optional: "Optional",
      none: "None"
    },
    allTypes: "All types",
    home: "Home",
    manage: "Manage",
    clients: "Clients",
    clientScopes: "Client scopes",
    realmRoles: "Realm roles",
    clientRoles: "Client roles",
    users: "Users",
    groups: "Groups",
    sessions: "Sessions",
    events: "Events",
    mappers: "Mappers",
    configure: "Configure",
    realmSettings: "Realm settings",
    authentication: "Authentication",
    identityProviders: "Identity providers",
    userFederation: "User federation",
    settings: "Settings",
    details: "Details",
    required: "Required field",
    maxLength: "Max length {{length}}",
    createRealm: "Create Realm",
    recent: "Recent",
    jumpToSection: "Jump to section",
    Sunday: "Sunday",
    Monday: "Monday",
    Tuesday: "Tuesday",
    Wednesday: "Wednesday",
    Thursday: "Thursday",
    Friday: "Friday",
    Saturday: "Saturday",
    unitLabel: "Select a time unit",
    times: {
      seconds: "Seconds",
      minutes: "Minutes",
      hours: "Hours",
      days: "Days",
      years: "Years"
    },
    attributes: "Attributes",
    credentials: "Credentials",
    clientId: "Client ID",
    id: "ID",
    addMapper: "Add mapper",
    createNewMapper: "Create new mapper",
    searchForMapper: "Search for mapper",
    mapperType: "Mapper type",
    mappingDeletedSuccess: "Mapping successfully deleted",
    mappingDeletedError: "Could not delete mapping: '{{error}}'",
    mappingDetails: "Mapper details",
    mappingUpdatedSuccess: "Mapping successfully updated",
    mappingUpdatedError: "Could not update mapping: '{{error}}'",
    mappingCreatedSuccess: "Mapping successfully created",
    mappingCreatedError: "Could not create mapping: '{{error}}'",
    deleteMappingTitle: "Delete mapping?",
    deleteMappingConfirm: "Are you sure you want to delete this mapping?",
    emptyMappers: "No mappers",
    emptyMappersInstructions: "If you want to add mappers, please click the button below to add some predefined mappers or to configure a new mapper.",
    emptyPrimaryAction: "Add predefined mapper",
    leaveDirtyTitle: "Leave without saving?",
    leaveDirtyConfirm: "Do you want to leave this page without saving? Any unsaved changes will be lost.",
    leave: "Leave",
    reorder: "Reorder",
    onDragStart: "Dragging started for item {{item}}",
    onDragMove: "Dragging item {{item}}",
    onDragCancel: "Dragging cancelled. List is unchanged.",
    onDragFinish: "Dragging finished {{list}}",
    notFound: "Could not find the resource that you are looking for",
    password: "Password",
    passwordConfirmation: "Password confirmation",
    temporaryPassword: "Temporary",
    temporaryPasswordHelpText: "If enabled, the user must change the password on next login"
  }
};

// build/common-help.js
var common_help_default = {
  "common-help": {
    helpToggleInfo: "This toggle will enable / disable part of the help info in the console. Includes any help text, links and popovers.",
    showPassword: "Show password field in clear text",
    helpFileUpload: "Upload a JSON file",
    dragHelp: "Press space or enter to begin dragging, and use the arrow keys to navigate up or down. Press enter to confirm the drag, or any other key to cancel the drag operation."
  }
};

// build/dashboard/messages.js
var messages_default = {
  dashboard: {
    realmName: "{{name}} realm",
    welcome: "Welcome to",
    introduction: "If you want to leave this page and mange this realm, please click the corresponding menu items in the left navigation bar.",
    serverInfo: "Server info",
    version: "Version",
    product: "Product",
    profile: "Profile",
    enabledFeatures: "Enabled features",
    experimental: "Experimental",
    preview: "Preview",
    infoEnabledFeatures: "Something about what enabled features are.",
    infoDisabledFeatures: "Something about what disabled features are.",
    disabledFeatures: "Disabled features",
    adminUiVersion: '<0 class="pf-u-mr-md">Admin UI version</0>{{version}}'
  }
};

// build/clients/messages.js
var messages_default2 = {
  clients: {
    protocolTypes: {
      openIdConnect: "OpenID Connect",
      saml: "SAML",
      all: "All"
    },
    protocol: "Protocol",
    clientType: "Client type",
    clientAuthorization: "Authorization",
    implicitFlow: "Implicit flow",
    createClient: "Create client",
    importClient: "Import client",
    homeURL: "Home URL",
    webOrigins: "Web origins",
    addWebOrigins: "Add web origins",
    adminURL: "Admin URL",
    formatOption: "Format option",
    encryptAssertions: "Encrypt assertions",
    clientSignature: "Client signature required",
    downloadAdaptorTitle: "Download adaptor configs",
    privateKeyMask: "PRIVATE KEY NOT SET UP OR KNOWN",
    keys: "Keys",
    credentials: "Credentials",
    roles: "Roles",
    createRole: "Create role",
    noRoles: "No roles for this client",
    noRolesInstructions: "You haven't created any roles for this client. Create a role to get started.",
    clientScopes: "Client scopes",
    addClientScope: "Add client scope",
    addClientScopesTo: "Add client scopes to {{clientName}}",
    clientScopeRemoveSuccess: "Scope mapping successfully removed",
    clientScopeRemoveError: "Could not remove the scope mapping {{error}}",
    clientScopeSuccess: "Scope mapping successfully updated",
    clientScopeError: "Could not update the scope mapping {{error}}",
    searchByName: "Search by name",
    setup: "Setup",
    evaluate: "Evaluate",
    assignRole: "Assign role",
    unAssignRole: "Unassign",
    removeMappingTitle: "Remove mapping?",
    removeMappingConfirm_one: "Are you sure you want to remove this mapping?",
    removeMappingConfirm_other: "Are you sure you want to remove {{count}} mappings",
    clientScopeSearch: {
      name: "Name",
      type: "Assigned type",
      protocol: "Protocol"
    },
    authorization: "Authorization",
    settings: "Settings",
    policyEnforcementMode: "Policy enforcement mode",
    policyEnforcementModes: {
      ENFORCING: "Enforcing",
      PERMISSIVE: "Permissive",
      DISABLED: "Disabled"
    },
    decisionStrategy: "Decision strategy",
    decisionStrategies: {
      UNANIMOUS: "Unanimous",
      AFFIRMATIVE: "Affirmative"
    },
    importResources: "The following settings and data will be imported:",
    importWarning: "The data and settings imported above may overwrite the data and settings that already exist.",
    importResourceSuccess: "The resource was successfully imported",
    importResourceError: "Could not import the resource due to {{error}}",
    createResource: "Create resource",
    createResourceBasedPermission: "Create resource-based permission",
    displayName: "Display name",
    type: "Type",
    addUri: "Add URI",
    authorizationScopes: "Authorization scopes",
    iconUri: "Icon URI",
    ownerManagedAccess: "User-Managed access enabled",
    resourceAttribute: "Resource attribute",
    createResourceSuccess: "Resource created successfully",
    updateResourceSuccess: "Resource successfully updated",
    resourceSaveError: "Could not persist resource due to {{error}}",
    associatedPermissions: "Associated permission",
    allowRemoteResourceManagement: "Remote resource management",
    resources: "Resources",
    owner: "Owner",
    uris: "URIs",
    scopes: "Scopes",
    policies: "Policies",
    createPermission: "Create permission",
    deleteResource: "Permanently delete resource?",
    deleteResourceConfirm: "If you delete this resource, some permissions will be affected.",
    deleteResourceWarning: "The permissions below will be removed when they are no longer used by other resources:",
    resourceDeletedSuccess: "The resource successfully deleted",
    resourceDeletedError: "Could not remove the resource {{error}}",
    assignedClientScope: "Assigned client scope",
    assignedType: "Assigned type",
    hideInheritedRoles: "Hide inherited roles",
    inherentFrom: "Inherited from",
    emptyClientScopes: "This client doesn't have any added client scopes",
    emptyClientScopesInstructions: "There are currently no client scopes linked to this client. You can add existing client scopes to this client to share protocol mappers and roles.",
    emptyClientScopesPrimaryAction: "Add client scopes",
    scopeParameter: "Scope parameter",
    scopeParameterPlaceholder: "Select scope parameters",
    effectiveProtocolMappers: "Effective protocol mappers",
    effectiveRoleScopeMappings: "Effective role scope mappings",
    generatedAccessToken: "Generated access token",
    searchForProtocol: "Search protocol mapper",
    parentClientScope: "Parent client scope",
    searchForRole: "Search role",
    origin: "Origin",
    user: "User",
    noGeneratedAccessToken: "No generated access token",
    generatedAccessTokenIsDisabled: "Generated access token is disabled when no user is selected",
    clientList: "Clients",
    clientsList: "Clients list",
    initialAccessToken: "Initial access token",
    clientSettings: "Client details",
    selectEncryptionType: "Select Encryption type",
    generalSettings: "General Settings",
    capabilityConfig: "Capability config",
    clientsExplain: "Clients are applications and services that can request authentication of a user",
    explainBearerOnly: "This is a special OIDC type. This client only allows bearer token requests and cannot participate in browser logins.",
    createSuccess: "Client created successfully",
    createError: "Could not create client: '{{error}}'",
    clientImportError: "Could not import client: {{error}}",
    clientSaveSuccess: "Client successfully updated",
    clientSaveError: "Client could not be updated: {{error}}",
    clientImportSuccess: "Client imported successfully",
    clientDelete: "Delete {{clientId}} ?",
    clientDeletedSuccess: "The client has been deleted",
    clientDeleteError: "Could not delete client: {{error}}",
    clientDeleteConfirmTitle: "Delete client?",
    disableConfirmTitle: "Disable client?",
    downloadAdapterConfig: "Download adapter config",
    disableConfirm: "If you disable this client, you cannot initiate a login or obtain access tokens.",
    clientDeleteConfirm: "If you delete this client, all associated data will be removed.",
    searchInitialAccessToken: "Search token",
    createToken: "Create initial access token",
    tokenDeleteConfirm: "Are you sure you want to permanently delete the initial access token {{id}}",
    tokenDeleteConfirmTitle: "Delete initial access token?",
    tokenDeleteSuccess: "initial access token created successfully",
    tokenDeleteError: "Could not delete initial access token: '{{error}}'",
    timestamp: "Created date",
    created: "Created",
    lastUpdated: "Last updated",
    expires: "Expires",
    count: "Count",
    remainingCount: "Remaining count",
    expiration: "Expiration",
    noTokens: "No initial access tokens",
    noTokensInstructions: `You haven't created any initial access tokens. Create an initial access token by clicking "Create".`,
    tokenSaveSuccess: "New initial access token has been created",
    tokenSaveError: "Could not create initial access token {{error}}",
    initialAccessTokenDetails: "Initial access token details",
    copyInitialAccessToken: "Please copy and paste the initial access token before closing as it can not be retrieved later.",
    clientAuthentication: "Client authentication",
    authentication: "Authentication",
    authenticationFlow: "Authentication flow",
    standardFlow: "Standard flow",
    directAccess: "Direct access grants",
    serviceAccount: "Service accounts roles",
    enableServiceAccount: "Enable service account roles",
    assignRolesTo: "Assign roles to {{client}} account",
    searchByRoleName: "Search by role name",
    filterByOrigin: "Filter by Origin",
    realmRoles: "Realm roles",
    clients: "Clients",
    assign: "Assign",
    roleMappingUpdatedSuccess: "Role mapping updated",
    roleMappingUpdatedError: "Could not update role mapping {{error}}",
    displayOnClient: "Display client on screen",
    consentScreenText: "Client consent screen text",
    loginSettings: "Login settings",
    accessSettings: "Access settings",
    rootUrl: "Root URL",
    validRedirectUri: "Valid redirect URIs",
    samlCapabilityConfig: "SAML capabilities",
    signatureAndEncryption: "Signature and Encryption",
    nameIdFormat: "Name ID format",
    forceNameIdFormat: "Force name ID format",
    forcePostBinding: "Force POST binding",
    forceArtifactBinding: "Force artifact binding",
    includeAuthnStatement: "Include AuthnStatement",
    includeOneTimeUseCondition: "Include OneTimeUse Condition",
    optimizeLookup: "Optimize REDIRECT signing key lookup",
    signDocuments: "Sign documents",
    signAssertions: "Sign assertions",
    signatureKeyName: "SAML signature key name",
    canonicalization: "Canonicalization method",
    addRedirectUri: "Add valid redirect URIs",
    loginTheme: "Login theme",
    consentRequired: "Consent required",
    clientAuthenticator: "Client Authenticator",
    changeAuthenticatorConfirmTitle: "Change to {{clientAuthenticatorType}}",
    changeAuthenticatorConfirm: "If you change authenticator to {{clientAuthenticatorType}}, the keycloak database will be updated and you may need to download a new adapter configuration for this client",
    signedJWTConfirm: 'You should configure JWKS URL or keys in the "Keys" tab to change the parameters of Signed JWT authenticator.',
    anyAlgorithm: "Any algorithm",
    clientSecret: "Client secret",
    regenerate: "Regenerate",
    confirmClientSecretTitle: "Regenerate secret for this client?",
    confirmClientSecretBody: "If you regenerate secret, the Keycloak database will be updated and you will need to download a new adapter for this client.",
    confirmAccessTokenTitle: "Regenerate registration access token?",
    confirmAccessTokenBody: "If you regenerate registration access token, the access data regarding the client registration service will be updated.",
    clientSecretSuccess: "Client secret regenerated",
    clientSecretError: "Could not regenerate client secret due to: {{error}}",
    signingKeysConfig: "Signing keys config",
    signingKeysConfigExplain: 'If you enable the "Client signature required" below, you must configure the signing keys by generating or importing keys, and the client will sign their saml requests and responses. The signature will be validated.',
    encryptionKeysConfig: "Encryption keys config",
    encryptionKeysConfigExplain: `If you enable the "Encryption assertions" below, you must configure the encryption keys by generating or importing keys, and the SAML assertions will be encrypted with the client's public key using AES.`,
    enableClientSignatureRequired: 'Enable "Client signature required"?',
    enableClientSignatureRequiredExplain: 'If you enable "Client signature required", the adapter of this client will be updated. You may need to download a new adapter for this client. You need to generate or import keys for this client otherwise the authentication will not work.',
    selectMethod: "Select method",
    selectMethodType: {
      generate: "Generate",
      import: "Import"
    },
    confirm: "Confirm",
    browse: "Browse",
    importKey: "Import key",
    disableSigning: 'Disable "{{key}}"',
    disableSigningExplain: 'If you disable "{{key}}", the Keycloak database will be updated and you may need to download a new adapter for this client.',
    reGenerateSigning: "Regenerate signing key for this client",
    reGenerateSigningExplain: "If you regenerate signing key for client, the Keycloak database will be updated and you may need to download a new adapter for this client.",
    registrationAccessToken: "Registration access token",
    accessTokenSuccess: "Access token regenerated",
    accessTokenError: "Could not regenerate access token due to: {{error}}",
    signatureAlgorithm: "Signature algorithm",
    subject: "Subject DN",
    searchForClient: "Search for client",
    advanced: "Advanced",
    revocation: "Revocation",
    clustering: "Clustering",
    notBefore: "Not before",
    setToNow: "Set to now",
    noAdminUrlSet: "No push sent. No admin URI configured or no registered cluster nodes available",
    notBeforeSetToNow: "Not Before set for client",
    notBeforeNowClear: "Not Before cleared for client",
    notBeforePushFail: 'Failed to push "not before" to: {{failedNodes}}',
    notBeforePushSuccess: 'Successfully push "not before" to: {{successNodes}}',
    testClusterFail: "Failed verified availability for: {{failedNodes}}. Fix or unregister failed cluster nodes and try again",
    testClusterSuccess: "Successfully verified availability for: {{successNodes}}",
    deleteNode: "Delete node?",
    deleteNodeBody: 'Are you sure you want to permanently delete the node "{{node}}"',
    deleteNodeSuccess: "Node successfully removed",
    deleteNodeFail: "Could not delete node: '{{error}}'",
    addedNodeSuccess: "Node successfully added",
    addedNodeFail: "Could not add node: '{{error}}'",
    addNode: "Add node",
    push: "Push",
    clear: "Clear",
    nodeReRegistrationTimeout: "Node Re-registration timeout",
    registeredClusterNodes: "Registered cluster nodes",
    nodeHost: "Node host",
    noNodes: "No nodes registered",
    noNodesInstructions: "There are no nodes registered, you can add one manually.",
    lastRegistration: "Last registration",
    testClusterAvailability: "Test cluster availability",
    registerNodeManually: "Register node manually",
    fineGrainOpenIdConnectConfiguration: "Fine grain OpenID Connect configuration",
    fineGrainSamlEndpointConfig: "Fine Grain SAML Endpoint Configuration",
    accessTokenSignatureAlgorithm: "Access token signature algorithm",
    idTokenSignatureAlgorithm: "ID token signature algorithm",
    idTokenEncryptionKeyManagementAlgorithm: "ID token encryption key management algorithm",
    idTokenEncryptionContentEncryptionAlgorithm: "ID token encryption content encryption algorithm",
    userInfoSignedResponseAlgorithm: "User info signed response algorithm",
    requestObjectSignatureAlgorithm: "Request object signature algorithm",
    requestObjectRequired: "Request object required",
    requestObject: {
      "not required": "Not required",
      "request or request_uri": "Request or Request URI",
      "request only": "Request only",
      "request_uri only": "Request URI only"
    },
    openIdConnectCompatibilityModes: "Open ID Connect Compatibly Modes",
    excludeSessionStateFromAuthenticationResponse: "Exclude Session State From Authentication Response",
    assertionConsumerServicePostBindingURL: "Assertion Consumer Service POST Binding URL",
    assertionConsumerServiceRedirectBindingURL: "Assertion Consumer Service Redirect Binding URL",
    logoutServicePostBindingURL: "Logout Service POST Binding URL",
    logoutServiceRedirectBindingURL: "Logout Service Redirect Binding URL",
    logoutServiceArtifactBindingUrl: "Logout Service ARTIFACT Binding URL",
    artifactBindingUrl: "Artifact Binding URL",
    artifactResolutionService: "Artifact Resolution Service",
    advancedSettings: "Advanced Settings",
    assertionLifespan: "Assertion Lifespan",
    accessTokenLifespan: "Access Token Lifespan",
    oAuthMutual: "OAuth 2.0 Mutual TLS Certificate Bound Access Tokens Enabled",
    keyForCodeExchange: "Proof Key for Code Exchange Code Challenge Method",
    authenticationOverrides: "Authentication flow overrides",
    browserFlow: "Browser Flow",
    directGrant: "Direct Grant Flow",
    jwksUrlConfig: "JWKS URL configs",
    keysIntro: 'If "Use JWKS URL switch" is on, you need to fill a valid JWKS URL. After saving, admin can download keys from the JWKS URL or keys will be downloaded automatically by Keycloak server when see the stuff signed by the unknown KID',
    useJwksUrl: "Use JWKS URL",
    certificate: "Certificate",
    jwksUrl: "JWKS URL",
    generateNewKeys: "Generate new keys",
    generateKeys: "Generate keys?",
    generate: "Generate",
    archiveFormat: "Archive format",
    keyAlias: "Key alias",
    keyPassword: "Key password",
    storePassword: "Store password",
    generateSuccess: "New key pair and certificate generated successfully",
    generateError: "Could not generate new key pair and certificate {{error}}",
    import: "Import",
    importFile: "Import file",
    importSuccess: "New certificate imported",
    importError: "Could not import certificate {{error}}",
    tokenLifespan: {
      expires: "Expires in",
      never: "Never expires"
    },
    mappers: "Mappers"
  }
};

// build/clients/help.js
var help_default = {
  "clients-help": {
    enableDisable: "Disabled clients cannot initiate a login or have obtained access tokens.",
    clientType: "'OpenID Connect' allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server.'SAML' enables web-based authentication and authorization scenarios including cross-domain single sign-on (SSO) and uses security tokens containing assertions to pass information.",
    serviceAccount: "Allows you to authenticate this client to Keycloak and retrieve access token dedicated to this client. In terms of OAuth2 specification, this enables support of 'Client Credentials Grant' for this client.",
    authentication: "This defines the type of the OIDC client. When it's ON, the OIDC type is set to confidential access type. When it's OFF, it is set to public access type",
    authorization: "Enable/Disable fine-grained authorization support for a client",
    directAccess: "This enables support for Direct Access Grants, which means that client has access to username/password of user and exchange it directly with Keycloak server for access token. In terms of OAuth2 specification, this enables support of 'Resource Owner Password Credentials Grant' for this client.",
    standardFlow: "This enables standard OpenID Connect redirect based authentication with authorization code. In terms of OpenID Connect or OAuth2 specifications, this enables support of 'Authorization Code Flow' for this client.",
    implicitFlow: "This enables support for OpenID Connect redirect based authentication without authorization code. In terms of OpenID Connect or OAuth2 specifications, this enables support of 'Implicit Flow' for this client.",
    rootURL: "Root URL appended to relative URLs",
    validRedirectURIs: "Valid URI pattern a browser can redirect to after a successful login or logout. Simple wildcards are allowed such as 'http://example.com/*'. Relative path can be specified too such as /my/relative/path/*. Relative paths are relative to the client root URL, or if none is specified the auth server root URL is used. For SAML, you must set valid URI patterns if you are relying on the consumer service URL embedded with the login request.",
    nameIdFormat: "The name ID format to use for the subject.",
    forceNameIdFormat: "Ignore requested NameID subject format and use admin console configured one.",
    forcePostBinding: "Always use POST binding for responses.",
    forceArtifactBinding: "Should response messages be returned to the client through the SAML ARTIFACT binding system?",
    includeAuthnStatement: "Should a statement specifying the method and timestamp be included in login responses?",
    includeOneTimeUseCondition: "Should a OneTimeUse Condition be included in login responses?",
    optimizeLookup: "When signing SAML documents in REDIRECT binding for SP that is secured by Keycloak adapter, should the ID of the signing key be included in SAML protocol message in <Extensions> element? This optimizes validation of the signature as the validating party uses a single key instead of trying every known key for validation.",
    signDocuments: "Should SAML documents be signed by the realm?",
    signAssertions: "Should assertions inside SAML documents be signed? This setting is not needed if document is already being signed.",
    signatureAlgorithm: "The signature algorithm to use to sign documents.",
    signatureKeyName: "Signed SAML documents contain identification of signing key in KeyName element. For Keycloak / RH-SSO counterparty, use KEY_ID, for MS AD FS use CERT_SUBJECT, for others check and use NONE if no other option works.",
    canonicalization: "Canonicalization Method for XML signatures.",
    webOrigins: "Allowed CORS origins. To permit all origins of Valid Redirect URIs, add '+'. This does not include the '*' wildcard though. To permit all origins, explicitly add '*'.",
    homeURL: "Default URL to use when the auth server needs to redirect or link back to the client.",
    adminURL: "URL to the admin interface of the client. Set this if the client supports the adapter REST API. This REST API allows the auth server to push revocation policies and other administrative tasks. Usually this is set to the base URL of the client.",
    clientId: "Specifies ID referenced in URI and tokens. For example 'my-client'. For SAML this is also the expected issuer value from authn requests",
    clientName: "Specifies display name of the client. For example 'My Client'. Supports keys for localized values as well. For example: ${my_client}",
    description: "Specifies description of the client. For example 'My Client for TimeSheets'. Supports keys for localized values as well. For example: ${my_client_description}",
    loginTheme: "Select theme for login, OTP, grant, registration, and forgot password pages.",
    encryptAssertions: "Should SAML assertions be encrypted with client's public key using AES?",
    clientSignature: "Will the client sign their saml requests and responses? And should they be validated?",
    downloadType: "this is information about the download type",
    details: "this is information about the details",
    createToken: "An initial access token can only be used to create clients",
    expiration: "Specifies how long the token should be valid",
    count: "Specifies how many clients can be created using the token",
    "client-authenticator-type": "Client Authenticator used for authentication of this client against Keycloak server",
    "registration-access-token": "The registration access token provides access for clients to the client registration service.",
    "signature-algorithm": "JWA algorithm, which the client needs to use when signing a JWT for authentication. If left blank, the client is allowed to use any algorithm.",
    subject: 'A regular expression for validating Subject DN in the Client Certificate. Use "(.*?)(?:$)" to match all kind of expressions.',
    evaluateExplain: "This page allows you to see all protocol mappers and role scope mappings",
    effectiveProtocolMappers: "Contains all default client scopes and selected optional scopes. All protocol mappers and role scope mappings of all those client scopes will be used when generating access token issued for your client",
    effectiveRoleScopeMappings: "Selected Optional Client Scopes, which will be used when issuing access token for this client. You can see above what value of OAuth Scope Parameter needs to be used when you want to have these optional client scopes applied when the initial OpenID Connect Authentication request will be sent from your client adapter",
    generatedAccessToken: "Example access token",
    scopeParameter: "You can copy/paste this value of scope parameter and use it in initial OpenID Connect Authentication Request sent from this client adapter. Default client scopes and selected optional client scopes will be used when generating token issued for this client",
    user: "Optionally select user, for whom the example access token will be generated. If you do not select a user, example access token will not be generated during evaluation",
    notBefore: "Revoke any tokens issued before this time for this client. To push the policy, you should set an effective admin URL in the Settings tab first.",
    notBeforeIntro: "In order to successfully push a revocation policy to the client, you need to set an Admin URL under the <1>Settings</1> tab for this client first",
    notBeforeTooltip: "The admin URL should be set in the Settings tab first.",
    nodeReRegistrationTimeout: "Interval to specify max time for registered clients cluster nodes to re-register. If cluster node will not send re-registration request to Keycloak within this time, it will be unregistered from Keycloak",
    fineGrainOpenIdConnectConfiguration: "This section is used to configure advanced settings of this client related to OpenID Connect protocol.",
    fineGrainSamlEndpointConfig: "This section to configure exact URLs for Assertion Consumer and Single Logout Service.",
    accessTokenSignatureAlgorithm: "JWA algorithm used for signing access tokens.",
    idTokenSignatureAlgorithm: "JWA algorithm used for signing ID tokens.",
    idTokenEncryptionKeyManagementAlgorithm: "JWA Algorithm used for key management in encrypting ID tokens. This option is needed if you want encrypted ID tokens. If left empty, ID Tokens are just signed, but not encrypted.",
    idTokenEncryptionContentEncryptionAlgorithm: "JWA Algorithm used for content encryption in encrypting ID tokens. This option is needed just if you want encrypted ID tokens. If left empty, ID Tokens are just signed, but not encrypted.",
    userInfoSignedResponseAlgorithm: "JWA algorithm used for signed User Info Endpoint response. If set to 'unsigned', User Info Response won't be signed and will be returned in application/json format.",
    requestObjectSignatureAlgorithm: "JWA algorithm, which client needs to use when sending OIDC request object specified by 'request' or 'request_uri' parameters. If set to 'any', Request object can be signed by any algorithm (including 'none' ).",
    requestObjectRequired: 'Specifies if the client needs to provide a request object with their authorization requests, and what method they can use for this. If set to "not required", providing a request object is optional. In all other cases, providing a request object is mandatory. If set to "request", the request object must be provided by value. If set to "request_uri", the request object must be provided by reference. If set to "request or request_uri", either method can be used.',
    openIdConnectCompatibilityModes: "This section is used to configure settings for backward compatibility with older OpenID Connect / OAuth 2 adaptors. It's useful especially if your client uses older version of Keycloak / RH-SSO adapter.",
    excludeSessionStateFromAuthenticationResponse: "If this is on, the parameter 'session_state' will not be included in OpenID Connect Authentication Response. It is useful if your client uses older OIDC / OAuth2 adapter, which does not support 'session_state' parameter.",
    "advancedSettingsOpenid-connect": "This section is used to configure advanced settings of this client related to OpenID Connect protocol",
    advancedSettingsSaml: "This section is used to configure advanced settings of this client",
    assertionLifespan: 'Lifespan set in the SAML assertion conditions. After that time the assertion will be invalid. The "SessionNotOnOrAfter" attribute is not modified and continue using the "SSO Session Max" time defined at realm level.',
    accessTokenLifespan: "Max time before an access token is expired. This value is recommended to be short relative to the SSO timeout.",
    oAuthMutual: "This enables support for OAuth 2.0 Mutual TLS Certificate Bound Access Tokens, which means that keycloak bind an access token and a refresh token with a X.509 certificate of a token requesting client exchanged in mutual TLS between keycloak's Token Endpoint and this client. These tokens can be treated as Holder-of-Key tokens instead of bearer tokens.",
    keyForCodeExchange: "Choose which code challenge method for PKCE is used. If not specified, keycloak does not applies PKCE to a client unless the client sends an authorization request with appropriate code challenge and code exchange method.",
    assertionConsumerServicePostBindingURL: "SAML POST Binding URL for the client's assertion consumer service (login responses). You can leave this blank if you do not have a URL for this binding.",
    assertionConsumerServiceRedirectBindingURL: "SAML Redirect Binding URL for the client's assertion consumer service (login responses). You can leave this blank if you do not have a URL for this binding.",
    logoutServicePostBindingURL: "SAML POST Binding URL for the client's single logout service. You can leave this blank if you are using a different binding",
    logoutServiceRedirectBindingURL: "SAML Redirect Binding URL for the client's single logout service. You can leave this blank if you are using a different binding.",
    logoutServiceArtifactBindingUrl: "SAML ARTIFACT Binding URL for the client's single logout service. You can leave this blank if you are using a different binding.",
    artifactBindingUrl: "URL to send the HTTP ARTIFACT messages to. You can leave this blank if you are using a different binding. This value should be set when forcing ARTIFACT binding together with IdP initiated login.",
    artifactResolutionService: "SAML Artifact resolution service for the client. This is the endpoint to which Keycloak will send a SOAP ArtifactResolve message. You can leave this blank if you do not have a URL for this binding.",
    authenticationOverrides: "Override realm authentication flow bindings.",
    browserFlow: "Select the flow you want to use for browser authentication.",
    directGrant: "Select the flow you want to use for direct grant authentication.",
    useJwksUrl: "If the switch is on, client public keys will be downloaded from given JWKS URL. This allows great flexibility because new keys will be always re-downloaded again when client generates new keypair. If the switch is off, public key (or certificate) from the Keycloak DB is used, so when client keypair changes, you always need to import new key (or certificate) to the Keycloak DB as well.",
    certificate: "Client Certificate for validate JWT issued by client and signed by Client private key from your keystore.",
    jwksUrl: `URL where client keys in JWK format are stored. See JWK specification for more details. If you use Keycloak client adapter with "jwt" credential, you can use URL of your app with '/k_jwks' suffix. For example 'http://www.myhost.com/myapp/k_jwks' .`,
    generateKeysDescription: "If you generate new keys, you can download the keystore with the private key automatically and save it on your client's side. Keycloak server will save just the certificate and public key, but not the private key.",
    archiveFormat: "Java keystore or PKCS12 archive format.",
    keyAlias: "Archive alias for your private key and certificate.",
    keyPassword: "Password to access the private key in the archive",
    storePassword: "Password to access the archive itself",
    consentRequired: "If enabled, users have to consent to client access.",
    displayOnClient: "Applicable only if 'Consent Required' is on for this client. If this switch is off, the consent screen will contain just the consents corresponding to configured client scopes. If on, there will be also one item on the consent screen about this client itself.",
    consentScreenText: "Applicable only if 'Display Client On Consent Screen' is on for this client. Contains the text which will be on the consent screen about permissions specific just for this client.",
    import: "Import a JSON file containing authorization settings for this resource server.",
    policyEnforcementMode: "The policy enforcement mode dictates how policies are enforced when evaluating authorization requests. 'Enforcing' means requests are denied by default even when there is no policy associated with a given resource. 'Permissive' means requests are allowed even when there is no policy associated with a given resource. 'Disabled' completely disables the evaluation of policies and allows access to any resource.",
    decisionStrategy: "The decision strategy dictates how permissions are evaluated and how a final decision is obtained. 'Affirmative' means that at least one permission must evaluate to a positive decision in order to grant access to a resource and its scopes. 'Unanimous' means that all permissions must evaluate to a positive decision in order for the final decision to be also positive.",
    allowRemoteResourceManagement: "Should resources be managed remotely by the resource server? If false, resources can be managed only from this admin console.",
    resourceName: "A unique name for this resource. The name can be used to uniquely identify a resource, useful when querying for a specific resource.",
    displayName: "A unique name for this resource. The name can be used to uniquely identify a resource, useful when querying for a specific resource.",
    type: "The type of this resource. It can be used to group different resource instances with the same type.",
    uris: "Set of URIs which are protected by resource.",
    scopes: "The scopes associated with this resource.",
    iconUri: "A URI pointing to an icon.",
    ownerManagedAccess: "If enabled, the access to this resource can be managed by the resource owner.",
    resourceAttribute: "The attributes associated wth the resource."
  }
};

// build/client-scopes/messages.js
var messages_default3 = {
  "client-scopes": {
    createClientScope: "Create client scope",
    clientScopeList: "Client scopes",
    grantedClientScopes: "Granted client scopes",
    clientScopeDetails: "Client scope details",
    clientScopeExplain: "Client scopes allow you to define a common set of protocol mappers and roles, which are shared between multiple clients",
    searchFor: "Search for client scope",
    protocol: "Protocol",
    assignedType: "Assigned type",
    displayOrder: "Display order",
    type: "Type",
    deleteClientScope_one: "Delete client scope {{name}}",
    deleteClientScope_other: "Delete {{count}} client scopes",
    deleteConfirm: "Are you sure you want to delete this client scope",
    changeTypeTo: "Change type to",
    changeTypeIntro: "{{count}} selected client scopes will be changed to",
    clientScopeSuccess: "Scope mapping updated",
    clientScopeError: "Could not update scope mapping {{error}}",
    deletedSuccess: "The client scope has been deleted",
    deleteError: "Could not delete client scope: {{error}}",
    includeInTokenScope: "Include in token scope",
    realmRolePrefix: "Realm role prefix",
    userInfo: "User info",
    createSuccess: "Client scope created",
    createError: "Could not create client scope: '{{error}}'",
    updateSuccess: "Client scope updated",
    updateError: "Could not update client scope: '{{error}}'",
    addMapperExplain: "If you want more fine-grain control, you can create protocol mapper on this client",
    realmRoles: "Realm roles",
    newRoleName: "New role name",
    searchClientByName: "Search client by name",
    clients: "Clients",
    mapperCreateSuccess: "New mapping has been added",
    mapperCreateError: "Could not create mapping: {{error}}",
    fromPredefinedMapper: "From predefined mappers",
    byConfiguration: "By configuration",
    emptyBuiltInMappersInstructions: "All built in mappers were added to this client",
    emptySecondaryAction: "Configure a new mapper",
    displayOnConsentScreen: "Display on consent screen",
    consentScreenText: "Consent screen text",
    guiOrder: "Display Order",
    shouldBeANumber: "Should be a number",
    chooseAMapperType: "Choose a mapper type",
    addPredefinedMappers: "Add predefined mappers",
    predefinedMappingDescription: "Choose any of the predefined mappings from this table",
    mappingTable: "Table with predefined mapping",
    scope: "Scope",
    roleMappingUpdatedSuccess: "Role mapping updated",
    roleMappingUpdatedError: "Could not update role mapping {{error}}",
    protocolTypes: {
      all: "All",
      saml: "SAML",
      "openid-connect": "openid-connect"
    }
  }
};

// build/client-scopes/help.js
var help_default2 = {
  "client-scopes-help": {
    name: "Name of the client scope. Must be unique in the realm. Name should not contain space characters as it is used as value of scope parameter",
    description: "Description of the client scope",
    protocol: "Which SSO protocol configuration is being supplied by this client scope",
    type: "Client scopes, which will be added as default scopes to each created client",
    displayOnConsentScreen: "If on, and this client scope is added to some client with consent required, the text specified by 'Consent Screen Text' will be displayed on consent screen. If off, this client scope will not be displayed on the consent screen",
    consentScreenText: "Text that will be shown on the consent screen when this client scope is added to some client with consent required. Defaults to name of client scope if it is not filled",
    includeInTokenScope: "If on, the name of this client scope will be added to the access token property 'scope' as well as to the Token Introspection Endpoint response. If off, this client scope will be omitted from the token and from the Token Introspection Endpoint response.",
    guiOrder: "Specify order of the provider in GUI (such as in Consent page) as integer",
    prefix: "A prefix for each Realm Role (optional).",
    multiValued: "Indicates if attribute supports multiple values. If true, the list of all values of this attribute will be set as claim. If false, just first value will be set as claim",
    tokenClaimName: "Name of the claim to insert into the token. This can be a fully qualified name like 'address.street'. In this case, a nested json object will be created. To prevent nesting and use dot literally, escape the dot with backslash (\\.).",
    claimJsonType: "JSON type that should be used to populate the json claim in the token. long, int, boolean, String and JSON are valid values.",
    protocolMapper: "Protocol...",
    mapperName: "Name of the mapper",
    role: "Role name you want changed. Click 'Select Role' button to browse roles, or just type it in the textbox. To reference an application role the syntax is appname.approle, i.e. myapp.myrole",
    newRoleName: "The new role name.  The new name format corresponds to where in the access token the role will be mapped to.  So, a new name of 'myapp.newname' will map the role to that position in the access token.  A new name of 'newname' will map the role to the realm roles in the token."
  }
};

// build/groups/messages.js
var messages_default4 = {
  groups: {
    groupDetails: "Group details",
    childGroups: "Child groups",
    createGroup: "Create group",
    groupName: "Group name",
    searchForGroups: "Search for groups",
    searchGroups: "Search groups",
    searchGroup: "Search group",
    renameGroup: "Rename group",
    deleteGroup: "Delete group",
    leave: "Leave group",
    usersLeft_one: "{{count}} user left the group",
    usersLeft_other: "{{count}} users left the group",
    usersLeftError: "Could not remove users from the group: {{error}}",
    usersAdded_one: "{{count}} user added to the group",
    usersAdded_other: "{{count}} users added to the group",
    usersAddedError: "Could not add users to the group: {{error}}",
    search: "Search",
    members: "Members",
    searchMembers: "Search members",
    addMember: "Add member",
    includeSubGroups: "Include sub-group users",
    path: "Path",
    moveTo: "Move to",
    moveToGroup: "Move {{group1}} to {{group2}}",
    root: "Root",
    moveHere: "Move here",
    moveGroupEmpty: "No sub groups",
    moveGroupEmptyInstructions: "There are no sub groups, select 'Move here' to move the selected group as a subgroup of this group",
    moveGroupSuccess: "Group moved",
    moveGroupError: "Could not move group {{error}}",
    tableOfGroups: "Table of groups",
    groupsDescription: "Description goes here",
    groupCreated: "Group created",
    couldNotCreateGroup: "Could not create group {{error}}",
    createAGroup: "Create a group",
    renameAGroup: "Rename group",
    create: "Create",
    rename: "Rename",
    email: "Email",
    lastName: "Last name",
    firstName: "First name",
    membership: "Membership",
    noSearchResults: "No search results",
    noSearchResultsInstructions: "Click on the search bar above to search for groups",
    noGroupsInThisRealm: "No groups in this realm",
    noGroupsInThisRealmInstructions: "You haven't created any groups in this realm. Create a group to get started.",
    noGroupsInThisSubGroup: "No groups in this sub group",
    noGroupsInThisSubGroupInstructions: "You haven't created any groups in this sub group.",
    deleteConfirmTitle_one: "Delete group?",
    deleteConfirmTitle_other: "Delete groups?",
    deleteConfirm_one: "Are you sure you want to delete this group",
    deleteConfirm_other: "Are you sure you want to delete this groups.",
    groupDeleted_one: "Group deleted",
    groupDeleted_other: "Groups deleted",
    groupDeleteError: "Error deleting group {error}",
    attributes: "Attributes",
    groupUpdated: "Group updated",
    groupUpdateError: "Error updating group {error}",
    roleMapping: "Role mapping"
  }
};

// build/realm/messages.js
var messages_default5 = {
  realm: {
    uploadFile: "Upload JSON file",
    realmName: "Realm name",
    enabled: "Enabled",
    createRealm: "Create realm",
    realmExplain: "A realm manages a set of users, credentials, roles, and groups. A user belongs to and logs into a realm. Realms are isolated from one another and can only manage and authenticate the users that they control.",
    noRealmRoles: "No realm roles",
    emptyStateText: "There aren't any realm roles in this realm. Create a realm role to get started.",
    saveRealmSuccess: "Realm created successfully",
    saveRealmError: "Could not create realm {{error}}"
  }
};

// build/realm-roles/messages.js
var messages_default6 = {
  roles: {
    addAttributeText: "Add an attribute",
    deleteAttributeText: "Delete an attribute",
    associatedRolesText: "Associated roles",
    addAssociatedRolesText: "Add associated roles",
    addAssociatedRolesSuccess: "Associated roles have been added",
    addAssociatedRolesError: "Could not associate roles {{error}}",
    associatedRolesModalTitle: "Add roles to {{name}}",
    title: "Realm roles",
    addRole: "Add role",
    createRole: "Create role",
    importRole: "Import role",
    roleID: "Role ID",
    homeURL: "Home URL",
    filterByClients: "Filter by clients",
    filterByRoles: "Filter by roles",
    roleExplain: "Realm-level roles are a global namespace to define your roles.",
    roleCreateExplain: "This is some description",
    roleName: "Role name",
    roleDetails: "Role details",
    composite: "Composite",
    deleteRole: "Delete this role",
    inheritedFrom: "Inherited from",
    roleList: "Role list",
    searchFor: "Search role by name",
    generalSettings: "General Settings",
    capabilityConfig: "Capability config",
    roleImportError: "Could not import role",
    roleCreated: "Role created",
    roleCreateError: "Could not create role: {{error}}",
    roleImportSuccess: "Role import successful",
    roleDeleteConfirm: "Delete role?",
    roleDeleteConfirmDialog: "This action will permanently delete the role {{selectedRoleName}} and cannot be undone.",
    roleDeletedSuccess: "The role has been deleted",
    roleDeleteError: "Could not delete role: {{error}}",
    defaultRole: "This role serves as a container for both realm and client default roles. It cannot be removed.",
    defaultRoleDeleteError: "You cannot delete a default role.",
    roleSaveSuccess: "The role has been saved",
    roleSaveError: "Could not save role: {{error}}",
    noRoles: "No roles in this realm",
    noRolesInstructions: "You haven't created any roles in this realm. Create a role to get started.",
    roleAuthentication: "Role authentication",
    removeAllAssociatedRoles: "Remove all associated roles",
    removeAssociatedRoles: "Remove associated roles",
    removeRoles: "Remove roles",
    removeAllAssociatedRolesConfirmDialog: "This action will remove the associated roles of {{name}}. Users who have permission to {{name}} will no longer have access to these roles.",
    roleRemoveAssociatedRoleConfirm: "Remove associated role?",
    roleRemoveAssociatedText: "This action will remove {{role}} from {{roleName}}. All the associated roles of {{role}} will also be removed.",
    compositeRoleOff: "Composite role turned off",
    associatedRolesRemoved: "Associated roles have been removed",
    compositesRemovedAlertDescription: "All the associated roles have been removed",
    whoWillAppearLinkText: "Who will appear in this user list?",
    whoWillAppearPopoverText: "This tab shows only the users who are assigned directly to this role. To see users who are assigned this role as an associated role or through a group, go to",
    whoWillAppearPopoverFooterText: "Users who have this role as an effective role cannot be added on this tab.",
    usersInRole: "Users in role",
    addUser: "Add user",
    removeUser: "Remove users",
    removeUserText: "Do you want to remove {{numSelected}} users?. These users will no longer have permissions of the role {{role}} and the associated roles of it.",
    noDirectUsers: "No direct users",
    noUsersEmptyStateDescription: "Only the users with this role directly assigned will appear under this tab. If you need to find users assigned to this role, go to",
    noUsersEmptyStateDescriptionContinued: "to find them. Users that already have this role as an effective role cannot be added here.",
    or: "or",
    users: "Users",
    userName: "Username",
    email: "Email",
    lastName: "Last name",
    firstName: "First name",
    clearAllFilters: "Clear all filters",
    noRolesAssociated: "No roles where associated",
    noRolesAssociatedInstructions: "To add roles to the this role press that 'Add role' button"
  }
};

// build/user/messages.js
var messages_default7 = {
  users: {
    title: "Users",
    searchForUser: "Search user",
    startBySearchingAUser: "Start by searching for users",
    searchForUserDescription: "This realm has a federated provider. Viewing all users may cause the system to slow down. Please search for a user above.",
    createUser: "Create user",
    createNewUser: "Create new user",
    noUsersFound: "No users found",
    noUsersFoundError: "No users found due to {{error}}",
    noGroups: "No groups",
    noGroupsText: "You haven't added this user to any groups. Join a group to get started.",
    joinGroup: "Join Group",
    joinGroups: "Join Groups",
    join: "Join",
    joinGroupsFor: "Join groups for user {{username}}",
    selectGroups: "Select groups to join",
    searchForGroups: "Search for groups",
    leave: "Leave",
    leaveGroup_one: "Leave group {{name}}?",
    leaveGroup_other: "Leave groups?",
    leaveGroupConfirmDialog_one: "Are you sure you want to remove {{username}} from the group {{groupname}}?",
    leaveGroupConfirmDialog_other: "Are you sure you want to remove {{username}} from the {{count}} selected groups?",
    directMembership: "Direct membership",
    groupMembership: "Group membership",
    addedGroupMembership: "Added group membership",
    addedGroupMembershipError: "Error adding group membership",
    removedGroupMembership: "Removed group membership",
    removedGroupMembershipError: "Error removing group membership",
    path: "Path",
    emptyInstructions: "Change your search criteria or add a user",
    createdAt: "Created at",
    username: "Username",
    email: "Email",
    emailVerified: "Email verified",
    lastName: "Last name",
    firstName: "First name",
    status: "Status",
    disabled: "Disabled",
    temporaryLocked: "Temporarily locked",
    unlockSuccess: "User successfully unlocked",
    unlockError: "Could not unlock user due to {{error}}",
    emailInvalid: "You must enter a valid email.",
    temporaryDisabled: "Temporarily disabled",
    notVerified: "Not verified",
    requiredUserActions: "Required user actions",
    addUser: "Add user",
    impersonate: "Impersonate",
    impersonateConfirm: "Impersonate user?",
    impersonateConfirmDialog: "Are you sure you want to log in as this user? If this user is in the same realm with you, your current login session will be logged out before you log in as this user.",
    impersonateError: "Could not impersonate the user: {{error}}",
    deleteUser: "Delete user",
    deleteConfirm: "Delete user?",
    deleteConfirmCurrentUser: "Are you sure you want to permanently delete this user",
    deleteConfirmDialog_one: "Are you sure you want to permanently delete {{count}} selected user",
    deleteConfirmDialog_other: "Are you sure you want to permanently delete {{count}} selected users",
    userID: "User ID",
    userCreated: "The user has been created",
    userSaved: "The user has been saved",
    userDetails: "User details",
    userCreateError: "Could not create user: {{error}}",
    userDeletedSuccess: "The user has been deleted",
    userDeletedError: "The user could not be deleted {{error}}",
    linkAccount: "Link account",
    unlink: "Unlink",
    unlinkAccount: "Unlink account",
    unlinkAccountTitle: "Unlink account from {{provider}}?",
    unlinkAccountConfirm: "Are you sure you want to permanently unlink this account from {{provider}}?",
    link: "Link",
    linkAccountTitle: "Link account to {{provider}}?",
    idpLinkSuccess: "Identity provider has been linked",
    couldNotLinkIdP: "Could not link identity provider {{error}}",
    configureOTP: "Configure OTP",
    updatePassword: "Update Password",
    updateProfile: "Update Profile",
    verifyEmail: "Verify Email",
    updateUserLocale: "Update User Locale",
    consents: "Consents",
    noConsents: "No consents",
    noConsentsText: "The consents will only be recorded when users try to access a client that is configured to require consent. In that case, users will get a consent page which asks them to grant access to the client.",
    identityProvider: "Identity provider",
    identityProviderLinks: "Identity provider links",
    noProvidersLinked: "No identity providers linked. Choose one from the list below.",
    noAvailableIdentityProviders: "No available identity providers.",
    linkedIdPs: "Linked identity providers",
    linkedIdPsText: "The identity providers which are already linked to this user account",
    availableIdPs: "Available identity providers",
    availableIdPsText: "All the configured identity providers in this realm are listed here. You can link the user account to any of the IdP accounts.",
    whoWillAppearLinkText: "Who will appear in this group list?",
    whoWillAppearPopoverText: "Groups are hierarchical. When you select Direct Membership, you see only the child group that the user joined. Ancestor groups are not included.",
    revoke: "Revoke",
    revokeClientScopesTitle: "Revoke all granted client scopes?",
    revokeClientScopes: "Are you sure you want to revoke all granted client scopes for {{clientId}}?",
    deleteGrantsSuccess: "Grants successfully revoked.",
    deleteGrantsError: "Error deleting grants.",
    roleMapping: "Role mapping",
    unlockAllUsers: "Unlock all users",
    unlockUsersConfirm: "All the users that are temporarily locked will be unlocked.",
    unlock: "Unlock",
    unlockUsersSuccess: "Any temporarily locked users are now unlocked",
    unlockUsersError: "Could not unlock all users {{error}}",
    noCredentials: "No credentials",
    noCredentialsText: "This user does not have any credentials. You can set password for this user.",
    setPassword: "Set password",
    setPasswordFor: "Set password for ",
    save: "Save",
    cancel: "Cancel",
    savePasswordSuccess: "The password has been set successfully.",
    savePasswordError: "Error saving password: {{error}}",
    savePasswordNotMatchError: "Error saving password: Password and confirmation does not match.",
    credentialType: "Type",
    credentialUserLabel: "User Label",
    credentialData: "Data",
    credentialsList: "Credentials List",
    setPasswordConfirm: "Set password?",
    setPasswordConfirmText: "Are you sure you want to set the password for the user",
    password: "Password",
    passwordConfirmation: "Password confirmation",
    resetPasswordConfirmation: "New password confirmation",
    questionMark: "?",
    savePassword: "Save password",
    deleteCredentialsConfirmTitle: "Delete credentials?",
    deleteCredentialsConfirm: "Are you sure you want to delete these users credentials?",
    deleteCredentialsSuccess: "The credentials has been deleted successfully.",
    deleteCredentialsError: "Error deleting users credentials: {{error}}",
    deleteBtn: "Delete",
    resetPasswordFor: "Reset password for ",
    resetPasswordConfirm: "Reset password?",
    resetPasswordConfirmText: "Are you sure you want to reset the password for the user",
    resetPassword: "Reset password",
    resetCredentialsSuccess: "The password has been reset successfully.",
    resetCredentialsError: "Error resetting users credentials: {{error}}",
    resetPasswordNotMatchError: "Error resetting password: Password and confirmation does not match.",
    resetPasswordError: "Error resetting password: {{error}}",
    resetPasswordBtn: "Reset password",
    showPasswordDataName: "Name",
    showPasswordDataValue: "Value",
    showDataBtn: "Show data",
    userCredentialsHelpText: "The top level handlers allow you to shift the priority of the credential for the user, the topmost credential having the highest priority. The handlers within one expandable panel allow you to change the visual order of the credentials, the topmost credential will show at the most left.",
    userCredentialsHelpTextLabel: "User Credentials Help Text",
    type: "Type",
    userLabel: "User label",
    data: "Data",
    passwordDataTitle: "Password data",
    updateCredentialUserLabelSuccess: "The user label has been changed successfully.",
    updateCredentialUserLabelError: "Error changing user label: {{error}}"
  }
};

// build/user/help.js
var help_default3 = {
  "users-help": {
    temporaryLocked: "The user may be locked due to multiple failed attempts to log in.",
    disabled: "A disabled user cannot log in.",
    emailVerified: "Has the user's email been verified?",
    requiredUserActions: "Require an action when the user logs in. 'Verify email' sends an email to the user to verify their email address. 'Update profile' requires user to enter in new personal information. 'Update password' requires user to enter in a new password. 'Configure OTP' requires setup of a mobile password generator.",
    groups: "Groups where the user has membership. To leave a group, select it and click Leave.",
    userIdHelperText: "Enter the unique ID of the user for this identity provider.",
    usernameHelperText: "Enter the username of the user for this identity provider."
  }
};

// build/sessions/messages.js
var messages_default8 = {
  sessions: {
    title: "Sessions",
    sessionExplain: "Some description about sessions",
    searchForSession: "Search session",
    subject: "Subject",
    lastAccess: "Last access",
    startDate: "Start date",
    accessedClients: "Accessed clients",
    sessionsType: {
      allSessions: "All session types",
      regularSSO: "Regular SSO",
      offline: "Offline",
      directGrant: "Direct grant",
      serviceAccount: "Service account"
    },
    revocation: "Revocation",
    revocationDescription: "This is a way to revoke all active sessions and access tokens. Not before means you can revoke any tokens issued before the date.",
    notBefore: "Not before",
    notBeforeSuccess: 'Success! "Not before" set for realm',
    notBeforeError: 'Error clearing "Not Before" for realm: {{error}}',
    notBeforeClearedSuccess: 'Success! "Not Before" cleared for realm.',
    signOutAllActiveSessions: "Sign out all active sessions",
    signOutAllActiveSessionsQuestion: "Sign out all active sessions?",
    setToNow: "Set to now",
    logoutAllDescription: "If you sign out all active sessions, active subjects in this realm will be signed out.",
    logoutAllSessionsError: "Error! Failed to log out of all sessions: {{error}}.",
    setToNowError: "Error! Failed to set notBefore to current date and time.",
    clear: "Clear",
    push: "Push",
    none: "None",
    noSessions: "No sessions",
    noSessionsDescription: "There are currently no active sessions in this realm."
  }
};

// build/events/messages.js
var messages_default9 = {
  events: {
    title: "Events",
    eventExplain: "If you want to configure user events, Admin events or Event listeners, please enter <1>Event configs</1> page realm settings to configure.",
    eventConfigs: "Event configs",
    userEvents: "User events",
    adminEvents: "Admin events",
    searchForUserEvent: "Search user event",
    searchForAdminEvent: "Search admin event",
    refresh: "Refresh",
    emptyEvents: "No events logged",
    emptyEventsInstructions: "Configure event logging in the realm settings",
    time: "Time",
    user: "User",
    userId: "User ID",
    username: "User name",
    email: "Email",
    eventType: "Event type",
    ipAddress: "IP address",
    client: "Client",
    dateFrom: "Date(from)",
    dateTo: "Date(to)",
    searchUserEventsBtn: "Search events",
    searchAdminEventsBtn: "Search admin events",
    realm: "Realm",
    resourcePath: "Resource path",
    resourceType: "Resource type",
    resourceTypes: "Resource types",
    operationType: "Operation type",
    operationTypes: "Operation types",
    auth: "Auth",
    attribute: "Attribute",
    value: "Value",
    representation: "Representation",
    noUserDetails: "No user details"
  }
};

// build/realm-settings/messages.js
var messages_default10 = {
  "realm-settings": {
    partialImport: "Partial import",
    partialExport: "Partial export",
    deleteRealm: "Delete realm",
    deleteConfirmTitle: "Delete realm?",
    dragInstruction: "Click and drag to change priority",
    deleteConfirm: "If you delete this realm, all associated data will be removed.",
    deleteProviderTitle: "Delete key provider?",
    deleteProviderConfirm: "Are you sure you want to permanently delete the key provider ",
    deleteProviderSuccess: "Success. The provider has been deleted.",
    deleteProviderError: "Error deleting the provider",
    deletedSuccess: "The realm has been deleted",
    deleteError: "Could not delete realm: {{error}}",
    deleteConditionSuccess: "The condition has been deleted",
    disableConfirmTitle: "Disable realm?",
    disableConfirm: "User and clients can't access the realm if it's disabled. Are you sure you want to continue?",
    disablePolicyConfirmTitle: "Disable policy?",
    disablePolicyConfirm: "Users and clients can't access the policy if it's disabled. Are you sure you want to continue?",
    editProvider: "Edit provider",
    saveSuccess: "Realm successfully updated",
    saveProviderSuccess: "The provider has been saved successfully.",
    saveProviderListSuccess: "The priority of the provider has been updated successfully.",
    saveProviderError: "Error saving provider: {{error}}",
    saveError: "Realm could not be updated: {{error}}",
    general: "General",
    login: "Login",
    themes: "Themes",
    events: "Events",
    eventListeners: "Event listeners",
    eventListenersHelpText: "Configure what listeners receive events for the realm.",
    saveEventListeners: "Save Event Listeners",
    saveEventListenersSuccess: "Event listener has been updated.",
    saveEventListenersError: "Error saving event listener: {{error}}",
    userEventsConfig: "User events configuration",
    userEventsSettings: "User events settings",
    adminEventsConfig: "Admin events configuration",
    adminEventsSettings: "Admin events settings",
    saveEvents: "Save events",
    expiration: "Expiration",
    clearUserEvents: "Clear user events",
    clearAdminEvents: "Clear admin events",
    includeRepresentation: "Include representation",
    email: "Email",
    template: "Template",
    connectionAndAuthentication: "Connection & Authentication",
    from: "From",
    fromDisplayName: "From display name",
    replyTo: "Reply to",
    replyToDisplayName: "Reply to display name",
    envelopeFrom: "Envelope from",
    host: "Host",
    port: "Port",
    encryption: "Encryption",
    authentication: "Authentication",
    enableSSL: "Enable SSL",
    enableStartTLS: "Enable StartTLS",
    username: "Username",
    password: "Password",
    keys: "Keys",
    keysList: "Keys list",
    searchKey: "Search key",
    keystore: "Keystore",
    keystorePassword: "Keystore password",
    keyAlias: "Key alias",
    keyPassword: "Key password",
    providers: "Providers",
    algorithm: "Algorithm",
    aesGenerated: "aes-generated",
    ecdsaGenerated: "ecdsca-generated",
    hmacGenerated: "hmac-generated",
    javaKeystore: "java-keystore",
    rsa: "rsa",
    rsaGenerated: "rsa-generated",
    consoleDisplayName: "Console Display Name",
    AESKeySize: "AES Key Size",
    active: "Active",
    privateRSAKey: "Private RSA Key",
    x509Certificate: "X509 Certificate",
    ellipticCurve: "Elliptic Curve",
    secretSize: "Secret size",
    type: "Type",
    name: "Name",
    providerId: "ID",
    kid: "Kid",
    provider: "Provider",
    providerDescription: "Provider description",
    addProvider: "Add provider",
    publicKeys: "Public keys",
    activeKeys: "Active keys",
    passiveKeys: "Passive keys",
    disabledKeys: "Disabled keys",
    noKeys: "No keys",
    noKeysDescription: "You haven't created any ",
    certificate: "Certificate",
    userRegistration: "User registration",
    userRegistrationHelpText: "Enable/disable the registration page. A link for registration will show on login page too.",
    forgotPassword: "Forgot password",
    forgotPasswordHelpText: "Show a link on login page for user to click when they have forgotten their credentials.",
    rememberMe: "Remember me",
    rememberMeHelpText: "Show checkbox on login page to allow user to remain logged in between browser restarts until session expires.",
    emailAsUsername: "Email as username",
    emailAsUsernameHelpText: "Allow users to set email as username.",
    loginWithEmail: "Login with email",
    loginWithEmailHelpText: "Allow users to log in with their email address.",
    duplicateEmails: "Duplicate emails",
    duplicateEmailsHelpText: "Allow multiple users to have the same email address. Changing this setting will also clear the user's cache. It is recommended to manually update email constraints of existing users in the database after switching off support for duplicate email addresses.",
    provideEmailTitle: "Provide your email address",
    provideEmail: "To test connection, you should provide your email address first.",
    verifyEmail: "Verify email",
    verifyEmailHelpText: "Require user to verify their email address after initial login or after address changes are submitted.",
    testConnection: "Test connection",
    testConnectionSuccess: "Success! SMTP connection successful. E-mail was sent!",
    testConnectionError: "Error! Failed to send email.",
    realmId: "Realm ID",
    displayName: "Display name",
    htmlDisplayName: "HTML Display name",
    frontendUrl: "Frontend URL",
    requireSsl: "Require SSL",
    sslType: {
      all: "All requests",
      external: "External requests",
      none: "None"
    },
    selectATheme: "Select a theme",
    allSupportedLocales: {
      ca: "Català",
      cs: "Čeština",
      da: "Dansk",
      de: "Deutsch",
      en: "English",
      es: "Español",
      fr: "Français",
      hu: "Magyar",
      it: "Italiano",
      ja: "日本語",
      lt: "Lietuvių kalba",
      nl: "Nederlands",
      no: "Norsk",
      pl: "Polski",
      "pt-BR": "Português (Brasil)",
      ru: "Русский",
      sk: "Slovenčina",
      sv: "Svenska",
      tr: "Türkçe",
      "zh-CN": "中文"
    },
    placeholderText: "Select one",
    userManagedAccess: "User-managed access",
    endpoints: "Endpoints",
    openIDEndpointConfiguration: "OpenID Endpoint Configuration",
    samlIdentityProviderMetadata: "SAML 2.0 Identity Provider Metadata",
    loginTheme: "Login theme",
    accountTheme: "Account theme",
    adminTheme: "Admin console theme",
    emailTheme: "Email theme",
    internationalization: "Internationalization",
    localization: "Localization",
    sessions: "Sessions",
    SSOSessionSettings: "SSO Session Settings",
    SSOSessionIdle: "SSO Session Idle",
    SSOSessionMax: "SSO Session Max",
    SSOSessionIdleRememberMe: "SSO Session Idle Remember Me",
    SSOSessionMaxRememberMe: "SSO Session Max Remember Me",
    clientSessionSettings: "Client session settings",
    clientSessionIdle: "Client Session Idle",
    clientSessionMax: "Client Session Max",
    offlineSessionSettings: "Offline session settings",
    offlineSessionIdle: "Offline Session Idle",
    offlineSessionMaxLimited: "Offline Session Max Limited",
    offlineSessionMax: "Offline Session Max",
    loginSettings: "Login settings",
    loginTimeout: "Login timeout",
    loginActionTimeout: "Login action timeout",
    refreshTokens: "Refresh tokens",
    accessTokens: "Access tokens",
    actionTokens: "Action tokens",
    overrideActionTokens: "Override Action Tokens",
    defaultSigAlg: "Default Signature Algorithm",
    revokeRefreshToken: "Revoke Refresh Token",
    refreshTokenMaxReuse: "Refresh Token Max Reuse",
    accessTokenLifespan: "Access Token Lifespan",
    accessTokenLifespanImplicitFlow: "Access Token Lifespan For Implicit Flow",
    clientLoginTimeout: "Client Login Timeout",
    userInitiatedActionLifespan: "User-Initiated Action Lifespan",
    defaultAdminInitiated: "Default Admin-Initated Action Lifespan",
    emailVerification: "Email Verification",
    idpAccountEmailVerification: "IdP account email verification",
    executeActions: "Execute actions",
    clientPolicies: "Client policies",
    noClientPolicies: "No client policies",
    noClientPoliciesInstructions: "There are no client policies. Select 'Create client policy' to create a new client policy.",
    createPolicy: "Create policy",
    createClientPolicy: "Create client policy",
    createClientPolicySuccess: "New policy created",
    updateClientPolicySuccess: "Client policy updated",
    createClientConditionSuccess: "Condition created successfully.",
    createClientConditionError: "Error creating condition: {{error}}",
    updateClientConditionSuccess: "Condition updated successfully.",
    deleteClientConditionSuccess: "Condition deleted successfully.",
    deleteClientConditionError: "Error creating condition: {{error}}",
    clientPolicySearch: "Search client policy",
    policiesConfigType: "Configure via:",
    policiesConfigTypes: {
      formView: "Form view",
      jsonEditor: "JSON editor"
    },
    deleteClientPolicy: "Delete client policy",
    deleteClientPolicyConfirmTitle: "Delete policy?",
    deleteClientPolicyConfirm: "This action will permanently delete the policy {{policyName}}. This cannot be undone.",
    deleteClientPolicySuccess: "Client policy deleted",
    deleteClientPolicyError: "Could not delete policy: {{error}}",
    profiles: "Profiles",
    policies: "Policies",
    clientPoliciesProfilesHelpText: "Client Profile allows to setup set of executors, which are enforced for various actions done with the client. Actions can be admin actions like creating or updating client, or user actions like authentication to the client.",
    clientPoliciesProfiles: "Client Policies Profiles",
    clientPoliciesPoliciesHelpText: "Client Policy allows to bind client profiles with various conditions to specify when exactly is enforced behavior specified by executors of the particular client profile.",
    clientPoliciesPolicies: "Client Policies Policies",
    clientPoliciesTab: "Client policies tab",
    clientProfilesSubTab: "Client profiles subtab",
    clientPoliciesSubTab: "Client policies subtab",
    profilesConfigType: "Configure via:",
    profilesConfigTypes: {
      formView: "Form view",
      jsonEditor: "JSON editor"
    },
    clientProfileSearch: "Search",
    searchProfile: "Search profile",
    clientProfileName: "Client profile name",
    clientProfileDescription: "Description",
    emptyClientProfiles: "No profiles",
    emptyClientProfilesInstructions: "There are no profiles, select 'Create client profile' to create a new client profile",
    deleteClientProfileConfirmTitle: "Delete profile?",
    deleteClientProfileConfirm: "This action will permanently delete the profile {{profileName}}. This cannot be undone.",
    deleteClientSuccess: "Client profile deleted",
    deleteClientError: "Could not delete profile: {{error}}",
    deleteClientPolicyProfileConfirmTitle: "Delete profile?",
    deleteClientPolicyProfileConfirm: "This action will permanently delete {{profileName}} from the policy {{policyName}}. This cannot be undone.",
    deleteClientPolicyProfileSuccess: "Profile successfully removed from the policy.",
    deleteClientPolicyProfileError: "Could not delete profile from the policy: {{error}}",
    createClientProfile: "Create client profile",
    deleteClientProfile: "Delete this client profile",
    createClientProfileSuccess: "New client profile created",
    updateClientProfileSuccess: "Client profile updated successfully",
    createClientProfileError: "Could not create client profile: '{{error}}'",
    addClientProfileSuccess: "New client profile added",
    addClientProfileError: "Could not create client profile: '{{error}}'",
    createClientProfileNameHelperText: "The name must be unique within the realm",
    allClientPolicies: "Client policies",
    newClientProfile: "Create client profile",
    newClientProfileName: "Client profile name",
    clientProfile: "Client profile details",
    executorDetails: "Executor details",
    back: "Back",
    delete: "delete",
    save: "Save",
    reload: "Reload",
    global: "Global",
    description: "description",
    executors: "Executors",
    executorsHelpText: "Executors, which will be applied for this client profile",
    executorsHelpItem: "Executors help item",
    addExecutor: "Add executor",
    executorType: "Executor type",
    executorTypeSwitchHelpText: "Executor Type Switch Help Text",
    executorTypeSelectHelpText: "Executor Type Select Help Text",
    executorTypeSelectAlgorithm: "Executor Type Select Algorithm",
    executorTypeTextHelpText: "Executor Type Text Help Text",
    executorAuthenticatorMultiSelectHelpText: "Executor Authenticator MultiSelect Help Text",
    executorClientAuthenticator: "Executor Client Authenticator",
    executorsTable: "Executors table",
    executorName: "Name",
    emptyExecutors: "No executors configured",
    addExecutorSuccess: "Success! Executor created successfully",
    addExecutorError: "Executor not created",
    updateExecutorSuccess: "Executor updated successfully",
    updateExecutorError: "Executor not updated",
    deleteExecutorProfileConfirmTitle: "Delete executor?",
    deleteExecutorProfileConfirm: "The action will permanently delete {{executorName}}. This cannot be undone.",
    deleteExecutorSuccess: "Success! The executor was deleted.",
    deleteExecutorError: "Could not delete executor: {{error}}",
    updateClientProfilesSuccess: "The client profiles configuration was updated",
    updateClientProfilesError: "Provided JSON is incorrect: Unexpected token { in JSON",
    deleteClientPolicyConditionConfirmTitle: "Delete condition?",
    deleteClientPolicyConditionConfirm: "This action will permanently delete {{condition}}. This cannot be undone.",
    selectACondition: "Select a condition",
    conditions: "Conditions",
    conditionType: "Condition type",
    policyDetails: "Policy details",
    anyClient: "The condition is satisfied by any client on any event.",
    clientAccesstype: "Client Access Type",
    clientRoles: "Client Roles",
    clientScopesCondition: "Expected Scopes",
    updateClientContext: "Update Client Context",
    clientUpdaterSourceGroups: "Groups",
    clientUpdaterTrustedHosts: "Trusted Hosts",
    clientUpdaterSourceRoles: "Updating entity role",
    conditionsHelpItem: "Conditions help item",
    addCondition: "Add condition",
    editCondition: "Edit condition",
    emptyConditions: "No conditions configured",
    updateClientPoliciesSuccess: "The client policies configuration was updated",
    updateClientPoliciesError: "Provided JSON is incorrect: Unexpected token { in JSON",
    clientProfiles: "Client profiles",
    clientProfilesHelpItem: "Client profiles help item",
    addClientProfile: "Add client profile",
    emptyProfiles: "No client profiles configured",
    tokens: "Tokens",
    userProfile: "User profile",
    jsonEditor: "JSON editor",
    attributes: "Attributes",
    attributesGroup: "Attributes group",
    invalidJsonError: "Unable to save user profile, the provided information is not valid JSON.",
    userProfileSuccess: "User profile settings successfully updated.",
    userProfileError: "Could not update user profile settings: {{error}}",
    status: "Status",
    convertedToYearsValue: "{{convertedToYears}}",
    convertedToDaysValue: "{{convertedToDays}}",
    convertedToHoursValue: "{{convertedToHours}}",
    convertedToMinutesValue: "{{convertedToMinutes}}",
    convertedToSecondsValue: "{{convertedToSeconds}}",
    pairCreatedSuccess: "Success! The localization text has been created.",
    pairCreatedError: "Error creating localization text.",
    supportedLocales: "Supported locales",
    defaultLocale: "Default locale",
    selectLocales: "Select locales",
    addMessageBundle: "Add message bundle",
    eventType: "Event saved type",
    searchEventType: "Search saved event type",
    addSavedTypes: "Add saved types",
    addTypes: "Add types",
    eventTypes: {
      SEND_RESET_PASSWORD: {
        name: "Send reset password",
        description: "Send reset password"
      },
      UPDATE_CONSENT_ERROR: {
        name: "Update consent error",
        description: "Update consent error"
      },
      GRANT_CONSENT: {
        name: "Grant consent",
        description: "Grant consent"
      },
      REMOVE_TOTP: {name: "Remove totp", description: "Remove totp"},
      REVOKE_GRANT: {name: "Revoke grant", description: "Revoke grant"},
      UPDATE_TOTP: {name: "Update totp", description: "Update totp"},
      LOGIN_ERROR: {name: "Login error", description: "Login error"},
      CLIENT_LOGIN: {name: "Client login", description: "Client login"},
      RESET_PASSWORD_ERROR: {
        name: "Reset password error",
        description: "Reset password error"
      },
      IMPERSONATE_ERROR: {
        name: "Impersonate error",
        description: "Impersonate error"
      },
      CODE_TO_TOKEN_ERROR: {
        name: "Code to token error",
        description: "Code to token error"
      },
      CUSTOM_REQUIRED_ACTION: {
        name: "Custom required action",
        description: "Custom required action"
      },
      RESTART_AUTHENTICATION: {
        name: "Restart authentication",
        description: "Restart authentication"
      },
      IMPERSONATE: {name: "Impersonate", description: "Impersonate"},
      UPDATE_PROFILE_ERROR: {
        name: "Update profile error",
        description: "Update profile error"
      },
      LOGIN: {name: "Login", description: "Login"},
      UPDATE_PASSWORD_ERROR: {
        name: "Update password error",
        description: "Update password error"
      },
      CLIENT_INITIATED_ACCOUNT_LINKING: {
        name: "Client initiated account linking",
        description: "Client initiated account linking"
      },
      TOKEN_EXCHANGE: {
        name: "Token exchange",
        description: "Token exchange"
      },
      LOGOUT: {name: "Logout", description: "Logout"},
      REGISTER: {name: "Register", description: "Register"},
      DELETE_ACCOUNT_ERROR: {
        name: "Delete account error",
        description: "Delete account error"
      },
      CLIENT_REGISTER: {
        name: "Client register",
        description: "Client register"
      },
      IDENTITY_PROVIDER_LINK_ACCOUNT: {
        name: "Identity provider link account",
        description: "Identity provider link account"
      },
      DELETE_ACCOUNT: {
        name: "Delete account",
        description: "Delete account"
      },
      UPDATE_PASSWORD: {
        name: "Update password",
        description: "Update password"
      },
      CLIENT_DELETE: {
        name: "Client delete",
        description: "Client delete"
      },
      FEDERATED_IDENTITY_LINK_ERROR: {
        name: "Federated identity link error",
        description: "Federated identity link error"
      },
      IDENTITY_PROVIDER_FIRST_LOGIN: {
        name: "Identity provider first login",
        description: "Identity provider first login"
      },
      CLIENT_DELETE_ERROR: {
        name: "Client delete error",
        description: "Client delete error"
      },
      VERIFY_EMAIL: {name: "Verify email", description: "Verify email"},
      CLIENT_LOGIN_ERROR: {
        name: "Client login error",
        description: "Client login error"
      },
      RESTART_AUTHENTICATION_ERROR: {
        name: "Restart authentication error",
        description: "Restart authentication error"
      },
      EXECUTE_ACTIONS: {
        name: "Execute actions",
        description: "Execute actions"
      },
      REMOVE_FEDERATED_IDENTITY_ERROR: {
        name: "Remove federated identity error",
        description: "Remove federated identity error"
      },
      TOKEN_EXCHANGE_ERROR: {
        name: "Token exchange error",
        description: "Token exchange error"
      },
      PERMISSION_TOKEN: {
        name: "Permission token",
        description: "Permission token"
      },
      SEND_IDENTITY_PROVIDER_LINK_ERROR: {
        name: "Send identity provider link error",
        description: "Send identity provider link error"
      },
      EXECUTE_ACTION_TOKEN_ERROR: {
        name: "Execute action token error",
        description: "Execute action token error"
      },
      SEND_VERIFY_EMAIL: {
        name: "Send verify email",
        description: "Send verify email"
      },
      EXECUTE_ACTIONS_ERROR: {
        name: "Execute actions error",
        description: "Execute actions error"
      },
      REMOVE_FEDERATED_IDENTITY: {
        name: "Remove federated identity",
        description: "Remove federated identity"
      },
      IDENTITY_PROVIDER_POST_LOGIN: {
        name: "Identity provider post login",
        description: "Identity provider post login"
      },
      IDENTITY_PROVIDER_LINK_ACCOUNT_ERROR: {
        name: "Identity provider link account error",
        description: "Identity provider link account error"
      },
      UPDATE_EMAIL: {name: "Update email", description: "Update email"},
      REGISTER_ERROR: {
        name: "Register error",
        description: "Register error"
      },
      REVOKE_GRANT_ERROR: {
        name: "Revoke grant error",
        description: "Revoke grant error"
      },
      EXECUTE_ACTION_TOKEN: {
        name: "Execute action token",
        description: "Execute action token"
      },
      LOGOUT_ERROR: {name: "Logout error", description: "Logout error"},
      UPDATE_EMAIL_ERROR: {
        name: "Update email error",
        description: "Update email error"
      },
      CLIENT_UPDATE_ERROR: {
        name: "Client update error",
        description: "Client update error"
      },
      UPDATE_PROFILE: {
        name: "Update profile",
        description: "Update profile"
      },
      CLIENT_REGISTER_ERROR: {
        name: "Client register error",
        description: "Client register error"
      },
      FEDERATED_IDENTITY_LINK: {
        name: "Federated identity link",
        description: "Federated identity link"
      },
      SEND_IDENTITY_PROVIDER_LINK: {
        name: "Send identity provider link",
        description: "Send identity provider link"
      },
      SEND_VERIFY_EMAIL_ERROR: {
        name: "Send verify email error",
        description: "Send verify email error"
      },
      RESET_PASSWORD: {
        name: "Reset password",
        description: "Reset password"
      },
      CLIENT_INITIATED_ACCOUNT_LINKING_ERROR: {
        name: "Client initiated account linking error",
        description: "Client initiated account linking error"
      },
      UPDATE_CONSENT: {
        name: "Update consent",
        description: "Update consent"
      },
      REMOVE_TOTP_ERROR: {
        name: "Remove totp error",
        description: "Remove totp error"
      },
      VERIFY_EMAIL_ERROR: {
        name: "Verify email error",
        description: "Verify email error"
      },
      SEND_RESET_PASSWORD_ERROR: {
        name: "Send reset password error",
        description: "Send reset password error"
      },
      CLIENT_UPDATE: {
        name: "Client update",
        description: "Client update"
      },
      CUSTOM_REQUIRED_ACTION_ERROR: {
        name: "Custom required action error",
        description: "Custom required action error"
      },
      IDENTITY_PROVIDER_POST_LOGIN_ERROR: {
        name: "Identity provider post login error",
        description: "Identity provider post login error"
      },
      UPDATE_TOTP_ERROR: {
        name: "Update totp error",
        description: "Update totp error"
      },
      CODE_TO_TOKEN: {
        name: "Code to token",
        description: "Code to token"
      },
      GRANT_CONSENT_ERROR: {
        name: "Grant consent error",
        description: "Grant consent error"
      },
      IDENTITY_PROVIDER_FIRST_LOGIN_ERROR: {
        name: "Identity provider first login error",
        description: "Identity provider first login error"
      },
      REGISTER_NODE_ERROR: {
        name: "Register node error",
        description: "Register node error"
      },
      PERMISSION_TOKEN_ERROR: {
        name: "Permission token error",
        description: "Permission token error"
      },
      IDENTITY_PROVIDER_RETRIEVE_TOKEN_ERROR: {
        name: "Identity provider retrieve token error",
        description: "Identity provider retrieve token error"
      },
      CLIENT_INFO: {
        name: "Client info",
        description: "Client info"
      },
      VALIDATE_ACCESS_TOKEN: {
        name: "Validate access token",
        description: "Validate access token"
      },
      IDENTITY_PROVIDER_LOGIN: {
        name: "Identity provider login",
        description: "Identity provider login"
      },
      CLIENT_INFO_ERROR: {
        name: "Client info error",
        description: "Client info error"
      },
      INTROSPECT_TOKEN_ERROR: {
        name: "Introspect token error",
        description: "Introspect token error"
      },
      INTROSPECT_TOKEN: {
        name: "Introspect token",
        description: "Introspect token"
      },
      UNREGISTER_NODE: {
        name: "Unregister node",
        description: "Unregister node"
      },
      REGISTER_NODE: {
        name: "Register node",
        description: "Register node"
      },
      INVALID_SIGNATURE: {
        name: "Invalid signature",
        description: "Invalid signature"
      },
      USER_INFO_REQUEST_ERROR: {
        name: "User info request error",
        description: "User info request error"
      },
      REFRESH_TOKEN: {
        name: "Refresh token",
        description: "Refresh token"
      },
      IDENTITY_PROVIDER_RESPONSE: {
        name: "Identity provider response",
        description: "Identity provider response"
      },
      IDENTITY_PROVIDER_RETRIEVE_TOKEN: {
        name: "Identity provider retrieve token",
        description: "Identity provider retrieve token"
      },
      UNREGISTER_NODE_ERROR: {
        name: "Unregister node error",
        description: "Unregister node error"
      },
      VALIDATE_ACCESS_TOKEN_ERROR: {
        name: "Validate access token error",
        description: "Validate access token error"
      },
      INVALID_SIGNATURE_ERROR: {
        name: "Invalid signature error",
        description: "Invalid signature error"
      },
      USER_INFO_REQUEST: {
        name: "User info request",
        description: "User info request"
      },
      IDENTITY_PROVIDER_RESPONSE_ERROR: {
        name: "Identity provider response error",
        description: "Identity provider response error"
      },
      IDENTITY_PROVIDER_LOGIN_ERROR: {
        name: "Identity provider login error",
        description: "Identity provider login error"
      },
      REFRESH_TOKEN_ERROR: {
        name: "Refresh token error",
        description: "Refresh token error"
      }
    },
    emptyEvents: "Nothing to add",
    emptyEventsInstructions: "There are no more events types left to add",
    eventConfigSuccessfully: "Successfully saved configuration",
    eventConfigError: "Could not save event configuration {{error}}",
    deleteEvents: "Clear events",
    deleteEventsConfirm: "If you clear all events of this realm, all records will be permanently cleared in the database",
    "admin-events-cleared": "The admin events have been cleared",
    "admin-events-cleared-error": "Could not clear the admin events {{error}}",
    "user-events-cleared": "The user events have been cleared",
    "user-events-cleared-error": "Could not clear the user events {{error}}",
    "events-disable-title": "Unsave events?",
    "events-disable-confirm": 'If "Save events" is disabled, subsequent events will not be displayed in the "Events" menu',
    confirm: "Confirm",
    noMessageBundles: "No message bundles",
    noMessageBundlesInstructions: "Add a message bundle to get started.",
    messageBundleDescription: "You can edit the supported locales. If you haven't selected supported locales yet, you can only edit the English locale.",
    defaultRoles: "Default roles",
    defaultGroups: "Default groups",
    securityDefences: "Security defenses",
    headers: "Headers",
    bruteForceDetection: "Brute force detection",
    xFrameOptions: "X-Frame-Options",
    contentSecurityPolicy: "Content-Security-Policy",
    contentSecurityPolicyReportOnly: "Content-Security-Policy-Report-Only",
    xContentTypeOptions: "X-Content-Type-Options",
    xRobotsTag: "X-Robots-Tag",
    xXSSProtection: "X-XSS-Protection",
    strictTransportSecurity: "HTTP Strict Transport Security (HSTS)",
    failureFactor: "Max login failures",
    permanentLockout: "Permanent lockout",
    waitIncrementSeconds: "Wait increment",
    maxFailureWaitSeconds: "Max wait",
    maxDeltaTimeSeconds: "Failure reset time",
    quickLoginCheckMilliSeconds: "Quick login check milliseconds",
    minimumQuickLoginWaitSeconds: "Minimum quick login wait"
  },
  "partial-import": {
    partialImportHeaderText: "Partial import allows you to import users, clients, and other resources from a previously exported json file.",
    selectRealm: "Select realm",
    chooseResources: "Choose the resources you want to import",
    selectIfResourceExists: "If a resource already exists, specify what should be done",
    import: "Import",
    resourcesToImport: "Resources to import",
    importFail: "Import failed: {{error}}",
    FAIL: "Fail import",
    SKIP: "Skip",
    OVERWRITE: "Overwrite",
    added: "Added",
    skipped: "Skipped",
    overwritten: "Overwritten",
    importAdded_zero: "No records added.",
    importAdded_one: "One record added.",
    importAdded_other: "{{count}} records added.",
    importOverwritten_zero: "No records overwritten.",
    importOverwritten_one: "One record overwritten.",
    importOverwritten_other: "{{count}} records overwritten.",
    importSkipped_zero: "No records skipped.",
    importSkipped_one: "One record skipped.",
    importSkipped_other: "{{count}} records skipped."
  },
  "partial-export": {
    partialExportHeaderText: "Partial export allows you to export realm configuration, and other associated resources into a json file.",
    includeGroupsAndRoles: "Include groups and roles",
    includeClients: "Include clients",
    exportWarningTitle: "Export with caution",
    exportWarningDescription: "If there is a great number of groups, roles or clients in your realm, the operation may make server unresponsive for a while.",
    exportSuccess: "Realm successfully exported.",
    exportFail: "Could not export realm: '{{error}}'"
  }
};

// build/realm-settings/help.js
var help_default4 = {
  "realm-settings-help": {
    fromDisplayName: "A user-friendly name for the 'From' address (optional).",
    replyToDisplayName: "A user-friendly name for the 'Reply-To' address (optional).",
    envelopeFrom: "An email address used for bounces (optional).",
    password: "SMTP password. This field is able to obtain its value from vault, use ${vault.ID} format.",
    frontendUrl: "Set the frontend URL for the realm. Use in combination with the default hostname provider to override the base URL for frontend requests for a specific realm.",
    requireSsl: "Is HTTPS required? 'None' means HTTPS is not required for any client IP address. 'External requests' means localhost and private IP addresses can access without HTTPS. 'All requests' means HTTPS is required for all IP addresses.",
    userManagedAccess: "If enabled, users are allowed to manage their resources and permissions using the Account Management Console.",
    endpoints: "Shows the configuration of the protocol endpoints",
    loginTheme: "Select theme for login, OTP, grant, registration and forgot password pages.",
    accountTheme: "Select theme for user account management pages.",
    adminConsoleTheme: "Select theme for admin console.",
    emailTheme: "Select theme for emails that are sent by the server.",
    displayName: "Display name of provider when linked in admin console",
    priority: "Priority of the provider",
    enabled: "Set if the keys are enabled",
    active: "Set if the keys can be used for signing",
    AESKeySize: "Size in bytes for the generated AES key. Size 16 is for AES-128, Size 24 for AES-192, and Size 32 for AES-256. WARN: Bigger keys than 128 are not allowed on some JDK implementations.",
    "save-user-events": "If enabled, login events are saved to the database, which makes events available to the admin and account management consoles.",
    "save-admin-events": "If enabled, admin events are saved to the database, which makes events available to the admin console.",
    expiration: "Sets the expiration for events. Expired events are periodically deleted from the database.",
    "admin-clearEvents": "Deletes all admin events in the database.",
    includeRepresentation: "Include JSON representation for create and update requests.",
    "user-clearEvents": "Deletes all user events in the database.",
    ellipticCurve: "Elliptic curve used in ECDSA",
    secretSize: "Size in bytes for the generated secret",
    algorithm: "Intended algorithm for the key",
    keystore: "Path to keys file",
    keystorePassword: "Password for the keys",
    keyAlias: "Alias for the private key",
    keyPassword: "Password for the private key",
    privateRSAKey: "Private RSA Key encoded in PEM format",
    x509Certificate: "X509 Certificate encoded in PEM format",
    xFrameOptions: "Default value prevents pages from being included by non-origin iframes <1>Learn more</1>",
    contentSecurityPolicy: "Default value prevents pages from being included by non-origin iframes <1>Learn more</1>",
    contentSecurityPolicyReportOnly: "For testing Content Security Policies <1>Learn more</1>",
    xContentTypeOptions: "Default value prevents Internet Explorer and Google Chrome from MIME-sniffing a response away from the declared content-type <1>Learn more</1>",
    xRobotsTag: "Prevent pages from appearing in search engines <1>Learn more</1>",
    xXSSProtection: "This header configures the Cross-site scripting (XSS) filter in your browser. Using the default behaviour, the browser will prevent rendering of the page when a XSS attack is detected. <1>Learn more</1>",
    strictTransportSecurity: "The Strict-Transport-Security HTTP header tells browsers to always use HTTPS. Once a browser sees this header, it will only visit the site over HTTPS for the time specified (1 year) at max-age, including the subdomains. <1>Learn more</1>",
    failureFactor: "How many failures before wait is triggered.",
    permanentLockout: "Lock the user permanently when the user exceeds the maximum login failures.",
    waitIncrementSeconds: "When failure threshold has been met, how much time should the user be locked out?",
    maxFailureWaitSeconds: "Max time a user will be locked out.",
    maxDeltaTimeSeconds: "When will failure count be reset?",
    quickLoginCheckMilliSeconds: "If a failure happens concurrently too quickly, lock out the user.",
    minimumQuickLoginWaitSeconds: "How long to wait after a quick login failure.",
    ssoSessionIdle: "Time a session is allowed to be idle before it expires. Tokens and browser sessions are invalidated when a session is expired.",
    ssoSessionMax: "Max time before a session is expired. Tokens and browser sessions are invalidated when a session is expired.",
    ssoSessionIdleRememberMe: "Time a remember me session is allowed to be idle before it expires. Tokens and browser sessions are invalidated when a session is expired. If not set it uses the standard SSO Session Idle value.",
    ssoSessionMaxRememberMe: "Max time before a session is expired when a user has set the remember me option. Tokens and browser sessions are invalidated when a session is expired. If not set it uses the standard SSO Session Max value.",
    clientSessionIdle: "Time a client session is allowed to be idle before it expires. Tokens are invalidated when a client session is expired. If not set it uses the standard SSO Session Idle value.",
    clientSessionMax: "Max time before a client session is expired. Tokens are invalidated when a session is expired. If not set it uses the standard SSO Session Max value.",
    offlineSessionIdle: "Time an offline session is allowed to be idle before it expires. You need to use offline token to refresh at least once within this period; otherwise offline session will expire.",
    offlineSessionMaxLimited: "Enable offline session max",
    offlineSessionMax: "Max time before an offline session is expired regardless of activity.",
    loginTimeout: "Max time a user has to complete a login. This is recommended to be relatively long, such as 30 minutes or more",
    loginActionTimeout: "Max time a user has to complete login related actions like update password or configure totp. This is recommended to be relatively long, such as 5 minutes or more",
    defaultSigAlg: "Default algorithm used to sign tokens for the realm",
    revokeRefreshToken: "If enabled a refresh token can only be used up to 'Refresh Token Max Reuse' and is revoked when a different token is used. Otherwise refresh tokens are not revoked when used and can be used multiple times.",
    refreshTokenMaxReuse: "Maximum number of times a refresh token can be reused. When a different token is used, revocation is immediate.",
    accessTokenLifespan: "Max time before an access token is expired. This value is recommended to be short relative to the SSO timeout",
    accessTokenLifespanImplicitFlow: "Max time before an access token issued during OpenID Connect Implicit Flow is expired. This value is recommended to be shorter than the SSO timeout. There is no possibility to refresh token during implicit flow, that's why there is a separate timeout different to 'Access Token Lifespan'",
    clientLoginTimeout: "Max time a client has to finish the access token protocol. This should normally be 1 minute.",
    userInitiatedActionLifespan: "Maximum time before an action permit sent by a user (such as a forgot password e-mail) is expired. This value is recommended to be short because it's expected that the user would react to self-created action quickly.",
    defaultAdminInitiatedActionLifespan: "Maximum time before an action permit sent to a user by administrator is expired. This value is recommended to be long to allow administrators to send e-mails for users that are currently offline. The default timeout can be overridden immediately before issuing the token.",
    overrideActionTokens: "Override default settings of maximum time before an action permit sent by a user (such as a forgot password e-mail) is expired for specific action. This value is recommended to be short because it's expected that the user would react to self-created action quickly.",
    internationalization: "If enabled, you can choose which locales you support for this realm and which locale is the default.",
    supportedLocales: "The locales to support for this realm. The user chooses one of these locales on the login screen.",
    defaultLocale: "The initial locale to use. It is used on the login screen and other screens in the Admin Console and Account Console.",
    conditions: "Conditions, which will be evaluated to determine if client policy should be applied during particular action or not.",
    clientProfiles: "Client profiles applied on this policy.",
    anyClient: "The condition is satisfied by any client on any event.",
    clientAccessType: "It uses the client's access type (confidential, public, bearer-only) to determine whether the policy is applied. Condition is checked during most of OpenID Connect requests (Authorization requests, token requests, introspection endpoint request, etc.)",
    clientAccesstypeTooltip: "Access Type of the client, for which the condition will be applied.",
    clientRoles: "The condition checks whether one of the specified client roles exists on the client to determine whether the policy is applied. This effectively allows client administrator to create client role of specified name on the client to make sure that particular client policy will be applied on requests of this client. Condition is checked during most of OpenID Connect requests (Authorization requests, token requests, introspection endpoint request, etc.)",
    clientRolesConditionTooltip: "Client roles, which will be checked during this condition evaluation. Condition evaluates to true if client has at least one client role with the name as the client roles specified in the configuration.",
    clientScopes: "It uses the scopes requested or assigned in advance to the client to determine whether the policy is applied to this client. Condition is evaluated during OpenID Connect authorization request and/or token request.",
    clientScopesConditionTooltip: "The list of expected client scopes. Condition evaluates to true if specified client request matches some of the client scopes. It depends also whether it should be default or optional client scope based on the 'Scope Type' configured.",
    clientUpdaterContext: "The condition checks the context how is client created/updated to determine whether the policy is applied. For example it checks if client is created with admin REST API or OIDC dynamic client registration. And for the letter case if it is ANONYMOUS client registration or AUTHENTICATED client registration with Initial access token or Registration access token and so on.",
    clientUpdaterSourceGroups: "The condition checks the group of the entity who tries to create/update the client to determine whether the policy is applied.",
    clientUpdaterSourceGroupsTooltip: "Name of groups to check. Condition evaluates to true if the entity, who creates/updates client is member of some of the specified groups. Configured groups are specified by their simple name, which must match to the name of the Keycloak group. No support for group hierarchy is used here.",
    clientUpdaterSourceHost: "The condition checks the host/domain of the entity who tries to create/update the client to determine whether the policy is applied.",
    clientUpdaterTrustedHostsTooltip: "List of Hosts, which are trusted. In case that client registration/update request comes from the host/domain specified in this configuration, condition evaluates to true. You can use hostnames or IP addresses. If you use star at the beginning (for example '*.example.com' ) then whole domain example.com will be trusted.",
    clientUpdaterSourceRoles: "The condition checks the role of the entity who tries to create/update the client to determine whether the policy is applied.",
    clientUpdaterSourceRolesTooltip: "The condition is checked during client registration/update requests and it evaluates to true if the entity (usually user), who is creating/updating client is member of the specified role. For reference the realm role, you can use the realm role name like 'my_realm_role' . For reference client role, you can use the client_id.role_name for example 'my_client.my_client_role' will refer to client role 'my_client_role' of client 'my_client'. "
  }
};

// build/authentication/messages.js
var messages_default11 = {
  authentication: {
    title: "Authentication",
    flows: "Flows",
    requiredActions: "Required actions",
    policies: "Policies",
    passwordPolicy: "Password policy",
    otpPolicy: "OTP Policy",
    webauthnPolicy: "Webauthn Policy",
    webauthnPasswordlessPolicy: "Webauthn Passwordless Policy",
    noPasswordPolicies: "No password policies",
    noPasswordPoliciesInstructions: "You haven't added any password policies to this realm. Add a policy to get started.",
    updatePasswordPolicySuccess: "Password policies successfully updated",
    updatePasswordPolicyError: "Could not update the password policies: '{{error}}'",
    webAuthnPolicyRpEntityName: "Relying party entity name",
    addPolicy: "Add policy",
    otpType: "OTP type",
    policyType: {
      totp: "Time based",
      hotp: "Counter based"
    },
    otpHashAlgorithm: "OTP hash algorithm",
    otpPolicyDigits: "Number of digits",
    lookAhead: "Look ahead window",
    otpPolicyPeriod: "OTP Token period",
    otpPolicyPeriodErrorHint: "Value needs to be between 1 second and 2 minutes",
    initialCounter: "Initial counter",
    initialCounterErrorHint: "Value needs to be between 1 and 120",
    supportedActions: "Supported actions",
    updateOtpSuccess: "OTP policy successfully updated",
    updateOtpError: "Could not update OTP policy: {{error}}",
    flowName: "Flow name",
    searchForFlow: "Search for flow",
    usedBy: "Used by",
    buildIn: "Built-in",
    appliedByProviders: "Applied by the following providers",
    appliedByClients: "Applied by the following clients",
    specificProviders: "Specific providers",
    specificClients: "Specific clients",
    default: "Default",
    notInUse: "Not in use",
    duplicate: "Duplicate",
    setAsDefault: "Set as default",
    editInfo: "Edit info",
    editFlow: "Edit flow",
    edit: "Edit",
    deleteConfirmFlow: "Delete flow?",
    deleteConfirmFlowMessage: 'Are you sure you want to permanently delete the flow "<1>{{flow}}</1>".',
    deleteFlowSuccess: "Flow successfully deleted",
    deleteFlowError: "Could not delete flow: {{error}}",
    duplicateFlow: "Duplicate flow",
    deleteConfirmExecution: "Delete execution?",
    deleteConfirmExecutionMessage: 'Are you sure you want to permanently delete the execution "<1>{{name}}</1>".',
    deleteExecutionSuccess: "Execution successfully deleted",
    deleteExecutionError: "Could not delete execution: {{error}}",
    updateFlowSuccess: "Flow successfully updated",
    updateFlowError: "Could not update flow: {{error}}",
    copyOf: "Copy of {{name}}",
    copyFlowSuccess: "Flow successfully duplicated",
    copyFlowError: "Could not duplicate flow: {{error}}",
    createFlow: "Create flow",
    flowType: "Flow type",
    "flow-type": {
      "basic-flow": "Generic",
      "form-flow": "Form"
    },
    "top-level-flow-type": {
      "basic-flow": "Basic flow",
      "client-flow": "Client flow"
    },
    flowCreatedSuccess: "Flow created",
    flowCreateError: "Could not create flow: {{error}}",
    flowDetails: "Flow details",
    tableView: "Table view",
    diagramView: "Diagram view",
    emptyExecution: "No steps",
    emptyExecutionInstructions: "You can start defining this flow by adding a sub-flow or an execution",
    addExecutionTitle: "Add an execution",
    addExecution: "Add execution",
    addSubFlowTitle: "Add a sub-flow",
    addSubFlow: "Add sub-flow",
    addCondition: "Add condition",
    addStep: "Add step",
    addStepTo: "Add step to {{name}}",
    steps: "Steps",
    requirement: "Requirement",
    requirements: {
      REQUIRED: "Required",
      ALTERNATIVE: "Alternative",
      DISABLED: "Disabled",
      CONDITIONAL: "Conditional"
    },
    executionConfig: "{{name}} config",
    alias: "Alias",
    configSaveSuccess: "Successfully saved the execution config",
    configSaveError: "Could not save the execution config: {{error}}",
    setAsDefaultAction: "Set as default action",
    disabledOff: "Disabled off",
    updatedRequiredActionSuccess: "Updated required action successfully",
    updatedRequiredActionError: "Could not update required action: {{error}}"
  }
};

// build/authentication/help.js
var help_default5 = {
  "authentication-help": {
    name: "Help text for the name of the new flow",
    description: "Help text for the description of the new flow",
    createFlow: "You can create a top level flow within this from",
    flowType: "What kind of form is it",
    topLevelFlowType: "What kind of top level flow is it? Type 'client' is used for authentication of clients (applications) when generic is for users and everything else",
    addExecution: "Execution can have a wide range of actions, from sending a reset email to validating an OTP",
    addSubFlow: "Sub-Flows can be either generic or form. The form type is used to construct a sub-flow that generates a single flow for the user. Sub-flows are a special type of execution that evaluate as successful depending on how the executions they contain evaluate.",
    alias: "Name of the configuration",
    otpType: "totp is Time-Based One Time Password. 'hotp' is a counter base one time password in which the server keeps a counter to hash against.",
    webAuthnPolicyRpEntityName: "Human-readable server name as WebAuthn Relying Party",
    otpHashAlgorithm: "What hashing algorithm should be used to generate the OTP.",
    otpPolicyDigits: "How many digits should the OTP have?",
    lookAhead: "How far ahead should the server look just in case the token generator and server are out of time sync or counter sync?",
    otpPolicyPeriod: "How many seconds should an OTP token be valid? Defaults to 30 seconds.",
    supportedActions: "Applications that are known to work with the current OTP policy"
  }
};

// build/user-federation/messages.js
var messages_default12 = {
  "user-federation": {
    userFederation: "User federation",
    descriptionLanding: "This is the description for the user federation landing page",
    userFederationExplanation: "Keycloak can federate external user databases. Out of the box we have support for LDAP and Active Directory.",
    getStarted: "To get started, select a provider from the list below.",
    providers: "Add providers",
    addKerberos: "Add Kerberos providers",
    addLdap: "Add LDAP providers",
    addOneLdap: "Add LDAP provider",
    addKerberosWizardTitle: "Add Kerberos user federation provider",
    addLdapWizardTitle: "Add LDAP user federation provider",
    syncChangedUsers: "Sync changed users",
    syncAllUsers: "Sync all users",
    unlinkUsers: "Unlink users",
    removeImported: "Remove imported",
    deleteProvider: "Delete provider",
    generalOptions: "General options",
    consoleDisplayName: "Console display name",
    vendor: "Vendor",
    connectionAndAuthenticationSettings: "Connection and authentication settings",
    connectionURL: "Connection URL",
    enableStartTls: "Enable StartTLS",
    useTruststoreSpi: "Use Truststore SPI",
    connectionPooling: "Connection pooling",
    connectionTimeout: "Connection timeout",
    bindType: "Bind type",
    bindDn: "Bind DN",
    bindCredentials: "Bind credentials",
    ldapSearchingAndUpdatingSettings: "LDAP searching and updating",
    editMode: "Edit mode",
    usersDN: "Users DN",
    usernameLdapAttribute: "Username LDAP attribute",
    rdnLdapAttribute: "RDN LDAP attribute",
    uuidLdapAttribute: "UUID LDAP attribute",
    userObjectClasses: "User object classes",
    userLdapFilter: "User LDAP filter",
    searchScope: "Search scope",
    readTimeout: "Read timeout",
    pagination: "Pagination",
    synchronizationSettings: "Synchronization settings",
    importUsers: "Import users",
    batchSize: "Batch size",
    periodicFullSync: "Periodic full sync",
    fullSyncPeriod: "Full sync period",
    periodicChangedUsersSync: "Periodic changed users sync",
    changedUsersSyncPeriod: "Changed users sync period",
    kerberosIntegration: "Kerberos integration",
    allowKerberosAuthentication: "Allow Kerberos authentication",
    useKerberosForPasswordAuthentication: "Use Kerberos for password authentication",
    cacheSettings: "Cache settings",
    cachePolicy: "Cache policy",
    evictionDay: "Eviction day",
    evictionHour: "Eviction hour",
    evictionMinute: "Eviction minute",
    maxLifespan: "Max lifespan",
    advancedSettings: "Advanced settings",
    enableLdapv3Password: "Enable the LDAPv3 password modify extended operation",
    validatePasswordPolicy: "Validate password policy",
    trustEmail: "Trust email",
    requiredSettings: "Required Settings",
    kerberosRealm: "Kerberos realm",
    serverPrincipal: "Server principal",
    keyTab: "Key tab",
    debug: "Debug",
    allowPasswordAuthentication: "Allow password authentication",
    updateFirstLogin: "Update first login",
    always: "Always",
    never: "Never",
    onlyLdaps: "Only for ldaps",
    oneLevel: "One Level",
    subtree: "Subtree",
    saveSuccess: "User federation provider successfully saved",
    saveError: "User federation provider could not be saved: {{error}}",
    createSuccess: "User federation provider successfully created",
    createError: "User federation provider could not be created: {{error}}",
    testAuthentication: "Test authentication",
    testSuccess: "Successfully connected to LDAP",
    testError: "Error when trying to connect to LDAP. See server.log for details. {{error}}",
    learnMore: "Learn more",
    addNewProvider: "Add new provider",
    userFedDeletedSuccess: "The user federation provider has been deleted.",
    userFedDeleteError: "Could not delete user federation provider: '{{error}}'",
    userFedDeleteConfirmTitle: "Delete user federation provider?",
    userFedDeleteConfirm: "If you delete this user federation provider, all associated data will be removed.",
    userFedDisableConfirmTitle: "Disable user federation provider?",
    userFedDisableConfirm: "If you disable this user federation provider, it will not be considered for queries and imported users will be disabled and read-only until the provider is enabled again.",
    userFedUnlinkUsersConfirmTitle: "Unlink all users?",
    userFedUnlinkUsersConfirm: "Do you want to unlink all the users? Any users without a password in the database will not be able to authenticate anymore.",
    removeImportedUsers: "Remove imported users?",
    removeImportedUsersMessage: "Do you really want to remove all imported users?",
    removeImportedUsersSuccess: "Imported users have been removed.",
    removeImportedUsersError: "Could not remove imported users: '{{error}}'",
    syncUsersSuccess: "Sync of users finished successfully.",
    syncUsersError: "Could not sync users: '{{error}}'",
    unlinkUsersSuccess: "Unlink of users finished successfully.",
    unlinkUsersError: "Could not unlink users: '{{error}}'",
    validateName: "You must enter a name",
    validateRealm: "You must enter a realm",
    validateServerPrincipal: "You must enter a server principal",
    validateKeyTab: "You must enter a key tab",
    validateConnectionUrl: "You must enter a connection URL",
    validateBindDn: "You must enter the DN of the LDAP admin",
    validateBindCredentials: "You must enter the password of the LDAP admin",
    validateUuidLDAPAttribute: "You must enter a UUID LDAP attribute",
    validateUserObjectClasses: "You must enter one or more user object classes",
    validateEditMode: "You must select an edit mode",
    validateUsersDn: "You must enter users DN",
    validateUsernameLDAPAttribute: "You must enter a username LDAP attribute",
    validateRdnLdapAttribute: "You must enter an RDN LDAP attribute",
    validateCustomUserSearchFilter: "Filter must be enclosed in parentheses, for example: (filter)",
    mapperTypeMsadUserAccountControlManager: "msad-user-account-control-mapper",
    mapperTypeMsadLdsUserAccountControlMapper: "msad-user-account-control-mapper",
    mapperTypeGroupLdapMapper: "group-ldap-mapper",
    mapperTypeUserAttributeLdapMapper: "user-attribute-ldap-mapper",
    mapperTypeRoleLdapMapper: "role-ldap-mapper",
    mapperTypeHardcodedAttributeMapper: "hardcoded-attribute-mapper",
    mapperTypeHardcodedLdapRoleMapper: "hardcoded-ldap-role-mapper",
    mapperTypeCertificateLdapMapper: "certificate-ldap-mapper",
    mapperTypeFullNameLdapMapper: "full-name-ldap-mapper",
    mapperTypeHardcodedLdapGroupMapper: "hardcoded-ldap-group-mapper",
    mapperTypeLdapAttributeMapper: "hardcoded-ldap-attribute-mapper",
    ldapMappersList: "LDAP Mappers",
    ldapFullNameAttribute: "LDAP full name attribute",
    writeOnly: "Write only",
    ldapGroupsDn: "LDAP groups DN",
    groupNameLdapAttribute: "Group name LDAP attribute",
    groupObjectClasses: "Group object classes",
    preserveGroupInheritance: "Preserve group inheritance",
    ignoreMissingGroups: "Ignore missing groups",
    userGroupsRetrieveStrategy: "User groups retrieve strategy",
    mappedGroupAttributes: "Mapped group attributes",
    dropNonexistingGroupsDuringSync: "Drop non-existing groups during sync",
    groupsPath: "Groups path",
    membershipLdapAttribute: "Membership LDAP attribute",
    membershipAttributeType: "Membership attribute type",
    membershipUserLdapAttribute: "Membership user LDAP attribute",
    ldapFilter: "LDAP filter",
    mode: "Mode",
    memberofLdapAttribute: "Member-of LDAP attribute",
    ldapRolesDn: "LDAP roles DN",
    roleNameLdapAttribute: "Role name LDAP attribute",
    roleObjectClasses: "Role object classes",
    userRolesRetrieveStrategy: "User roles retrieve strategy",
    useRealmRolesMapping: "Use realm roles mapping",
    ldapAttributeName: "LDAP attribute name",
    ldapAttributeValue: "LDAP attribute value",
    userModelAttribute: "User model attribute",
    ldapAttribute: "LDAP attribute",
    readOnly: "Read only",
    alwaysReadValueFromLdap: "Always read value from LDAP",
    isMandatoryInLdap: "Is mandatory in LDAP",
    attributeDefaultValue: "Attribute default value",
    isBinaryAttribute: "Is binary attribute",
    derFormatted: "DER formatted",
    passwordPolicyHintsEnabled: "Password policy hints enabled",
    userModelAttributeName: "User model attribute name",
    attributeValue: "Attribute value",
    selectRole: "Select role",
    group: "Group"
  }
};

// build/user-federation/help.js
var help_default6 = {
  "user-federation-help": {
    addKerberosWizardDescription: "Text needed here",
    addLdapWizardDescription: "Text needed here",
    ldapGeneralOptionsSettingsDescription: "This section contains a few basic options common to all user storage providers.",
    consoleDisplayNameHelp: "Display name of provider when linked in admin console",
    vendorHelp: "LDAP vendor (provider)",
    ldapConnectionAndAuthorizationSettingsDescription: "This section contains options related to the configuration of the connection to the LDAP server. It also contains options related to authentication of the LDAP connection to the LDAP server.",
    consoleDisplayConnectionUrlHelp: "Connection URL to your LDAP server",
    enableStartTlsHelp: "Encrypts the connection to LDAP using STARTTLS, which will disable connection pooling",
    useTruststoreSpiHelp: "Specifies whether LDAP connection will use the Truststore SPI with the truststore configured in standalone.xml/domain.sml. 'Always' means that it will always use it. 'Never' means that it will not use it. 'Only for ldaps' means that it will use it if your connection URL use ldaps. Note that even if standalone.xml/domain.xml is not configured, the default java cacerts or certificate specified by 'javax.net.ssl.trustStore' property will be used.",
    connectionPoolingHelp: "Determines if Keycloak should use connection pooling for accessing LDAP server.",
    connectionTimeoutHelp: "LDAP connection timeout in milliseconds",
    bindTypeHelp: "Type of the authentication method used during LDAP bind operation. It is used in most of the requests sent to the LDAP server. Currently only 'none' (anonymous LDAP authentication) or 'simple' (bind credential + bind password authentication) mechanisms are available.",
    bindDnHelp: "DN of the LDAP admin, which will be used by Keycloak to access LDAP server",
    bindCredentialsHelp: "Password of LDAP admin. This field is able to obtain its value from vault, use ${vault.ID} format.",
    ldapSearchingAndUpdatingSettingsDescription: "This section contains options related to searching the LDAP server for the available users.",
    editModeLdapHelp: "READ_ONLY is a read-only LDAP store. WRITABLE means data will be synced back to LDAP on demand. UNSYNCED means user data will be imported, but not synced back to LDAP.",
    usersDNHelp: "Full DN of LDAP tree where your users are. This DN is the parent of LDAP users. It could be for example 'ou=users,dc=example,dc=com' assuming that your typical user will have DN like 'uid='john',ou=users,dc=example,dc=com'.",
    usernameLdapAttributeHelp: "Name of the LDAP attribute, which is mapped as Keycloak username. For many LDAP server vendors it can be 'uid'. For Active directory it can be 'sAMAccountName' or 'cn'. The attribute should be filled for all LDAP user records you want to import from LDAP to Keycloak.",
    rdnLdapAttributeHelp: "Name of the LDAP attribute, which is used as RDN (top attribute) of typical user DN. Usually it's the same as the Username LDAP attribute, however it is not required. For example for Active directory, it is common to use 'cn' as RDN attribute when username attribute might be 'sAMAccountName'.",
    uuidLdapAttributeHelp: "Name of the LDAP attribute, which is used as a unique object identifier (UUID) for objects in LDAP. For many LDAP server vendors, it is 'entryUUID'; however some are different. For example, for Active directory it should be 'objectGUID'. If your LDAP server does not support the notion of UUID, you can use any other attribute that is supposed to be unique among LDAP users in tree. For example 'uid' or 'entryDN'.",
    userObjectClassesHelp: "All values of LDAP objectClass attribute for users in LDAP, divided by commas. For example: 'inetOrgPerson, organizationalPerson'. Newly created Keycloak users will be written to LDAP with all those object classes and existing LDAP user records are found just if they contain all those object classes.",
    userLdapFilterHelp: "Additional LDAP filter for filtering searched users. Leave this empty if you don't need an additional filter. Make sure that it starts with '(' and ends with ')'.",
    searchScopeHelp: "For one level, the search applies only for users in the DNs specified by User DNs. For subtree, the search applies to the whole subtree. See LDAP documentation for more details.",
    readTimeoutHelp: "LDAP read timeout in milliseconds. This timeout applies for LDAP read operations.",
    paginationHelp: "Whether the LDAP server supports pagination",
    ldapSynchronizationSettingsDescription: "This section contains options related to synchronization of users from LDAP to the Keycloak database.",
    importUsersHelp: "If true, LDAP users will be imported into the Keycloak DB and synced by the configured sync policies.",
    batchSizeHelp: "Count of LDAP users to be imported from LDAP to Keycloak within a single transaction",
    periodicFullSyncHelp: "Whether periodic full synchronization of LDAP users to Keycloak should be enabled or not",
    fullSyncPeriodHelp: "Period for full synchronization in seconds",
    periodicChangedUsersSyncHelp: "Whether periodic synchronization of changed or newly created LDAP users to Keycloak should be enabled or not",
    changedUsersSyncHelp: "Period for synchronization of changed or newly created LDAP users in seconds",
    ldapKerberosSettingsDescription: "This section contains options useful for the Kerberos integration. This is used only when the LDAP server is used together with Kerberos/SPNEGO for user authentication.",
    allowKerberosAuthenticationHelp: "Enable/disable HTTP authentication of users with SPNEGO/Kerberos tokens. The data about authenticated users will be provisioned from this LDAP server.",
    useKerberosForPasswordAuthenticationHelp: "User Kerberos login module for authenticating username/password against Kerberos server instead of authenticating against LDAP server with Directory Service API",
    cacheSettingsDescription: "This section contains options useful for caching users, which were loaded from this user storage provider.",
    cachePolicyHelp: "Cache Policy for this storage provider. 'DEFAULT' is whatever the default settings are for the global cache. 'EVICT_DAILY' is a time of day every day that the cache will be invalidated. 'EVICT_WEEKLY' is a day of the week and time the cache will be invalidated. 'MAX_LIFESPAN' is the time in milliseconds that will be the lifespan of a cache entry.",
    evictionDayHelp: "Day of the week the entry will become invalid",
    evictionHourHelp: "Hour of the day the entry will become invalid",
    evictionMinuteHelp: "Minute of the hour the entry will become invalid",
    maxLifespanHelp: "Max lifespan of cache entry in milliseconds",
    ldapAdvancedSettingsDescription: "This section contains all the other options for more fine-grained configuration of the LDAP storage provider.",
    enableLdapv3PasswordHelp: "Use the LDAPv3 Password Modify Extended Operation (RFC-3062). The password modify extended operation usually requires that LDAP user already has password in the LDAP server. So when this is used with 'Sync Registrations', it can be good to add also 'Hardcoded LDAP attribute mapper' with randomly generated initial password.",
    validatePasswordPolicyHelp: "Determines if Keycloak should validate the password with the realm password policy before updating it",
    trustEmailHelp: "If enabled, email provided by this provider is not verified even if verification is enabled for the realm.",
    "IDK-periodicChangedUsersSyncHelp": "Should newly created users be created within LDAP store? Priority affects which provider is chosen to sync the new user.",
    kerberosWizardDescription: "Text needed here.",
    kerberosRequiredSettingsDescription: "This section contains a few basic options common to all user storage providers.",
    kerberosRealmHelp: "Name of kerberos realm. For example, FOO.ORG",
    serverPrincipalHelp: "Full name of server principal for HTTP service including server and domain name. For example, HTTP/host.foo.org@FOO.ORG",
    keyTabHelp: "Location of Kerberos KeyTab file containing the credentials of server principal. For example, /etc/krb5.keytab",
    debugHelp: "Enable/disable debug logging to standard output for Krb5LoginModule.",
    allowPasswordAuthenticationHelp: "Enable/disable possibility of username/password authentication against Kerberos database",
    editModeKerberosHelp: "READ_ONLY means that password updates are not allowed and user always authenticates with Kerberos password. UNSYNCED means that the user can change the password in the Keycloak database and this one will be used instead of the Kerberos password.",
    updateFirstLoginHelp: "Update profile on first login",
    mapperTypeMsadUserAccountControlManagerHelp: "Mapper specific to MSAD. It's able to integrate the MSAD user account state into Keycloak account state (account enabled, password is expired etc). It's using userAccountControl and pwdLastSet MSAD attributes for that. For example if pwdLastSet is 0, the Keycloak user is required to update the password; if userAccountControl is 514 (disabled account) the Keycloak user is disabled as well etc. Mapper is also able to handle the exception code from LDAP user authentication.",
    mapperTypeMsadLdsUserAccountControlMapperHelp: "Mapper specific to MSAD LDS. It's able to integrate the MSAD LDS user account state into Keycloak account state (account enabled, password is expired etc). It's using msDS-UserAccountDisabled and pwdLastSet is 0, the Keycloak user is required to update password, if msDS-UserAccountDisabled is 'TRUE' the Keycloak user is disabled as well etc. Mapper is also able to handle exception code from LDAP user authentication.",
    mapperTypeGroupLdapMapperHelp: "Used to map group mappings of groups from some LDAP DN to Keycloak group mappings",
    mapperTypeUserAttributeLdapMapperHelp: "Used to map single attribute from LDAP user to attribute of UserModel in Keycloak DB",
    mapperTypeRoleLdapMapperHelp: "Used to map role mappings of roles from some LDAP DN to Keycloak role mappings of either realm roles or client roles of particular client",
    mapperTypeHardcodedAttributeMapperHelp: "This mapper will hardcode any model user attribute and some property (like emailVerified or enabled) when importing user from LDAP.",
    mapperTypeHardcodedLdapRoleMapperHelp: "Users imported from LDAP will be automatically added into this configured role.",
    mapperTypeCertificateLdapMapperHelp: "Used to map single attribute which contains a certificate from LDAP user to attribute of UserModel in Keycloak DB",
    mapperTypeFullNameLdapMapperHelp: "Used to map the full-name of a user from single attribute in LDAP (usually 'cn' attribute) to firstName and lastName attributes of UserModel in Keycloak DB",
    mapperTypeHardcodedLdapGroupMapperHelp: "Users imported from LDAP will be automatically added into this configured group.",
    mapperTypeLdapAttributeMapperHelp: "This mapper is supported just if syncRegistrations is enabled. New users registered in Keycloak will be written to the LDAP with the hardcoded value of some specified attribute.",
    passwordPolicyHintsEnabledHelp: "Applicable just for writable MSAD. If on, then updating password of MSAD user will use LDAP_SERVER_POLICY_HINTS_OID extension, which means that advanced MSAD password policies like 'password history' or 'minimal password age' will be applied. This extension works just for MSAD 2008 R2 or newer.",
    nameHelp: "Name of the mapper",
    mapperTypeHelp: "Used to map single attribute from LDAP user to attribute of UserModel in Keycloak DB",
    userModelAttributeHelp: "Name of the UserModel property or attribute you want to map the LDAP attribute into. For example 'firstName', 'lastName, 'email', 'street' etc.",
    ldapAttributeHelp: "Name of mapped attribute on LDAP object. For example 'cn', 'sn', 'mail', 'street', etc.",
    readOnlyHelp: "Read-only attribute is imported from LDAP to UserModel, but it's not saved back to LDAP when user is updated in Keycloak.",
    alwaysReadValueFromLdapHelp: "If on, then during reading of the LDAP attribute value will always used instead of the value from Keycloak DB.",
    isMandatoryInLdapHelp: "If true, attribute is mandatory in LDAP. Hence if there is no value in Keycloak DB, the empty value will be set to be propagated to LDAP.",
    attributeDefaultValueHelp: "If there is no value in Keycloak DB and attribute is mandatory in LDAP, this value will be propagated to LDAP.",
    isBinaryAttributeHelp: "Should be true for binary LDAP attributes.",
    derFormattedHelp: "Activate this if the certificate is DER formatted in LDAP and not PEM formatted.",
    ldapFullNameAttributeHelp: "Name of the LDAP attribute, which contains the fullName of the user. Usually it will be 'cn'.",
    fullNameLdapReadOnlyHelp: "For Read-only, data is imported from LDAP to Keycloak DB, but it's not saved back to LDAP when the user is updated in Keycloak.",
    fullNameLdapWriteOnlyHelp: "For Write-only, data is propagated to LDAP when a user is created or updated in Keycloak. But this mapper is not used to propagate data from LDAP back into Keycloak. This setting is useful if you configured separate firstName and lastName attribute mappers and you want to use those to read the attribute from LDAP into Keycloak.",
    ldapGroupsDnHelp: "LDAP DN where groups of this tree are saved. For example 'ou=groups,dc=example,dc=org'",
    groupNameLdapAttributeHelp: "Name of LDAP attribute, which is used in group objects for name and RDN of group. Usually it will be 'cn'. In this case typical group/role object may have DN like 'cn=Group1,ouu=groups,dc=example,dc=org'.",
    groupObjectClassesHelp: "Object class (or classes) of the group object. It's divided by commas if more classes needed. In typical LDAP deployment it could be 'groupOfNames'. In Active Directory it's usually 'group'.",
    preserveGroupInheritanceHelp: "Flag whether group inheritance from LDAP should be propagated to Keycloak. If false, then all LDAP groups will be mapped as flat top-level groups in Keycloak. Otherwise group inheritance is preserved into Keycloak, but the group sync might fail if LDAP structure contains recursions or multiple parent groups per child groups.",
    ignoreMissingGroupsHelp: "Ignore missing groups in the group hierarchy.",
    userGroupsRetrieveStrategyHelp: "Specify how to retrieve groups of user. LOAD_GROUPS_BY_MEMBER_ATTRIBUTE means that roles of user will be retrieved by sending LDAP query to retrieve all groups where 'member' is our user. GET_GROUPS_FROM_USER_MEMBEROF_ATTRIBUTE means that groups of user will be retrieved from 'memberOf' attribute of our user or from the other attribute specified by 'Member-Of LDAP Attribute'.",
    mappedGroupAttributesHelp: "List of names of attributes divided by commas. This points to the list of attributes on LDAP group, which will be mapped as attributes of Group in Keycloak. Leave this empty if no additional group attributes are required to be mapped in Keycloak.",
    dropNonexistingGroupsDuringSyncHelp: "If this flag is true, then during sync of groups from LDAP to Keycloak, we will keep just those Keycloak groups that still exist in LDAP. The rest will be deleted.",
    groupsPathHelp: "Keycloak group path the LDAP groups are added to. For example if value '/Applications/App1' is used, then LDAP groups will be available in Keycloak under group 'App1', which is child of top level group 'Applications'. The default value is '/' so LDAP groups will be mapped to the Keycloak groups at the top level. The configured group path must already exist in the Keycloak when creating this mapper.",
    ldapRolesDnHelp: "LDAP DN where roles of this tree are saved. For example, 'ou=finance,dc=example,dc=org'",
    roleNameLdapAttributeHelp: "Name of LDAP attribute, which is used in role objects for name and RDN of role. Usually it will be 'cn'. In this case typical group/role object may have DN like 'cn=role1,ou=finance,dc=example,dc=org'.",
    roleObjectClassesHelp: "Object class (or classes) of the role object. It's divided by commas if more classes are needed. In typical LDAP deployment it could be 'groupOfNames'. In Active Directory it's usually 'group'.",
    userRolesRetrieveStrategyHelp: "Specify how to retrieve roles of user. LOAD_ROLES_BY_MEMBER_ATTRIBUTE means that roles fo user will be retrieved by sending LDAP query to retrieve all roles where 'member' is our user. GET_ROLES_FROM_USER_MEMBEROF means that roles of user will be retrieved from 'memberOf' attribute of our user. Or from the other attributes specified by 'Member-Of LDAP Attribute'. LOAD_ROLES_BY_MEMBER_ATTRIBUTE is applicable just in Active Directory and it means that roles of user will be retrieved recursively with usage of LDAP_MATCHING_RULE_IN_CHAIN LDAP extension.",
    useRealmRolesMappingHelp: "If true, then LDAP role mappings will be mapped to realm role mappings in Keycloak. Otherwise it will be mapped to client role mappings.",
    clientIdHelp: "Client ID of client to which LDAP role mappings will be mapped. Applicable only if 'Use Realm Roles Mapping' is false.",
    membershipLdapAttributeHelp: "Name of LDAP attribute on group, which is used for membership mappings. Usually it will be 'member'. However when 'Membership Attribute Type' is 'UID', then 'Membership LDAP Attribute' could be typically 'memberUid'.",
    membershipAttributeTypeHelp: "DN means that LDAP group has it's members declared in form of their full DN. For example 'member: uid=john,ou=users,dc=example,dc=com'. UID means that LDAP group has it's members declared in form of pure user uids. For example 'memberUid: john'.",
    membershipUserLdapAttributeHelp: "Used just if Membership Attribute Type is UID. It is the name of the LDAP attribute on user, which is used for membership mappings. Usually it will be 'uid'. For example if the value of 'Membership User LDAP Attribute' is 'uid' and  LDAP group has 'memberUid: john', then it is expected that particular LDAP user will have attribute 'uid: john'.",
    ldapFilterHelp: "LDAP Filter adds an additional custom filter to the whole query for retrieve LDAP groups. Leave this empty if no additional filtering is needed and you want to retrieve all groups from LDAP. Otherwise make sure that filter starts with '(' and ends with ')'.",
    modeHelp: "LDAP_ONLY means that all group mappings of users are retrieved from LDAP and saved into LDAP. READ_ONLY is Read-only LDAP mode where group mappings are retrieved from both LDAP and DB and merged together. New group joins are not saved to LDAP but to DB. IMPORT is Read-only LDAP mode where group mappings are retrieved from LDAP just at the time when user is imported from LDAP and then they are saved to local keycloak DB.",
    memberofLdapAttributeHelp: "Used just when 'User Roles Retrieve Strategy' is GET_GROUPS_FROM_USER_MEMBEROF_ATTRIBUTE. It specifies the name of the LDAP attribute on the LDAP user, which contains the groups, which the user is member of. Usually it will be the default 'memberOf'.",
    userModelAttributeNameHelp: "Name of the model attribute to be added when importing user from LDAP",
    attributeValueHelp: "Value of the model attribute to be added when importing user from LDAP",
    roleHelp: "Role to grant to user. Click 'Select Role' button to browse roles, or just type it in the textbox. To reference an application role the syntax is appname.approle, i.e. myapp.myrole.",
    groupHelp: "Group to add the user in. Fill the full path of the group including path. For example: '/root-group/child-group'.",
    ldapAttributeNameHelp: "Name of the LDAP attribute, which will be added to the new user during registration",
    ldapAttributeValueHelp: "Value of the LDAP attribute, which will be added to the new user during registration. You can either hardcode any value like 'foo' but you can also use some special tokens. Only supported token right now is '${RANDOM}', which will be replaced with some randomly generated string."
  }
};

// build/identity-providers/messages.js
var messages_default13 = {
  "identity-providers": {
    listExplain: "Through Identity Brokering it's easy to allow users to authenticate to Keycloak using external Identity Provider or Social Networks.",
    searchForProvider: "Search for provider",
    providerDetails: "Provider details",
    addProvider: "Add provider",
    addMapper: "Add mapper",
    addIdPMapper: "Add {{providerId}} Identity Provider Mapper",
    editIdPMapper: "Edit {{providerId}} Identity Provider Mapper",
    mappersList: "Mappers list",
    noMappers: "No Mappers",
    noMappersInstructions: "There are currently no mappers for this identity provider.",
    searchForMapper: "Search for mapper",
    addKeycloakOpenIdProvider: "Add Keycloak OpenID Connect provider",
    addOpenIdProvider: "Add OpenID Connect provider",
    addSamlProvider: "Add SAML provider",
    manageDisplayOrder: "Manage display order",
    deleteProvider: "Delete provider?",
    deleteProviderMapper: "Delete mapper?",
    deleteConfirm: "Are you sure you want to permanently delete the provider '{{provider}}'?",
    deleteMapperConfirm: "Are you sure you want to permanently delete the mapper {{mapper}}?",
    deleteMapperSuccess: "Mapper successfully deleted.",
    deletedSuccess: "Provider successfully deleted.",
    deleteError: "Could not delete the provider {{error}}",
    disableProvider: "Disable provider?",
    disableConfirm: "Are you sure you want to disable the provider '{{provider}}'",
    disableSuccess: "Provider successfully disabled",
    disableError: "Could not disable the provider {{error}}",
    updateSuccess: "Provider successfully updated",
    updateError: "Could not update the provider {{error}}",
    getStarted: "To get started, select a provider from the list below.",
    addIdentityProvider: "Add {{provider}} provider",
    redirectURI: "Redirect URI",
    clientId: "Client ID",
    clientSecret: "Client Secret",
    displayOrder: "Display order",
    createSuccess: "Identity provider successfully created",
    createError: "Could not create the identity provider: {{error}}",
    oderDialogIntro: "The order that the providers are listed in the login page or the account console. You can drag the row handles to change the order.",
    manageOrderTableAria: "List of identity providers in the order listed on the login page",
    manageOrderItemAria: "Press space or enter to begin dragging, and use the arrow keys to navigate up or down. Press enter to confirm the drag, or any other key to cancel the drag operation.",
    orderChangeSuccess: "Successfully changed display order of identity providers",
    orderChangeError: "Could not change display order of identity providers {{error}}",
    alias: "Alias",
    displayName: "Display name",
    useDiscoveryEndpoint: "Use discovery endpoint",
    discoveryEndpoint: "Discovery endpoint",
    useEntityDescriptor: "Use entity descriptor",
    samlEntityDescriptor: "SAML entity descriptor",
    ssoServiceUrl: "Single Sign-On service URL",
    singleLogoutServiceUrl: "Single logout service URL",
    nameIdPolicyFormat: "NameID policy format",
    persistent: "Persistent",
    transient: "Transient",
    email: "Email",
    kerberos: "Kerberos",
    x509: "X.509 Subject Name",
    windowsDomainQN: "Windows Domain Qualified Name",
    unspecified: "Unspecified",
    principalType: "Principal type",
    principalAttribute: "Principal attribute",
    allowCreate: "Allow create",
    subjectNameId: "Subject NameID",
    attributeName: "Attribute [Name]",
    attributeFriendlyName: "Attribute [Friendly Name]",
    claim: "Claim",
    claimValue: "Claim Value",
    claims: "Claims",
    socialProfileJSONFieldPath: "Social Profile JSON Field Path",
    mapperAttributeName: "Attribute Name",
    mapperUserAttributeName: "User Attribute Name",
    mapperAttributeFriendlyName: "Friendly name",
    httpPostBindingResponse: "HTTP-POST binding response",
    httpPostBindingAuthnRequest: "HTTP-POST binding for AuthnRequest",
    httpPostBindingLogout: "HTTP-POST binding logout",
    wantAuthnRequestsSigned: "Want AuthnRequests signed",
    signatureAlgorithm: "Signature algorithm",
    samlSignatureKeyName: "SAML signature key name",
    wantAssertionsSigned: "Want Assertions signed",
    wantAssertionsEncrypted: "Want Assertions encrypted",
    forceAuthentication: "Force authentication",
    validatingX509Certs: "Validating X509 certificates",
    signServiceProviderMetadata: "Sign service provider metadata",
    passSubject: "Pass subject",
    serviceProviderEntityId: "Service provider entity ID",
    importConfig: "Import config from file",
    showMetaData: "Show metadata",
    hideMetaData: "Hide metadata",
    noValidMetaDataFound: "No valid metadata was found at this URL",
    advanced: "Advanced",
    metadataOfDiscoveryEndpoint: "Metadata of the discovery endpoint",
    authorizationUrl: "Authorization URL",
    passLoginHint: "Pass login_hint",
    passCurrentLocale: "Pass current locale",
    tokenUrl: "Token URL",
    logoutUrl: "Logout URL",
    backchannelLogout: "Backchannel logout",
    disableUserInfo: "Disable user info",
    userInfoUrl: "User Info URL",
    issuer: "Issuer",
    scopes: "Scopes",
    prompt: "Prompt",
    prompts: {
      unspecified: "Unspecified",
      none: "None",
      consent: "Consent",
      login: "Login",
      select_account: "Select account"
    },
    clientAuthentication: "Client authentication",
    clientAuthentications: {
      clientAuth_post: "Client secret sent as post",
      clientAuth_basic: "Client secret sent as basic auth",
      clientAuth_secret_jwt: "Client secret as jwt",
      clientAuth_privatekey_jwt: "JWT signed with private key"
    },
    acceptsPromptNone: "Accepts prompt=none forward from client",
    validateSignature: "Validate Signatures",
    useJwksUrl: "Use JWKS URL",
    jwksUrl: "JWKS URL",
    allowedClockSkew: "Allowed clock skew",
    attributeConsumingServiceIndex: "Attribute Consuming Service Index",
    attributeConsumingServiceName: "Attribute Consuming Service Name",
    forwardParameters: "Forwarded query parameters",
    generalSettings: "General settings",
    oidcSettings: "OpenID Connect settings",
    samlSettings: "SAML settings",
    advancedSettings: "Advanced settings",
    reqAuthnConstraints: "Requested AuthnContext Constraints",
    keyID: "KEY_ID",
    NONE: "NONE",
    certSubject: "CERT_SUBJECT",
    storeTokens: "Store tokens",
    storedTokensReadable: "Stored tokens readable",
    comparison: "Comparison",
    authnContextClassRefs: "AuthnContext ClassRefs",
    authnContextDeclRefs: "AuthnContext DeclRefs",
    trustEmail: "Trust Email",
    accountLinkingOnly: "Account linking only",
    hideOnLoginPage: "Hide on login page",
    firstBrokerLoginFlowAlias: "First login flow",
    postBrokerLoginFlowAlias: "Post login flow",
    syncMode: "Sync mode",
    syncModes: {
      inherit: "Inherit",
      import: "Import",
      legacy: "Legacy",
      force: "Force"
    },
    syncModeOverride: "Sync mode override",
    mapperType: "Mapper type",
    regexAttributeValues: "Regex Attribute Values",
    regexClaimValues: "Regex Claim Values",
    selectRole: "Select role",
    mapperCreateSuccess: "Mapper created successfully.",
    mapperCreateError: "Error creating mapper.",
    mapperSaveSuccess: "Mapper saved successfully.",
    mapperSaveError: "Error saving mapper: {{error}}",
    userAttribute: "User Attribute",
    attributeValue: "Attribute Value",
    userAttributeValue: "User Attribute Value",
    userSessionAttribute: "User Session Attribute",
    userSessionAttributeValue: "User Session Attribute Value",
    template: "Template",
    target: "Target",
    targetOptions: {
      local: "LOCAL",
      brokerId: "BROKER_ID",
      brokerUsername: "BROKER_USERNAME"
    }
  }
};

// build/identity-providers/help.js
var help_default7 = {
  "identity-providers-help": {
    redirectURI: "The redirect uri to use when configuring the identity provider.",
    alias: "The alias uniquely identifies an identity provider and it is also used to build the redirect uri.",
    displayName: "Friendly name for Identity Providers.",
    clientId: "The client identifier registered with the identity provider.",
    clientSecret: "The client secret registered with the identity provider. This field is able to obtain its value from vault, use ${vault.ID} format.",
    displayOrder: "Number defining the order of the providers in GUI (for example, on the Login page). The lowest number will be applied first.",
    useDiscoveryEndpoint: "If this setting is enabled, the discovery endpoint will be used to fetch the provider config. Keycloak can load the config from the endpoint and automatically update the config if the source has any updates",
    discoveryEndpoint: "Import metadata from a remote IDP discovery descriptor.",
    importConfig: "Import metadata from a downloaded IDP discovery descriptor.",
    passLoginHint: "Pass login_hint to identity provider.",
    passCurrentLocale: "Pass the current locale to the identity provider as a ui_locales parameter.",
    logoutUrl: "End session endpoint to use to logout user from external IDP.",
    backchannelLogout: "Does the external IDP support backchannel logout?",
    disableUserInfo: "Disable usage of User Info service to obtain additional user information?  Default is to use this OIDC service.",
    userInfoUrl: "The User Info Url. This is optional.",
    issuer: "The issuer identifier for the issuer of the response. If not provided, no validation will be performed.",
    scopes: "The scopes to be sent when asking for authorization. It can be a space-separated list of scopes. Defaults to 'openid'.",
    prompt: "Specifies whether the Authorization Server prompts the End-User for re-authentication and consent.",
    acceptsPromptNone: "This is just used together with Identity Provider Authenticator or when kc_idp_hint points to this identity provider. In case that client sends a request with prompt=none and user is not yet authenticated, the error will not be directly returned to client, but the request with prompt=none will be forwarded to this identity provider.",
    validateSignature: "Enable/disable signature validation of external IDP signatures.",
    useJwksUrl: "If the switch is on, identity provider public keys will be downloaded from given JWKS URL. This allows great flexibility because new keys will be always re-downloaded again when identity provider generates new keypair. If the switch is off, public key (or certificate) from the Keycloak DB is used, so when the identity provider keypair changes, you always need to import the new key to the Keycloak DB as well.",
    jwksUrl: "URL where identity provider keys in JWK format are stored. See JWK specification for more details. If you use external Keycloak identity provider, you can use URL like 'http://broker-keycloak:8180/auth/realms/test/protocol/openid-connect/certs' assuming your brokered Keycloak is running on 'http://broker-keycloak:8180' and its realm is 'test' .",
    allowedClockSkew: "Clock skew in seconds that is tolerated when validating identity provider tokens. Default value is zero.",
    attributeConsumingServiceIndex: "Index of the Attribute Consuming Service profile to request during authentication.",
    attributeConsumingServiceName: "Name of the Attribute Consuming Service profile to advertise in the SP metadata.",
    forwardParameters: "Non OpenID Connect/OAuth standard query parameters to be forwarded to external IDP from the initial application request to Authorization Endpoint. Multiple parameters can be entered, separated by comma (,).",
    clientAuthentication: "The client authentication method (cfr. https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication). In case of JWT signed with private key, the realm private key is used.",
    storeTokens: "Enable/disable if tokens must be stored after authenticating users.",
    storedTokensReadable: "Enable/disable if new users can read any stored tokens. This assigns the broker.read-token role.",
    trustEmail: "If enabled, email provided by this provider is not verified even if verification is enabled for the realm.",
    accountLinkingOnly: "If true, users cannot log in through this provider.  They can only link to this provider.  This is useful if you don't want to allow login from the provider, but want to integrate with a provider",
    hideOnLoginPage: "If hidden, login with this provider is possible only if requested explicitly, for example using the 'kc_idp_hint' parameter.",
    firstBrokerLoginFlowAlias: "Alias of authentication flow, which is triggered after first login with this identity provider. Term 'First Login' means that no Keycloak account is currently linked to the authenticated identity provider account.",
    postBrokerLoginFlowAlias: 'Alias of authentication flow, which is triggered after each login with this identity provider. Useful if you want additional verification of each user authenticated with this identity provider (for example OTP). Leave this to "None" if you need no any additional authenticators to be triggered after login with this identity provider. Also note that authenticator implementations must assume that user is already set in ClientSession as identity provider already set it.',
    syncMode: "Default sync mode for all mappers. The sync mode determines when user data will be synced using the mappers. Possible values are: 'legacy' to keep the behaviour before this option was introduced, 'import' to only import the user once during first login of the user with this identity provider, 'force' to always update the user during every login with this identity provider.",
    serviceProviderEntityId: "The Entity ID that will be used to uniquely identify this SAML Service Provider.",
    useEntityDescriptor: "Import metadata from a remote IDP SAML entity descriptor.",
    samlEntityDescriptor: "Allows you to load external IDP metadata from a config file or to download it from a URL.",
    ssoServiceUrl: "The Url that must be used to send authentication requests (SAML AuthnRequest).",
    singleLogoutServiceUrl: "The Url that must be used to send logout requests.",
    nameIdPolicyFormat: "Specifies the URI reference corresponding to a name identifier format.",
    principalType: "Way to identify and track external users from the assertion. Default is using Subject NameID, alternatively you can set up identifying attribute.",
    principalAttribute: "Name or Friendly Name of the attribute used to identify external users.",
    allowCreate: "Allow the external identity provider to create a new identifier to represent the principal.",
    httpPostBindingResponse: "Indicates whether to respond to requests using HTTP-POST binding. If false, HTTP-REDIRECT binding will be used.",
    httpPostBindingAuthnRequest: "Indicates whether the AuthnRequest must be sent using HTTP-POST binding. If false, HTTP-REDIRECT binding will be used.",
    httpPostBindingLogout: "Indicates whether to respond to requests using HTTP-POST binding. If false, HTTP-REDIRECT binding will be used.",
    wantAuthnRequestsSigned: "Indicates whether the identity provider expects a signed AuthnRequest.",
    signatureAlgorithm: "The signature algorithm to use to sign documents.",
    samlSignatureKeyName: "Signed SAML documents contain identification of signing key in KeyName element. For Keycloak / RH-SSO counter-party, use KEY_ID, for MS AD FS use CERT_SUBJECT, for others check and use NONE if no other option works.",
    wantAssertionsSigned: "Indicates whether this service provider expects a signed Assertion.",
    wantAssertionsEncrypted: "Indicates whether this service provider expects an encrypted Assertion.",
    forceAuthentication: "Indicates whether the identity provider must authenticate the presenter directly rather than rely on a previous security context.",
    validateSignatures: "Enable/disable signature validation of SAML responses.",
    validatingX509Certs: "The certificate in PEM format that must be used to check for signatures. Multiple certificates can be entered, separated by comma (,).",
    signServiceProviderMetadata: "Enable/disable signature of the provider SAML metadata.",
    passSubject: "During login phase, forward an optional login_hint query parameter to SAML AuthnRequest's Subject.",
    comparison: 'Specifies the comparison method used to evaluate the requested context classes or statements. The default is "Exact".',
    authnContextClassRefs: "Ordered list of requested AuthnContext ClassRefs.",
    authnContextDeclRefs: "Ordered list of requested AuthnContext DeclRefs.",
    addIdpMapperName: "Name of the mapper.",
    syncModeOverride: "Overrides the default sync mode of the IDP for this mapper. Values are: 'legacy' to keep the behaviour before this option was introduced, 'import' to only import the user once during first login of the user with this identity provider, 'force' to always update the user during every login with this identity provider and 'inherit' to use the sync mode defined in the identity provider for this mapper.",
    advancedAttributeToRole: "If the set of attributes exists and can be matched, grant the user the specified realm or client role.",
    usernameTemplateImporter: "Format the username to import.",
    hardcodedUserSessionAttribute: "When a user is imported from a provider, hardcode a value to a specific user session attribute.",
    externalRoleToRole: "Looks for an external role in a keycloak access token. If external role exists, grant the user the specified realm or client role.",
    advancedClaimToRole: "If all claims exist, grant the user the specified realm or client role.",
    claimToRole: "If a claim exists, grant the user the specified realm or client role.",
    oidcAttributeImporter: "Import declared claim if it exists in ID, access token, or the claim set returned by the user profile endpoint into the specified user property or attribute.",
    attributeImporter: "Import declared SAML attribute if it exists in assertion into the specified user property or attribute.",
    hardcodedRole: "When user is imported from provider, hardcode a role mapping for it.",
    hardcodedAttribute: "When user is imported from provider, hardcode a value to a specific user attribute.",
    samlAttributeToRole: "If an attribute exists, grant the user the specified realm or client role.",
    template: "Template to use to format the username to import.  Substitutions are enclosed in ${}.  For example: '${ALIAS}.${CLAIM.sub}'.  ALIAS is the provider alias.  CLAIM.<NAME> references an ID or Access token claim. The substitution can be converted to upper or lower case by appending |uppercase or |lowercase to the substituted value, e.g. '${CLAIM.sub | lowercase}",
    target: "Destination field for the mapper. LOCAL (default) means that the changes are applied to the username stored in local database upon user import. BROKER_ID and BROKER_USERNAME means that the changes are stored into the ID or username used for federation user lookup, respectively.",
    userSessionAttribute: "Name of user session attribute you want to hardcode",
    userAttribute: "Name of user attribute you want to hardcode",
    claim: "Name of claim to search for in token. You can reference nested claims by using a '.', i.e. 'address.locality'. To use dot (.) literally, escape it with backslash. (\\.)",
    socialProfileJSONFieldPath: "Path of field in Social Provider User Profile JSON data to get value from. You can use dot notation for nesting and square brackets for array index. E.g. 'contact.address[0].country'.",
    userAttributeValue: "Value you want to hardcode",
    attributeName: "Name of attribute to search for in assertion. You can leave this blank and specify a friendly name instead.",
    friendlyName: "Friendly name of attribute to search for in assertion. You can leave this blank and specify a name instead.",
    userAttributeName: "User attribute name to store SAML attribute. Use email, lastName, and firstName to map to those predefined user properties.",
    socialUserAttributeName: "User attribute name to store information.",
    attributeValue: "Value the attribute must have. If the attribute is a list, then the value must be contained in the list.",
    attributes: "Name and (regex) value of the attributes to search for in token. The configured name of an attribute is searched in SAML attribute name and attribute friendly name fields. Every given attribute description must be met to set the role. If the attribute is an array, then the value must be contained in the array. If an attribute can be found several times, then one match is sufficient.",
    regexAttributeValues: "If enabled attribute values are interpreted as regular expressions.",
    role: "Role to grant to user if all attributes are present. Click 'Select Role' button to browse roles, or just type it in the textbox. To reference a client role the syntax is clientname.clientrole, i.e. myclient.myrole"
  }
};

// build/components/dynamic/labels.js
var labels_default = {
  dynamic: {
    addMultivaluedLabel: "Add {{fieldLabel}}",
    selectARole: "Select a role",
    selectASourceOfRoles: "Select a source of roles",
    clientRoles: "Client roles",
    roleGroup: "Use a realm role from:",
    clientGroup: "Use a client role from:",
    selectGroup: "Select group",
    usermodel: {
      prop: {
        label: "Property",
        tooltip: "Name of the property method in the UserModel interface. For example, a value of 'email' would reference the UserModel.getEmail() method."
      },
      attr: {
        label: "User Attribute",
        tooltip: "Name of stored user attribute which is the name of an attribute within the UserModel.attribute map."
      },
      clientRoleMapping: {
        clientId: {
          label: "Client ID",
          tooltip: "Client ID for role mappings. Just client roles of this client will be added to the token. If this is unset, client roles of all clients will be added to the token."
        },
        rolePrefix: {
          label: "Client Role prefix",
          tooltip: "A prefix for each client role (optional)."
        },
        tokenClaimName: {
          tooltip: "Name of the claim to insert into the token. This can be a fully qualified name like 'address.street'. In this case, a nested json object will be created. To prevent nesting and use dot literally, escape the dot with backslash (\\.). The special token ${client_id} can be used and this will be replaced by the actual client ID. Example usage is 'resource_access.${client_id}.roles'. This is useful especially when you are adding roles from all the clients (Hence 'Client ID' switch is unset) and you want client roles of each client stored separately."
        }
      },
      realmRoleMapping: {
        rolePrefix: {
          label: "Realm Role prefix",
          tooltip: "A prefix for each Realm Role (optional)."
        }
      }
    },
    userSession: {
      modelNote: {
        label: "User Session Note",
        tooltip: "Name of stored user session note within the UserSessionModel.note map."
      }
    },
    multivalued: {
      label: "Multivalued",
      tooltip: "Indicates if attribute supports multiple values. If true, the list of all values of this attribute will be set as claim. If false, just first value will be set as claim"
    },
    aggregate: {
      attrs: {
        label: "Aggregate attribute values",
        tooltip: "Indicates if attribute values should be aggregated with the group attributes. If using OpenID Connect mapper the multivalued option needs to be enabled too in order to get all the values. Duplicated values are discarded and the order of values is not guaranteed with this option."
      }
    },
    selectRole: {
      label: "Select Role",
      tooltip: "Enter role in the textbox to the left, or click this button to browse and select the role you want."
    },
    tokenClaimName: {
      label: "Token Claim Name",
      tooltip: "Name of the claim to insert into the token. This can be a fully qualified name like 'address.street'. In this case, a nested json object will be created. To prevent nesting and use dot literally, escape the dot with backslash (\\.)."
    },
    jsonType: {
      label: "Claim JSON Type",
      tooltip: "JSON type that should be used to populate the json claim in the token. long, int, boolean, String and JSON are valid values."
    },
    includeInIdToken: {
      label: "Add to ID token",
      tooltip: "Should the claim be added to the ID token?"
    },
    includeInAccessToken: {
      label: "Add to access token",
      tooltip: "Should the claim be added to the access token?"
    },
    includeInUserInfo: {
      label: "Add to userinfo",
      tooltip: "Should the claim be added to the userinfo?"
    },
    sectorIdentifierUri: {
      label: "Sector Identifier URI",
      tooltip: "Providers that use pairwise sub values and support Dynamic Client Registration SHOULD use the sector_identifier_uri parameter. It provides a way for a group of websites under common administrative control to have consistent pairwise sub values independent of the individual domain names. It also provides a way for Clients to change redirect_uri domains without having to reregister all their users."
    },
    pairwiseSubAlgorithmSalt: {
      label: "Salt",
      tooltip: "Salt used when calculating the pairwise subject identifier. If left blank, a salt will be generated."
    },
    addressClaim: {
      street: {
        label: "User Attribute Name for Street",
        tooltip: "Name of User Attribute, which will be used to map to 'street_address' subclaim inside 'address' token claim. Defaults to 'street' ."
      },
      locality: {
        label: "User Attribute Name for Locality",
        tooltip: "Name of User Attribute, which will be used to map to 'locality' subclaim inside 'address' token claim. Defaults to 'locality' ."
      },
      region: {
        label: "User Attribute Name for Region",
        tooltip: "Name of User Attribute, which will be used to map to 'region' subclaim inside 'address' token claim. Defaults to 'region' ."
      },
      postal_code: {
        label: "User Attribute Name for Postal Code",
        tooltip: "Name of User Attribute, which will be used to map to 'postal_code' subclaim inside 'address' token claim. Defaults to 'postal_code' ."
      },
      country: {
        label: "User Attribute Name for Country",
        tooltip: "Name of User Attribute, which will be used to map to 'country' subclaim inside 'address' token claim. Defaults to 'country' ."
      },
      formatted: {
        label: "User Attribute Name for Formatted Address",
        tooltip: "Name of User Attribute, which will be used to map to 'formatted' subclaim inside 'address' token claim. Defaults to 'formatted' ."
      }
    },
    included: {
      client: {
        audience: {
          label: "Included Client Audience",
          tooltip: "The Client ID of the specified audience client will be included in audience (aud) field of the token. If there are existing audiences in the token, the specified value is just added to them. It won't override existing audiences."
        }
      },
      custom: {
        audience: {
          label: "Included Custom Audience",
          tooltip: "This is used just if 'Included Client Audience' is not filled. The specified value will be included in audience (aud) field of the token. If there are existing audiences in the token, the specified value is just added to them. It won't override existing audiences."
        }
      }
    },
    "name-id-format": "Name ID Format",
    mapper: {
      nameid: {
        format: {
          tooltip: "Name ID Format using Mapper"
        }
      }
    },
    "client-scopes-condition": {
      label: "Expected Scopes",
      tooltip: "The list of expected client scopes. Condition evaluates to true if specified client request matches some of the client scopes. It depends also whether it should be default or optional client scope based on the 'Scope Type' configured."
    },
    "client-accesstype": {
      label: "Client Access Type",
      tooltip: "Access Type of the client, for which the condition will be applied."
    },
    "client-roles": {
      label: "Client Roles"
    },
    "client-roles-condition": {
      tooltip: "Client roles, which will be checked during this condition evaluation. Condition evaluates to true if client has at least one client role with the name as the client roles specified in the configuration."
    },
    "client-updater-source-groups": {
      label: "Groups",
      tooltip: "Name of groups to check. Condition evaluates to true if the entity, who creates/updates client is member of some of the specified groups. Configured groups are specified by their simple name, which must match to the name of the Keycloak group. No support for group hierarchy is used here."
    },
    "client-updater-trusted-hosts": {
      label: "Trusted hosts",
      tooltip: "List of Hosts, which are trusted. In case that client registration/update request comes from the host/domain specified in this configuration, condition evaluates to true. You can use hostnames or IP addresses. If you use star at the beginning (for example '*.example.com' ) then whole domain example.com will be trusted."
    },
    "client-updater-source-roles": {
      label: "Updating entity role",
      tooltip: "The condition is checked during client registration/update requests and it evaluates to true if the entity (usually user), who is creating/updating client is member of the specified role. For reference the realm role, you can use the realm role name like 'my_realm_role' . For reference client role, you can use the client_id.role_name for example 'my_client.my_client_role' will refer to client role 'my_client_role' of client 'my_client'."
    }
  }
};

// build/i18n.js
var DEFAULT_LOCALE = "en";
var initOptions = {
  defaultNS: "common",
  resources: {
    en: {
      ...common_messages_default,
      ...common_help_default,
      ...messages_default,
      ...messages_default2,
      ...help_default,
      ...messages_default3,
      ...help_default2,
      ...messages_default4,
      ...messages_default5,
      ...messages_default6,
      ...messages_default4,
      ...messages_default7,
      ...help_default3,
      ...messages_default8,
      ...messages_default12,
      ...messages_default9,
      ...messages_default10,
      ...help_default4,
      ...messages_default11,
      ...help_default5,
      ...messages_default13,
      ...help_default7,
      ...messages_default12,
      ...help_default6,
      ...labels_default
    }
  },
  lng: DEFAULT_LOCALE,
  fallbackLng: DEFAULT_LOCALE,
  interpolation: {
    escapeValue: false
  }
};
i18next_default.use(initReactI18next).init(initOptions);
var i18n_default = i18next_default;

// build/context/whoami/WhoAmI.js
var WhoAmI = class {
  constructor(me2) {
    this.me = me2;
    if (this.me?.locale) {
      i18n_default.changeLanguage(this.me.locale, (error2) => {
        if (error2)
          console.error("Unable to set locale to", this.me?.locale);
      });
    }
  }
  getDisplayName() {
    if (this.me === void 0)
      return "";
    return this.me.displayName;
  }
  getLocale() {
    return this.me?.locale ?? DEFAULT_LOCALE;
  }
  getRealm() {
    return this.me?.realm ?? "";
  }
  getUserId() {
    if (this.me === void 0)
      return "";
    return this.me.userId;
  }
  canCreateRealm() {
    return !!this.me?.createRealm;
  }
  getRealmAccess() {
    if (this.me === void 0)
      return {};
    return this.me.realm_access;
  }
};
var WhoAmIContext = react.createContext(void 0);
var useWhoAmI = () => useRequiredContext(WhoAmIContext);
var WhoAmIContextProvider = ({children: children2}) => {
  const adminClient = useAdminClient();
  const [whoAmI2, setWhoAmI] = useState(new WhoAmI());
  const [key, setKey] = useState(0);
  useFetch(() => adminClient.whoAmI.find({realm: environment_default.loginRealm}), (me2) => {
    const whoAmI22 = new WhoAmI(me2);
    setWhoAmI(whoAmI22);
  }, [key]);
  return /* @__PURE__ */ react.createElement(WhoAmIContext.Provider, {
    value: {refresh: () => setKey(key + 1), whoAmI: whoAmI2}
  }, children2);
};

// build/PageHeader.js
var Header = () => {
  const {realm: realm2} = useRealm();
  const adminClient = useAdminClient();
  const {t: t5} = useTranslation();
  const ManageAccountDropdownItem = () => adminClient.keycloak ? /* @__PURE__ */ react.createElement(DropdownItem, {
    key: "manage account",
    id: "manage-account",
    onClick: () => adminClient.keycloak?.accountManagement()
  }, t5("manageAccount")) : null;
  const SignOutDropdownItem = () => adminClient.keycloak ? /* @__PURE__ */ react.createElement(DropdownItem, {
    id: "sign-out",
    key: "sign out",
    onClick: () => adminClient.keycloak?.logout({redirectUri: ""})
  }, t5("signOut")) : null;
  const ServerInfoDropdownItem = () => {
    const {realm: realm22} = useRealm();
    const {t: t22} = useTranslation();
    return /* @__PURE__ */ react.createElement(DropdownItem, {
      key: "server info",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toDashboard({realm: realm22})
      })
    }, t22("realmInfo"));
  };
  const HelpDropdownItem = () => {
    const {t: t22} = useTranslation();
    const {enabled, toggleHelp} = useHelp();
    return /* @__PURE__ */ react.createElement(DropdownItem, {
      icon: /* @__PURE__ */ react.createElement(HelpIcon, null),
      onClick: toggleHelp
    }, enabled ? t22("helpEnabled") : t22("helpDisabled"));
  };
  const kebabDropdownItems = [
    /* @__PURE__ */ react.createElement(ManageAccountDropdownItem, {
      key: "kebab Manage Account"
    }),
    /* @__PURE__ */ react.createElement(ServerInfoDropdownItem, {
      key: "kebab Server Info"
    }),
    /* @__PURE__ */ react.createElement(HelpDropdownItem, {
      key: "kebab Help"
    }),
    /* @__PURE__ */ react.createElement(DropdownSeparator, {
      key: "kebab sign out separator"
    }),
    /* @__PURE__ */ react.createElement(SignOutDropdownItem, {
      key: "kebab Sign out"
    })
  ];
  const userDropdownItems = [
    /* @__PURE__ */ react.createElement(ManageAccountDropdownItem, {
      key: "Manage Account"
    }),
    /* @__PURE__ */ react.createElement(ServerInfoDropdownItem, {
      key: "Server info"
    }),
    /* @__PURE__ */ react.createElement(DropdownSeparator, {
      key: "sign out separator"
    }),
    /* @__PURE__ */ react.createElement(SignOutDropdownItem, {
      key: "Sign out"
    })
  ];
  const headerTools = () => {
    return /* @__PURE__ */ react.createElement(PageHeaderTools, null, /* @__PURE__ */ react.createElement(PageHeaderToolsGroup, {
      visibility: {
        default: "hidden",
        md: "visible"
      }
    }, /* @__PURE__ */ react.createElement(PageHeaderToolsItem, null, /* @__PURE__ */ react.createElement(HelpHeader, null))), /* @__PURE__ */ react.createElement(PageHeaderToolsGroup, null, /* @__PURE__ */ react.createElement(PageHeaderToolsItem, {
      visibility: {
        md: "hidden"
      }
    }, /* @__PURE__ */ react.createElement(KebabDropdown, null)), /* @__PURE__ */ react.createElement(PageHeaderToolsItem, {
      visibility: {
        default: "hidden",
        md: "visible"
      }
    }, /* @__PURE__ */ react.createElement(UserDropdown, null))), /* @__PURE__ */ react.createElement(Avatar, {
      src: environment_default.resourceUrl + "/img_avatar.svg",
      alt: "Avatar image"
    }));
  };
  const KebabDropdown = () => {
    const [isDropdownOpen, setDropdownOpen] = useState(false);
    return /* @__PURE__ */ react.createElement(Dropdown, {
      id: "user-dropdown-kebab",
      isPlain: true,
      position: "right",
      toggle: /* @__PURE__ */ react.createElement(KebabToggle, {
        onToggle: setDropdownOpen
      }),
      isOpen: isDropdownOpen,
      dropdownItems: kebabDropdownItems
    });
  };
  const UserDropdown = () => {
    const {whoAmI: whoAmI2} = useWhoAmI();
    const [isDropdownOpen, setDropdownOpen] = useState(false);
    return /* @__PURE__ */ react.createElement(Dropdown, {
      isPlain: true,
      position: "right",
      id: "user-dropdown",
      isOpen: isDropdownOpen,
      toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
        onToggle: setDropdownOpen
      }, whoAmI2.getDisplayName()),
      dropdownItems: userDropdownItems
    });
  };
  return /* @__PURE__ */ react.createElement(PageHeader, {
    showNavToggle: true,
    logo: /* @__PURE__ */ react.createElement(Link, {
      to: toDashboard({realm: realm2})
    }, /* @__PURE__ */ react.createElement(Brand, {
      src: environment_default.resourceUrl + "/logo.svg",
      id: "masthead-logo",
      alt: "Logo",
      className: "keycloak__pageheader_brand"
    })),
    logoComponent: "div",
    headerTools: headerTools()
  });
};

// build/context/RealmsContext.js
var RealmsContext = createContext(void 0);
var RealmsProvider = ({children: children2}) => {
  const adminClient = useAdminClient();
  const [realms2, setRealms] = useState([]);
  const recentUsed = useMemo(() => new RecentUsed(), []);
  function updateRealms(realms22) {
    setRealms(sortBy(realms22, "realm"));
    recentUsed.clean(realms22.map(({realm: realm2}) => realm2));
  }
  useFetch(() => adminClient.realms.find(), (realms22) => updateRealms(realms22), []);
  const refresh = useCallback(async () => {
    await adminClient.keycloak?.updateToken(Number.MAX_VALUE);
    updateRealms(await adminClient.realms.find());
  }, []);
  const value = useMemo(() => ({realms: realms2, refresh}), [realms2, refresh]);
  return /* @__PURE__ */ react.createElement(RealmsContext.Provider, {
    value
  }, children2);
};
var useRealms = () => useRequiredContext(RealmsContext);

// build/_snowpack/pkg/react-hook-form.js
var isHTMLElement2 = (value) => value instanceof HTMLElement;
var EVENTS = {
  BLUR: "blur",
  CHANGE: "change",
  INPUT: "input"
};
var VALIDATION_MODE = {
  onBlur: "onBlur",
  onChange: "onChange",
  onSubmit: "onSubmit",
  onTouched: "onTouched",
  all: "all"
};
var SELECT = "select";
var UNDEFINED = "undefined";
var INPUT_VALIDATION_RULES = {
  max: "max",
  min: "min",
  maxLength: "maxLength",
  minLength: "minLength",
  pattern: "pattern",
  required: "required",
  validate: "validate"
};
function attachEventListeners({ref}, shouldAttachChangeEvent, handleChange) {
  if (isHTMLElement2(ref) && handleChange) {
    ref.addEventListener(shouldAttachChangeEvent ? EVENTS.CHANGE : EVENTS.INPUT, handleChange);
    ref.addEventListener(EVENTS.BLUR, handleChange);
  }
}
var isNullOrUndefined = (value) => value == null;
var isObjectType = (value) => typeof value === "object";
var isObject2 = (value) => !isNullOrUndefined(value) && !Array.isArray(value) && isObjectType(value) && !(value instanceof Date);
var isKey = (value) => /^\w*$/.test(value);
var compact = (value) => value.filter(Boolean);
var stringToPath = (input) => compact(input.replace(/["|']/g, "").replace(/\[/g, ".").replace(/\]/g, "").split("."));
function set(object, path, value) {
  let index3 = -1;
  const tempPath = isKey(path) ? [path] : stringToPath(path);
  const length = tempPath.length;
  const lastIndex = length - 1;
  while (++index3 < length) {
    const key = tempPath[index3];
    let newValue = value;
    if (index3 !== lastIndex) {
      const objValue = object[key];
      newValue = isObject2(objValue) || Array.isArray(objValue) ? objValue : !isNaN(+tempPath[index3 + 1]) ? [] : {};
    }
    object[key] = newValue;
    object = object[key];
  }
  return object;
}
var transformToNestObject = (data2, value = {}) => {
  for (const key in data2) {
    !isKey(key) ? set(value, key, data2[key]) : value[key] = data2[key];
  }
  return value;
};
var isUndefined2 = (val) => val === void 0;
var get3 = (obj = {}, path, defaultValue) => {
  const result = compact(path.split(/[,[\].]+?/)).reduce((result2, key) => isNullOrUndefined(result2) ? result2 : result2[key], obj);
  return isUndefined2(result) || result === obj ? isUndefined2(obj[path]) ? defaultValue : obj[path] : result;
};
var focusOnErrorField = (fields, fieldErrors) => {
  for (const key in fields) {
    if (get3(fieldErrors, key)) {
      const field = fields[key];
      if (field) {
        if (field.ref.focus && isUndefined2(field.ref.focus())) {
          break;
        } else if (field.options) {
          field.options[0].ref.focus();
          break;
        }
      }
    }
  }
};
var removeAllEventListeners = (ref, validateWithStateUpdate) => {
  if (isHTMLElement2(ref) && ref.removeEventListener) {
    ref.removeEventListener(EVENTS.INPUT, validateWithStateUpdate);
    ref.removeEventListener(EVENTS.CHANGE, validateWithStateUpdate);
    ref.removeEventListener(EVENTS.BLUR, validateWithStateUpdate);
  }
};
var defaultReturn = {
  isValid: false,
  value: null
};
var getRadioValue = (options) => Array.isArray(options) ? options.reduce((previous, option) => option && option.ref.checked ? {
  isValid: true,
  value: option.ref.value
} : previous, defaultReturn) : defaultReturn;
var getMultipleSelectValue = (options) => [...options].filter(({selected}) => selected).map(({value}) => value);
var isRadioInput = (element) => element.type === "radio";
var isFileInput = (element) => element.type === "file";
var isCheckBoxInput = (element) => element.type === "checkbox";
var isMultipleSelect = (element) => element.type === `${SELECT}-multiple`;
var defaultResult = {
  value: false,
  isValid: false
};
var validResult = {value: true, isValid: true};
var getCheckboxValue = (options) => {
  if (Array.isArray(options)) {
    if (options.length > 1) {
      const values2 = options.filter((option) => option && option.ref.checked).map(({ref: {value: value2}}) => value2);
      return {value: values2, isValid: !!values2.length};
    }
    const {checked, value, attributes} = options[0].ref;
    return checked ? attributes && !isUndefined2(attributes.value) ? isUndefined2(value) || value === "" ? validResult : {value, isValid: true} : validResult : defaultResult;
  }
  return defaultResult;
};
function getFieldValue(fieldsRef, name, shallowFieldsStateRef, excludeDisabled, shouldKeepRawValue) {
  const field = fieldsRef.current[name];
  if (field) {
    const {ref: {value, disabled}, ref, valueAsNumber, valueAsDate, setValueAs} = field;
    if (disabled && excludeDisabled) {
      return;
    }
    if (isFileInput(ref)) {
      return ref.files;
    }
    if (isRadioInput(ref)) {
      return getRadioValue(field.options).value;
    }
    if (isMultipleSelect(ref)) {
      return getMultipleSelectValue(ref.options);
    }
    if (isCheckBoxInput(ref)) {
      return getCheckboxValue(field.options).value;
    }
    return shouldKeepRawValue ? value : valueAsNumber ? value === "" ? NaN : +value : valueAsDate ? ref.valueAsDate : setValueAs ? setValueAs(value) : value;
  }
  if (shallowFieldsStateRef) {
    return get3(shallowFieldsStateRef.current, name);
  }
}
function isDetached(element) {
  if (!element) {
    return true;
  }
  if (!(element instanceof HTMLElement) || element.nodeType === Node.DOCUMENT_NODE) {
    return false;
  }
  return isDetached(element.parentNode);
}
var isEmptyObject = (value) => isObject2(value) && !Object.keys(value).length;
var isBoolean = (value) => typeof value === "boolean";
function baseGet(object, updatePath) {
  const length = updatePath.slice(0, -1).length;
  let index3 = 0;
  while (index3 < length) {
    object = isUndefined2(object) ? index3++ : object[updatePath[index3++]];
  }
  return object;
}
function unset(object, path) {
  const updatePath = isKey(path) ? [path] : stringToPath(path);
  const childObject = updatePath.length == 1 ? object : baseGet(object, updatePath);
  const key = updatePath[updatePath.length - 1];
  let previousObjRef;
  if (childObject) {
    delete childObject[key];
  }
  for (let k2 = 0; k2 < updatePath.slice(0, -1).length; k2++) {
    let index3 = -1;
    let objectRef;
    const currentPaths = updatePath.slice(0, -(k2 + 1));
    const currentPathsLength = currentPaths.length - 1;
    if (k2 > 0) {
      previousObjRef = object;
    }
    while (++index3 < currentPaths.length) {
      const item = currentPaths[index3];
      objectRef = objectRef ? objectRef[item] : object[item];
      if (currentPathsLength === index3 && (isObject2(objectRef) && isEmptyObject(objectRef) || Array.isArray(objectRef) && !objectRef.filter((data2) => isObject2(data2) && !isEmptyObject(data2) || isBoolean(data2)).length)) {
        previousObjRef ? delete previousObjRef[item] : delete object[item];
      }
      previousObjRef = objectRef;
    }
  }
  return object;
}
var isSameRef = (fieldValue, ref) => fieldValue && fieldValue.ref === ref;
function findRemovedFieldAndRemoveListener(fieldsRef, handleChange, field, shallowFieldsStateRef, shouldUnregister, forceDelete) {
  const {ref, ref: {name}} = field;
  const fieldRef = fieldsRef.current[name];
  if (!shouldUnregister) {
    const value = getFieldValue(fieldsRef, name, shallowFieldsStateRef);
    !isUndefined2(value) && set(shallowFieldsStateRef.current, name, value);
  }
  if (!ref.type || !fieldRef) {
    delete fieldsRef.current[name];
    return;
  }
  if (isRadioInput(ref) || isCheckBoxInput(ref)) {
    if (Array.isArray(fieldRef.options) && fieldRef.options.length) {
      compact(fieldRef.options).forEach((option = {}, index3) => {
        if (isDetached(option.ref) && isSameRef(option, option.ref) || forceDelete) {
          removeAllEventListeners(option.ref, handleChange);
          unset(fieldRef.options, `[${index3}]`);
        }
      });
      if (fieldRef.options && !compact(fieldRef.options).length) {
        delete fieldsRef.current[name];
      }
    } else {
      delete fieldsRef.current[name];
    }
  } else if (isDetached(ref) && isSameRef(fieldRef, ref) || forceDelete) {
    removeAllEventListeners(ref, handleChange);
    delete fieldsRef.current[name];
  }
}
var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
function deepMerge(target, source2) {
  if (isPrimitive(target) || isPrimitive(source2)) {
    return source2;
  }
  for (const key in source2) {
    const targetValue = target[key];
    const sourceValue = source2[key];
    try {
      target[key] = isObject2(targetValue) && isObject2(sourceValue) || Array.isArray(targetValue) && Array.isArray(sourceValue) ? deepMerge(targetValue, sourceValue) : sourceValue;
    } catch (_a) {
    }
  }
  return target;
}
function deepEqual(object1, object2, isErrorObject) {
  if (isPrimitive(object1) || isPrimitive(object2) || object1 instanceof Date || object2 instanceof Date) {
    return object1 === object2;
  }
  if (!react.isValidElement(object1)) {
    const keys1 = Object.keys(object1);
    const keys2 = Object.keys(object2);
    if (keys1.length !== keys2.length) {
      return false;
    }
    for (const key of keys1) {
      const val1 = object1[key];
      if (!(isErrorObject && key === "ref")) {
        const val2 = object2[key];
        if ((isObject2(val1) || Array.isArray(val1)) && (isObject2(val2) || Array.isArray(val2)) ? !deepEqual(val1, val2, isErrorObject) : val1 !== val2) {
          return false;
        }
      }
    }
  }
  return true;
}
function setDirtyFields(values2, defaultValues2, dirtyFields, parentNode, parentName) {
  let index3 = -1;
  while (++index3 < values2.length) {
    for (const key in values2[index3]) {
      if (Array.isArray(values2[index3][key])) {
        !dirtyFields[index3] && (dirtyFields[index3] = {});
        dirtyFields[index3][key] = [];
        setDirtyFields(values2[index3][key], get3(defaultValues2[index3] || {}, key, []), dirtyFields[index3][key], dirtyFields[index3], key);
      } else {
        deepEqual(get3(defaultValues2[index3] || {}, key), values2[index3][key]) ? set(dirtyFields[index3] || {}, key) : dirtyFields[index3] = Object.assign(Object.assign({}, dirtyFields[index3]), {[key]: true});
      }
    }
    parentNode && !dirtyFields.length && delete parentNode[parentName];
  }
  return dirtyFields;
}
var setFieldArrayDirtyFields = (values2, defaultValues2, dirtyFields) => deepMerge(setDirtyFields(values2, defaultValues2, dirtyFields.slice(0, values2.length)), setDirtyFields(defaultValues2, values2, dirtyFields.slice(0, values2.length)));
var isString2 = (value) => typeof value === "string";
var getFieldsValues = (fieldsRef, shallowFieldsState, shouldUnregister, excludeDisabled, search2) => {
  const output2 = {};
  for (const name in fieldsRef.current) {
    if (isUndefined2(search2) || (isString2(search2) ? name.startsWith(search2) : Array.isArray(search2) && search2.find((data2) => name.startsWith(data2)))) {
      output2[name] = getFieldValue(fieldsRef, name, void 0, excludeDisabled);
    }
  }
  return shouldUnregister ? transformToNestObject(output2) : deepMerge(shallowFieldsState, transformToNestObject(output2));
};
var isErrorStateChanged = ({errors, name, error: error2, validFields, fieldsWithValidation}) => {
  const isValid = isUndefined2(error2);
  const previousError = get3(errors, name);
  return isValid && !!previousError || !isValid && !deepEqual(previousError, error2, true) || isValid && get3(fieldsWithValidation, name) && !get3(validFields, name);
};
var isRegex = (value) => value instanceof RegExp;
var getValueAndMessage = (validationData) => isObject2(validationData) && !isRegex(validationData) ? validationData : {
  value: validationData,
  message: ""
};
var isFunction2 = (value) => typeof value === "function";
var isMessage = (value) => isString2(value) || react.isValidElement(value);
function getValidateError(result, ref, type = "validate") {
  if (isMessage(result) || isBoolean(result) && !result) {
    return {
      type,
      message: isMessage(result) ? result : "",
      ref
    };
  }
}
var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria ? Object.assign(Object.assign({}, errors[name]), {types: Object.assign(Object.assign({}, errors[name] && errors[name].types ? errors[name].types : {}), {[type]: message || true})}) : {};
var validateField = async (fieldsRef, validateAllFieldCriteria, {ref, ref: {value}, options, required, maxLength, minLength, min: min2, max: max2, pattern, validate}, shallowFieldsStateRef) => {
  const name = ref.name;
  const error2 = {};
  const isRadio3 = isRadioInput(ref);
  const isCheckBox = isCheckBoxInput(ref);
  const isRadioOrCheckbox = isRadio3 || isCheckBox;
  const isEmpty3 = value === "";
  const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error2);
  const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
    const message = exceedMax ? maxLengthMessage : minLengthMessage;
    error2[name] = Object.assign({
      type: exceedMax ? maxType : minType,
      message,
      ref
    }, exceedMax ? appendErrorsCurry(maxType, message) : appendErrorsCurry(minType, message));
  };
  if (required && (!isRadio3 && !isCheckBox && (isEmpty3 || isNullOrUndefined(value)) || isBoolean(value) && !value || isCheckBox && !getCheckboxValue(options).isValid || isRadio3 && !getRadioValue(options).isValid)) {
    const {value: value2, message} = isMessage(required) ? {value: !!required, message: required} : getValueAndMessage(required);
    if (value2) {
      error2[name] = Object.assign({type: INPUT_VALIDATION_RULES.required, message, ref: isRadioOrCheckbox ? ((fieldsRef.current[name].options || [])[0] || {}).ref : ref}, appendErrorsCurry(INPUT_VALIDATION_RULES.required, message));
      if (!validateAllFieldCriteria) {
        return error2;
      }
    }
  }
  if ((!isNullOrUndefined(min2) || !isNullOrUndefined(max2)) && value !== "") {
    let exceedMax;
    let exceedMin;
    const maxOutput = getValueAndMessage(max2);
    const minOutput = getValueAndMessage(min2);
    if (!isNaN(value)) {
      const valueNumber = ref.valueAsNumber || parseFloat(value);
      if (!isNullOrUndefined(maxOutput.value)) {
        exceedMax = valueNumber > maxOutput.value;
      }
      if (!isNullOrUndefined(minOutput.value)) {
        exceedMin = valueNumber < minOutput.value;
      }
    } else {
      const valueDate = ref.valueAsDate || new Date(value);
      if (isString2(maxOutput.value)) {
        exceedMax = valueDate > new Date(maxOutput.value);
      }
      if (isString2(minOutput.value)) {
        exceedMin = valueDate < new Date(minOutput.value);
      }
    }
    if (exceedMax || exceedMin) {
      getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
      if (!validateAllFieldCriteria) {
        return error2;
      }
    }
  }
  if (isString2(value) && !isEmpty3 && (maxLength || minLength)) {
    const maxLengthOutput = getValueAndMessage(maxLength);
    const minLengthOutput = getValueAndMessage(minLength);
    const exceedMax = !isNullOrUndefined(maxLengthOutput.value) && value.length > maxLengthOutput.value;
    const exceedMin = !isNullOrUndefined(minLengthOutput.value) && value.length < minLengthOutput.value;
    if (exceedMax || exceedMin) {
      getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
      if (!validateAllFieldCriteria) {
        return error2;
      }
    }
  }
  if (isString2(value) && pattern && !isEmpty3) {
    const {value: patternValue, message} = getValueAndMessage(pattern);
    if (isRegex(patternValue) && !patternValue.test(value)) {
      error2[name] = Object.assign({
        type: INPUT_VALIDATION_RULES.pattern,
        message,
        ref
      }, appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message));
      if (!validateAllFieldCriteria) {
        return error2;
      }
    }
  }
  if (validate) {
    const fieldValue = getFieldValue(fieldsRef, name, shallowFieldsStateRef, false, true);
    const validateRef = isRadioOrCheckbox && options ? options[0].ref : ref;
    if (isFunction2(validate)) {
      const result = await validate(fieldValue);
      const validateError = getValidateError(result, validateRef);
      if (validateError) {
        error2[name] = Object.assign(Object.assign({}, validateError), appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message));
        if (!validateAllFieldCriteria) {
          return error2;
        }
      }
    } else if (isObject2(validate)) {
      let validationResult = {};
      for (const [key, validateFunction] of Object.entries(validate)) {
        if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
          break;
        }
        const validateResult = await validateFunction(fieldValue);
        const validateError = getValidateError(validateResult, validateRef, key);
        if (validateError) {
          validationResult = Object.assign(Object.assign({}, validateError), appendErrorsCurry(key, validateError.message));
          if (validateAllFieldCriteria) {
            error2[name] = validationResult;
          }
        }
      }
      if (!isEmptyObject(validationResult)) {
        error2[name] = Object.assign({ref: validateRef}, validationResult);
        if (!validateAllFieldCriteria) {
          return error2;
        }
      }
    }
  }
  return error2;
};
var getPath2 = (rootPath, values2, paths = []) => {
  for (const property2 in values2) {
    const rootName = rootPath + (isObject2(values2) ? `.${property2}` : `[${property2}]`);
    isPrimitive(values2[property2]) ? paths.push(rootName) : getPath2(rootName, values2[property2], paths);
  }
  return paths;
};
var assignWatchFields = (fieldValues, fieldName, watchFields, inputValue, isSingleField) => {
  let value = void 0;
  watchFields.add(fieldName);
  if (!isEmptyObject(fieldValues)) {
    value = get3(fieldValues, fieldName);
    if (isObject2(value) || Array.isArray(value)) {
      getPath2(fieldName, value).forEach((name) => watchFields.add(name));
    }
  }
  return isUndefined2(value) ? isSingleField ? inputValue : get3(inputValue, fieldName) : value;
};
var skipValidation = ({isOnBlur, isOnChange, isOnTouch, isTouched, isReValidateOnBlur, isReValidateOnChange, isBlurEvent, isSubmitted, isOnAll}) => {
  if (isOnAll) {
    return false;
  } else if (!isSubmitted && isOnTouch) {
    return !(isTouched || isBlurEvent);
  } else if (isSubmitted ? isReValidateOnBlur : isOnBlur) {
    return !isBlurEvent;
  } else if (isSubmitted ? isReValidateOnChange : isOnChange) {
    return isBlurEvent;
  }
  return true;
};
var getFieldArrayParentName = (name) => name.substring(0, name.indexOf("["));
var isMatchFieldArrayName = (name, searchName) => RegExp(`^${searchName}([|.)\\d+`.replace(/\[/g, "\\[").replace(/\]/g, "\\]")).test(name);
var isNameInFieldArray = (names, name) => [...names].some((current) => isMatchFieldArrayName(name, current));
var isSelectInput = (element) => element.type === `${SELECT}-one`;
function onDomRemove(fieldsRef, removeFieldEventListenerAndRef) {
  const observer = new MutationObserver(() => {
    for (const field of Object.values(fieldsRef.current)) {
      if (field && field.options) {
        for (const option of field.options) {
          if (option && option.ref && isDetached(option.ref)) {
            removeFieldEventListenerAndRef(field);
          }
        }
      } else if (field && isDetached(field.ref)) {
        removeFieldEventListenerAndRef(field);
      }
    }
  });
  observer.observe(window.document, {
    childList: true,
    subtree: true
  });
  return observer;
}
var isWeb = typeof window !== UNDEFINED && typeof document !== UNDEFINED;
function cloneObject(data2) {
  var _a;
  let copy2;
  if (isPrimitive(data2) || isWeb && (data2 instanceof File || isHTMLElement2(data2))) {
    return data2;
  }
  if (!["Set", "Map", "Object", "Date", "Array"].includes((_a = data2.constructor) === null || _a === void 0 ? void 0 : _a.name)) {
    return data2;
  }
  if (data2 instanceof Date) {
    copy2 = new Date(data2.getTime());
    return copy2;
  }
  if (data2 instanceof Set) {
    copy2 = new Set();
    for (const item of data2) {
      copy2.add(item);
    }
    return copy2;
  }
  if (data2 instanceof Map) {
    copy2 = new Map();
    for (const key of data2.keys()) {
      copy2.set(key, cloneObject(data2.get(key)));
    }
    return copy2;
  }
  copy2 = Array.isArray(data2) ? [] : {};
  for (const key in data2) {
    copy2[key] = cloneObject(data2[key]);
  }
  return copy2;
}
var modeChecker = (mode) => ({
  isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
  isOnBlur: mode === VALIDATION_MODE.onBlur,
  isOnChange: mode === VALIDATION_MODE.onChange,
  isOnAll: mode === VALIDATION_MODE.all,
  isOnTouch: mode === VALIDATION_MODE.onTouched
});
var isRadioOrCheckboxFunction = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
var isWindowUndefined = typeof window === UNDEFINED;
var isProxyEnabled = isWeb ? "Proxy" in window : typeof Proxy !== UNDEFINED;
function useForm({mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_MODE.onChange, resolver, context: context2, defaultValues: defaultValues2 = {}, shouldFocusError = true, shouldUnregister = true, criteriaMode} = {}) {
  const fieldsRef = react.useRef({});
  const fieldArrayDefaultValuesRef = react.useRef({});
  const fieldArrayValuesRef = react.useRef({});
  const watchFieldsRef = react.useRef(new Set());
  const useWatchFieldsRef = react.useRef({});
  const useWatchRenderFunctionsRef = react.useRef({});
  const fieldsWithValidationRef = react.useRef({});
  const validFieldsRef = react.useRef({});
  const defaultValuesRef = react.useRef(defaultValues2);
  const isUnMount = react.useRef(false);
  const isWatchAllRef = react.useRef(false);
  const handleChangeRef = react.useRef();
  const shallowFieldsStateRef = react.useRef({});
  const resetFieldArrayFunctionRef = react.useRef({});
  const contextRef = react.useRef(context2);
  const resolverRef = react.useRef(resolver);
  const fieldArrayNamesRef = react.useRef(new Set());
  const modeRef = react.useRef(modeChecker(mode));
  const {isOnSubmit, isOnTouch} = modeRef.current;
  const isValidateAllFieldCriteria = criteriaMode === VALIDATION_MODE.all;
  const [formState, setFormState] = react.useState({
    isDirty: false,
    isValidating: false,
    dirtyFields: {},
    isSubmitted: false,
    submitCount: 0,
    touched: {},
    isSubmitting: false,
    isSubmitSuccessful: false,
    isValid: !isOnSubmit,
    errors: {}
  });
  const readFormStateRef = react.useRef({
    isDirty: !isProxyEnabled,
    dirtyFields: !isProxyEnabled,
    touched: !isProxyEnabled || isOnTouch,
    isValidating: !isProxyEnabled,
    isSubmitting: !isProxyEnabled,
    isValid: !isProxyEnabled
  });
  const formStateRef = react.useRef(formState);
  const observerRef = react.useRef();
  const {isOnBlur: isReValidateOnBlur, isOnChange: isReValidateOnChange} = react.useRef(modeChecker(reValidateMode)).current;
  contextRef.current = context2;
  resolverRef.current = resolver;
  formStateRef.current = formState;
  shallowFieldsStateRef.current = shouldUnregister ? {} : isEmptyObject(shallowFieldsStateRef.current) ? cloneObject(defaultValues2) : shallowFieldsStateRef.current;
  const updateFormState = react.useCallback((state = {}) => {
    if (!isUnMount.current) {
      formStateRef.current = Object.assign(Object.assign({}, formStateRef.current), state);
      setFormState(formStateRef.current);
    }
  }, []);
  const updateIsValidating = () => readFormStateRef.current.isValidating && updateFormState({
    isValidating: true
  });
  const shouldRenderBaseOnError = react.useCallback((name, error2, shouldRender = false, state = {}, isValid) => {
    let shouldReRender = shouldRender || isErrorStateChanged({
      errors: formStateRef.current.errors,
      error: error2,
      name,
      validFields: validFieldsRef.current,
      fieldsWithValidation: fieldsWithValidationRef.current
    });
    const previousError = get3(formStateRef.current.errors, name);
    if (error2) {
      unset(validFieldsRef.current, name);
      shouldReRender = shouldReRender || !previousError || !deepEqual(previousError, error2, true);
      set(formStateRef.current.errors, name, error2);
    } else {
      if (get3(fieldsWithValidationRef.current, name) || resolverRef.current) {
        set(validFieldsRef.current, name, true);
        shouldReRender = shouldReRender || previousError;
      }
      unset(formStateRef.current.errors, name);
    }
    if (shouldReRender && !isNullOrUndefined(shouldRender) || !isEmptyObject(state) || readFormStateRef.current.isValidating) {
      updateFormState(Object.assign(Object.assign(Object.assign({}, state), resolverRef.current ? {isValid: !!isValid} : {}), {isValidating: false}));
    }
  }, []);
  const setFieldValue = react.useCallback((name, rawValue) => {
    const {ref, options} = fieldsRef.current[name];
    const value = isWeb && isHTMLElement2(ref) && isNullOrUndefined(rawValue) ? "" : rawValue;
    if (isRadioInput(ref)) {
      (options || []).forEach(({ref: radioRef}) => radioRef.checked = radioRef.value === value);
    } else if (isFileInput(ref) && !isString2(value)) {
      ref.files = value;
    } else if (isMultipleSelect(ref)) {
      [...ref.options].forEach((selectRef) => selectRef.selected = value.includes(selectRef.value));
    } else if (isCheckBoxInput(ref) && options) {
      options.length > 1 ? options.forEach(({ref: checkboxRef}) => checkboxRef.checked = Array.isArray(value) ? !!value.find((data2) => data2 === checkboxRef.value) : value === checkboxRef.value) : options[0].ref.checked = !!value;
    } else {
      ref.value = value;
    }
  }, []);
  const isFormDirty = react.useCallback((name, data2) => {
    if (readFormStateRef.current.isDirty) {
      const formValues = getValues();
      name && data2 && set(formValues, name, data2);
      return !deepEqual(formValues, defaultValuesRef.current);
    }
    return false;
  }, []);
  const updateAndGetDirtyState = react.useCallback((name, shouldRender = true) => {
    if (readFormStateRef.current.isDirty || readFormStateRef.current.dirtyFields) {
      const isFieldDirty = !deepEqual(get3(defaultValuesRef.current, name), getFieldValue(fieldsRef, name, shallowFieldsStateRef));
      const isDirtyFieldExist = get3(formStateRef.current.dirtyFields, name);
      const previousIsDirty = formStateRef.current.isDirty;
      isFieldDirty ? set(formStateRef.current.dirtyFields, name, true) : unset(formStateRef.current.dirtyFields, name);
      const state = {
        isDirty: isFormDirty(),
        dirtyFields: formStateRef.current.dirtyFields
      };
      const isChanged = readFormStateRef.current.isDirty && previousIsDirty !== state.isDirty || readFormStateRef.current.dirtyFields && isDirtyFieldExist !== get3(formStateRef.current.dirtyFields, name);
      isChanged && shouldRender && updateFormState(state);
      return isChanged ? state : {};
    }
    return {};
  }, []);
  const executeValidation = react.useCallback(async (name, skipReRender) => {
    const error2 = (await validateField(fieldsRef, isValidateAllFieldCriteria, fieldsRef.current[name], shallowFieldsStateRef))[name];
    shouldRenderBaseOnError(name, error2, skipReRender);
    return isUndefined2(error2);
  }, [shouldRenderBaseOnError, isValidateAllFieldCriteria]);
  const executeSchemaOrResolverValidation = react.useCallback(async (names) => {
    const {errors} = await resolverRef.current(getValues(), contextRef.current, isValidateAllFieldCriteria);
    const previousFormIsValid = formStateRef.current.isValid;
    if (Array.isArray(names)) {
      const isInputsValid = names.map((name) => {
        const error2 = get3(errors, name);
        error2 ? set(formStateRef.current.errors, name, error2) : unset(formStateRef.current.errors, name);
        return !error2;
      }).every(Boolean);
      updateFormState({
        isValid: isEmptyObject(errors),
        isValidating: false
      });
      return isInputsValid;
    } else {
      const error2 = get3(errors, names);
      shouldRenderBaseOnError(names, error2, previousFormIsValid !== isEmptyObject(errors), {}, isEmptyObject(errors));
      return !error2;
    }
  }, [shouldRenderBaseOnError, isValidateAllFieldCriteria]);
  const trigger = react.useCallback(async (name) => {
    const fields = name || Object.keys(fieldsRef.current);
    updateIsValidating();
    if (resolverRef.current) {
      return executeSchemaOrResolverValidation(fields);
    }
    if (Array.isArray(fields)) {
      !name && (formStateRef.current.errors = {});
      const result = await Promise.all(fields.map(async (data2) => await executeValidation(data2, null)));
      updateFormState({
        isValidating: false
      });
      return result.every(Boolean);
    }
    return await executeValidation(fields);
  }, [executeSchemaOrResolverValidation, executeValidation]);
  const setInternalValues = react.useCallback((name, value, {shouldDirty, shouldValidate}) => {
    const data2 = {};
    set(data2, name, value);
    for (const fieldName of getPath2(name, value)) {
      if (fieldsRef.current[fieldName]) {
        setFieldValue(fieldName, get3(data2, fieldName));
        shouldDirty && updateAndGetDirtyState(fieldName);
        shouldValidate && trigger(fieldName);
      }
    }
  }, [trigger, setFieldValue, updateAndGetDirtyState]);
  const setInternalValue = react.useCallback((name, value, config2) => {
    !shouldUnregister && !isPrimitive(value) && set(shallowFieldsStateRef.current, name, Array.isArray(value) ? [...value] : Object.assign({}, value));
    if (fieldsRef.current[name]) {
      setFieldValue(name, value);
      config2.shouldDirty && updateAndGetDirtyState(name);
      config2.shouldValidate && trigger(name);
    } else if (!isPrimitive(value)) {
      setInternalValues(name, value, config2);
      if (fieldArrayNamesRef.current.has(name)) {
        const parentName = getFieldArrayParentName(name) || name;
        set(fieldArrayDefaultValuesRef.current, name, value);
        resetFieldArrayFunctionRef.current[parentName]({
          [parentName]: get3(fieldArrayDefaultValuesRef.current, parentName)
        });
        if ((readFormStateRef.current.isDirty || readFormStateRef.current.dirtyFields) && config2.shouldDirty) {
          set(formStateRef.current.dirtyFields, name, setFieldArrayDirtyFields(value, get3(defaultValuesRef.current, name, []), get3(formStateRef.current.dirtyFields, name, [])));
          updateFormState({
            isDirty: !deepEqual(Object.assign(Object.assign({}, getValues()), {[name]: value}), defaultValuesRef.current)
          });
        }
      }
    }
    !shouldUnregister && set(shallowFieldsStateRef.current, name, value);
  }, [updateAndGetDirtyState, setFieldValue, setInternalValues]);
  const isFieldWatched = (name) => isWatchAllRef.current || watchFieldsRef.current.has(name) || watchFieldsRef.current.has((name.match(/\w+/) || [])[0]);
  const renderWatchedInputs = (name) => {
    let found = true;
    if (!isEmptyObject(useWatchFieldsRef.current)) {
      for (const key in useWatchFieldsRef.current) {
        if (!name || !useWatchFieldsRef.current[key].size || useWatchFieldsRef.current[key].has(name) || useWatchFieldsRef.current[key].has(getFieldArrayParentName(name))) {
          useWatchRenderFunctionsRef.current[key]();
          found = false;
        }
      }
    }
    return found;
  };
  function setValue(name, value, config2) {
    setInternalValue(name, value, config2 || {});
    isFieldWatched(name) && updateFormState();
    renderWatchedInputs(name);
  }
  handleChangeRef.current = handleChangeRef.current ? handleChangeRef.current : async ({type, target}) => {
    let name = target.name;
    const field = fieldsRef.current[name];
    let error2;
    let isValid;
    if (field) {
      const isBlurEvent = type === EVENTS.BLUR;
      const shouldSkipValidation = skipValidation(Object.assign({
        isBlurEvent,
        isReValidateOnChange,
        isReValidateOnBlur,
        isTouched: !!get3(formStateRef.current.touched, name),
        isSubmitted: formStateRef.current.isSubmitted
      }, modeRef.current));
      let state = updateAndGetDirtyState(name, false);
      let shouldRender = !isEmptyObject(state) || !isBlurEvent && isFieldWatched(name);
      if (isBlurEvent && !get3(formStateRef.current.touched, name) && readFormStateRef.current.touched) {
        set(formStateRef.current.touched, name, true);
        state = Object.assign(Object.assign({}, state), {touched: formStateRef.current.touched});
      }
      if (!shouldUnregister && isCheckBoxInput(target)) {
        set(shallowFieldsStateRef.current, name, getFieldValue(fieldsRef, name));
      }
      if (shouldSkipValidation) {
        !isBlurEvent && renderWatchedInputs(name);
        return (!isEmptyObject(state) || shouldRender && isEmptyObject(state)) && updateFormState(state);
      }
      updateIsValidating();
      if (resolverRef.current) {
        const {errors} = await resolverRef.current(getValues(), contextRef.current, isValidateAllFieldCriteria);
        const previousFormIsValid = formStateRef.current.isValid;
        error2 = get3(errors, name);
        if (isCheckBoxInput(target) && !error2 && resolverRef.current) {
          const parentNodeName = getFieldArrayParentName(name);
          const currentError = get3(errors, parentNodeName, {});
          currentError.type && currentError.message && (error2 = currentError);
          if (parentNodeName && (currentError || get3(formStateRef.current.errors, parentNodeName))) {
            name = parentNodeName;
          }
        }
        isValid = isEmptyObject(errors);
        previousFormIsValid !== isValid && (shouldRender = true);
      } else {
        error2 = (await validateField(fieldsRef, isValidateAllFieldCriteria, field, shallowFieldsStateRef))[name];
      }
      !isBlurEvent && renderWatchedInputs(name);
      shouldRenderBaseOnError(name, error2, shouldRender, state, isValid);
    }
  };
  function setFieldArrayDefaultValues(data2) {
    if (!shouldUnregister) {
      let copy2 = cloneObject(data2);
      for (const value of fieldArrayNamesRef.current) {
        if (isKey(value) && !copy2[value]) {
          copy2 = Object.assign(Object.assign({}, copy2), {[value]: []});
        }
      }
      return copy2;
    }
    return data2;
  }
  function getValues(payload) {
    if (isString2(payload)) {
      return getFieldValue(fieldsRef, payload, shallowFieldsStateRef);
    }
    if (Array.isArray(payload)) {
      const data2 = {};
      for (const name of payload) {
        set(data2, name, getFieldValue(fieldsRef, name, shallowFieldsStateRef));
      }
      return data2;
    }
    return setFieldArrayDefaultValues(getFieldsValues(fieldsRef, cloneObject(shallowFieldsStateRef.current), shouldUnregister));
  }
  const validateResolver = react.useCallback(async (values2 = {}) => {
    const newDefaultValues = isEmptyObject(fieldsRef.current) ? defaultValuesRef.current : {};
    const {errors} = await resolverRef.current(Object.assign(Object.assign(Object.assign({}, newDefaultValues), getValues()), values2), contextRef.current, isValidateAllFieldCriteria) || {};
    const isValid = isEmptyObject(errors);
    formStateRef.current.isValid !== isValid && updateFormState({
      isValid
    });
  }, [isValidateAllFieldCriteria]);
  const removeFieldEventListener = react.useCallback((field, forceDelete) => {
    findRemovedFieldAndRemoveListener(fieldsRef, handleChangeRef.current, field, shallowFieldsStateRef, shouldUnregister, forceDelete);
    if (shouldUnregister) {
      unset(validFieldsRef.current, field.ref.name);
      unset(fieldsWithValidationRef.current, field.ref.name);
    }
  }, [shouldUnregister]);
  const updateWatchedValue = react.useCallback((name) => {
    if (isWatchAllRef.current) {
      updateFormState();
    } else {
      for (const watchField of watchFieldsRef.current) {
        if (watchField.startsWith(name)) {
          updateFormState();
          break;
        }
      }
      renderWatchedInputs(name);
    }
  }, []);
  const removeFieldEventListenerAndRef = react.useCallback((field, forceDelete) => {
    if (field) {
      removeFieldEventListener(field, forceDelete);
      if (shouldUnregister && !compact(field.options || []).length) {
        unset(formStateRef.current.errors, field.ref.name);
        set(formStateRef.current.dirtyFields, field.ref.name, true);
        updateFormState({
          isDirty: isFormDirty()
        });
        readFormStateRef.current.isValid && resolverRef.current && validateResolver();
        updateWatchedValue(field.ref.name);
      }
    }
  }, [validateResolver, removeFieldEventListener]);
  function clearErrors(name) {
    name && (Array.isArray(name) ? name : [name]).forEach((inputName) => fieldsRef.current[inputName] && isKey(inputName) ? delete formStateRef.current.errors[inputName] : unset(formStateRef.current.errors, inputName));
    updateFormState({
      errors: name ? formStateRef.current.errors : {}
    });
  }
  function setError(name, error2) {
    const ref = (fieldsRef.current[name] || {}).ref;
    set(formStateRef.current.errors, name, Object.assign(Object.assign({}, error2), {ref}));
    updateFormState({
      isValid: false
    });
    error2.shouldFocus && ref && ref.focus && ref.focus();
  }
  const watchInternal = react.useCallback((fieldNames, defaultValue, watchId) => {
    const watchFields = watchId ? useWatchFieldsRef.current[watchId] : watchFieldsRef.current;
    let fieldValues = getFieldsValues(fieldsRef, cloneObject(shallowFieldsStateRef.current), shouldUnregister, false, fieldNames);
    if (isString2(fieldNames)) {
      const parentNodeName = getFieldArrayParentName(fieldNames) || fieldNames;
      if (fieldArrayNamesRef.current.has(parentNodeName)) {
        fieldValues = Object.assign(Object.assign({}, fieldArrayValuesRef.current), fieldValues);
      }
      return assignWatchFields(fieldValues, fieldNames, watchFields, isUndefined2(get3(defaultValuesRef.current, fieldNames)) ? defaultValue : get3(defaultValuesRef.current, fieldNames), true);
    }
    const combinedDefaultValues = isUndefined2(defaultValue) ? defaultValuesRef.current : defaultValue;
    if (Array.isArray(fieldNames)) {
      return fieldNames.reduce((previous, name) => Object.assign(Object.assign({}, previous), {[name]: assignWatchFields(fieldValues, name, watchFields, combinedDefaultValues)}), {});
    }
    isWatchAllRef.current = isUndefined2(watchId);
    return transformToNestObject(!isEmptyObject(fieldValues) && fieldValues || combinedDefaultValues);
  }, []);
  function watch(fieldNames, defaultValue) {
    return watchInternal(fieldNames, defaultValue);
  }
  function unregister(name) {
    for (const fieldName of Array.isArray(name) ? name : [name]) {
      removeFieldEventListenerAndRef(fieldsRef.current[fieldName], true);
    }
  }
  function registerFieldRef(ref, options = {}) {
    const {name, type, value} = ref;
    const fieldRefAndValidationOptions = Object.assign({ref}, options);
    const fields = fieldsRef.current;
    const isRadioOrCheckbox = isRadioOrCheckboxFunction(ref);
    const isFieldArray = isNameInFieldArray(fieldArrayNamesRef.current, name);
    const compareRef = (currentRef) => isWeb && (!isHTMLElement2(ref) || currentRef === ref);
    let field = fields[name];
    let isEmptyDefaultValue = true;
    let defaultValue;
    if (field && (isRadioOrCheckbox ? Array.isArray(field.options) && compact(field.options).find((option) => {
      return value === option.ref.value && compareRef(option.ref);
    }) : compareRef(field.ref))) {
      fields[name] = Object.assign(Object.assign({}, field), options);
      return;
    }
    if (type) {
      field = isRadioOrCheckbox ? Object.assign({options: [
        ...compact(field && field.options || []),
        {
          ref
        }
      ], ref: {type, name}}, options) : Object.assign({}, fieldRefAndValidationOptions);
    } else {
      field = fieldRefAndValidationOptions;
    }
    fields[name] = field;
    const isEmptyUnmountFields = isUndefined2(get3(shallowFieldsStateRef.current, name));
    if (!isEmptyObject(defaultValuesRef.current) || !isEmptyUnmountFields) {
      defaultValue = get3(isEmptyUnmountFields ? defaultValuesRef.current : shallowFieldsStateRef.current, name);
      isEmptyDefaultValue = isUndefined2(defaultValue);
      if (!isEmptyDefaultValue && !isFieldArray) {
        setFieldValue(name, defaultValue);
      }
    }
    if (!isEmptyObject(options)) {
      set(fieldsWithValidationRef.current, name, true);
      if (!isOnSubmit && readFormStateRef.current.isValid) {
        validateField(fieldsRef, isValidateAllFieldCriteria, field, shallowFieldsStateRef).then((error2) => {
          const previousFormIsValid = formStateRef.current.isValid;
          isEmptyObject(error2) ? set(validFieldsRef.current, name, true) : unset(validFieldsRef.current, name);
          previousFormIsValid !== isEmptyObject(error2) && updateFormState();
        });
      }
    }
    if (shouldUnregister && !(isFieldArray && isEmptyDefaultValue)) {
      !isFieldArray && unset(formStateRef.current.dirtyFields, name);
    }
    if (type) {
      attachEventListeners(isRadioOrCheckbox && field.options ? field.options[field.options.length - 1] : field, isRadioOrCheckbox || isSelectInput(ref), handleChangeRef.current);
    }
  }
  function register2(refOrRegisterOptions, options) {
    if (!isWindowUndefined) {
      if (isString2(refOrRegisterOptions)) {
        registerFieldRef({name: refOrRegisterOptions}, options);
      } else if (isObject2(refOrRegisterOptions) && "name" in refOrRegisterOptions) {
        registerFieldRef(refOrRegisterOptions, options);
      } else {
        return (ref) => ref && registerFieldRef(ref, refOrRegisterOptions);
      }
    }
  }
  const handleSubmit = react.useCallback((onValid, onInvalid) => async (e2) => {
    if (e2 && e2.preventDefault) {
      e2.preventDefault();
      e2.persist();
    }
    let fieldErrors = {};
    let fieldValues = setFieldArrayDefaultValues(getFieldsValues(fieldsRef, cloneObject(shallowFieldsStateRef.current), shouldUnregister, true));
    readFormStateRef.current.isSubmitting && updateFormState({
      isSubmitting: true
    });
    try {
      if (resolverRef.current) {
        const {errors, values: values2} = await resolverRef.current(fieldValues, contextRef.current, isValidateAllFieldCriteria);
        formStateRef.current.errors = fieldErrors = errors;
        fieldValues = values2;
      } else {
        for (const field of Object.values(fieldsRef.current)) {
          if (field) {
            const {name} = field.ref;
            const fieldError = await validateField(fieldsRef, isValidateAllFieldCriteria, field, shallowFieldsStateRef);
            if (fieldError[name]) {
              set(fieldErrors, name, fieldError[name]);
              unset(validFieldsRef.current, name);
            } else if (get3(fieldsWithValidationRef.current, name)) {
              unset(formStateRef.current.errors, name);
              set(validFieldsRef.current, name, true);
            }
          }
        }
      }
      if (isEmptyObject(fieldErrors) && Object.keys(formStateRef.current.errors).every((name) => name in fieldsRef.current)) {
        updateFormState({
          errors: {},
          isSubmitting: true
        });
        await onValid(fieldValues, e2);
      } else {
        formStateRef.current.errors = Object.assign(Object.assign({}, formStateRef.current.errors), fieldErrors);
        onInvalid && await onInvalid(formStateRef.current.errors, e2);
        shouldFocusError && focusOnErrorField(fieldsRef.current, formStateRef.current.errors);
      }
    } finally {
      formStateRef.current.isSubmitting = false;
      updateFormState({
        isSubmitted: true,
        isSubmitting: false,
        isSubmitSuccessful: isEmptyObject(formStateRef.current.errors),
        submitCount: formStateRef.current.submitCount + 1
      });
    }
  }, [shouldFocusError, isValidateAllFieldCriteria]);
  const resetRefs = ({errors, isDirty, isSubmitted, touched, isValid, submitCount, dirtyFields}) => {
    if (!isValid) {
      validFieldsRef.current = {};
      fieldsWithValidationRef.current = {};
    }
    fieldArrayDefaultValuesRef.current = {};
    watchFieldsRef.current = new Set();
    isWatchAllRef.current = false;
    updateFormState({
      submitCount: submitCount ? formStateRef.current.submitCount : 0,
      isDirty: isDirty ? formStateRef.current.isDirty : false,
      isSubmitted: isSubmitted ? formStateRef.current.isSubmitted : false,
      isValid: isValid ? formStateRef.current.isValid : false,
      dirtyFields: dirtyFields ? formStateRef.current.dirtyFields : {},
      touched: touched ? formStateRef.current.touched : {},
      errors: errors ? formStateRef.current.errors : {},
      isSubmitting: false,
      isSubmitSuccessful: false
    });
  };
  const reset2 = (values2, omitResetState = {}) => {
    if (isWeb) {
      for (const field of Object.values(fieldsRef.current)) {
        if (field) {
          const {ref, options} = field;
          const inputRef = isRadioOrCheckboxFunction(ref) && Array.isArray(options) ? options[0].ref : ref;
          if (isHTMLElement2(inputRef)) {
            try {
              inputRef.closest("form").reset();
              break;
            } catch (_a) {
            }
          }
        }
      }
    }
    fieldsRef.current = {};
    defaultValuesRef.current = Object.assign({}, values2 || defaultValuesRef.current);
    values2 && renderWatchedInputs("");
    Object.values(resetFieldArrayFunctionRef.current).forEach((resetFieldArray) => isFunction2(resetFieldArray) && resetFieldArray());
    shallowFieldsStateRef.current = shouldUnregister ? {} : cloneObject(values2 || defaultValuesRef.current);
    resetRefs(omitResetState);
  };
  react.useEffect(() => {
    resolver && readFormStateRef.current.isValid && validateResolver();
    observerRef.current = observerRef.current || !isWeb ? observerRef.current : onDomRemove(fieldsRef, removeFieldEventListenerAndRef);
  }, [removeFieldEventListenerAndRef, defaultValuesRef.current]);
  react.useEffect(() => () => {
    observerRef.current && observerRef.current.disconnect();
    isUnMount.current = true;
    Object.values(fieldsRef.current).forEach((field) => removeFieldEventListenerAndRef(field, true));
  }, []);
  if (!resolver && readFormStateRef.current.isValid) {
    formState.isValid = deepEqual(validFieldsRef.current, fieldsWithValidationRef.current) && isEmptyObject(formStateRef.current.errors);
  }
  const commonProps = {
    trigger,
    setValue: react.useCallback(setValue, [setInternalValue, trigger]),
    getValues: react.useCallback(getValues, []),
    register: react.useCallback(register2, [defaultValuesRef.current]),
    unregister: react.useCallback(unregister, []),
    formState: isProxyEnabled ? new Proxy(formState, {
      get: (obj, prop) => {
        if (prop in obj) {
          readFormStateRef.current[prop] = true;
          return obj[prop];
        }
        return void 0;
      }
    }) : formState
  };
  const control = react.useMemo(() => Object.assign({
    isFormDirty,
    updateWatchedValue,
    shouldUnregister,
    updateFormState,
    removeFieldEventListener,
    watchInternal,
    mode: modeRef.current,
    reValidateMode: {
      isReValidateOnBlur,
      isReValidateOnChange
    },
    validateResolver: resolver ? validateResolver : void 0,
    fieldsRef,
    resetFieldArrayFunctionRef,
    useWatchFieldsRef,
    useWatchRenderFunctionsRef,
    fieldArrayDefaultValuesRef,
    validFieldsRef,
    fieldsWithValidationRef,
    fieldArrayNamesRef,
    readFormStateRef,
    formStateRef,
    defaultValuesRef,
    shallowFieldsStateRef,
    fieldArrayValuesRef
  }, commonProps), [
    defaultValuesRef.current,
    updateWatchedValue,
    shouldUnregister,
    removeFieldEventListener,
    watchInternal
  ]);
  return Object.assign({
    watch,
    control,
    handleSubmit,
    reset: react.useCallback(reset2, []),
    clearErrors: react.useCallback(clearErrors, []),
    setError: react.useCallback(setError, []),
    errors: formState.errors
  }, commonProps);
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

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

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __rest2(s2, e2) {
  var t5 = {};
  for (var p2 in s2)
    if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
      t5[p2] = s2[p2];
  if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i3 = 0, p2 = Object.getOwnPropertySymbols(s2); i3 < p2.length; i3++) {
      if (e2.indexOf(p2[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i3]))
        t5[p2[i3]] = s2[p2[i3]];
    }
  return t5;
}
var FormContext = react.createContext(null);
FormContext.displayName = "RHFContext";
var useFormContext = () => react.useContext(FormContext);
var FormProvider = (_a) => {
  var {children: children2} = _a, props = __rest2(_a, ["children"]);
  return react.createElement(FormContext.Provider, {value: Object.assign({}, props)}, children2);
};
var generateId = () => {
  const d2 = typeof performance === UNDEFINED ? Date.now() : performance.now() * 1e3;
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c3) => {
    const r3 = (Math.random() * 16 + d2) % 16 | 0;
    return (c3 == "x" ? r3 : r3 & 3 | 8).toString(16);
  });
};
function removeAtIndexes(data2, indexes) {
  let i3 = 0;
  const temp = [...data2];
  for (const index3 of indexes) {
    temp.splice(index3 - i3, 1);
    i3++;
  }
  return compact(temp).length ? temp : [];
}
var removeArrayAt = (data2, index3) => isUndefined2(index3) ? [] : removeAtIndexes(data2, (Array.isArray(index3) ? index3 : [index3]).sort((a2, b2) => a2 - b2));
var moveArrayAt = (data2, from, to) => {
  if (Array.isArray(data2)) {
    if (isUndefined2(data2[to])) {
      data2[to] = void 0;
    }
    data2.splice(to, 0, data2.splice(from, 1)[0]);
    return data2;
  }
  return [];
};
var swapArrayAt = (data2, indexA, indexB) => {
  const temp = [data2[indexB], data2[indexA]];
  data2[indexA] = temp[0];
  data2[indexB] = temp[1];
};
function prepend(data2, value) {
  return [...Array.isArray(value) ? value : [value || void 0], ...data2];
}
function insert(data2, index3, value) {
  return [
    ...data2.slice(0, index3),
    ...Array.isArray(value) ? value : [value || void 0],
    ...data2.slice(index3)
  ];
}
var fillEmptyArray = (value) => Array.isArray(value) ? Array(value.length).fill(void 0) : void 0;
var fillBooleanArray = (value) => (Array.isArray(value) ? value : [value]).map((data2) => {
  if (isObject2(data2)) {
    const object = {};
    for (const key in data2) {
      object[key] = true;
    }
    return object;
  }
  return true;
});
var mapIds = (values2 = [], keyName, skipWarn) => {
  return values2.map((value) => Object.assign({[keyName]: value[keyName] || generateId()}, value));
};
var useFieldArray = ({control, name, keyName = "id"}) => {
  const methods = useFormContext();
  const focusIndexRef = react.useRef(-1);
  const isUnMount = react.useRef(false);
  const {isFormDirty, updateWatchedValue, resetFieldArrayFunctionRef, fieldArrayNamesRef, fieldsRef, defaultValuesRef, removeFieldEventListener, formStateRef, shallowFieldsStateRef, updateFormState, readFormStateRef, validFieldsRef, fieldsWithValidationRef, fieldArrayDefaultValuesRef, validateResolver, getValues, shouldUnregister, fieldArrayValuesRef} = control || methods.control;
  const getDefaultValues2 = (values2) => get3(shouldUnregister ? values2 : shallowFieldsStateRef.current, name, []);
  const fieldArrayParentName = getFieldArrayParentName(name);
  const memoizedDefaultValues = react.useRef([
    ...get3(fieldArrayDefaultValuesRef.current, fieldArrayParentName) ? getDefaultValues2(fieldArrayDefaultValuesRef.current) : getDefaultValues2(defaultValuesRef.current)
  ]);
  const [fields, setFields] = react.useState(mapIds(memoizedDefaultValues.current, keyName));
  set(fieldArrayValuesRef.current, name, compact(fields));
  const omitKey = (fields2) => fields2.map((_a = {}) => {
    var _b = keyName, omitted = _a[_b], rest = __rest2(_a, [typeof _b === "symbol" ? _b : _b + ""]);
    return rest;
  });
  fieldArrayNamesRef.current.add(name);
  const getFieldArrayValue = react.useCallback(() => get3(fieldArrayValuesRef.current, name, []), [name]);
  const getCurrentFieldsValues = () => mapIds(get3(getValues(), name, getFieldArrayValue()).map((item, index3) => Object.assign(Object.assign({}, getFieldArrayValue()[index3]), item)), keyName);
  fieldArrayNamesRef.current.add(name);
  if (fieldArrayParentName && !get3(fieldArrayDefaultValuesRef.current, fieldArrayParentName)) {
    set(fieldArrayDefaultValuesRef.current, fieldArrayParentName, cloneObject(get3(defaultValuesRef.current, fieldArrayParentName)));
  }
  const setFieldAndValidState = (fieldsValues) => {
    setFields(fieldsValues);
    set(fieldArrayValuesRef.current, name, fieldsValues);
    if (readFormStateRef.current.isValid && validateResolver) {
      const values2 = getValues();
      set(values2, name, fieldsValues);
      validateResolver(values2);
    }
  };
  const resetFields = () => {
    for (const key in fieldsRef.current) {
      if (isMatchFieldArrayName(key, name)) {
        removeFieldEventListener(fieldsRef.current[key], true);
        delete fieldsRef.current[key];
      }
    }
  };
  const cleanup2 = (ref) => !compact(get3(ref, name, [])).length && unset(ref, name);
  const updateDirtyFieldsWithDefaultValues = (updatedFieldArrayValues) => {
    if (updatedFieldArrayValues) {
      set(formStateRef.current.dirtyFields, name, setFieldArrayDirtyFields(omitKey(updatedFieldArrayValues), get3(defaultValuesRef.current, name, []), get3(formStateRef.current.dirtyFields, name, [])));
    }
  };
  const batchStateUpdate = (method, args, updatedFieldValues, updatedFormValues = [], shouldSet = true, shouldUpdateValid = false) => {
    if (get3(shallowFieldsStateRef.current, name)) {
      const output2 = method(get3(shallowFieldsStateRef.current, name), args.argA, args.argB);
      shouldSet && set(shallowFieldsStateRef.current, name, output2);
    }
    if (get3(fieldArrayDefaultValuesRef.current, name)) {
      const output2 = method(get3(fieldArrayDefaultValuesRef.current, name), args.argA, args.argB);
      shouldSet && set(fieldArrayDefaultValuesRef.current, name, output2);
    }
    if (Array.isArray(get3(formStateRef.current.errors, name))) {
      const output2 = method(get3(formStateRef.current.errors, name), args.argA, args.argB);
      shouldSet && set(formStateRef.current.errors, name, output2);
      cleanup2(formStateRef.current.errors);
    }
    if (readFormStateRef.current.touched && get3(formStateRef.current.touched, name)) {
      const output2 = method(get3(formStateRef.current.touched, name), args.argA, args.argB);
      shouldSet && set(formStateRef.current.touched, name, output2);
      cleanup2(formStateRef.current.touched);
    }
    if (readFormStateRef.current.dirtyFields || readFormStateRef.current.isDirty) {
      set(formStateRef.current.dirtyFields, name, setFieldArrayDirtyFields(omitKey(updatedFormValues), get3(defaultValuesRef.current, name, []), get3(formStateRef.current.dirtyFields, name, [])));
      updateDirtyFieldsWithDefaultValues(updatedFieldValues);
      cleanup2(formStateRef.current.dirtyFields);
    }
    if (shouldUpdateValid && readFormStateRef.current.isValid && !validateResolver) {
      set(validFieldsRef.current, name, method(get3(validFieldsRef.current, name, []), args.argA));
      cleanup2(validFieldsRef.current);
      set(fieldsWithValidationRef.current, name, method(get3(fieldsWithValidationRef.current, name, []), args.argA));
      cleanup2(fieldsWithValidationRef.current);
    }
    if (!isUnMount.current && readFormStateRef.current.isDirty) {
      updateFormState({
        isDirty: isFormDirty(name, omitKey(updatedFormValues))
      });
    }
  };
  const append2 = (value, shouldFocus = true) => {
    const appendValue = Array.isArray(value) ? value : [value];
    const updateFormValues = [
      ...getCurrentFieldsValues(),
      ...mapIds(appendValue, keyName)
    ];
    setFieldAndValidState(updateFormValues);
    if (readFormStateRef.current.dirtyFields || readFormStateRef.current.isDirty) {
      updateDirtyFieldsWithDefaultValues(updateFormValues);
      updateFormState({
        isDirty: true,
        dirtyFields: formStateRef.current.dirtyFields
      });
    }
    !shouldUnregister && set(shallowFieldsStateRef.current, name, [
      ...get3(shallowFieldsStateRef.current, name) || [],
      ...cloneObject(appendValue)
    ]);
    focusIndexRef.current = shouldFocus ? get3(fieldArrayValuesRef.current, name).length - 1 : -1;
  };
  const prepend$1 = (value, shouldFocus = true) => {
    const emptyArray = fillEmptyArray(value);
    const updatedFieldArrayValues = prepend(getCurrentFieldsValues(), mapIds(Array.isArray(value) ? value : [value], keyName));
    setFieldAndValidState(updatedFieldArrayValues);
    resetFields();
    batchStateUpdate(prepend, {
      argA: emptyArray,
      argC: fillBooleanArray(value)
    }, updatedFieldArrayValues);
    focusIndexRef.current = shouldFocus ? 0 : -1;
  };
  const remove3 = (index3) => {
    const fieldValues = getCurrentFieldsValues();
    const updatedFieldValues = removeArrayAt(fieldValues, index3);
    setFieldAndValidState(updatedFieldValues);
    resetFields();
    batchStateUpdate(removeArrayAt, {
      argA: index3,
      argC: index3
    }, updatedFieldValues, removeArrayAt(fieldValues, index3), true, true);
  };
  const insert$1 = (index3, value, shouldFocus = true) => {
    const emptyArray = fillEmptyArray(value);
    const fieldValues = getCurrentFieldsValues();
    const updatedFieldArrayValues = insert(fieldValues, index3, mapIds(Array.isArray(value) ? value : [value], keyName));
    setFieldAndValidState(updatedFieldArrayValues);
    resetFields();
    batchStateUpdate(insert, {
      argA: index3,
      argB: emptyArray,
      argC: index3,
      argD: fillBooleanArray(value)
    }, updatedFieldArrayValues, insert(fieldValues, index3));
    focusIndexRef.current = shouldFocus ? index3 : -1;
  };
  const swap = (indexA, indexB) => {
    const fieldValues = getCurrentFieldsValues();
    swapArrayAt(fieldValues, indexA, indexB);
    resetFields();
    setFieldAndValidState([...fieldValues]);
    batchStateUpdate(swapArrayAt, {
      argA: indexA,
      argB: indexB,
      argC: indexA,
      argD: indexB
    }, void 0, fieldValues, false);
  };
  const move = (from, to) => {
    const fieldValues = getCurrentFieldsValues();
    moveArrayAt(fieldValues, from, to);
    resetFields();
    setFieldAndValidState([...fieldValues]);
    batchStateUpdate(moveArrayAt, {
      argA: from,
      argB: to,
      argC: from,
      argD: to
    }, void 0, fieldValues, false);
  };
  react.useEffect(() => {
    const defaultValues2 = get3(fieldArrayDefaultValuesRef.current, name);
    if (defaultValues2 && fields.length < defaultValues2.length) {
      set(fieldArrayDefaultValuesRef.current, name, defaultValues2.slice(1));
    }
    updateWatchedValue(name);
    if (focusIndexRef.current > -1) {
      for (const key in fieldsRef.current) {
        const field = fieldsRef.current[key];
        if (key.startsWith(`${name}[${focusIndexRef.current}]`) && field.ref.focus) {
          field.ref.focus();
          break;
        }
      }
    }
    focusIndexRef.current = -1;
  }, [fields, name]);
  react.useEffect(() => {
    const resetFunctions = resetFieldArrayFunctionRef.current;
    const fieldArrayNames = fieldArrayNamesRef.current;
    if (!getFieldArrayParentName(name)) {
      resetFunctions[name] = (data2) => {
        resetFields();
        !data2 && unset(fieldArrayDefaultValuesRef.current, name);
        unset(shallowFieldsStateRef.current, name);
        memoizedDefaultValues.current = get3(data2 || defaultValuesRef.current, name);
        if (!isUnMount.current) {
          setFields(mapIds(memoizedDefaultValues.current, keyName));
        }
      };
    }
    return () => {
      isUnMount.current = true;
      shouldUnregister && remove3();
      resetFields();
      delete resetFunctions[name];
      unset(fieldArrayValuesRef.current, name);
      fieldArrayNames.delete(name);
    };
  }, []);
  return {
    swap: react.useCallback(swap, [name]),
    move: react.useCallback(move, [name]),
    prepend: react.useCallback(prepend$1, [name]),
    append: react.useCallback(append2, [name]),
    remove: react.useCallback(remove3, [name]),
    insert: react.useCallback(insert$1, [name]),
    fields: compact(fields)
  };
};
var getInputValue = (event) => isPrimitive(event) || !isObject2(event.target) || isObject2(event.target) && !event.type ? event : isUndefined2(event.target.value) ? event.target.checked : event.target.value;
function useController({name, rules, defaultValue, control, onFocus}) {
  const methods = useFormContext();
  const {defaultValuesRef, setValue, register: register2, unregister, trigger, mode, reValidateMode: {isReValidateOnBlur, isReValidateOnChange}, formState, formStateRef: {current: {isSubmitted, touched, errors}}, updateFormState, readFormStateRef, fieldsRef, fieldArrayNamesRef, shallowFieldsStateRef} = control || methods.control;
  const isNotFieldArray = !isNameInFieldArray(fieldArrayNamesRef.current, name);
  const getInitialValue = () => !isUndefined2(get3(shallowFieldsStateRef.current, name)) && isNotFieldArray ? get3(shallowFieldsStateRef.current, name) : isUndefined2(defaultValue) ? get3(defaultValuesRef.current, name) : defaultValue;
  const [value, setInputStateValue] = react.useState(getInitialValue());
  const valueRef = react.useRef(value);
  const ref = react.useRef({
    focus: () => null
  });
  const onFocusRef = react.useRef(onFocus || (() => {
    if (isFunction2(ref.current.focus)) {
      ref.current.focus();
    }
  }));
  const shouldValidate = react.useCallback((isBlurEvent) => !skipValidation(Object.assign({
    isBlurEvent,
    isReValidateOnBlur,
    isReValidateOnChange,
    isSubmitted,
    isTouched: !!get3(touched, name)
  }, mode)), [
    isReValidateOnBlur,
    isReValidateOnChange,
    isSubmitted,
    touched,
    name,
    mode
  ]);
  const commonTask = react.useCallback(([event]) => {
    const data2 = getInputValue(event);
    setInputStateValue(data2);
    valueRef.current = data2;
    return data2;
  }, []);
  const registerField = react.useCallback((shouldUpdateValue) => {
    if (fieldsRef.current[name]) {
      fieldsRef.current[name] = Object.assign({ref: fieldsRef.current[name].ref}, rules);
    } else {
      register2(Object.defineProperties({
        name,
        focus: onFocusRef.current
      }, {
        value: {
          set(data2) {
            setInputStateValue(data2);
            valueRef.current = data2;
          },
          get() {
            return valueRef.current;
          }
        }
      }), rules);
      shouldUpdateValue = isUndefined2(get3(defaultValuesRef.current, name));
    }
    shouldUpdateValue && isNotFieldArray && setInputStateValue(getInitialValue());
  }, [rules, name, register2]);
  react.useEffect(() => () => unregister(name), [name]);
  react.useEffect(() => {
    registerField();
  }, [registerField]);
  react.useEffect(() => {
    !fieldsRef.current[name] && registerField(true);
  });
  const onBlur = react.useCallback(() => {
    if (readFormStateRef.current.touched && !get3(touched, name)) {
      set(touched, name, true);
      updateFormState({
        touched
      });
    }
    shouldValidate(true) && trigger(name);
  }, [name, updateFormState, shouldValidate, trigger, readFormStateRef]);
  const onChange = react.useCallback((...event) => setValue(name, commonTask(event), {
    shouldValidate: shouldValidate(),
    shouldDirty: true
  }), [setValue, name, shouldValidate]);
  return {
    field: {
      onChange,
      onBlur,
      name,
      value,
      ref
    },
    meta: Object.defineProperties({
      invalid: !!get3(errors, name)
    }, {
      isDirty: {
        get() {
          return !!get3(formState.dirtyFields, name);
        }
      },
      isTouched: {
        get() {
          return !!get3(formState.touched, name);
        }
      }
    })
  };
}
function useWatch({control, name, defaultValue}) {
  const methods = useFormContext();
  const {useWatchFieldsRef, useWatchRenderFunctionsRef, watchInternal, defaultValuesRef} = control || methods.control;
  const updateValue = react.useState()[1];
  const idRef = react.useRef();
  const defaultValueRef = react.useRef(defaultValue);
  react.useEffect(() => {
    const id3 = idRef.current = generateId();
    const watchFieldsHookRender = useWatchRenderFunctionsRef.current;
    const watchFieldsHook = useWatchFieldsRef.current;
    watchFieldsHook[id3] = new Set();
    watchFieldsHookRender[id3] = () => updateValue({});
    watchInternal(name, defaultValueRef.current, id3);
    return () => {
      delete watchFieldsHook[id3];
      delete watchFieldsHookRender[id3];
    };
  }, [
    name,
    useWatchRenderFunctionsRef,
    useWatchFieldsRef,
    watchInternal,
    defaultValueRef
  ]);
  return idRef.current ? watchInternal(name, defaultValueRef.current, idRef.current) : isUndefined2(defaultValue) ? isString2(name) ? get3(defaultValuesRef.current, name) : Array.isArray(name) ? name.reduce((previous, inputName) => Object.assign(Object.assign({}, previous), {[inputName]: get3(defaultValuesRef.current, inputName)}), {}) : defaultValuesRef.current : defaultValue;
}
var Controller = (props) => {
  const {rules, as, render: render4, defaultValue, control, onFocus} = props, rest = __rest2(props, ["rules", "as", "render", "defaultValue", "control", "onFocus"]);
  const {field, meta} = useController(props);
  const componentProps = Object.assign(Object.assign({}, rest), field);
  return as ? react.isValidElement(as) ? react.cloneElement(as, componentProps) : react.createElement(as, componentProps) : render4 ? render4(field, meta) : null;
};

// build/components/alert/AlertPanel.js
function AlertPanel({alerts, onCloseAlert}) {
  return /* @__PURE__ */ react.createElement(AlertGroup, {
    isToast: true
  }, alerts.map(({key, variant, message, description}) => /* @__PURE__ */ react.createElement(Alert, {
    key,
    isLiveRegion: true,
    variant: AlertVariant[variant],
    variantLabel: "",
    title: message,
    actionClose: /* @__PURE__ */ react.createElement(AlertActionCloseButton, {
      title: message,
      onClose: () => onCloseAlert(key)
    })
  }, description && /* @__PURE__ */ react.createElement("p", null, description))));
}

// build/components/alert/Alerts.js
var AlertContext2 = createContext(void 0);
var useAlerts = () => useRequiredContext(AlertContext2);
var AlertProvider = ({children: children2}) => {
  const {t: t5} = useTranslation();
  const [alerts, setAlerts] = useState([]);
  const createId = () => new Date().getTime();
  const hideAlert = (key) => {
    setAlerts((alerts2) => [...alerts2.filter((el) => el.key !== key)]);
  };
  const addAlert = (message, variant = AlertVariant.success, description) => {
    const key = createId();
    setTimeout(() => hideAlert(key), 8e3);
    setAlerts([{key, message, variant, description}, ...alerts]);
  };
  const addError = (message, error2) => {
    addAlert(t5(message, {
      error: "response" in error2 ? error2.response?.data?.errorMessage || error2.response?.data?.error : error2
    }), AlertVariant.danger);
  };
  return /* @__PURE__ */ react.createElement(AlertContext2.Provider, {
    value: {addAlert, addError}
  }, /* @__PURE__ */ react.createElement(AlertPanel, {
    alerts,
    onCloseAlert: hideAlert
  }), children2);
};

// build/context/access/Access.js
var AccessContext = createContext(void 0);
var useAccess = () => useRequiredContext(AccessContext);
var AccessContextProvider = ({children: children2}) => {
  const {whoAmI: whoAmI2} = useWhoAmI();
  const {realm: realm2} = useRealm();
  const [access, setAccess] = useState([]);
  useEffect(() => {
    if (whoAmI2.getRealmAccess()[realm2]) {
      setAccess(whoAmI2.getRealmAccess()[realm2]);
    }
  }, [whoAmI2, realm2]);
  const hasAccess = (...types2) => {
    return types2.every((type) => type === "anyone" || access.includes(type));
  };
  const hasSomeAccess = (...types2) => {
    return types2.some((type) => type === "anyone" || access.includes(type));
  };
  return /* @__PURE__ */ react.createElement(AccessContext.Provider, {
    value: {hasAccess, hasSomeAccess}
  }, children2);
};

// build/components/form-access/FormAccess.js
var FormAccess = ({
  children: children2,
  role,
  fineGrainedAccess = false,
  unWrap = false,
  ...rest
}) => {
  const {hasAccess} = useAccess();
  const recursiveCloneChildren = (children22, newProps) => {
    return Children.map(children22, (child) => {
      if (!isValidElement(child)) {
        return child;
      }
      if (child.props) {
        const element = child;
        if (child.type === Controller) {
          return cloneElement(child, {
            ...element.props,
            render: (props) => {
              const renderElement = element.props.render(props);
              return cloneElement(renderElement, {
                ...renderElement.props,
                ...newProps
              });
            }
          });
        }
        const children3 = recursiveCloneChildren(element.props.children, newProps);
        if (child.type === TextArea) {
          return cloneElement(child, {
            readOnly: newProps.isDisabled,
            children: children3
          });
        }
        return cloneElement(child, child.type === FormGroup || child.type === GridItem || child.type === Grid || child.type === ActionGroup || child.type === ClipboardCopy || child.type === Stack || child.type === StackItem ? {children: children3} : {...newProps, children: children3});
      }
      return child;
    });
  };
  const isDisabled = !hasAccess(role) && !fineGrainedAccess;
  return /* @__PURE__ */ react.createElement(react.Fragment, null, !unWrap && /* @__PURE__ */ react.createElement(Form, {
    ...rest,
    className: "keycloak__form " + (rest.className || "")
  }, recursiveCloneChildren(children2, isDisabled ? {isDisabled} : {})), unWrap && recursiveCloneChildren(children2, isDisabled ? {isDisabled} : {}));
};

// build/_snowpack/pkg/@patternfly/react-code-editor.js
var codeEditor = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    codeEditor: "pf-c-code-editor",
    codeEditorCode: "pf-c-code-editor__code",
    codeEditorCodePre: "pf-c-code-editor__code-pre",
    codeEditorControls: "pf-c-code-editor__controls",
    codeEditorHeader: "pf-c-code-editor__header",
    codeEditorMain: "pf-c-code-editor__main",
    codeEditorTab: "pf-c-code-editor__tab",
    codeEditorTabIcon: "pf-c-code-editor__tab-icon",
    codeEditorTabText: "pf-c-code-editor__tab-text",
    modifiers: {
      readOnly: "pf-m-read-only",
      control: "pf-m-control",
      dragHover: "pf-m-drag-hover"
    },
    monacoEditor: "monaco-editor"
  };
});
var styles4 = /* @__PURE__ */ getDefaultExportFromCjs(codeEditor);
function _format(message, args) {
  let result;
  if (args.length === 0) {
    result = message;
  } else {
    result = message.replace(/\{(\d+)\}/g, function(match2, rest) {
      const index3 = rest[0];
      return typeof args[index3] !== "undefined" ? args[index3] : match2;
    });
  }
  return result;
}
function localize(data2, message, ...args) {
  return _format(message, args);
}
var LANGUAGE_DEFAULT = "en";
var _isWindows = false;
var _isMacintosh = false;
var _isLinux = false;
var _isNative = false;
var _isWeb = false;
var _isIOS = false;
var _locale = void 0;
var _language = LANGUAGE_DEFAULT;
var _translationsConfigFile = void 0;
var _userAgent = void 0;
var isElectronRenderer = typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.electron !== "undefined" && process.type === "renderer";
if (typeof navigator === "object" && !isElectronRenderer) {
  _userAgent = navigator.userAgent;
  _isWindows = _userAgent.indexOf("Windows") >= 0;
  _isMacintosh = _userAgent.indexOf("Macintosh") >= 0;
  _isIOS = (_userAgent.indexOf("Macintosh") >= 0 || _userAgent.indexOf("iPad") >= 0 || _userAgent.indexOf("iPhone") >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0;
  _isLinux = _userAgent.indexOf("Linux") >= 0;
  _isWeb = true;
  _locale = navigator.language;
  _language = _locale;
} else if (typeof process === "object") {
  _isWindows = process.platform === "win32";
  _isMacintosh = process.platform === "darwin";
  _isLinux = process.platform === "linux";
  _locale = LANGUAGE_DEFAULT;
  _language = LANGUAGE_DEFAULT;
  const rawNlsConfig = process.env["VSCODE_NLS_CONFIG"];
  if (rawNlsConfig) {
    try {
      const nlsConfig = JSON.parse(rawNlsConfig);
      const resolved = nlsConfig.availableLanguages["*"];
      _locale = nlsConfig.locale;
      _language = resolved ? resolved : LANGUAGE_DEFAULT;
      _translationsConfigFile = nlsConfig._translationsConfigFile;
    } catch (e2) {
    }
  }
  _isNative = true;
}
var isWindows = _isWindows;
var isMacintosh = _isMacintosh;
var isLinux = _isLinux;
var isNative = _isNative;
var isWeb2 = _isWeb;
var isIOS = _isIOS;
var _globals = typeof self === "object" ? self : typeof global === "object" ? global : {};
var globals = _globals;
var setImmediate = function defineSetImmediate() {
  if (globals.setImmediate) {
    return globals.setImmediate.bind(globals);
  }
  if (typeof globals.postMessage === "function" && !globals.importScripts) {
    let pending = [];
    globals.addEventListener("message", (e2) => {
      if (e2.data && e2.data.vscodeSetImmediateId) {
        for (let i3 = 0, len2 = pending.length; i3 < len2; i3++) {
          const candidate = pending[i3];
          if (candidate.id === e2.data.vscodeSetImmediateId) {
            pending.splice(i3, 1);
            candidate.callback();
            return;
          }
        }
      }
    });
    let lastId = 0;
    return (callback) => {
      const myId = ++lastId;
      pending.push({
        id: myId,
        callback
      });
      globals.postMessage({vscodeSetImmediateId: myId}, "*");
    };
  }
  if (typeof process !== "undefined" && typeof process.nextTick === "function") {
    return process.nextTick.bind(process);
  }
  const _promise = Promise.resolve();
  return (callback) => _promise.then(callback);
}();
var OS = _isMacintosh || _isIOS ? 2 : _isWindows ? 1 : 3;
var _isLittleEndian = true;
var _isLittleEndianComputed = false;
function isLittleEndian() {
  if (!_isLittleEndianComputed) {
    _isLittleEndianComputed = true;
    const test = new Uint8Array(2);
    test[0] = 1;
    test[1] = 2;
    const view = new Uint16Array(test.buffer);
    _isLittleEndian = view[0] === (2 << 8) + 1;
  }
  return _isLittleEndian;
}
var USUAL_WORD_SEPARATORS = "`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";
function createWordRegExp(allowInWords = "") {
  let source2 = "(-?\\d*\\.\\d\\w*)|([^";
  for (const sep3 of USUAL_WORD_SEPARATORS) {
    if (allowInWords.indexOf(sep3) >= 0) {
      continue;
    }
    source2 += "\\" + sep3;
  }
  source2 += "\\s]+)";
  return new RegExp(source2, "g");
}
var DEFAULT_WORD_REGEXP = createWordRegExp();
function ensureValidWordDefinition(wordDefinition) {
  let result = DEFAULT_WORD_REGEXP;
  if (wordDefinition && wordDefinition instanceof RegExp) {
    if (!wordDefinition.global) {
      let flags2 = "g";
      if (wordDefinition.ignoreCase) {
        flags2 += "i";
      }
      if (wordDefinition.multiline) {
        flags2 += "m";
      }
      if (wordDefinition.unicode) {
        flags2 += "u";
      }
      result = new RegExp(wordDefinition.source, flags2);
    } else {
      result = wordDefinition;
    }
  }
  result.lastIndex = 0;
  return result;
}
var _defaultConfig = {
  maxLen: 1e3,
  windowSize: 15,
  timeBudget: 150
};
function getWordAtText(column, wordDefinition, text, textOffset, config2 = _defaultConfig) {
  if (text.length > config2.maxLen) {
    let start3 = column - config2.maxLen / 2;
    if (start3 < 0) {
      textOffset += column;
      start3 = 0;
    } else {
      textOffset += start3;
    }
    text = text.substring(start3, column + config2.maxLen / 2);
    return getWordAtText(column, wordDefinition, text, textOffset, config2);
  }
  const t1 = Date.now();
  const pos = column - 1 - textOffset;
  let prevRegexIndex = -1;
  let match2 = null;
  for (let i3 = 1; ; i3++) {
    if (Date.now() - t1 >= config2.timeBudget)
      ;
    const regexIndex = pos - config2.windowSize * i3;
    wordDefinition.lastIndex = Math.max(0, regexIndex);
    const thisMatch = _findRegexMatchEnclosingPosition(wordDefinition, text, pos, prevRegexIndex);
    if (!thisMatch && match2) {
      break;
    }
    match2 = thisMatch;
    if (regexIndex <= 0) {
      break;
    }
    prevRegexIndex = regexIndex;
  }
  if (match2) {
    let result = {
      word: match2[0],
      startColumn: textOffset + 1 + match2.index,
      endColumn: textOffset + 1 + match2.index + match2[0].length
    };
    wordDefinition.lastIndex = 0;
    return result;
  }
  return null;
}
function _findRegexMatchEnclosingPosition(wordDefinition, text, pos, stopPos) {
  let match2;
  while (match2 = wordDefinition.exec(text)) {
    const matchIndex = match2.index || 0;
    if (matchIndex <= pos && wordDefinition.lastIndex >= pos) {
      return match2;
    } else if (stopPos > 0 && matchIndex > stopPos) {
      return null;
    }
  }
  return null;
}
var MINIMAP_GUTTER_WIDTH = 8;
var ConfigurationChangedEvent = class {
  constructor(values2) {
    this._values = values2;
  }
  hasChanged(id3) {
    return this._values[id3];
  }
};
var ValidatedEditorOptions = class {
  constructor() {
    this._values = [];
  }
  _read(option) {
    return this._values[option];
  }
  get(id3) {
    return this._values[id3];
  }
  _write(option, value) {
    this._values[option] = value;
  }
};
var ComputeOptionsMemory = class {
  constructor() {
    this.stableMinimapLayoutInput = null;
    this.stableFitMaxMinimapScale = 0;
    this.stableFitRemainingWidth = 0;
  }
};
var BaseEditorOption = class {
  constructor(id3, name, defaultValue, schema) {
    this.id = id3;
    this.name = name;
    this.defaultValue = defaultValue;
    this.schema = schema;
  }
  compute(env2, options, value) {
    return value;
  }
};
var ComputedEditorOption = class {
  constructor(id3, deps = null) {
    this.schema = void 0;
    this.id = id3;
    this.name = "_never_";
    this.defaultValue = void 0;
    this.deps = deps;
  }
  validate(input) {
    return this.defaultValue;
  }
};
var SimpleEditorOption = class {
  constructor(id3, name, defaultValue, schema) {
    this.id = id3;
    this.name = name;
    this.defaultValue = defaultValue;
    this.schema = schema;
  }
  validate(input) {
    if (typeof input === "undefined") {
      return this.defaultValue;
    }
    return input;
  }
  compute(env2, options, value) {
    return value;
  }
};
var EditorBooleanOption = class extends SimpleEditorOption {
  static boolean(value, defaultValue) {
    if (typeof value === "undefined") {
      return defaultValue;
    }
    if (value === "false") {
      return false;
    }
    return Boolean(value);
  }
  constructor(id3, name, defaultValue, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "boolean";
      schema.default = defaultValue;
    }
    super(id3, name, defaultValue, schema);
  }
  validate(input) {
    return EditorBooleanOption.boolean(input, this.defaultValue);
  }
};
var EditorIntOption = class extends SimpleEditorOption {
  constructor(id3, name, defaultValue, minimum, maximum, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "integer";
      schema.default = defaultValue;
      schema.minimum = minimum;
      schema.maximum = maximum;
    }
    super(id3, name, defaultValue, schema);
    this.minimum = minimum;
    this.maximum = maximum;
  }
  static clampedInt(value, defaultValue, minimum, maximum) {
    if (typeof value === "undefined") {
      return defaultValue;
    }
    let r3 = parseInt(value, 10);
    if (isNaN(r3)) {
      return defaultValue;
    }
    r3 = Math.max(minimum, r3);
    r3 = Math.min(maximum, r3);
    return r3 | 0;
  }
  validate(input) {
    return EditorIntOption.clampedInt(input, this.defaultValue, this.minimum, this.maximum);
  }
};
var EditorFloatOption = class extends SimpleEditorOption {
  constructor(id3, name, defaultValue, validationFn, schema) {
    if (typeof schema !== "undefined") {
      schema.type = "number";
      schema.default = defaultValue;
    }
    super(id3, name, defaultValue, schema);
    this.validationFn = validationFn;
  }
  static clamp(n3, min2, max2) {
    if (n3 < min2) {
      return min2;
    }
    if (n3 > max2) {
      return max2;
    }
    return n3;
  }
  static float(value, defaultValue) {
    if (typeof value === "number") {
      return value;
    }
    if (typeof value === "undefined") {
      return defaultValue;
    }
    const r3 = parseFloat(value);
    return isNaN(r3) ? defaultValue : r3;
  }
  validate(input) {
    return this.validationFn(EditorFloatOption.float(input, this.defaultValue));
  }
};
var EditorStringOption = class extends SimpleEditorOption {
  static string(value, defaultValue) {
    if (typeof value !== "string") {
      return defaultValue;
    }
    return value;
  }
  constructor(id3, name, defaultValue, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "string";
      schema.default = defaultValue;
    }
    super(id3, name, defaultValue, schema);
  }
  validate(input) {
    return EditorStringOption.string(input, this.defaultValue);
  }
};
var EditorStringEnumOption = class extends SimpleEditorOption {
  constructor(id3, name, defaultValue, allowedValues, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "string";
      schema.enum = allowedValues;
      schema.default = defaultValue;
    }
    super(id3, name, defaultValue, schema);
    this._allowedValues = allowedValues;
  }
  static stringSet(value, defaultValue, allowedValues) {
    if (typeof value !== "string") {
      return defaultValue;
    }
    if (allowedValues.indexOf(value) === -1) {
      return defaultValue;
    }
    return value;
  }
  validate(input) {
    return EditorStringEnumOption.stringSet(input, this.defaultValue, this._allowedValues);
  }
};
var EditorEnumOption = class extends BaseEditorOption {
  constructor(id3, name, defaultValue, defaultStringValue, allowedValues, convert, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "string";
      schema.enum = allowedValues;
      schema.default = defaultStringValue;
    }
    super(id3, name, defaultValue, schema);
    this._allowedValues = allowedValues;
    this._convert = convert;
  }
  validate(input) {
    if (typeof input !== "string") {
      return this.defaultValue;
    }
    if (this._allowedValues.indexOf(input) === -1) {
      return this.defaultValue;
    }
    return this._convert(input);
  }
};
function _autoIndentFromString(autoIndent) {
  switch (autoIndent) {
    case "none":
      return 0;
    case "keep":
      return 1;
    case "brackets":
      return 2;
    case "advanced":
      return 3;
    case "full":
      return 4;
  }
}
var EditorAccessibilitySupport = class extends BaseEditorOption {
  constructor() {
    super(2, "accessibilitySupport", 0, {
      type: "string",
      enum: ["auto", "on", "off"],
      enumDescriptions: [
        localize("accessibilitySupport.auto", "The editor will use platform APIs to detect when a Screen Reader is attached."),
        localize("accessibilitySupport.on", "The editor will be permanently optimized for usage with a Screen Reader."),
        localize("accessibilitySupport.off", "The editor will never be optimized for usage with a Screen Reader.")
      ],
      default: "auto",
      description: localize("accessibilitySupport", "Controls whether the editor should run in a mode where it is optimized for screen readers.")
    });
  }
  validate(input) {
    switch (input) {
      case "auto":
        return 0;
      case "off":
        return 1;
      case "on":
        return 2;
    }
    return this.defaultValue;
  }
  compute(env2, options, value) {
    if (value === 0) {
      return env2.accessibilitySupport;
    }
    return value;
  }
};
var EditorComments = class extends BaseEditorOption {
  constructor() {
    const defaults3 = {
      insertSpace: true,
      ignoreEmptyLines: true
    };
    super(14, "comments", defaults3, {
      "editor.comments.insertSpace": {
        type: "boolean",
        default: defaults3.insertSpace,
        description: localize("comments.insertSpace", "Controls whether a space character is inserted when commenting.")
      },
      "editor.comments.ignoreEmptyLines": {
        type: "boolean",
        default: defaults3.ignoreEmptyLines,
        description: localize("comments.ignoreEmptyLines", "Controls if empty lines should be ignored with toggle, add or remove actions for line comments.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      insertSpace: EditorBooleanOption.boolean(input.insertSpace, this.defaultValue.insertSpace),
      ignoreEmptyLines: EditorBooleanOption.boolean(input.ignoreEmptyLines, this.defaultValue.ignoreEmptyLines)
    };
  }
};
function _cursorBlinkingStyleFromString(cursorBlinkingStyle) {
  switch (cursorBlinkingStyle) {
    case "blink":
      return 1;
    case "smooth":
      return 2;
    case "phase":
      return 3;
    case "expand":
      return 4;
    case "solid":
      return 5;
  }
}
var TextEditorCursorStyle;
(function(TextEditorCursorStyle2) {
  TextEditorCursorStyle2[TextEditorCursorStyle2["Line"] = 1] = "Line";
  TextEditorCursorStyle2[TextEditorCursorStyle2["Block"] = 2] = "Block";
  TextEditorCursorStyle2[TextEditorCursorStyle2["Underline"] = 3] = "Underline";
  TextEditorCursorStyle2[TextEditorCursorStyle2["LineThin"] = 4] = "LineThin";
  TextEditorCursorStyle2[TextEditorCursorStyle2["BlockOutline"] = 5] = "BlockOutline";
  TextEditorCursorStyle2[TextEditorCursorStyle2["UnderlineThin"] = 6] = "UnderlineThin";
})(TextEditorCursorStyle || (TextEditorCursorStyle = {}));
function _cursorStyleFromString(cursorStyle) {
  switch (cursorStyle) {
    case "line":
      return TextEditorCursorStyle.Line;
    case "block":
      return TextEditorCursorStyle.Block;
    case "underline":
      return TextEditorCursorStyle.Underline;
    case "line-thin":
      return TextEditorCursorStyle.LineThin;
    case "block-outline":
      return TextEditorCursorStyle.BlockOutline;
    case "underline-thin":
      return TextEditorCursorStyle.UnderlineThin;
  }
}
var EditorClassName = class extends ComputedEditorOption {
  constructor() {
    super(114, [57, 27]);
  }
  compute(env2, options, _23) {
    const classNames2 = ["monaco-editor"];
    if (options.get(27)) {
      classNames2.push(options.get(27));
    }
    if (env2.extraEditorClassName) {
      classNames2.push(env2.extraEditorClassName);
    }
    if (options.get(57) === "default") {
      classNames2.push("mouse-default");
    } else if (options.get(57) === "copy") {
      classNames2.push("mouse-copy");
    }
    if (options.get(92)) {
      classNames2.push("showUnused");
    }
    if (options.get(113)) {
      classNames2.push("showDeprecated");
    }
    return classNames2.join(" ");
  }
};
var EditorEmptySelectionClipboard = class extends EditorBooleanOption {
  constructor() {
    super(26, "emptySelectionClipboard", true, {description: localize("emptySelectionClipboard", "Controls whether copying without a selection copies the current line.")});
  }
  compute(env2, options, value) {
    return value && env2.emptySelectionClipboard;
  }
};
var EditorFind = class extends BaseEditorOption {
  constructor() {
    const defaults3 = {
      cursorMoveOnType: true,
      seedSearchStringFromSelection: true,
      autoFindInSelection: "never",
      globalFindClipboard: false,
      addExtraSpaceOnTop: true,
      loop: true
    };
    super(29, "find", defaults3, {
      "editor.find.cursorMoveOnType": {
        type: "boolean",
        default: defaults3.cursorMoveOnType,
        description: localize("find.cursorMoveOnType", "Controls whether the cursor should jump to find matches while typing.")
      },
      "editor.find.seedSearchStringFromSelection": {
        type: "boolean",
        default: defaults3.seedSearchStringFromSelection,
        description: localize("find.seedSearchStringFromSelection", "Controls whether the search string in the Find Widget is seeded from the editor selection.")
      },
      "editor.find.autoFindInSelection": {
        type: "string",
        enum: ["never", "always", "multiline"],
        default: defaults3.autoFindInSelection,
        enumDescriptions: [
          localize("editor.find.autoFindInSelection.never", "Never turn on Find in selection automatically (default)"),
          localize("editor.find.autoFindInSelection.always", "Always turn on Find in selection automatically"),
          localize("editor.find.autoFindInSelection.multiline", "Turn on Find in selection automatically when multiple lines of content are selected.")
        ],
        description: localize("find.autoFindInSelection", "Controls the condition for turning on find in selection automatically.")
      },
      "editor.find.globalFindClipboard": {
        type: "boolean",
        default: defaults3.globalFindClipboard,
        description: localize("find.globalFindClipboard", "Controls whether the Find Widget should read or modify the shared find clipboard on macOS."),
        included: isMacintosh
      },
      "editor.find.addExtraSpaceOnTop": {
        type: "boolean",
        default: defaults3.addExtraSpaceOnTop,
        description: localize("find.addExtraSpaceOnTop", "Controls whether the Find Widget should add extra lines on top of the editor. When true, you can scroll beyond the first line when the Find Widget is visible.")
      },
      "editor.find.loop": {
        type: "boolean",
        default: defaults3.loop,
        description: localize("find.loop", "Controls whether the search automatically restarts from the beginning (or the end) when no further matches can be found.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      cursorMoveOnType: EditorBooleanOption.boolean(input.cursorMoveOnType, this.defaultValue.cursorMoveOnType),
      seedSearchStringFromSelection: EditorBooleanOption.boolean(input.seedSearchStringFromSelection, this.defaultValue.seedSearchStringFromSelection),
      autoFindInSelection: typeof _input.autoFindInSelection === "boolean" ? _input.autoFindInSelection ? "always" : "never" : EditorStringEnumOption.stringSet(input.autoFindInSelection, this.defaultValue.autoFindInSelection, ["never", "always", "multiline"]),
      globalFindClipboard: EditorBooleanOption.boolean(input.globalFindClipboard, this.defaultValue.globalFindClipboard),
      addExtraSpaceOnTop: EditorBooleanOption.boolean(input.addExtraSpaceOnTop, this.defaultValue.addExtraSpaceOnTop),
      loop: EditorBooleanOption.boolean(input.loop, this.defaultValue.loop)
    };
  }
};
var EditorFontLigatures = class extends BaseEditorOption {
  constructor() {
    super(37, "fontLigatures", EditorFontLigatures.OFF, {
      anyOf: [
        {
          type: "boolean",
          description: localize("fontLigatures", "Enables/Disables font ligatures.")
        },
        {
          type: "string",
          description: localize("fontFeatureSettings", "Explicit font-feature-settings.")
        }
      ],
      description: localize("fontLigaturesGeneral", "Configures font ligatures or font features."),
      default: false
    });
  }
  validate(input) {
    if (typeof input === "undefined") {
      return this.defaultValue;
    }
    if (typeof input === "string") {
      if (input === "false") {
        return EditorFontLigatures.OFF;
      }
      if (input === "true") {
        return EditorFontLigatures.ON;
      }
      return input;
    }
    if (Boolean(input)) {
      return EditorFontLigatures.ON;
    }
    return EditorFontLigatures.OFF;
  }
};
EditorFontLigatures.OFF = '"liga" off, "calt" off';
EditorFontLigatures.ON = '"liga" on, "calt" on';
var EditorFontInfo = class extends ComputedEditorOption {
  constructor() {
    super(36);
  }
  compute(env2, options, _23) {
    return env2.fontInfo;
  }
};
var EditorFontSize = class extends SimpleEditorOption {
  constructor() {
    super(38, "fontSize", EDITOR_FONT_DEFAULTS.fontSize, {
      type: "number",
      minimum: 6,
      maximum: 100,
      default: EDITOR_FONT_DEFAULTS.fontSize,
      description: localize("fontSize", "Controls the font size in pixels.")
    });
  }
  validate(input) {
    let r3 = EditorFloatOption.float(input, this.defaultValue);
    if (r3 === 0) {
      return EDITOR_FONT_DEFAULTS.fontSize;
    }
    return EditorFloatOption.clamp(r3, 6, 100);
  }
  compute(env2, options, value) {
    return env2.fontInfo.fontSize;
  }
};
var EditorFontWeight = class extends BaseEditorOption {
  constructor() {
    super(39, "fontWeight", EDITOR_FONT_DEFAULTS.fontWeight, {
      anyOf: [
        {
          type: "number",
          minimum: EditorFontWeight.MINIMUM_VALUE,
          maximum: EditorFontWeight.MAXIMUM_VALUE,
          errorMessage: localize("fontWeightErrorMessage", 'Only "normal" and "bold" keywords or numbers between 1 and 1000 are allowed.')
        },
        {
          type: "string",
          pattern: "^(normal|bold|1000|[1-9][0-9]{0,2})$"
        },
        {
          enum: EditorFontWeight.SUGGESTION_VALUES
        }
      ],
      default: EDITOR_FONT_DEFAULTS.fontWeight,
      description: localize("fontWeight", 'Controls the font weight. Accepts "normal" and "bold" keywords or numbers between 1 and 1000.')
    });
  }
  validate(input) {
    if (input === "normal" || input === "bold") {
      return input;
    }
    return String(EditorIntOption.clampedInt(input, EDITOR_FONT_DEFAULTS.fontWeight, EditorFontWeight.MINIMUM_VALUE, EditorFontWeight.MAXIMUM_VALUE));
  }
};
EditorFontWeight.SUGGESTION_VALUES = ["normal", "bold", "100", "200", "300", "400", "500", "600", "700", "800", "900"];
EditorFontWeight.MINIMUM_VALUE = 1;
EditorFontWeight.MAXIMUM_VALUE = 1e3;
var EditorGoToLocation = class extends BaseEditorOption {
  constructor() {
    const defaults3 = {
      multiple: "peek",
      multipleDefinitions: "peek",
      multipleTypeDefinitions: "peek",
      multipleDeclarations: "peek",
      multipleImplementations: "peek",
      multipleReferences: "peek",
      alternativeDefinitionCommand: "editor.action.goToReferences",
      alternativeTypeDefinitionCommand: "editor.action.goToReferences",
      alternativeDeclarationCommand: "editor.action.goToReferences",
      alternativeImplementationCommand: "",
      alternativeReferenceCommand: ""
    };
    const jsonSubset = {
      type: "string",
      enum: ["peek", "gotoAndPeek", "goto"],
      default: defaults3.multiple,
      enumDescriptions: [
        localize("editor.gotoLocation.multiple.peek", "Show peek view of the results (default)"),
        localize("editor.gotoLocation.multiple.gotoAndPeek", "Go to the primary result and show a peek view"),
        localize("editor.gotoLocation.multiple.goto", "Go to the primary result and enable peek-less navigation to others")
      ]
    };
    super(43, "gotoLocation", defaults3, {
      "editor.gotoLocation.multiple": {
        deprecationMessage: localize("editor.gotoLocation.multiple.deprecated", "This setting is deprecated, please use separate settings like 'editor.editor.gotoLocation.multipleDefinitions' or 'editor.editor.gotoLocation.multipleImplementations' instead.")
      },
      "editor.gotoLocation.multipleDefinitions": Object.assign({description: localize("editor.editor.gotoLocation.multipleDefinitions", "Controls the behavior the 'Go to Definition'-command when multiple target locations exist.")}, jsonSubset),
      "editor.gotoLocation.multipleTypeDefinitions": Object.assign({description: localize("editor.editor.gotoLocation.multipleTypeDefinitions", "Controls the behavior the 'Go to Type Definition'-command when multiple target locations exist.")}, jsonSubset),
      "editor.gotoLocation.multipleDeclarations": Object.assign({description: localize("editor.editor.gotoLocation.multipleDeclarations", "Controls the behavior the 'Go to Declaration'-command when multiple target locations exist.")}, jsonSubset),
      "editor.gotoLocation.multipleImplementations": Object.assign({description: localize("editor.editor.gotoLocation.multipleImplemenattions", "Controls the behavior the 'Go to Implementations'-command when multiple target locations exist.")}, jsonSubset),
      "editor.gotoLocation.multipleReferences": Object.assign({description: localize("editor.editor.gotoLocation.multipleReferences", "Controls the behavior the 'Go to References'-command when multiple target locations exist.")}, jsonSubset),
      "editor.gotoLocation.alternativeDefinitionCommand": {
        type: "string",
        default: defaults3.alternativeDefinitionCommand,
        description: localize("alternativeDefinitionCommand", "Alternative command id that is being executed when the result of 'Go to Definition' is the current location.")
      },
      "editor.gotoLocation.alternativeTypeDefinitionCommand": {
        type: "string",
        default: defaults3.alternativeTypeDefinitionCommand,
        description: localize("alternativeTypeDefinitionCommand", "Alternative command id that is being executed when the result of 'Go to Type Definition' is the current location.")
      },
      "editor.gotoLocation.alternativeDeclarationCommand": {
        type: "string",
        default: defaults3.alternativeDeclarationCommand,
        description: localize("alternativeDeclarationCommand", "Alternative command id that is being executed when the result of 'Go to Declaration' is the current location.")
      },
      "editor.gotoLocation.alternativeImplementationCommand": {
        type: "string",
        default: defaults3.alternativeImplementationCommand,
        description: localize("alternativeImplementationCommand", "Alternative command id that is being executed when the result of 'Go to Implementation' is the current location.")
      },
      "editor.gotoLocation.alternativeReferenceCommand": {
        type: "string",
        default: defaults3.alternativeReferenceCommand,
        description: localize("alternativeReferenceCommand", "Alternative command id that is being executed when the result of 'Go to Reference' is the current location.")
      }
    });
  }
  validate(_input) {
    var _a, _b, _c, _d, _e;
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      multiple: EditorStringEnumOption.stringSet(input.multiple, this.defaultValue.multiple, ["peek", "gotoAndPeek", "goto"]),
      multipleDefinitions: (_a = input.multipleDefinitions) !== null && _a !== void 0 ? _a : EditorStringEnumOption.stringSet(input.multipleDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleTypeDefinitions: (_b = input.multipleTypeDefinitions) !== null && _b !== void 0 ? _b : EditorStringEnumOption.stringSet(input.multipleTypeDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleDeclarations: (_c = input.multipleDeclarations) !== null && _c !== void 0 ? _c : EditorStringEnumOption.stringSet(input.multipleDeclarations, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleImplementations: (_d = input.multipleImplementations) !== null && _d !== void 0 ? _d : EditorStringEnumOption.stringSet(input.multipleImplementations, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleReferences: (_e = input.multipleReferences) !== null && _e !== void 0 ? _e : EditorStringEnumOption.stringSet(input.multipleReferences, "peek", ["peek", "gotoAndPeek", "goto"]),
      alternativeDefinitionCommand: EditorStringOption.string(input.alternativeDefinitionCommand, this.defaultValue.alternativeDefinitionCommand),
      alternativeTypeDefinitionCommand: EditorStringOption.string(input.alternativeTypeDefinitionCommand, this.defaultValue.alternativeTypeDefinitionCommand),
      alternativeDeclarationCommand: EditorStringOption.string(input.alternativeDeclarationCommand, this.defaultValue.alternativeDeclarationCommand),
      alternativeImplementationCommand: EditorStringOption.string(input.alternativeImplementationCommand, this.defaultValue.alternativeImplementationCommand),
      alternativeReferenceCommand: EditorStringOption.string(input.alternativeReferenceCommand, this.defaultValue.alternativeReferenceCommand)
    };
  }
};
var EditorHover = class extends BaseEditorOption {
  constructor() {
    const defaults3 = {
      enabled: true,
      delay: 300,
      sticky: true
    };
    super(46, "hover", defaults3, {
      "editor.hover.enabled": {
        type: "boolean",
        default: defaults3.enabled,
        description: localize("hover.enabled", "Controls whether the hover is shown.")
      },
      "editor.hover.delay": {
        type: "number",
        default: defaults3.delay,
        description: localize("hover.delay", "Controls the delay in milliseconds after which the hover is shown.")
      },
      "editor.hover.sticky": {
        type: "boolean",
        default: defaults3.sticky,
        description: localize("hover.sticky", "Controls whether the hover should remain visible when mouse is moved over it.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled),
      delay: EditorIntOption.clampedInt(input.delay, this.defaultValue.delay, 0, 1e4),
      sticky: EditorBooleanOption.boolean(input.sticky, this.defaultValue.sticky)
    };
  }
};
var EditorLayoutInfoComputer = class extends ComputedEditorOption {
  constructor() {
    super(117, [
      42,
      50,
      31,
      56,
      84,
      52,
      53,
      86,
      106,
      109,
      110,
      2
    ]);
  }
  compute(env2, options, _23) {
    return EditorLayoutInfoComputer.computeLayout(options, {
      memory: env2.memory,
      outerWidth: env2.outerWidth,
      outerHeight: env2.outerHeight,
      isDominatedByLongLines: env2.isDominatedByLongLines,
      lineHeight: env2.fontInfo.lineHeight,
      viewLineCount: env2.viewLineCount,
      lineNumbersDigitCount: env2.lineNumbersDigitCount,
      typicalHalfwidthCharacterWidth: env2.fontInfo.typicalHalfwidthCharacterWidth,
      maxDigitWidth: env2.fontInfo.maxDigitWidth,
      pixelRatio: env2.pixelRatio
    });
  }
  static computeContainedMinimapLineCount(input) {
    const typicalViewportLineCount = input.height / input.lineHeight;
    const extraLinesBeyondLastLine = input.scrollBeyondLastLine ? typicalViewportLineCount - 1 : 0;
    const desiredRatio = (input.viewLineCount + extraLinesBeyondLastLine) / (input.pixelRatio * input.height);
    const minimapLineCount = Math.floor(input.viewLineCount / desiredRatio);
    return {typicalViewportLineCount, extraLinesBeyondLastLine, desiredRatio, minimapLineCount};
  }
  static _computeMinimapLayout(input, memory) {
    const outerWidth2 = input.outerWidth;
    const outerHeight2 = input.outerHeight;
    const pixelRatio = input.pixelRatio;
    if (!input.minimap.enabled) {
      return {
        renderMinimap: 0,
        minimapLeft: 0,
        minimapWidth: 0,
        minimapHeightIsEditorHeight: false,
        minimapIsSampling: false,
        minimapScale: 1,
        minimapLineHeight: 1,
        minimapCanvasInnerWidth: 0,
        minimapCanvasInnerHeight: Math.floor(pixelRatio * outerHeight2),
        minimapCanvasOuterWidth: 0,
        minimapCanvasOuterHeight: outerHeight2
      };
    }
    const stableMinimapLayoutInput = memory.stableMinimapLayoutInput;
    const couldUseMemory = stableMinimapLayoutInput && input.outerHeight === stableMinimapLayoutInput.outerHeight && input.lineHeight === stableMinimapLayoutInput.lineHeight && input.typicalHalfwidthCharacterWidth === stableMinimapLayoutInput.typicalHalfwidthCharacterWidth && input.pixelRatio === stableMinimapLayoutInput.pixelRatio && input.scrollBeyondLastLine === stableMinimapLayoutInput.scrollBeyondLastLine && input.minimap.enabled === stableMinimapLayoutInput.minimap.enabled && input.minimap.side === stableMinimapLayoutInput.minimap.side && input.minimap.size === stableMinimapLayoutInput.minimap.size && input.minimap.showSlider === stableMinimapLayoutInput.minimap.showSlider && input.minimap.renderCharacters === stableMinimapLayoutInput.minimap.renderCharacters && input.minimap.maxColumn === stableMinimapLayoutInput.minimap.maxColumn && input.minimap.scale === stableMinimapLayoutInput.minimap.scale && input.verticalScrollbarWidth === stableMinimapLayoutInput.verticalScrollbarWidth && input.isViewportWrapping === stableMinimapLayoutInput.isViewportWrapping;
    const lineHeight = input.lineHeight;
    const typicalHalfwidthCharacterWidth = input.typicalHalfwidthCharacterWidth;
    const scrollBeyondLastLine = input.scrollBeyondLastLine;
    const minimapRenderCharacters = input.minimap.renderCharacters;
    let minimapScale = pixelRatio >= 2 ? Math.round(input.minimap.scale * 2) : input.minimap.scale;
    const minimapMaxColumn = input.minimap.maxColumn;
    const minimapSize = input.minimap.size;
    const minimapSide = input.minimap.side;
    const verticalScrollbarWidth = input.verticalScrollbarWidth;
    const viewLineCount = input.viewLineCount;
    const remainingWidth = input.remainingWidth;
    const isViewportWrapping = input.isViewportWrapping;
    const baseCharHeight = minimapRenderCharacters ? 2 : 3;
    let minimapCanvasInnerHeight = Math.floor(pixelRatio * outerHeight2);
    const minimapCanvasOuterHeight = minimapCanvasInnerHeight / pixelRatio;
    let minimapHeightIsEditorHeight = false;
    let minimapIsSampling = false;
    let minimapLineHeight = baseCharHeight * minimapScale;
    let minimapCharWidth = minimapScale / pixelRatio;
    let minimapWidthMultiplier = 1;
    if (minimapSize === "fill" || minimapSize === "fit") {
      const {typicalViewportLineCount, extraLinesBeyondLastLine, desiredRatio, minimapLineCount} = EditorLayoutInfoComputer.computeContainedMinimapLineCount({
        viewLineCount,
        scrollBeyondLastLine,
        height: outerHeight2,
        lineHeight,
        pixelRatio
      });
      const ratio = viewLineCount / minimapLineCount;
      if (ratio > 1) {
        minimapHeightIsEditorHeight = true;
        minimapIsSampling = true;
        minimapScale = 1;
        minimapLineHeight = 1;
        minimapCharWidth = minimapScale / pixelRatio;
      } else {
        let fitBecomesFill = false;
        let maxMinimapScale = minimapScale + 1;
        if (minimapSize === "fit") {
          const effectiveMinimapHeight = Math.ceil((viewLineCount + extraLinesBeyondLastLine) * minimapLineHeight);
          if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) {
            fitBecomesFill = true;
            maxMinimapScale = memory.stableFitMaxMinimapScale;
          } else {
            fitBecomesFill = effectiveMinimapHeight > minimapCanvasInnerHeight;
            if (isViewportWrapping && fitBecomesFill) {
              memory.stableMinimapLayoutInput = input;
              memory.stableFitRemainingWidth = remainingWidth;
            } else {
              memory.stableMinimapLayoutInput = null;
              memory.stableFitRemainingWidth = 0;
            }
          }
        }
        if (minimapSize === "fill" || fitBecomesFill) {
          minimapHeightIsEditorHeight = true;
          const configuredMinimapScale = minimapScale;
          minimapLineHeight = Math.min(lineHeight * pixelRatio, Math.max(1, Math.floor(1 / desiredRatio)));
          minimapScale = Math.min(maxMinimapScale, Math.max(1, Math.floor(minimapLineHeight / baseCharHeight)));
          if (minimapScale > configuredMinimapScale) {
            minimapWidthMultiplier = Math.min(2, minimapScale / configuredMinimapScale);
          }
          minimapCharWidth = minimapScale / pixelRatio / minimapWidthMultiplier;
          minimapCanvasInnerHeight = Math.ceil(Math.max(typicalViewportLineCount, viewLineCount + extraLinesBeyondLastLine) * minimapLineHeight);
          if (isViewportWrapping && fitBecomesFill) {
            memory.stableFitMaxMinimapScale = minimapScale;
          }
        }
      }
    }
    const minimapMaxWidth = Math.floor(minimapMaxColumn * minimapCharWidth);
    const minimapWidth = Math.min(minimapMaxWidth, Math.max(0, Math.floor((remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth / (typicalHalfwidthCharacterWidth + minimapCharWidth))) + MINIMAP_GUTTER_WIDTH);
    let minimapCanvasInnerWidth = Math.floor(pixelRatio * minimapWidth);
    const minimapCanvasOuterWidth = minimapCanvasInnerWidth / pixelRatio;
    minimapCanvasInnerWidth = Math.floor(minimapCanvasInnerWidth * minimapWidthMultiplier);
    const renderMinimap = minimapRenderCharacters ? 1 : 2;
    const minimapLeft = minimapSide === "left" ? 0 : outerWidth2 - minimapWidth - verticalScrollbarWidth;
    return {
      renderMinimap,
      minimapLeft,
      minimapWidth,
      minimapHeightIsEditorHeight,
      minimapIsSampling,
      minimapScale,
      minimapLineHeight,
      minimapCanvasInnerWidth,
      minimapCanvasInnerHeight,
      minimapCanvasOuterWidth,
      minimapCanvasOuterHeight
    };
  }
  static computeLayout(options, env2) {
    const outerWidth2 = env2.outerWidth | 0;
    const outerHeight2 = env2.outerHeight | 0;
    const lineHeight = env2.lineHeight | 0;
    const lineNumbersDigitCount = env2.lineNumbersDigitCount | 0;
    const typicalHalfwidthCharacterWidth = env2.typicalHalfwidthCharacterWidth;
    const maxDigitWidth = env2.maxDigitWidth;
    const pixelRatio = env2.pixelRatio;
    const viewLineCount = env2.viewLineCount;
    const wordWrap = options.get(106);
    const wordWrapColumn = options.get(109);
    const wordWrapMinified = options.get(110);
    const accessibilitySupport = options.get(2);
    const isDominatedByLongLines = env2.isDominatedByLongLines;
    const showGlyphMargin = options.get(42);
    const showLineNumbers = options.get(52).renderType !== 0;
    const lineNumbersMinChars = options.get(53);
    const scrollBeyondLastLine = options.get(86);
    const minimap = options.get(56);
    const scrollbar = options.get(84);
    const verticalScrollbarWidth = scrollbar.verticalScrollbarSize;
    const verticalScrollbarHasArrows = scrollbar.verticalHasArrows;
    const scrollbarArrowSize = scrollbar.arrowSize;
    const horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize;
    const rawLineDecorationsWidth = options.get(50);
    const folding = options.get(31);
    let lineDecorationsWidth;
    if (typeof rawLineDecorationsWidth === "string" && /^\d+(\.\d+)?ch$/.test(rawLineDecorationsWidth)) {
      const multiple = parseFloat(rawLineDecorationsWidth.substr(0, rawLineDecorationsWidth.length - 2));
      lineDecorationsWidth = EditorIntOption.clampedInt(multiple * typicalHalfwidthCharacterWidth, 0, 0, 1e3);
    } else {
      lineDecorationsWidth = EditorIntOption.clampedInt(rawLineDecorationsWidth, 0, 0, 1e3);
    }
    if (folding) {
      lineDecorationsWidth += 16;
    }
    let lineNumbersWidth = 0;
    if (showLineNumbers) {
      const digitCount = Math.max(lineNumbersDigitCount, lineNumbersMinChars);
      lineNumbersWidth = Math.round(digitCount * maxDigitWidth);
    }
    let glyphMarginWidth = 0;
    if (showGlyphMargin) {
      glyphMarginWidth = lineHeight;
    }
    let glyphMarginLeft = 0;
    let lineNumbersLeft = glyphMarginLeft + glyphMarginWidth;
    let decorationsLeft = lineNumbersLeft + lineNumbersWidth;
    let contentLeft = decorationsLeft + lineDecorationsWidth;
    const remainingWidth = outerWidth2 - glyphMarginWidth - lineNumbersWidth - lineDecorationsWidth;
    let isWordWrapMinified = false;
    let isViewportWrapping = false;
    let wrappingColumn = -1;
    if (accessibilitySupport !== 2) {
      if (wordWrapMinified && isDominatedByLongLines) {
        isWordWrapMinified = true;
        isViewportWrapping = true;
      } else if (wordWrap === "on" || wordWrap === "bounded") {
        isViewportWrapping = true;
      } else if (wordWrap === "wordWrapColumn") {
        wrappingColumn = wordWrapColumn;
      }
    }
    const minimapLayout = EditorLayoutInfoComputer._computeMinimapLayout({
      outerWidth: outerWidth2,
      outerHeight: outerHeight2,
      lineHeight,
      typicalHalfwidthCharacterWidth,
      pixelRatio,
      scrollBeyondLastLine,
      minimap,
      verticalScrollbarWidth,
      viewLineCount,
      remainingWidth,
      isViewportWrapping
    }, env2.memory || new ComputeOptionsMemory());
    if (minimapLayout.renderMinimap !== 0 && minimapLayout.minimapLeft === 0) {
      glyphMarginLeft += minimapLayout.minimapWidth;
      lineNumbersLeft += minimapLayout.minimapWidth;
      decorationsLeft += minimapLayout.minimapWidth;
      contentLeft += minimapLayout.minimapWidth;
    }
    const contentWidth = remainingWidth - minimapLayout.minimapWidth;
    const viewportColumn = Math.max(1, Math.floor((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth));
    const verticalArrowSize = verticalScrollbarHasArrows ? scrollbarArrowSize : 0;
    if (isViewportWrapping) {
      wrappingColumn = Math.max(1, viewportColumn);
      if (wordWrap === "bounded") {
        wrappingColumn = Math.min(wrappingColumn, wordWrapColumn);
      }
    }
    return {
      width: outerWidth2,
      height: outerHeight2,
      glyphMarginLeft,
      glyphMarginWidth,
      lineNumbersLeft,
      lineNumbersWidth,
      decorationsLeft,
      decorationsWidth: lineDecorationsWidth,
      contentLeft,
      contentWidth,
      minimap: minimapLayout,
      viewportColumn,
      isWordWrapMinified,
      isViewportWrapping,
      wrappingColumn,
      verticalScrollbarWidth,
      horizontalScrollbarHeight,
      overviewRuler: {
        top: verticalArrowSize,
        width: verticalScrollbarWidth,
        height: outerHeight2 - 2 * verticalArrowSize,
        right: 0
      }
    };
  }
};
var EditorLightbulb = class extends BaseEditorOption {
  constructor() {
    const defaults3 = {enabled: true};
    super(49, "lightbulb", defaults3, {
      "editor.lightbulb.enabled": {
        type: "boolean",
        default: defaults3.enabled,
        description: localize("codeActions", "Enables the code action lightbulb in the editor.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled)
    };
  }
};
var EditorLineHeight = class extends EditorIntOption {
  constructor() {
    super(51, "lineHeight", EDITOR_FONT_DEFAULTS.lineHeight, 0, 150, {description: localize("lineHeight", "Controls the line height. Use 0 to compute the line height from the font size.")});
  }
  compute(env2, options, value) {
    return env2.fontInfo.lineHeight;
  }
};
var EditorMinimap = class extends BaseEditorOption {
  constructor() {
    const defaults3 = {
      enabled: true,
      size: "proportional",
      side: "right",
      showSlider: "mouseover",
      renderCharacters: true,
      maxColumn: 120,
      scale: 1
    };
    super(56, "minimap", defaults3, {
      "editor.minimap.enabled": {
        type: "boolean",
        default: defaults3.enabled,
        description: localize("minimap.enabled", "Controls whether the minimap is shown.")
      },
      "editor.minimap.size": {
        type: "string",
        enum: ["proportional", "fill", "fit"],
        enumDescriptions: [
          localize("minimap.size.proportional", "The minimap has the same size as the editor contents (and might scroll)."),
          localize("minimap.size.fill", "The minimap will stretch or shrink as necessary to fill the height of the editor (no scrolling)."),
          localize("minimap.size.fit", "The minimap will shrink as necessary to never be larger than the editor (no scrolling).")
        ],
        default: defaults3.size,
        description: localize("minimap.size", "Controls the size of the minimap.")
      },
      "editor.minimap.side": {
        type: "string",
        enum: ["left", "right"],
        default: defaults3.side,
        description: localize("minimap.side", "Controls the side where to render the minimap.")
      },
      "editor.minimap.showSlider": {
        type: "string",
        enum: ["always", "mouseover"],
        default: defaults3.showSlider,
        description: localize("minimap.showSlider", "Controls when the minimap slider is shown.")
      },
      "editor.minimap.scale": {
        type: "number",
        default: defaults3.scale,
        minimum: 1,
        maximum: 3,
        enum: [1, 2, 3],
        description: localize("minimap.scale", "Scale of content drawn in the minimap: 1, 2 or 3.")
      },
      "editor.minimap.renderCharacters": {
        type: "boolean",
        default: defaults3.renderCharacters,
        description: localize("minimap.renderCharacters", "Render the actual characters on a line as opposed to color blocks.")
      },
      "editor.minimap.maxColumn": {
        type: "number",
        default: defaults3.maxColumn,
        description: localize("minimap.maxColumn", "Limit the width of the minimap to render at most a certain number of columns.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled),
      size: EditorStringEnumOption.stringSet(input.size, this.defaultValue.size, ["proportional", "fill", "fit"]),
      side: EditorStringEnumOption.stringSet(input.side, this.defaultValue.side, ["right", "left"]),
      showSlider: EditorStringEnumOption.stringSet(input.showSlider, this.defaultValue.showSlider, ["always", "mouseover"]),
      renderCharacters: EditorBooleanOption.boolean(input.renderCharacters, this.defaultValue.renderCharacters),
      scale: EditorIntOption.clampedInt(input.scale, 1, 1, 3),
      maxColumn: EditorIntOption.clampedInt(input.maxColumn, this.defaultValue.maxColumn, 1, 1e4)
    };
  }
};
function _multiCursorModifierFromString(multiCursorModifier) {
  if (multiCursorModifier === "ctrlCmd") {
    return isMacintosh ? "metaKey" : "ctrlKey";
  }
  return "altKey";
}
var EditorPadding = class extends BaseEditorOption {
  constructor() {
    super(66, "padding", {top: 0, bottom: 0}, {
      "editor.padding.top": {
        type: "number",
        default: 0,
        minimum: 0,
        maximum: 1e3,
        description: localize("padding.top", "Controls the amount of space between the top edge of the editor and the first line.")
      },
      "editor.padding.bottom": {
        type: "number",
        default: 0,
        minimum: 0,
        maximum: 1e3,
        description: localize("padding.bottom", "Controls the amount of space between the bottom edge of the editor and the last line.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      top: EditorIntOption.clampedInt(input.top, 0, 0, 1e3),
      bottom: EditorIntOption.clampedInt(input.bottom, 0, 0, 1e3)
    };
  }
};
var EditorParameterHints = class extends BaseEditorOption {
  constructor() {
    const defaults3 = {
      enabled: true,
      cycle: false
    };
    super(67, "parameterHints", defaults3, {
      "editor.parameterHints.enabled": {
        type: "boolean",
        default: defaults3.enabled,
        description: localize("parameterHints.enabled", "Enables a pop-up that shows parameter documentation and type information as you type.")
      },
      "editor.parameterHints.cycle": {
        type: "boolean",
        default: defaults3.cycle,
        description: localize("parameterHints.cycle", "Controls whether the parameter hints menu cycles or closes when reaching the end of the list.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled),
      cycle: EditorBooleanOption.boolean(input.cycle, this.defaultValue.cycle)
    };
  }
};
var EditorPixelRatio = class extends ComputedEditorOption {
  constructor() {
    super(115);
  }
  compute(env2, options, _23) {
    return env2.pixelRatio;
  }
};
var EditorQuickSuggestions = class extends BaseEditorOption {
  constructor() {
    const defaults3 = {
      other: true,
      comments: false,
      strings: false
    };
    super(70, "quickSuggestions", defaults3, {
      anyOf: [
        {
          type: "boolean"
        },
        {
          type: "object",
          properties: {
            strings: {
              type: "boolean",
              default: defaults3.strings,
              description: localize("quickSuggestions.strings", "Enable quick suggestions inside strings.")
            },
            comments: {
              type: "boolean",
              default: defaults3.comments,
              description: localize("quickSuggestions.comments", "Enable quick suggestions inside comments.")
            },
            other: {
              type: "boolean",
              default: defaults3.other,
              description: localize("quickSuggestions.other", "Enable quick suggestions outside of strings and comments.")
            }
          }
        }
      ],
      default: defaults3,
      description: localize("quickSuggestions", "Controls whether suggestions should automatically show up while typing.")
    });
    this.defaultValue = defaults3;
  }
  validate(_input) {
    if (typeof _input === "boolean") {
      return _input;
    }
    if (_input && typeof _input === "object") {
      const input = _input;
      const opts = {
        other: EditorBooleanOption.boolean(input.other, this.defaultValue.other),
        comments: EditorBooleanOption.boolean(input.comments, this.defaultValue.comments),
        strings: EditorBooleanOption.boolean(input.strings, this.defaultValue.strings)
      };
      if (opts.other && opts.comments && opts.strings) {
        return true;
      } else if (!opts.other && !opts.comments && !opts.strings) {
        return false;
      } else {
        return opts;
      }
    }
    return this.defaultValue;
  }
};
var EditorRenderLineNumbersOption = class extends BaseEditorOption {
  constructor() {
    super(52, "lineNumbers", {renderType: 1, renderFn: null}, {
      type: "string",
      enum: ["off", "on", "relative", "interval"],
      enumDescriptions: [
        localize("lineNumbers.off", "Line numbers are not rendered."),
        localize("lineNumbers.on", "Line numbers are rendered as absolute number."),
        localize("lineNumbers.relative", "Line numbers are rendered as distance in lines to cursor position."),
        localize("lineNumbers.interval", "Line numbers are rendered every 10 lines.")
      ],
      default: "on",
      description: localize("lineNumbers", "Controls the display of line numbers.")
    });
  }
  validate(lineNumbers) {
    let renderType = this.defaultValue.renderType;
    let renderFn = this.defaultValue.renderFn;
    if (typeof lineNumbers !== "undefined") {
      if (typeof lineNumbers === "function") {
        renderType = 4;
        renderFn = lineNumbers;
      } else if (lineNumbers === "interval") {
        renderType = 3;
      } else if (lineNumbers === "relative") {
        renderType = 2;
      } else if (lineNumbers === "on") {
        renderType = 1;
      } else {
        renderType = 0;
      }
    }
    return {
      renderType,
      renderFn
    };
  }
};
function filterValidationDecorations(options) {
  const renderValidationDecorations = options.get(79);
  if (renderValidationDecorations === "editable") {
    return options.get(72);
  }
  return renderValidationDecorations === "on" ? false : true;
}
var EditorRulers = class extends BaseEditorOption {
  constructor() {
    const defaults3 = [];
    const columnSchema = {type: "number", description: localize("rulers.size", "Number of monospace characters at which this editor ruler will render.")};
    super(83, "rulers", defaults3, {
      type: "array",
      items: {
        anyOf: [
          columnSchema,
          {
            type: [
              "object"
            ],
            properties: {
              column: columnSchema,
              color: {
                type: "string",
                description: localize("rulers.color", "Color of this editor ruler."),
                format: "color-hex"
              }
            }
          }
        ]
      },
      default: defaults3,
      description: localize("rulers", "Render vertical rulers after a certain number of monospace characters. Use multiple values for multiple rulers. No rulers are drawn if array is empty.")
    });
  }
  validate(input) {
    if (Array.isArray(input)) {
      let rulers = [];
      for (let _element of input) {
        if (typeof _element === "number") {
          rulers.push({
            column: EditorIntOption.clampedInt(_element, 0, 0, 1e4),
            color: null
          });
        } else if (_element && typeof _element === "object") {
          const element = _element;
          rulers.push({
            column: EditorIntOption.clampedInt(element.column, 0, 0, 1e4),
            color: element.color
          });
        }
      }
      rulers.sort((a2, b2) => a2.column - b2.column);
      return rulers;
    }
    return this.defaultValue;
  }
};
function _scrollbarVisibilityFromString(visibility, defaultValue) {
  if (typeof visibility !== "string") {
    return defaultValue;
  }
  switch (visibility) {
    case "hidden":
      return 2;
    case "visible":
      return 3;
    default:
      return 1;
  }
}
var EditorScrollbar = class extends BaseEditorOption {
  constructor() {
    super(84, "scrollbar", {
      vertical: 1,
      horizontal: 1,
      arrowSize: 11,
      useShadows: true,
      verticalHasArrows: false,
      horizontalHasArrows: false,
      horizontalScrollbarSize: 12,
      horizontalSliderSize: 12,
      verticalScrollbarSize: 14,
      verticalSliderSize: 14,
      handleMouseWheel: true,
      alwaysConsumeMouseWheel: true
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    const horizontalScrollbarSize = EditorIntOption.clampedInt(input.horizontalScrollbarSize, this.defaultValue.horizontalScrollbarSize, 0, 1e3);
    const verticalScrollbarSize = EditorIntOption.clampedInt(input.verticalScrollbarSize, this.defaultValue.verticalScrollbarSize, 0, 1e3);
    return {
      arrowSize: EditorIntOption.clampedInt(input.arrowSize, this.defaultValue.arrowSize, 0, 1e3),
      vertical: _scrollbarVisibilityFromString(input.vertical, this.defaultValue.vertical),
      horizontal: _scrollbarVisibilityFromString(input.horizontal, this.defaultValue.horizontal),
      useShadows: EditorBooleanOption.boolean(input.useShadows, this.defaultValue.useShadows),
      verticalHasArrows: EditorBooleanOption.boolean(input.verticalHasArrows, this.defaultValue.verticalHasArrows),
      horizontalHasArrows: EditorBooleanOption.boolean(input.horizontalHasArrows, this.defaultValue.horizontalHasArrows),
      handleMouseWheel: EditorBooleanOption.boolean(input.handleMouseWheel, this.defaultValue.handleMouseWheel),
      alwaysConsumeMouseWheel: EditorBooleanOption.boolean(input.alwaysConsumeMouseWheel, this.defaultValue.alwaysConsumeMouseWheel),
      horizontalScrollbarSize,
      horizontalSliderSize: EditorIntOption.clampedInt(input.horizontalSliderSize, horizontalScrollbarSize, 0, 1e3),
      verticalScrollbarSize,
      verticalSliderSize: EditorIntOption.clampedInt(input.verticalSliderSize, verticalScrollbarSize, 0, 1e3)
    };
  }
};
var EditorSuggest = class extends BaseEditorOption {
  constructor() {
    const defaults3 = {
      insertMode: "insert",
      filterGraceful: true,
      snippetsPreventQuickSuggestions: true,
      localityBonus: false,
      shareSuggestSelections: false,
      showIcons: true,
      maxVisibleSuggestions: 12,
      showMethods: true,
      showFunctions: true,
      showConstructors: true,
      showFields: true,
      showVariables: true,
      showClasses: true,
      showStructs: true,
      showInterfaces: true,
      showModules: true,
      showProperties: true,
      showEvents: true,
      showOperators: true,
      showUnits: true,
      showValues: true,
      showConstants: true,
      showEnums: true,
      showEnumMembers: true,
      showKeywords: true,
      showWords: true,
      showColors: true,
      showFiles: true,
      showReferences: true,
      showFolders: true,
      showTypeParameters: true,
      showSnippets: true,
      showUsers: true,
      showIssues: true,
      statusBar: {
        visible: false
      }
    };
    super(96, "suggest", defaults3, {
      "editor.suggest.insertMode": {
        type: "string",
        enum: ["insert", "replace"],
        enumDescriptions: [
          localize("suggest.insertMode.insert", "Insert suggestion without overwriting text right of the cursor."),
          localize("suggest.insertMode.replace", "Insert suggestion and overwrite text right of the cursor.")
        ],
        default: defaults3.insertMode,
        description: localize("suggest.insertMode", "Controls whether words are overwritten when accepting completions. Note that this depends on extensions opting into this feature.")
      },
      "editor.suggest.filterGraceful": {
        type: "boolean",
        default: defaults3.filterGraceful,
        description: localize("suggest.filterGraceful", "Controls whether filtering and sorting suggestions accounts for small typos.")
      },
      "editor.suggest.localityBonus": {
        type: "boolean",
        default: defaults3.localityBonus,
        description: localize("suggest.localityBonus", "Controls whether sorting favours words that appear close to the cursor.")
      },
      "editor.suggest.shareSuggestSelections": {
        type: "boolean",
        default: defaults3.shareSuggestSelections,
        markdownDescription: localize("suggest.shareSuggestSelections", "Controls whether remembered suggestion selections are shared between multiple workspaces and windows (needs `#editor.suggestSelection#`).")
      },
      "editor.suggest.snippetsPreventQuickSuggestions": {
        type: "boolean",
        default: defaults3.snippetsPreventQuickSuggestions,
        description: localize("suggest.snippetsPreventQuickSuggestions", "Controls whether an active snippet prevents quick suggestions.")
      },
      "editor.suggest.showIcons": {
        type: "boolean",
        default: defaults3.showIcons,
        description: localize("suggest.showIcons", "Controls whether to show or hide icons in suggestions.")
      },
      "editor.suggest.maxVisibleSuggestions": {
        type: "number",
        default: defaults3.maxVisibleSuggestions,
        minimum: 1,
        maximum: 15,
        description: localize("suggest.maxVisibleSuggestions", "Controls how many suggestions IntelliSense will show before showing a scrollbar (maximum 15).")
      },
      "editor.suggest.filteredTypes": {
        type: "object",
        deprecationMessage: localize("deprecated", "This setting is deprecated, please use separate settings like 'editor.suggest.showKeywords' or 'editor.suggest.showSnippets' instead.")
      },
      "editor.suggest.showMethods": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showMethods", "When enabled IntelliSense shows `method`-suggestions.")
      },
      "editor.suggest.showFunctions": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showFunctions", "When enabled IntelliSense shows `function`-suggestions.")
      },
      "editor.suggest.showConstructors": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showConstructors", "When enabled IntelliSense shows `constructor`-suggestions.")
      },
      "editor.suggest.showFields": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showFields", "When enabled IntelliSense shows `field`-suggestions.")
      },
      "editor.suggest.showVariables": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showVariables", "When enabled IntelliSense shows `variable`-suggestions.")
      },
      "editor.suggest.showClasses": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showClasss", "When enabled IntelliSense shows `class`-suggestions.")
      },
      "editor.suggest.showStructs": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showStructs", "When enabled IntelliSense shows `struct`-suggestions.")
      },
      "editor.suggest.showInterfaces": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showInterfaces", "When enabled IntelliSense shows `interface`-suggestions.")
      },
      "editor.suggest.showModules": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showModules", "When enabled IntelliSense shows `module`-suggestions.")
      },
      "editor.suggest.showProperties": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showPropertys", "When enabled IntelliSense shows `property`-suggestions.")
      },
      "editor.suggest.showEvents": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showEvents", "When enabled IntelliSense shows `event`-suggestions.")
      },
      "editor.suggest.showOperators": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showOperators", "When enabled IntelliSense shows `operator`-suggestions.")
      },
      "editor.suggest.showUnits": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showUnits", "When enabled IntelliSense shows `unit`-suggestions.")
      },
      "editor.suggest.showValues": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showValues", "When enabled IntelliSense shows `value`-suggestions.")
      },
      "editor.suggest.showConstants": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showConstants", "When enabled IntelliSense shows `constant`-suggestions.")
      },
      "editor.suggest.showEnums": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showEnums", "When enabled IntelliSense shows `enum`-suggestions.")
      },
      "editor.suggest.showEnumMembers": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showEnumMembers", "When enabled IntelliSense shows `enumMember`-suggestions.")
      },
      "editor.suggest.showKeywords": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showKeywords", "When enabled IntelliSense shows `keyword`-suggestions.")
      },
      "editor.suggest.showWords": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showTexts", "When enabled IntelliSense shows `text`-suggestions.")
      },
      "editor.suggest.showColors": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showColors", "When enabled IntelliSense shows `color`-suggestions.")
      },
      "editor.suggest.showFiles": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showFiles", "When enabled IntelliSense shows `file`-suggestions.")
      },
      "editor.suggest.showReferences": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showReferences", "When enabled IntelliSense shows `reference`-suggestions.")
      },
      "editor.suggest.showCustomcolors": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showCustomcolors", "When enabled IntelliSense shows `customcolor`-suggestions.")
      },
      "editor.suggest.showFolders": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showFolders", "When enabled IntelliSense shows `folder`-suggestions.")
      },
      "editor.suggest.showTypeParameters": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showTypeParameters", "When enabled IntelliSense shows `typeParameter`-suggestions.")
      },
      "editor.suggest.showSnippets": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showSnippets", "When enabled IntelliSense shows `snippet`-suggestions.")
      },
      "editor.suggest.showUsers": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showUsers", "When enabled IntelliSense shows `user`-suggestions.")
      },
      "editor.suggest.showIssues": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showIssues", "When enabled IntelliSense shows `issues`-suggestions.")
      },
      "editor.suggest.statusBar.visible": {
        type: "boolean",
        default: false,
        markdownDescription: localize("editor.suggest.statusBar.visible", "Controls the visibility of the status bar at the bottom of the suggest widget.")
      }
    });
  }
  validate(_input) {
    var _a;
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      insertMode: EditorStringEnumOption.stringSet(input.insertMode, this.defaultValue.insertMode, ["insert", "replace"]),
      filterGraceful: EditorBooleanOption.boolean(input.filterGraceful, this.defaultValue.filterGraceful),
      snippetsPreventQuickSuggestions: EditorBooleanOption.boolean(input.snippetsPreventQuickSuggestions, this.defaultValue.filterGraceful),
      localityBonus: EditorBooleanOption.boolean(input.localityBonus, this.defaultValue.localityBonus),
      shareSuggestSelections: EditorBooleanOption.boolean(input.shareSuggestSelections, this.defaultValue.shareSuggestSelections),
      showIcons: EditorBooleanOption.boolean(input.showIcons, this.defaultValue.showIcons),
      maxVisibleSuggestions: EditorIntOption.clampedInt(input.maxVisibleSuggestions, this.defaultValue.maxVisibleSuggestions, 1, 15),
      showMethods: EditorBooleanOption.boolean(input.showMethods, this.defaultValue.showMethods),
      showFunctions: EditorBooleanOption.boolean(input.showFunctions, this.defaultValue.showFunctions),
      showConstructors: EditorBooleanOption.boolean(input.showConstructors, this.defaultValue.showConstructors),
      showFields: EditorBooleanOption.boolean(input.showFields, this.defaultValue.showFields),
      showVariables: EditorBooleanOption.boolean(input.showVariables, this.defaultValue.showVariables),
      showClasses: EditorBooleanOption.boolean(input.showClasses, this.defaultValue.showClasses),
      showStructs: EditorBooleanOption.boolean(input.showStructs, this.defaultValue.showStructs),
      showInterfaces: EditorBooleanOption.boolean(input.showInterfaces, this.defaultValue.showInterfaces),
      showModules: EditorBooleanOption.boolean(input.showModules, this.defaultValue.showModules),
      showProperties: EditorBooleanOption.boolean(input.showProperties, this.defaultValue.showProperties),
      showEvents: EditorBooleanOption.boolean(input.showEvents, this.defaultValue.showEvents),
      showOperators: EditorBooleanOption.boolean(input.showOperators, this.defaultValue.showOperators),
      showUnits: EditorBooleanOption.boolean(input.showUnits, this.defaultValue.showUnits),
      showValues: EditorBooleanOption.boolean(input.showValues, this.defaultValue.showValues),
      showConstants: EditorBooleanOption.boolean(input.showConstants, this.defaultValue.showConstants),
      showEnums: EditorBooleanOption.boolean(input.showEnums, this.defaultValue.showEnums),
      showEnumMembers: EditorBooleanOption.boolean(input.showEnumMembers, this.defaultValue.showEnumMembers),
      showKeywords: EditorBooleanOption.boolean(input.showKeywords, this.defaultValue.showKeywords),
      showWords: EditorBooleanOption.boolean(input.showWords, this.defaultValue.showWords),
      showColors: EditorBooleanOption.boolean(input.showColors, this.defaultValue.showColors),
      showFiles: EditorBooleanOption.boolean(input.showFiles, this.defaultValue.showFiles),
      showReferences: EditorBooleanOption.boolean(input.showReferences, this.defaultValue.showReferences),
      showFolders: EditorBooleanOption.boolean(input.showFolders, this.defaultValue.showFolders),
      showTypeParameters: EditorBooleanOption.boolean(input.showTypeParameters, this.defaultValue.showTypeParameters),
      showSnippets: EditorBooleanOption.boolean(input.showSnippets, this.defaultValue.showSnippets),
      showUsers: EditorBooleanOption.boolean(input.showUsers, this.defaultValue.showUsers),
      showIssues: EditorBooleanOption.boolean(input.showIssues, this.defaultValue.showIssues),
      statusBar: {
        visible: EditorBooleanOption.boolean((_a = input.statusBar) === null || _a === void 0 ? void 0 : _a.visible, !!this.defaultValue.statusBar.visible)
      }
    };
  }
};
var EditorTabFocusMode = class extends ComputedEditorOption {
  constructor() {
    super(116, [72]);
  }
  compute(env2, options, _23) {
    const readOnly = options.get(72);
    return readOnly ? true : env2.tabFocusMode;
  }
};
function _wrappingIndentFromString(wrappingIndent) {
  switch (wrappingIndent) {
    case "none":
      return 0;
    case "same":
      return 1;
    case "indent":
      return 2;
    case "deepIndent":
      return 3;
  }
}
var EditorWrappingInfoComputer = class extends ComputedEditorOption {
  constructor() {
    super(118, [117]);
  }
  compute(env2, options, _23) {
    const layoutInfo = options.get(117);
    return {
      isDominatedByLongLines: env2.isDominatedByLongLines,
      isWordWrapMinified: layoutInfo.isWordWrapMinified,
      isViewportWrapping: layoutInfo.isViewportWrapping,
      wrappingColumn: layoutInfo.wrappingColumn
    };
  }
};
var DEFAULT_WINDOWS_FONT_FAMILY = "Consolas, 'Courier New', monospace";
var DEFAULT_MAC_FONT_FAMILY = "Menlo, Monaco, 'Courier New', monospace";
var DEFAULT_LINUX_FONT_FAMILY = "'Droid Sans Mono', 'monospace', monospace, 'Droid Sans Fallback'";
var EDITOR_FONT_DEFAULTS = {
  fontFamily: isMacintosh ? DEFAULT_MAC_FONT_FAMILY : isLinux ? DEFAULT_LINUX_FONT_FAMILY : DEFAULT_WINDOWS_FONT_FAMILY,
  fontWeight: "normal",
  fontSize: isMacintosh ? 12 : 14,
  lineHeight: 0,
  letterSpacing: 0
};
var EDITOR_MODEL_DEFAULTS = {
  tabSize: 4,
  indentSize: 4,
  insertSpaces: true,
  detectIndentation: true,
  trimAutoWhitespace: true,
  largeFileOptimizations: true
};
var editorOptionsRegistry = [];
function register(option) {
  editorOptionsRegistry[option.id] = option;
  return option;
}
var EditorOptions = {
  acceptSuggestionOnCommitCharacter: register(new EditorBooleanOption(0, "acceptSuggestionOnCommitCharacter", true, {markdownDescription: localize("acceptSuggestionOnCommitCharacter", "Controls whether suggestions should be accepted on commit characters. For example, in JavaScript, the semi-colon (`;`) can be a commit character that accepts a suggestion and types that character.")})),
  acceptSuggestionOnEnter: register(new EditorStringEnumOption(1, "acceptSuggestionOnEnter", "on", ["on", "smart", "off"], {
    markdownEnumDescriptions: [
      "",
      localize("acceptSuggestionOnEnterSmart", "Only accept a suggestion with `Enter` when it makes a textual change."),
      ""
    ],
    markdownDescription: localize("acceptSuggestionOnEnter", "Controls whether suggestions should be accepted on `Enter`, in addition to `Tab`. Helps to avoid ambiguity between inserting new lines or accepting suggestions.")
  })),
  accessibilitySupport: register(new EditorAccessibilitySupport()),
  accessibilityPageSize: register(new EditorIntOption(3, "accessibilityPageSize", 10, 1, 1073741824, {description: localize("accessibilityPageSize", "Controls the number of lines in the editor that can be read out by a screen reader. Warning: this has a performance implication for numbers larger than the default.")})),
  ariaLabel: register(new EditorStringOption(4, "ariaLabel", localize("editorViewAccessibleLabel", "Editor content"))),
  autoClosingBrackets: register(new EditorStringEnumOption(5, "autoClosingBrackets", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
    enumDescriptions: [
      "",
      localize("editor.autoClosingBrackets.languageDefined", "Use language configurations to determine when to autoclose brackets."),
      localize("editor.autoClosingBrackets.beforeWhitespace", "Autoclose brackets only when the cursor is to the left of whitespace."),
      ""
    ],
    description: localize("autoClosingBrackets", "Controls whether the editor should automatically close brackets after the user adds an opening bracket.")
  })),
  autoClosingOvertype: register(new EditorStringEnumOption(6, "autoClosingOvertype", "auto", ["always", "auto", "never"], {
    enumDescriptions: [
      "",
      localize("editor.autoClosingOvertype.auto", "Type over closing quotes or brackets only if they were automatically inserted."),
      ""
    ],
    description: localize("autoClosingOvertype", "Controls whether the editor should type over closing quotes or brackets.")
  })),
  autoClosingQuotes: register(new EditorStringEnumOption(7, "autoClosingQuotes", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
    enumDescriptions: [
      "",
      localize("editor.autoClosingQuotes.languageDefined", "Use language configurations to determine when to autoclose quotes."),
      localize("editor.autoClosingQuotes.beforeWhitespace", "Autoclose quotes only when the cursor is to the left of whitespace."),
      ""
    ],
    description: localize("autoClosingQuotes", "Controls whether the editor should automatically close quotes after the user adds an opening quote.")
  })),
  autoIndent: register(new EditorEnumOption(8, "autoIndent", 4, "full", ["none", "keep", "brackets", "advanced", "full"], _autoIndentFromString, {
    enumDescriptions: [
      localize("editor.autoIndent.none", "The editor will not insert indentation automatically."),
      localize("editor.autoIndent.keep", "The editor will keep the current line's indentation."),
      localize("editor.autoIndent.brackets", "The editor will keep the current line's indentation and honor language defined brackets."),
      localize("editor.autoIndent.advanced", "The editor will keep the current line's indentation, honor language defined brackets and invoke special onEnterRules defined by languages."),
      localize("editor.autoIndent.full", "The editor will keep the current line's indentation, honor language defined brackets, invoke special onEnterRules defined by languages, and honor indentationRules defined by languages.")
    ],
    description: localize("autoIndent", "Controls whether the editor should automatically adjust the indentation when users type, paste, move or indent lines.")
  })),
  automaticLayout: register(new EditorBooleanOption(9, "automaticLayout", false)),
  autoSurround: register(new EditorStringEnumOption(10, "autoSurround", "languageDefined", ["languageDefined", "quotes", "brackets", "never"], {
    enumDescriptions: [
      localize("editor.autoSurround.languageDefined", "Use language configurations to determine when to automatically surround selections."),
      localize("editor.autoSurround.quotes", "Surround with quotes but not brackets."),
      localize("editor.autoSurround.brackets", "Surround with brackets but not quotes."),
      ""
    ],
    description: localize("autoSurround", "Controls whether the editor should automatically surround selections.")
  })),
  codeLens: register(new EditorBooleanOption(11, "codeLens", true, {description: localize("codeLens", "Controls whether the editor shows CodeLens.")})),
  colorDecorators: register(new EditorBooleanOption(12, "colorDecorators", true, {description: localize("colorDecorators", "Controls whether the editor should render the inline color decorators and color picker.")})),
  columnSelection: register(new EditorBooleanOption(13, "columnSelection", false, {description: localize("columnSelection", "Enable that the selection with the mouse and keys is doing column selection.")})),
  comments: register(new EditorComments()),
  contextmenu: register(new EditorBooleanOption(15, "contextmenu", true)),
  copyWithSyntaxHighlighting: register(new EditorBooleanOption(16, "copyWithSyntaxHighlighting", true, {description: localize("copyWithSyntaxHighlighting", "Controls whether syntax highlighting should be copied into the clipboard.")})),
  cursorBlinking: register(new EditorEnumOption(17, "cursorBlinking", 1, "blink", ["blink", "smooth", "phase", "expand", "solid"], _cursorBlinkingStyleFromString, {description: localize("cursorBlinking", "Control the cursor animation style.")})),
  cursorSmoothCaretAnimation: register(new EditorBooleanOption(18, "cursorSmoothCaretAnimation", false, {description: localize("cursorSmoothCaretAnimation", "Controls whether the smooth caret animation should be enabled.")})),
  cursorStyle: register(new EditorEnumOption(19, "cursorStyle", TextEditorCursorStyle.Line, "line", ["line", "block", "underline", "line-thin", "block-outline", "underline-thin"], _cursorStyleFromString, {description: localize("cursorStyle", "Controls the cursor style.")})),
  cursorSurroundingLines: register(new EditorIntOption(20, "cursorSurroundingLines", 0, 0, 1073741824, {description: localize("cursorSurroundingLines", "Controls the minimal number of visible leading and trailing lines surrounding the cursor. Known as 'scrollOff' or `scrollOffset` in some other editors.")})),
  cursorSurroundingLinesStyle: register(new EditorStringEnumOption(21, "cursorSurroundingLinesStyle", "default", ["default", "all"], {
    enumDescriptions: [
      localize("cursorSurroundingLinesStyle.default", "`cursorSurroundingLines` is enforced only when triggered via the keyboard or API."),
      localize("cursorSurroundingLinesStyle.all", "`cursorSurroundingLines` is enforced always.")
    ],
    description: localize("cursorSurroundingLinesStyle", "Controls when `cursorSurroundingLines` should be enforced.")
  })),
  cursorWidth: register(new EditorIntOption(22, "cursorWidth", 0, 0, 1073741824, {markdownDescription: localize("cursorWidth", "Controls the width of the cursor when `#editor.cursorStyle#` is set to `line`.")})),
  disableLayerHinting: register(new EditorBooleanOption(23, "disableLayerHinting", false)),
  disableMonospaceOptimizations: register(new EditorBooleanOption(24, "disableMonospaceOptimizations", false)),
  dragAndDrop: register(new EditorBooleanOption(25, "dragAndDrop", true, {description: localize("dragAndDrop", "Controls whether the editor should allow moving selections via drag and drop.")})),
  emptySelectionClipboard: register(new EditorEmptySelectionClipboard()),
  extraEditorClassName: register(new EditorStringOption(27, "extraEditorClassName", "")),
  fastScrollSensitivity: register(new EditorFloatOption(28, "fastScrollSensitivity", 5, (x2) => x2 <= 0 ? 5 : x2, {markdownDescription: localize("fastScrollSensitivity", "Scrolling speed multiplier when pressing `Alt`.")})),
  find: register(new EditorFind()),
  fixedOverflowWidgets: register(new EditorBooleanOption(30, "fixedOverflowWidgets", false)),
  folding: register(new EditorBooleanOption(31, "folding", true, {description: localize("folding", "Controls whether the editor has code folding enabled.")})),
  foldingStrategy: register(new EditorStringEnumOption(32, "foldingStrategy", "auto", ["auto", "indentation"], {
    enumDescriptions: [
      localize("foldingStrategy.auto", "Use a language-specific folding strategy if available, else the indentation-based one."),
      localize("foldingStrategy.indentation", "Use the indentation-based folding strategy.")
    ],
    description: localize("foldingStrategy", "Controls the strategy for computing folding ranges.")
  })),
  foldingHighlight: register(new EditorBooleanOption(33, "foldingHighlight", true, {description: localize("foldingHighlight", "Controls whether the editor should highlight folded ranges.")})),
  unfoldOnClickAfterEndOfLine: register(new EditorBooleanOption(34, "unfoldOnClickAfterEndOfLine", false, {description: localize("unfoldOnClickAfterEndOfLine", "Controls whether clicking on the empty content after a folded line will unfold the line.")})),
  fontFamily: register(new EditorStringOption(35, "fontFamily", EDITOR_FONT_DEFAULTS.fontFamily, {description: localize("fontFamily", "Controls the font family.")})),
  fontInfo: register(new EditorFontInfo()),
  fontLigatures2: register(new EditorFontLigatures()),
  fontSize: register(new EditorFontSize()),
  fontWeight: register(new EditorFontWeight()),
  formatOnPaste: register(new EditorBooleanOption(40, "formatOnPaste", false, {description: localize("formatOnPaste", "Controls whether the editor should automatically format the pasted content. A formatter must be available and the formatter should be able to format a range in a document.")})),
  formatOnType: register(new EditorBooleanOption(41, "formatOnType", false, {description: localize("formatOnType", "Controls whether the editor should automatically format the line after typing.")})),
  glyphMargin: register(new EditorBooleanOption(42, "glyphMargin", true, {description: localize("glyphMargin", "Controls whether the editor should render the vertical glyph margin. Glyph margin is mostly used for debugging.")})),
  gotoLocation: register(new EditorGoToLocation()),
  hideCursorInOverviewRuler: register(new EditorBooleanOption(44, "hideCursorInOverviewRuler", false, {description: localize("hideCursorInOverviewRuler", "Controls whether the cursor should be hidden in the overview ruler.")})),
  highlightActiveIndentGuide: register(new EditorBooleanOption(45, "highlightActiveIndentGuide", true, {description: localize("highlightActiveIndentGuide", "Controls whether the editor should highlight the active indent guide.")})),
  hover: register(new EditorHover()),
  inDiffEditor: register(new EditorBooleanOption(47, "inDiffEditor", false)),
  letterSpacing: register(new EditorFloatOption(48, "letterSpacing", EDITOR_FONT_DEFAULTS.letterSpacing, (x2) => EditorFloatOption.clamp(x2, -5, 20), {description: localize("letterSpacing", "Controls the letter spacing in pixels.")})),
  lightbulb: register(new EditorLightbulb()),
  lineDecorationsWidth: register(new SimpleEditorOption(50, "lineDecorationsWidth", 10)),
  lineHeight: register(new EditorLineHeight()),
  lineNumbers: register(new EditorRenderLineNumbersOption()),
  lineNumbersMinChars: register(new EditorIntOption(53, "lineNumbersMinChars", 5, 1, 300)),
  links: register(new EditorBooleanOption(54, "links", true, {description: localize("links", "Controls whether the editor should detect links and make them clickable.")})),
  matchBrackets: register(new EditorStringEnumOption(55, "matchBrackets", "always", ["always", "near", "never"], {description: localize("matchBrackets", "Highlight matching brackets.")})),
  minimap: register(new EditorMinimap()),
  mouseStyle: register(new EditorStringEnumOption(57, "mouseStyle", "text", ["text", "default", "copy"])),
  mouseWheelScrollSensitivity: register(new EditorFloatOption(58, "mouseWheelScrollSensitivity", 1, (x2) => x2 === 0 ? 1 : x2, {markdownDescription: localize("mouseWheelScrollSensitivity", "A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.")})),
  mouseWheelZoom: register(new EditorBooleanOption(59, "mouseWheelZoom", false, {markdownDescription: localize("mouseWheelZoom", "Zoom the font of the editor when using mouse wheel and holding `Ctrl`.")})),
  multiCursorMergeOverlapping: register(new EditorBooleanOption(60, "multiCursorMergeOverlapping", true, {description: localize("multiCursorMergeOverlapping", "Merge multiple cursors when they are overlapping.")})),
  multiCursorModifier: register(new EditorEnumOption(61, "multiCursorModifier", "altKey", "alt", ["ctrlCmd", "alt"], _multiCursorModifierFromString, {
    markdownEnumDescriptions: [
      localize("multiCursorModifier.ctrlCmd", "Maps to `Control` on Windows and Linux and to `Command` on macOS."),
      localize("multiCursorModifier.alt", "Maps to `Alt` on Windows and Linux and to `Option` on macOS.")
    ],
    markdownDescription: localize({
      key: "multiCursorModifier",
      comment: [
        "- `ctrlCmd` refers to a value the setting can take and should not be localized.",
        "- `Control` and `Command` refer to the modifier keys Ctrl or Cmd on the keyboard and can be localized."
      ]
    }, "The modifier to be used to add multiple cursors with the mouse. The Go To Definition and Open Link mouse gestures will adapt such that they do not conflict with the multicursor modifier. [Read more](https://code.visualstudio.com/docs/editor/codebasics#_multicursor-modifier).")
  })),
  multiCursorPaste: register(new EditorStringEnumOption(62, "multiCursorPaste", "spread", ["spread", "full"], {
    markdownEnumDescriptions: [
      localize("multiCursorPaste.spread", "Each cursor pastes a single line of the text."),
      localize("multiCursorPaste.full", "Each cursor pastes the full text.")
    ],
    markdownDescription: localize("multiCursorPaste", "Controls pasting when the line count of the pasted text matches the cursor count.")
  })),
  occurrencesHighlight: register(new EditorBooleanOption(63, "occurrencesHighlight", true, {description: localize("occurrencesHighlight", "Controls whether the editor should highlight semantic symbol occurrences.")})),
  overviewRulerBorder: register(new EditorBooleanOption(64, "overviewRulerBorder", true, {description: localize("overviewRulerBorder", "Controls whether a border should be drawn around the overview ruler.")})),
  overviewRulerLanes: register(new EditorIntOption(65, "overviewRulerLanes", 3, 0, 3)),
  padding: register(new EditorPadding()),
  parameterHints: register(new EditorParameterHints()),
  peekWidgetDefaultFocus: register(new EditorStringEnumOption(68, "peekWidgetDefaultFocus", "tree", ["tree", "editor"], {
    enumDescriptions: [
      localize("peekWidgetDefaultFocus.tree", "Focus the tree when opening peek"),
      localize("peekWidgetDefaultFocus.editor", "Focus the editor when opening peek")
    ],
    description: localize("peekWidgetDefaultFocus", "Controls whether to focus the inline editor or the tree in the peek widget.")
  })),
  definitionLinkOpensInPeek: register(new EditorBooleanOption(69, "definitionLinkOpensInPeek", false, {description: localize("definitionLinkOpensInPeek", "Controls whether the Go to Definition mouse gesture always opens the peek widget.")})),
  quickSuggestions: register(new EditorQuickSuggestions()),
  quickSuggestionsDelay: register(new EditorIntOption(71, "quickSuggestionsDelay", 10, 0, 1073741824, {description: localize("quickSuggestionsDelay", "Controls the delay in milliseconds after which quick suggestions will show up.")})),
  readOnly: register(new EditorBooleanOption(72, "readOnly", false)),
  renameOnType: register(new EditorBooleanOption(73, "renameOnType", false, {description: localize("renameOnType", "Controls whether the editor auto renames on type.")})),
  renderControlCharacters: register(new EditorBooleanOption(74, "renderControlCharacters", false, {description: localize("renderControlCharacters", "Controls whether the editor should render control characters.")})),
  renderIndentGuides: register(new EditorBooleanOption(75, "renderIndentGuides", true, {description: localize("renderIndentGuides", "Controls whether the editor should render indent guides.")})),
  renderFinalNewline: register(new EditorBooleanOption(76, "renderFinalNewline", true, {description: localize("renderFinalNewline", "Render last line number when the file ends with a newline.")})),
  renderLineHighlight: register(new EditorStringEnumOption(77, "renderLineHighlight", "line", ["none", "gutter", "line", "all"], {
    enumDescriptions: [
      "",
      "",
      "",
      localize("renderLineHighlight.all", "Highlights both the gutter and the current line.")
    ],
    description: localize("renderLineHighlight", "Controls how the editor should render the current line highlight.")
  })),
  renderLineHighlightOnlyWhenFocus: register(new EditorBooleanOption(78, "renderLineHighlightOnlyWhenFocus", false, {description: localize("renderLineHighlightOnlyWhenFocus", "Controls if the editor should render the current line highlight only when the editor is focused")})),
  renderValidationDecorations: register(new EditorStringEnumOption(79, "renderValidationDecorations", "editable", ["editable", "on", "off"])),
  renderWhitespace: register(new EditorStringEnumOption(80, "renderWhitespace", "selection", ["none", "boundary", "selection", "trailing", "all"], {
    enumDescriptions: [
      "",
      localize("renderWhitespace.boundary", "Render whitespace characters except for single spaces between words."),
      localize("renderWhitespace.selection", "Render whitespace characters only on selected text."),
      localize("renderWhitespace.trailing", "Render only trailing whitespace characters"),
      ""
    ],
    description: localize("renderWhitespace", "Controls how the editor should render whitespace characters.")
  })),
  revealHorizontalRightPadding: register(new EditorIntOption(81, "revealHorizontalRightPadding", 30, 0, 1e3)),
  roundedSelection: register(new EditorBooleanOption(82, "roundedSelection", true, {description: localize("roundedSelection", "Controls whether selections should have rounded corners.")})),
  rulers: register(new EditorRulers()),
  scrollbar: register(new EditorScrollbar()),
  scrollBeyondLastColumn: register(new EditorIntOption(85, "scrollBeyondLastColumn", 5, 0, 1073741824, {description: localize("scrollBeyondLastColumn", "Controls the number of extra characters beyond which the editor will scroll horizontally.")})),
  scrollBeyondLastLine: register(new EditorBooleanOption(86, "scrollBeyondLastLine", true, {description: localize("scrollBeyondLastLine", "Controls whether the editor will scroll beyond the last line.")})),
  scrollPredominantAxis: register(new EditorBooleanOption(87, "scrollPredominantAxis", true, {description: localize("scrollPredominantAxis", "Scroll only along the predominant axis when scrolling both vertically and horizontally at the same time. Prevents horizontal drift when scrolling vertically on a trackpad.")})),
  selectionClipboard: register(new EditorBooleanOption(88, "selectionClipboard", true, {
    description: localize("selectionClipboard", "Controls whether the Linux primary clipboard should be supported."),
    included: isLinux
  })),
  selectionHighlight: register(new EditorBooleanOption(89, "selectionHighlight", true, {description: localize("selectionHighlight", "Controls whether the editor should highlight matches similar to the selection.")})),
  selectOnLineNumbers: register(new EditorBooleanOption(90, "selectOnLineNumbers", true)),
  showFoldingControls: register(new EditorStringEnumOption(91, "showFoldingControls", "mouseover", ["always", "mouseover"], {
    enumDescriptions: [
      localize("showFoldingControls.always", "Always show the folding controls."),
      localize("showFoldingControls.mouseover", "Only show the folding controls when the mouse is over the gutter.")
    ],
    description: localize("showFoldingControls", "Controls when the folding controls on the gutter are shown.")
  })),
  showUnused: register(new EditorBooleanOption(92, "showUnused", true, {description: localize("showUnused", "Controls fading out of unused code.")})),
  showDeprecated: register(new EditorBooleanOption(113, "showDeprecated", true, {description: localize("showDeprecated", "Controls strikethrough deprecated variables.")})),
  snippetSuggestions: register(new EditorStringEnumOption(93, "snippetSuggestions", "inline", ["top", "bottom", "inline", "none"], {
    enumDescriptions: [
      localize("snippetSuggestions.top", "Show snippet suggestions on top of other suggestions."),
      localize("snippetSuggestions.bottom", "Show snippet suggestions below other suggestions."),
      localize("snippetSuggestions.inline", "Show snippets suggestions with other suggestions."),
      localize("snippetSuggestions.none", "Do not show snippet suggestions.")
    ],
    description: localize("snippetSuggestions", "Controls whether snippets are shown with other suggestions and how they are sorted.")
  })),
  smoothScrolling: register(new EditorBooleanOption(94, "smoothScrolling", false, {description: localize("smoothScrolling", "Controls whether the editor will scroll using an animation.")})),
  stopRenderingLineAfter: register(new EditorIntOption(95, "stopRenderingLineAfter", 1e4, -1, 1073741824)),
  suggest: register(new EditorSuggest()),
  suggestFontSize: register(new EditorIntOption(97, "suggestFontSize", 0, 0, 1e3, {markdownDescription: localize("suggestFontSize", "Font size for the suggest widget. When set to `0`, the value of `#editor.fontSize#` is used.")})),
  suggestLineHeight: register(new EditorIntOption(98, "suggestLineHeight", 0, 0, 1e3, {markdownDescription: localize("suggestLineHeight", "Line height for the suggest widget. When set to `0`, the value of `#editor.lineHeight#` is used.")})),
  suggestOnTriggerCharacters: register(new EditorBooleanOption(99, "suggestOnTriggerCharacters", true, {description: localize("suggestOnTriggerCharacters", "Controls whether suggestions should automatically show up when typing trigger characters.")})),
  suggestSelection: register(new EditorStringEnumOption(100, "suggestSelection", "recentlyUsed", ["first", "recentlyUsed", "recentlyUsedByPrefix"], {
    markdownEnumDescriptions: [
      localize("suggestSelection.first", "Always select the first suggestion."),
      localize("suggestSelection.recentlyUsed", "Select recent suggestions unless further typing selects one, e.g. `console.| -> console.log` because `log` has been completed recently."),
      localize("suggestSelection.recentlyUsedByPrefix", "Select suggestions based on previous prefixes that have completed those suggestions, e.g. `co -> console` and `con -> const`.")
    ],
    description: localize("suggestSelection", "Controls how suggestions are pre-selected when showing the suggest list.")
  })),
  tabCompletion: register(new EditorStringEnumOption(101, "tabCompletion", "off", ["on", "off", "onlySnippets"], {
    enumDescriptions: [
      localize("tabCompletion.on", "Tab complete will insert the best matching suggestion when pressing tab."),
      localize("tabCompletion.off", "Disable tab completions."),
      localize("tabCompletion.onlySnippets", "Tab complete snippets when their prefix match. Works best when 'quickSuggestions' aren't enabled.")
    ],
    description: localize("tabCompletion", "Enables tab completions.")
  })),
  tabIndex: register(new EditorIntOption(102, "tabIndex", 0, -1, 1073741824)),
  unusualLineTerminators: register(new EditorStringEnumOption(103, "unusualLineTerminators", "prompt", ["off", "prompt", "auto"], {
    enumDescriptions: [
      localize("unusualLineTerminators.off", "Unusual line terminators are ignored."),
      localize("unusualLineTerminators.prompt", "Unusual line terminators prompt to be removed."),
      localize("unusualLineTerminators.auto", "Unusual line terminators are automatically removed.")
    ],
    description: localize("unusualLineTerminators", "Remove unusual line terminators that might cause problems.")
  })),
  useTabStops: register(new EditorBooleanOption(104, "useTabStops", true, {description: localize("useTabStops", "Inserting and deleting whitespace follows tab stops.")})),
  wordSeparators: register(new EditorStringOption(105, "wordSeparators", USUAL_WORD_SEPARATORS, {description: localize("wordSeparators", "Characters that will be used as word separators when doing word related navigations or operations.")})),
  wordWrap: register(new EditorStringEnumOption(106, "wordWrap", "off", ["off", "on", "wordWrapColumn", "bounded"], {
    markdownEnumDescriptions: [
      localize("wordWrap.off", "Lines will never wrap."),
      localize("wordWrap.on", "Lines will wrap at the viewport width."),
      localize({
        key: "wordWrap.wordWrapColumn",
        comment: [
          "- `editor.wordWrapColumn` refers to a different setting and should not be localized."
        ]
      }, "Lines will wrap at `#editor.wordWrapColumn#`."),
      localize({
        key: "wordWrap.bounded",
        comment: [
          "- viewport means the edge of the visible window size.",
          "- `editor.wordWrapColumn` refers to a different setting and should not be localized."
        ]
      }, "Lines will wrap at the minimum of viewport and `#editor.wordWrapColumn#`.")
    ],
    description: localize({
      key: "wordWrap",
      comment: [
        "- 'off', 'on', 'wordWrapColumn' and 'bounded' refer to values the setting can take and should not be localized.",
        "- `editor.wordWrapColumn` refers to a different setting and should not be localized."
      ]
    }, "Controls how lines should wrap.")
  })),
  wordWrapBreakAfterCharacters: register(new EditorStringOption(107, "wordWrapBreakAfterCharacters", " 	})]?|/&.,;¢°′″‰℃、。｡､￠，．：；？！％・･ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ｧｨｩｪｫｬｭｮｯｰ”〉》」』】〕）］｝｣")),
  wordWrapBreakBeforeCharacters: register(new EditorStringOption(108, "wordWrapBreakBeforeCharacters", "([{‘“〈《「『【〔（［｛｢£¥＄￡￥+＋")),
  wordWrapColumn: register(new EditorIntOption(109, "wordWrapColumn", 80, 1, 1073741824, {
    markdownDescription: localize({
      key: "wordWrapColumn",
      comment: [
        "- `editor.wordWrap` refers to a different setting and should not be localized.",
        "- 'wordWrapColumn' and 'bounded' refer to values the different setting can take and should not be localized."
      ]
    }, "Controls the wrapping column of the editor when `#editor.wordWrap#` is `wordWrapColumn` or `bounded`.")
  })),
  wordWrapMinified: register(new EditorBooleanOption(110, "wordWrapMinified", true)),
  wrappingIndent: register(new EditorEnumOption(111, "wrappingIndent", 1, "same", ["none", "same", "indent", "deepIndent"], _wrappingIndentFromString, {
    enumDescriptions: [
      localize("wrappingIndent.none", "No indentation. Wrapped lines begin at column 1."),
      localize("wrappingIndent.same", "Wrapped lines get the same indentation as the parent."),
      localize("wrappingIndent.indent", "Wrapped lines get +1 indentation toward the parent."),
      localize("wrappingIndent.deepIndent", "Wrapped lines get +2 indentation toward the parent.")
    ],
    description: localize("wrappingIndent", "Controls the indentation of wrapped lines.")
  })),
  wrappingStrategy: register(new EditorStringEnumOption(112, "wrappingStrategy", "simple", ["simple", "advanced"], {
    enumDescriptions: [
      localize("wrappingStrategy.simple", "Assumes that all characters are of the same width. This is a fast algorithm that works correctly for monospace fonts and certain scripts (like Latin characters) where glyphs are of equal width."),
      localize("wrappingStrategy.advanced", "Delegates wrapping points computation to the browser. This is a slow algorithm, that might cause freezes for large files, but it works correctly in all cases.")
    ],
    description: localize("wrappingStrategy", "Controls the algorithm that computes wrapping points.")
  })),
  editorClassName: register(new EditorClassName()),
  pixelRatio: register(new EditorPixelRatio()),
  tabFocusMode: register(new EditorTabFocusMode()),
  layoutInfo: register(new EditorLayoutInfoComputer()),
  wrappingInfo: register(new EditorWrappingInfoComputer())
};
var ErrorHandler = class {
  constructor() {
    this.listeners = [];
    this.unexpectedErrorHandler = function(e2) {
      setTimeout(() => {
        if (e2.stack) {
          throw new Error(e2.message + "\n\n" + e2.stack);
        }
        throw e2;
      }, 0);
    };
  }
  emit(e2) {
    this.listeners.forEach((listener) => {
      listener(e2);
    });
  }
  onUnexpectedError(e2) {
    this.unexpectedErrorHandler(e2);
    this.emit(e2);
  }
  onUnexpectedExternalError(e2) {
    this.unexpectedErrorHandler(e2);
  }
};
var errorHandler = new ErrorHandler();
function onUnexpectedError(e2) {
  if (!isPromiseCanceledError(e2)) {
    errorHandler.onUnexpectedError(e2);
  }
  return void 0;
}
function transformErrorForSerialization(error2) {
  if (error2 instanceof Error) {
    let {name, message} = error2;
    const stack2 = error2.stacktrace || error2.stack;
    return {
      $isError: true,
      name,
      message,
      stack: stack2
    };
  }
  return error2;
}
var canceledName = "Canceled";
function isPromiseCanceledError(error2) {
  return error2 instanceof Error && error2.name === canceledName && error2.message === canceledName;
}
function canceled() {
  const error2 = new Error(canceledName);
  error2.name = error2.message;
  return error2;
}
function illegalArgument(name) {
  if (name) {
    return new Error(`Illegal argument: ${name}`);
  } else {
    return new Error("Illegal argument");
  }
}
function illegalState(name) {
  if (name) {
    return new Error(`Illegal state: ${name}`);
  } else {
    return new Error("Illegal state");
  }
}
var Iterable;
(function(Iterable2) {
  function is(thing) {
    return thing && typeof thing === "object" && typeof thing[Symbol.iterator] === "function";
  }
  Iterable2.is = is;
  const _empty2 = Object.freeze([]);
  function empty3() {
    return _empty2;
  }
  Iterable2.empty = empty3;
  function* single(element) {
    yield element;
  }
  Iterable2.single = single;
  function from(iterable) {
    return iterable || _empty2;
  }
  Iterable2.from = from;
  function first2(iterable) {
    return iterable[Symbol.iterator]().next().value;
  }
  Iterable2.first = first2;
  function some(iterable, predicate) {
    for (const element of iterable) {
      if (predicate(element)) {
        return true;
      }
    }
    return false;
  }
  Iterable2.some = some;
  function* filter3(iterable, predicate) {
    for (const element of iterable) {
      if (predicate(element)) {
        yield element;
      }
    }
  }
  Iterable2.filter = filter3;
  function* map2(iterable, fn) {
    for (const element of iterable) {
      yield fn(element);
    }
  }
  Iterable2.map = map2;
  function* concat2(...iterables) {
    for (const iterable of iterables) {
      for (const element of iterable) {
        yield element;
      }
    }
  }
  Iterable2.concat = concat2;
  function consume(iterable, atMost = Number.POSITIVE_INFINITY) {
    const consumed = [];
    if (atMost === 0) {
      return [consumed, iterable];
    }
    const iterator = iterable[Symbol.iterator]();
    for (let i3 = 0; i3 < atMost; i3++) {
      const next = iterator.next();
      if (next.done) {
        return [consumed, Iterable2.empty()];
      }
      consumed.push(next.value);
    }
    return [consumed, {[Symbol.iterator]() {
      return iterator;
    }}];
  }
  Iterable2.consume = consume;
})(Iterable || (Iterable = {}));
function markTracked(x2) {
  {
    return;
  }
}
function trackDisposable(x2) {
  {
    return x2;
  }
}
var MultiDisposeError = class extends Error {
  constructor(errors) {
    super(`Encounter errors while disposing of store. Errors: [${errors.join(", ")}]`);
    this.errors = errors;
  }
};
function isDisposable(thing) {
  return typeof thing.dispose === "function" && thing.dispose.length === 0;
}
function dispose(arg) {
  if (Iterable.is(arg)) {
    let errors = [];
    for (const d2 of arg) {
      if (d2) {
        try {
          d2.dispose();
        } catch (e2) {
          errors.push(e2);
        }
      }
    }
    if (errors.length === 1) {
      throw errors[0];
    } else if (errors.length > 1) {
      throw new MultiDisposeError(errors);
    }
    return Array.isArray(arg) ? [] : arg;
  } else if (arg) {
    arg.dispose();
    return arg;
  }
}
function combinedDisposable(...disposables) {
  disposables.forEach(markTracked);
  return trackDisposable({dispose: () => dispose(disposables)});
}
function toDisposable(fn) {
  const self2 = trackDisposable({
    dispose: () => {
      fn();
    }
  });
  return self2;
}
var DisposableStore = class {
  constructor() {
    this._toDispose = new Set();
    this._isDisposed = false;
  }
  dispose() {
    if (this._isDisposed) {
      return;
    }
    this._isDisposed = true;
    this.clear();
  }
  clear() {
    try {
      dispose(this._toDispose.values());
    } finally {
      this._toDispose.clear();
    }
  }
  add(t5) {
    if (!t5) {
      return t5;
    }
    if (t5 === this) {
      throw new Error("Cannot register a disposable on itself!");
    }
    if (this._isDisposed) {
      if (!DisposableStore.DISABLE_DISPOSED_WARNING) {
        console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack);
      }
    } else {
      this._toDispose.add(t5);
    }
    return t5;
  }
};
DisposableStore.DISABLE_DISPOSED_WARNING = false;
var Disposable = class {
  constructor() {
    this._store = new DisposableStore();
  }
  dispose() {
    this._store.dispose();
  }
  _register(t5) {
    if (t5 === this) {
      throw new Error("Cannot register a disposable on itself!");
    }
    return this._store.add(t5);
  }
};
Disposable.None = Object.freeze({dispose() {
}});
var ImmortalReference = class {
  constructor(object) {
    this.object = object;
  }
  dispose() {
  }
};
var Node$1 = class {
  constructor(element) {
    this.element = element;
    this.next = Node$1.Undefined;
    this.prev = Node$1.Undefined;
  }
};
Node$1.Undefined = new Node$1(void 0);
var LinkedList = class {
  constructor() {
    this._first = Node$1.Undefined;
    this._last = Node$1.Undefined;
    this._size = 0;
  }
  get size() {
    return this._size;
  }
  isEmpty() {
    return this._first === Node$1.Undefined;
  }
  clear() {
    this._first = Node$1.Undefined;
    this._last = Node$1.Undefined;
    this._size = 0;
  }
  unshift(element) {
    return this._insert(element, false);
  }
  push(element) {
    return this._insert(element, true);
  }
  _insert(element, atTheEnd) {
    const newNode = new Node$1(element);
    if (this._first === Node$1.Undefined) {
      this._first = newNode;
      this._last = newNode;
    } else if (atTheEnd) {
      const oldLast = this._last;
      this._last = newNode;
      newNode.prev = oldLast;
      oldLast.next = newNode;
    } else {
      const oldFirst = this._first;
      this._first = newNode;
      newNode.next = oldFirst;
      oldFirst.prev = newNode;
    }
    this._size += 1;
    let didRemove = false;
    return () => {
      if (!didRemove) {
        didRemove = true;
        this._remove(newNode);
      }
    };
  }
  shift() {
    if (this._first === Node$1.Undefined) {
      return void 0;
    } else {
      const res = this._first.element;
      this._remove(this._first);
      return res;
    }
  }
  pop() {
    if (this._last === Node$1.Undefined) {
      return void 0;
    } else {
      const res = this._last.element;
      this._remove(this._last);
      return res;
    }
  }
  _remove(node) {
    if (node.prev !== Node$1.Undefined && node.next !== Node$1.Undefined) {
      const anchor = node.prev;
      anchor.next = node.next;
      node.next.prev = anchor;
    } else if (node.prev === Node$1.Undefined && node.next === Node$1.Undefined) {
      this._first = Node$1.Undefined;
      this._last = Node$1.Undefined;
    } else if (node.next === Node$1.Undefined) {
      this._last = this._last.prev;
      this._last.next = Node$1.Undefined;
    } else if (node.prev === Node$1.Undefined) {
      this._first = this._first.next;
      this._first.prev = Node$1.Undefined;
    }
    this._size -= 1;
  }
  *[Symbol.iterator]() {
    let node = this._first;
    while (node !== Node$1.Undefined) {
      yield node.element;
      node = node.next;
    }
  }
  toArray() {
    const result = [];
    for (let node = this._first; node !== Node$1.Undefined; node = node.next) {
      result.push(node.element);
    }
    return result;
  }
};
var Event;
(function(Event2) {
  Event2.None = () => Disposable.None;
  function once3(event) {
    return (listener, thisArgs = null, disposables) => {
      let didFire = false;
      let result;
      result = event((e2) => {
        if (didFire) {
          return;
        } else if (result) {
          result.dispose();
        } else {
          didFire = true;
        }
        return listener.call(thisArgs, e2);
      }, null, disposables);
      if (didFire) {
        result.dispose();
      }
      return result;
    };
  }
  Event2.once = once3;
  function map2(event, map3) {
    return snapshot((listener, thisArgs = null, disposables) => event((i3) => listener.call(thisArgs, map3(i3)), null, disposables));
  }
  Event2.map = map2;
  function forEach5(event, each2) {
    return snapshot((listener, thisArgs = null, disposables) => event((i3) => {
      each2(i3);
      listener.call(thisArgs, i3);
    }, null, disposables));
  }
  Event2.forEach = forEach5;
  function filter3(event, filter4) {
    return snapshot((listener, thisArgs = null, disposables) => event((e2) => filter4(e2) && listener.call(thisArgs, e2), null, disposables));
  }
  Event2.filter = filter3;
  function signal(event) {
    return event;
  }
  Event2.signal = signal;
  function any(...events) {
    return (listener, thisArgs = null, disposables) => combinedDisposable(...events.map((event) => event((e2) => listener.call(thisArgs, e2), null, disposables)));
  }
  Event2.any = any;
  function reduce2(event, merge3, initial) {
    let output2 = initial;
    return map2(event, (e2) => {
      output2 = merge3(output2, e2);
      return output2;
    });
  }
  Event2.reduce = reduce2;
  function snapshot(event) {
    let listener;
    const emitter = new Emitter({
      onFirstListenerAdd() {
        listener = event(emitter.fire, emitter);
      },
      onLastListenerRemove() {
        listener.dispose();
      }
    });
    return emitter.event;
  }
  Event2.snapshot = snapshot;
  function debounce2(event, merge3, delay3 = 100, leading = false, leakWarningThreshold) {
    let subscription;
    let output2 = void 0;
    let handle2 = void 0;
    let numDebouncedCalls = 0;
    const emitter = new Emitter({
      leakWarningThreshold,
      onFirstListenerAdd() {
        subscription = event((cur) => {
          numDebouncedCalls++;
          output2 = merge3(output2, cur);
          if (leading && !handle2) {
            emitter.fire(output2);
            output2 = void 0;
          }
          clearTimeout(handle2);
          handle2 = setTimeout(() => {
            const _output = output2;
            output2 = void 0;
            handle2 = void 0;
            if (!leading || numDebouncedCalls > 1) {
              emitter.fire(_output);
            }
            numDebouncedCalls = 0;
          }, delay3);
        });
      },
      onLastListenerRemove() {
        subscription.dispose();
      }
    });
    return emitter.event;
  }
  Event2.debounce = debounce2;
  function stopwatch(event) {
    const start3 = new Date().getTime();
    return map2(once3(event), (_23) => new Date().getTime() - start3);
  }
  Event2.stopwatch = stopwatch;
  function latch(event) {
    let firstCall = true;
    let cache3;
    return filter3(event, (value) => {
      const shouldEmit = firstCall || value !== cache3;
      firstCall = false;
      cache3 = value;
      return shouldEmit;
    });
  }
  Event2.latch = latch;
  function buffer(event, nextTick2 = false, _buffer = []) {
    let buffer2 = _buffer.slice();
    let listener = event((e2) => {
      if (buffer2) {
        buffer2.push(e2);
      } else {
        emitter.fire(e2);
      }
    });
    const flush = () => {
      if (buffer2) {
        buffer2.forEach((e2) => emitter.fire(e2));
      }
      buffer2 = null;
    };
    const emitter = new Emitter({
      onFirstListenerAdd() {
        if (!listener) {
          listener = event((e2) => emitter.fire(e2));
        }
      },
      onFirstListenerDidAdd() {
        if (buffer2) {
          if (nextTick2) {
            setTimeout(flush);
          } else {
            flush();
          }
        }
      },
      onLastListenerRemove() {
        if (listener) {
          listener.dispose();
        }
        listener = null;
      }
    });
    return emitter.event;
  }
  Event2.buffer = buffer;
  class ChainableEvent {
    constructor(event) {
      this.event = event;
    }
    map(fn) {
      return new ChainableEvent(map2(this.event, fn));
    }
    forEach(fn) {
      return new ChainableEvent(forEach5(this.event, fn));
    }
    filter(fn) {
      return new ChainableEvent(filter3(this.event, fn));
    }
    reduce(merge3, initial) {
      return new ChainableEvent(reduce2(this.event, merge3, initial));
    }
    latch() {
      return new ChainableEvent(latch(this.event));
    }
    debounce(merge3, delay3 = 100, leading = false, leakWarningThreshold) {
      return new ChainableEvent(debounce2(this.event, merge3, delay3, leading, leakWarningThreshold));
    }
    on(listener, thisArgs, disposables) {
      return this.event(listener, thisArgs, disposables);
    }
    once(listener, thisArgs, disposables) {
      return once3(this.event)(listener, thisArgs, disposables);
    }
  }
  function chain(event) {
    return new ChainableEvent(event);
  }
  Event2.chain = chain;
  function fromNodeEventEmitter(emitter, eventName, map3 = (id3) => id3) {
    const fn = (...args) => result.fire(map3(...args));
    const onFirstListenerAdd = () => emitter.on(eventName, fn);
    const onLastListenerRemove = () => emitter.removeListener(eventName, fn);
    const result = new Emitter({onFirstListenerAdd, onLastListenerRemove});
    return result.event;
  }
  Event2.fromNodeEventEmitter = fromNodeEventEmitter;
  function fromDOMEventEmitter(emitter, eventName, map3 = (id3) => id3) {
    const fn = (...args) => result.fire(map3(...args));
    const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);
    const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn);
    const result = new Emitter({onFirstListenerAdd, onLastListenerRemove});
    return result.event;
  }
  Event2.fromDOMEventEmitter = fromDOMEventEmitter;
  function fromPromise(promise) {
    const emitter = new Emitter();
    let shouldEmit = false;
    promise.then(void 0, () => null).then(() => {
      if (!shouldEmit) {
        setTimeout(() => emitter.fire(void 0), 0);
      } else {
        emitter.fire(void 0);
      }
    });
    shouldEmit = true;
    return emitter.event;
  }
  Event2.fromPromise = fromPromise;
  function toPromise(event) {
    return new Promise((c3) => once3(event)(c3));
  }
  Event2.toPromise = toPromise;
})(Event || (Event = {}));
var Emitter = class {
  constructor(options) {
    this._disposed = false;
    this._options = options;
    this._leakageMon = void 0;
  }
  get event() {
    if (!this._event) {
      this._event = (listener, thisArgs, disposables) => {
        if (!this._listeners) {
          this._listeners = new LinkedList();
        }
        const firstListener = this._listeners.isEmpty();
        if (firstListener && this._options && this._options.onFirstListenerAdd) {
          this._options.onFirstListenerAdd(this);
        }
        const remove3 = this._listeners.push(!thisArgs ? listener : [listener, thisArgs]);
        if (firstListener && this._options && this._options.onFirstListenerDidAdd) {
          this._options.onFirstListenerDidAdd(this);
        }
        if (this._options && this._options.onListenerDidAdd) {
          this._options.onListenerDidAdd(this, listener, thisArgs);
        }
        let removeMonitor;
        if (this._leakageMon) {
          removeMonitor = this._leakageMon.check(this._listeners.size);
        }
        let result;
        result = {
          dispose: () => {
            if (removeMonitor) {
              removeMonitor();
            }
            result.dispose = Emitter._noop;
            if (!this._disposed) {
              remove3();
              if (this._options && this._options.onLastListenerRemove) {
                const hasListeners = this._listeners && !this._listeners.isEmpty();
                if (!hasListeners) {
                  this._options.onLastListenerRemove(this);
                }
              }
            }
          }
        };
        if (disposables instanceof DisposableStore) {
          disposables.add(result);
        } else if (Array.isArray(disposables)) {
          disposables.push(result);
        }
        return result;
      };
    }
    return this._event;
  }
  fire(event) {
    if (this._listeners) {
      if (!this._deliveryQueue) {
        this._deliveryQueue = new LinkedList();
      }
      for (let listener of this._listeners) {
        this._deliveryQueue.push([listener, event]);
      }
      while (this._deliveryQueue.size > 0) {
        const [listener, event2] = this._deliveryQueue.shift();
        try {
          if (typeof listener === "function") {
            listener.call(void 0, event2);
          } else {
            listener[0].call(listener[1], event2);
          }
        } catch (e2) {
          onUnexpectedError(e2);
        }
      }
    }
  }
  dispose() {
    if (this._listeners) {
      this._listeners.clear();
    }
    if (this._deliveryQueue) {
      this._deliveryQueue.clear();
    }
    if (this._leakageMon) {
      this._leakageMon.dispose();
    }
    this._disposed = true;
  }
};
Emitter._noop = function() {
};
var PauseableEmitter = class extends Emitter {
  constructor(options) {
    super(options);
    this._isPaused = 0;
    this._eventQueue = new LinkedList();
    this._mergeFn = options && options.merge;
  }
  pause() {
    this._isPaused++;
  }
  resume() {
    if (this._isPaused !== 0 && --this._isPaused === 0) {
      if (this._mergeFn) {
        const events = this._eventQueue.toArray();
        this._eventQueue.clear();
        super.fire(this._mergeFn(events));
      } else {
        while (!this._isPaused && this._eventQueue.size !== 0) {
          super.fire(this._eventQueue.shift());
        }
      }
    }
  }
  fire(event) {
    if (this._listeners) {
      if (this._isPaused !== 0) {
        this._eventQueue.push(event);
      } else {
        super.fire(event);
      }
    }
  }
};
var EventBufferer = class {
  constructor() {
    this.buffers = [];
  }
  wrapEvent(event) {
    return (listener, thisArgs, disposables) => {
      return event((i3) => {
        const buffer = this.buffers[this.buffers.length - 1];
        if (buffer) {
          buffer.push(() => listener.call(thisArgs, i3));
        } else {
          listener.call(thisArgs, i3);
        }
      }, void 0, disposables);
    };
  }
  bufferEvents(fn) {
    const buffer = [];
    this.buffers.push(buffer);
    const r3 = fn();
    this.buffers.pop();
    buffer.forEach((flush) => flush());
    return r3;
  }
};
var Relay = class {
  constructor() {
    this.listening = false;
    this.inputEvent = Event.None;
    this.inputEventListener = Disposable.None;
    this.emitter = new Emitter({
      onFirstListenerDidAdd: () => {
        this.listening = true;
        this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter);
      },
      onLastListenerRemove: () => {
        this.listening = false;
        this.inputEventListener.dispose();
      }
    });
    this.event = this.emitter.event;
  }
  set input(event) {
    this.inputEvent = event;
    if (this.listening) {
      this.inputEventListener.dispose();
      this.inputEventListener = event(this.emitter.fire, this.emitter);
    }
  }
  dispose() {
    this.inputEventListener.dispose();
    this.emitter.dispose();
  }
};
var shortcutEvent = Object.freeze(function(callback, context2) {
  const handle2 = setTimeout(callback.bind(context2), 0);
  return {dispose() {
    clearTimeout(handle2);
  }};
});
var CancellationToken;
(function(CancellationToken2) {
  function isCancellationToken(thing) {
    if (thing === CancellationToken2.None || thing === CancellationToken2.Cancelled) {
      return true;
    }
    if (thing instanceof MutableToken) {
      return true;
    }
    if (!thing || typeof thing !== "object") {
      return false;
    }
    return typeof thing.isCancellationRequested === "boolean" && typeof thing.onCancellationRequested === "function";
  }
  CancellationToken2.isCancellationToken = isCancellationToken;
  CancellationToken2.None = Object.freeze({
    isCancellationRequested: false,
    onCancellationRequested: Event.None
  });
  CancellationToken2.Cancelled = Object.freeze({
    isCancellationRequested: true,
    onCancellationRequested: shortcutEvent
  });
})(CancellationToken || (CancellationToken = {}));
var MutableToken = class {
  constructor() {
    this._isCancelled = false;
    this._emitter = null;
  }
  cancel() {
    if (!this._isCancelled) {
      this._isCancelled = true;
      if (this._emitter) {
        this._emitter.fire(void 0);
        this.dispose();
      }
    }
  }
  get isCancellationRequested() {
    return this._isCancelled;
  }
  get onCancellationRequested() {
    if (this._isCancelled) {
      return shortcutEvent;
    }
    if (!this._emitter) {
      this._emitter = new Emitter();
    }
    return this._emitter.event;
  }
  dispose() {
    if (this._emitter) {
      this._emitter.dispose();
      this._emitter = null;
    }
  }
};
var CancellationTokenSource = class {
  constructor(parent) {
    this._token = void 0;
    this._parentListener = void 0;
    this._parentListener = parent && parent.onCancellationRequested(this.cancel, this);
  }
  get token() {
    if (!this._token) {
      this._token = new MutableToken();
    }
    return this._token;
  }
  cancel() {
    if (!this._token) {
      this._token = CancellationToken.Cancelled;
    } else if (this._token instanceof MutableToken) {
      this._token.cancel();
    }
  }
  dispose(cancel = false) {
    if (cancel) {
      this.cancel();
    }
    if (this._parentListener) {
      this._parentListener.dispose();
    }
    if (!this._token) {
      this._token = CancellationToken.None;
    } else if (this._token instanceof MutableToken) {
      this._token.dispose();
    }
  }
};
var KeyCodeStrMap = class {
  constructor() {
    this._keyCodeToStr = [];
    this._strToKeyCode = Object.create(null);
  }
  define(keyCode, str) {
    this._keyCodeToStr[keyCode] = str;
    this._strToKeyCode[str.toLowerCase()] = keyCode;
  }
  keyCodeToStr(keyCode) {
    return this._keyCodeToStr[keyCode];
  }
  strToKeyCode(str) {
    return this._strToKeyCode[str.toLowerCase()] || 0;
  }
};
var uiMap = new KeyCodeStrMap();
var userSettingsUSMap = new KeyCodeStrMap();
var userSettingsGeneralMap = new KeyCodeStrMap();
(function() {
  function define2(keyCode, uiLabel, usUserSettingsLabel = uiLabel, generalUserSettingsLabel = usUserSettingsLabel) {
    uiMap.define(keyCode, uiLabel);
    userSettingsUSMap.define(keyCode, usUserSettingsLabel);
    userSettingsGeneralMap.define(keyCode, generalUserSettingsLabel);
  }
  define2(0, "unknown");
  define2(1, "Backspace");
  define2(2, "Tab");
  define2(3, "Enter");
  define2(4, "Shift");
  define2(5, "Ctrl");
  define2(6, "Alt");
  define2(7, "PauseBreak");
  define2(8, "CapsLock");
  define2(9, "Escape");
  define2(10, "Space");
  define2(11, "PageUp");
  define2(12, "PageDown");
  define2(13, "End");
  define2(14, "Home");
  define2(15, "LeftArrow", "Left");
  define2(16, "UpArrow", "Up");
  define2(17, "RightArrow", "Right");
  define2(18, "DownArrow", "Down");
  define2(19, "Insert");
  define2(20, "Delete");
  define2(21, "0");
  define2(22, "1");
  define2(23, "2");
  define2(24, "3");
  define2(25, "4");
  define2(26, "5");
  define2(27, "6");
  define2(28, "7");
  define2(29, "8");
  define2(30, "9");
  define2(31, "A");
  define2(32, "B");
  define2(33, "C");
  define2(34, "D");
  define2(35, "E");
  define2(36, "F");
  define2(37, "G");
  define2(38, "H");
  define2(39, "I");
  define2(40, "J");
  define2(41, "K");
  define2(42, "L");
  define2(43, "M");
  define2(44, "N");
  define2(45, "O");
  define2(46, "P");
  define2(47, "Q");
  define2(48, "R");
  define2(49, "S");
  define2(50, "T");
  define2(51, "U");
  define2(52, "V");
  define2(53, "W");
  define2(54, "X");
  define2(55, "Y");
  define2(56, "Z");
  define2(57, "Meta");
  define2(58, "ContextMenu");
  define2(59, "F1");
  define2(60, "F2");
  define2(61, "F3");
  define2(62, "F4");
  define2(63, "F5");
  define2(64, "F6");
  define2(65, "F7");
  define2(66, "F8");
  define2(67, "F9");
  define2(68, "F10");
  define2(69, "F11");
  define2(70, "F12");
  define2(71, "F13");
  define2(72, "F14");
  define2(73, "F15");
  define2(74, "F16");
  define2(75, "F17");
  define2(76, "F18");
  define2(77, "F19");
  define2(78, "NumLock");
  define2(79, "ScrollLock");
  define2(80, ";", ";", "OEM_1");
  define2(81, "=", "=", "OEM_PLUS");
  define2(82, ",", ",", "OEM_COMMA");
  define2(83, "-", "-", "OEM_MINUS");
  define2(84, ".", ".", "OEM_PERIOD");
  define2(85, "/", "/", "OEM_2");
  define2(86, "`", "`", "OEM_3");
  define2(110, "ABNT_C1");
  define2(111, "ABNT_C2");
  define2(87, "[", "[", "OEM_4");
  define2(88, "\\", "\\", "OEM_5");
  define2(89, "]", "]", "OEM_6");
  define2(90, "'", "'", "OEM_7");
  define2(91, "OEM_8");
  define2(92, "OEM_102");
  define2(93, "NumPad0");
  define2(94, "NumPad1");
  define2(95, "NumPad2");
  define2(96, "NumPad3");
  define2(97, "NumPad4");
  define2(98, "NumPad5");
  define2(99, "NumPad6");
  define2(100, "NumPad7");
  define2(101, "NumPad8");
  define2(102, "NumPad9");
  define2(103, "NumPad_Multiply");
  define2(104, "NumPad_Add");
  define2(105, "NumPad_Separator");
  define2(106, "NumPad_Subtract");
  define2(107, "NumPad_Decimal");
  define2(108, "NumPad_Divide");
})();
var KeyCodeUtils;
(function(KeyCodeUtils2) {
  function toString5(keyCode) {
    return uiMap.keyCodeToStr(keyCode);
  }
  KeyCodeUtils2.toString = toString5;
  function fromString(key) {
    return uiMap.strToKeyCode(key);
  }
  KeyCodeUtils2.fromString = fromString;
  function toUserSettingsUS(keyCode) {
    return userSettingsUSMap.keyCodeToStr(keyCode);
  }
  KeyCodeUtils2.toUserSettingsUS = toUserSettingsUS;
  function toUserSettingsGeneral(keyCode) {
    return userSettingsGeneralMap.keyCodeToStr(keyCode);
  }
  KeyCodeUtils2.toUserSettingsGeneral = toUserSettingsGeneral;
  function fromUserSettings(key) {
    return userSettingsUSMap.strToKeyCode(key) || userSettingsGeneralMap.strToKeyCode(key);
  }
  KeyCodeUtils2.fromUserSettings = fromUserSettings;
})(KeyCodeUtils || (KeyCodeUtils = {}));
function KeyChord(firstPart, secondPart) {
  const chordPart = (secondPart & 65535) << 16 >>> 0;
  return (firstPart | chordPart) >>> 0;
}
function createKeybinding(keybinding, OS2) {
  if (keybinding === 0) {
    return null;
  }
  const firstPart = (keybinding & 65535) >>> 0;
  const chordPart = (keybinding & 4294901760) >>> 16;
  if (chordPart !== 0) {
    return new ChordKeybinding([
      createSimpleKeybinding(firstPart, OS2),
      createSimpleKeybinding(chordPart, OS2)
    ]);
  }
  return new ChordKeybinding([createSimpleKeybinding(firstPart, OS2)]);
}
function createSimpleKeybinding(keybinding, OS2) {
  const ctrlCmd = keybinding & 2048 ? true : false;
  const winCtrl = keybinding & 256 ? true : false;
  const ctrlKey = OS2 === 2 ? winCtrl : ctrlCmd;
  const shiftKey = keybinding & 1024 ? true : false;
  const altKey = keybinding & 512 ? true : false;
  const metaKey = OS2 === 2 ? ctrlCmd : winCtrl;
  const keyCode = keybinding & 255;
  return new SimpleKeybinding(ctrlKey, shiftKey, altKey, metaKey, keyCode);
}
var SimpleKeybinding = class {
  constructor(ctrlKey, shiftKey, altKey, metaKey, keyCode) {
    this.ctrlKey = ctrlKey;
    this.shiftKey = shiftKey;
    this.altKey = altKey;
    this.metaKey = metaKey;
    this.keyCode = keyCode;
  }
  equals(other) {
    return this.ctrlKey === other.ctrlKey && this.shiftKey === other.shiftKey && this.altKey === other.altKey && this.metaKey === other.metaKey && this.keyCode === other.keyCode;
  }
  isModifierKey() {
    return this.keyCode === 0 || this.keyCode === 5 || this.keyCode === 57 || this.keyCode === 6 || this.keyCode === 4;
  }
  toChord() {
    return new ChordKeybinding([this]);
  }
  isDuplicateModifierCase() {
    return this.ctrlKey && this.keyCode === 5 || this.shiftKey && this.keyCode === 4 || this.altKey && this.keyCode === 6 || this.metaKey && this.keyCode === 57;
  }
};
var ChordKeybinding = class {
  constructor(parts) {
    if (parts.length === 0) {
      throw illegalArgument(`parts`);
    }
    this.parts = parts;
  }
};
var ResolvedKeybindingPart = class {
  constructor(ctrlKey, shiftKey, altKey, metaKey, kbLabel, kbAriaLabel) {
    this.ctrlKey = ctrlKey;
    this.shiftKey = shiftKey;
    this.altKey = altKey;
    this.metaKey = metaKey;
    this.keyLabel = kbLabel;
    this.keyAriaLabel = kbAriaLabel;
  }
};
var ResolvedKeybinding = class {
};
var safeProcess = typeof process === "undefined" ? {
  cwd() {
    return "/";
  },
  env: Object.create(null),
  get platform() {
    return isWindows ? "win32" : isMacintosh ? "darwin" : "linux";
  },
  nextTick(callback) {
    return setImmediate(callback);
  }
} : process;
var cwd2 = safeProcess.cwd;
var env = safeProcess.env;
var platform2 = safeProcess.platform;
var CHAR_UPPERCASE_A = 65;
var CHAR_LOWERCASE_A = 97;
var CHAR_UPPERCASE_Z = 90;
var CHAR_LOWERCASE_Z = 122;
var CHAR_DOT = 46;
var CHAR_FORWARD_SLASH = 47;
var CHAR_BACKWARD_SLASH = 92;
var CHAR_COLON = 58;
var CHAR_QUESTION_MARK = 63;
var ErrorInvalidArgType = class extends Error {
  constructor(name, expected, actual) {
    let determiner;
    if (typeof expected === "string" && expected.indexOf("not ") === 0) {
      determiner = "must not be";
      expected = expected.replace(/^not /, "");
    } else {
      determiner = "must be";
    }
    const type = name.indexOf(".") !== -1 ? "property" : "argument";
    let msg = `The "${name}" ${type} ${determiner} of type ${expected}`;
    msg += `. Received type ${typeof actual}`;
    super(msg);
    this.code = "ERR_INVALID_ARG_TYPE";
  }
};
function validateString(value, name) {
  if (typeof value !== "string") {
    throw new ErrorInvalidArgType(name, "string", value);
  }
}
function isPathSeparator(code2) {
  return code2 === CHAR_FORWARD_SLASH || code2 === CHAR_BACKWARD_SLASH;
}
function isPosixPathSeparator(code2) {
  return code2 === CHAR_FORWARD_SLASH;
}
function isWindowsDeviceRoot(code2) {
  return code2 >= CHAR_UPPERCASE_A && code2 <= CHAR_UPPERCASE_Z || code2 >= CHAR_LOWERCASE_A && code2 <= CHAR_LOWERCASE_Z;
}
function normalizeString(path, allowAboveRoot, separator, isPathSeparator2) {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let code2 = 0;
  for (let i3 = 0; i3 <= path.length; ++i3) {
    if (i3 < path.length) {
      code2 = path.charCodeAt(i3);
    } else if (isPathSeparator2(code2)) {
      break;
    } else {
      code2 = CHAR_FORWARD_SLASH;
    }
    if (isPathSeparator2(code2)) {
      if (lastSlash === i3 - 1 || dots === 1)
        ;
      else if (dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator);
            if (lastSlashIndex === -1) {
              res = "";
              lastSegmentLength = 0;
            } else {
              res = res.slice(0, lastSlashIndex);
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
            }
            lastSlash = i3;
            dots = 0;
            continue;
          } else if (res.length !== 0) {
            res = "";
            lastSegmentLength = 0;
            lastSlash = i3;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : "..";
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.slice(lastSlash + 1, i3)}`;
        } else {
          res = path.slice(lastSlash + 1, i3);
        }
        lastSegmentLength = i3 - lastSlash - 1;
      }
      lastSlash = i3;
      dots = 0;
    } else if (code2 === CHAR_DOT && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}
function _format$1(sep3, pathObject) {
  if (pathObject === null || typeof pathObject !== "object") {
    throw new ErrorInvalidArgType("pathObject", "Object", pathObject);
  }
  const dir = pathObject.dir || pathObject.root;
  const base = pathObject.base || `${pathObject.name || ""}${pathObject.ext || ""}`;
  if (!dir) {
    return base;
  }
  return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep3}${base}`;
}
var win32 = {
  resolve(...pathSegments) {
    let resolvedDevice = "";
    let resolvedTail = "";
    let resolvedAbsolute = false;
    for (let i3 = pathSegments.length - 1; i3 >= -1; i3--) {
      let path;
      if (i3 >= 0) {
        path = pathSegments[i3];
        validateString(path, "path");
        if (path.length === 0) {
          continue;
        }
      } else if (resolvedDevice.length === 0) {
        path = cwd2();
      } else {
        path = env[`=${resolvedDevice}`] || cwd2();
        if (path === void 0 || path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
          path = `${resolvedDevice}\\`;
        }
      }
      const len2 = path.length;
      let rootEnd = 0;
      let device = "";
      let isAbsolute2 = false;
      const code2 = path.charCodeAt(0);
      if (len2 === 1) {
        if (isPathSeparator(code2)) {
          rootEnd = 1;
          isAbsolute2 = true;
        }
      } else if (isPathSeparator(code2)) {
        isAbsolute2 = true;
        if (isPathSeparator(path.charCodeAt(1))) {
          let j = 2;
          let last2 = j;
          while (j < len2 && !isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len2 && j !== last2) {
            const firstPart = path.slice(last2, j);
            last2 = j;
            while (j < len2 && isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j < len2 && j !== last2) {
              last2 = j;
              while (j < len2 && !isPathSeparator(path.charCodeAt(j))) {
                j++;
              }
              if (j === len2 || j !== last2) {
                device = `\\\\${firstPart}\\${path.slice(last2, j)}`;
                rootEnd = j;
              }
            }
          }
        } else {
          rootEnd = 1;
        }
      } else if (isWindowsDeviceRoot(code2) && path.charCodeAt(1) === CHAR_COLON) {
        device = path.slice(0, 2);
        rootEnd = 2;
        if (len2 > 2 && isPathSeparator(path.charCodeAt(2))) {
          isAbsolute2 = true;
          rootEnd = 3;
        }
      }
      if (device.length > 0) {
        if (resolvedDevice.length > 0) {
          if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
            continue;
          }
        } else {
          resolvedDevice = device;
        }
      }
      if (resolvedAbsolute) {
        if (resolvedDevice.length > 0) {
          break;
        }
      } else {
        resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`;
        resolvedAbsolute = isAbsolute2;
        if (isAbsolute2 && resolvedDevice.length > 0) {
          break;
        }
      }
    }
    resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator);
    return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || ".";
  },
  normalize(path) {
    validateString(path, "path");
    const len2 = path.length;
    if (len2 === 0) {
      return ".";
    }
    let rootEnd = 0;
    let device;
    let isAbsolute2 = false;
    const code2 = path.charCodeAt(0);
    if (len2 === 1) {
      return isPosixPathSeparator(code2) ? "\\" : path;
    }
    if (isPathSeparator(code2)) {
      isAbsolute2 = true;
      if (isPathSeparator(path.charCodeAt(1))) {
        let j = 2;
        let last2 = j;
        while (j < len2 && !isPathSeparator(path.charCodeAt(j))) {
          j++;
        }
        if (j < len2 && j !== last2) {
          const firstPart = path.slice(last2, j);
          last2 = j;
          while (j < len2 && isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len2 && j !== last2) {
            last2 = j;
            while (j < len2 && !isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j === len2) {
              return `\\\\${firstPart}\\${path.slice(last2)}\\`;
            }
            if (j !== last2) {
              device = `\\\\${firstPart}\\${path.slice(last2, j)}`;
              rootEnd = j;
            }
          }
        }
      } else {
        rootEnd = 1;
      }
    } else if (isWindowsDeviceRoot(code2) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.slice(0, 2);
      rootEnd = 2;
      if (len2 > 2 && isPathSeparator(path.charCodeAt(2))) {
        isAbsolute2 = true;
        rootEnd = 3;
      }
    }
    let tail3 = rootEnd < len2 ? normalizeString(path.slice(rootEnd), !isAbsolute2, "\\", isPathSeparator) : "";
    if (tail3.length === 0 && !isAbsolute2) {
      tail3 = ".";
    }
    if (tail3.length > 0 && isPathSeparator(path.charCodeAt(len2 - 1))) {
      tail3 += "\\";
    }
    if (device === void 0) {
      return isAbsolute2 ? `\\${tail3}` : tail3;
    }
    return isAbsolute2 ? `${device}\\${tail3}` : `${device}${tail3}`;
  },
  isAbsolute(path) {
    validateString(path, "path");
    const len2 = path.length;
    if (len2 === 0) {
      return false;
    }
    const code2 = path.charCodeAt(0);
    return isPathSeparator(code2) || len2 > 2 && isWindowsDeviceRoot(code2) && path.charCodeAt(1) === CHAR_COLON && isPathSeparator(path.charCodeAt(2));
  },
  join(...paths) {
    if (paths.length === 0) {
      return ".";
    }
    let joined;
    let firstPart;
    for (let i3 = 0; i3 < paths.length; ++i3) {
      const arg = paths[i3];
      validateString(arg, "path");
      if (arg.length > 0) {
        if (joined === void 0) {
          joined = firstPart = arg;
        } else {
          joined += `\\${arg}`;
        }
      }
    }
    if (joined === void 0) {
      return ".";
    }
    let needsReplace = true;
    let slashCount = 0;
    if (typeof firstPart === "string" && isPathSeparator(firstPart.charCodeAt(0))) {
      ++slashCount;
      const firstLen = firstPart.length;
      if (firstLen > 1 && isPathSeparator(firstPart.charCodeAt(1))) {
        ++slashCount;
        if (firstLen > 2) {
          if (isPathSeparator(firstPart.charCodeAt(2))) {
            ++slashCount;
          } else {
            needsReplace = false;
          }
        }
      }
    }
    if (needsReplace) {
      while (slashCount < joined.length && isPathSeparator(joined.charCodeAt(slashCount))) {
        slashCount++;
      }
      if (slashCount >= 2) {
        joined = `\\${joined.slice(slashCount)}`;
      }
    }
    return win32.normalize(joined);
  },
  relative(from, to) {
    validateString(from, "from");
    validateString(to, "to");
    if (from === to) {
      return "";
    }
    const fromOrig = win32.resolve(from);
    const toOrig = win32.resolve(to);
    if (fromOrig === toOrig) {
      return "";
    }
    from = fromOrig.toLowerCase();
    to = toOrig.toLowerCase();
    if (from === to) {
      return "";
    }
    let fromStart = 0;
    while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
      fromStart++;
    }
    let fromEnd = from.length;
    while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
      fromEnd--;
    }
    const fromLen = fromEnd - fromStart;
    let toStart = 0;
    while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
      toStart++;
    }
    let toEnd = to.length;
    while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
      toEnd--;
    }
    const toLen = toEnd - toStart;
    const length = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i3 = 0;
    for (; i3 < length; i3++) {
      const fromCode = from.charCodeAt(fromStart + i3);
      if (fromCode !== to.charCodeAt(toStart + i3)) {
        break;
      } else if (fromCode === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i3;
      }
    }
    if (i3 !== length) {
      if (lastCommonSep === -1) {
        return toOrig;
      }
    } else {
      if (toLen > length) {
        if (to.charCodeAt(toStart + i3) === CHAR_BACKWARD_SLASH) {
          return toOrig.slice(toStart + i3 + 1);
        }
        if (i3 === 2) {
          return toOrig.slice(toStart + i3);
        }
      }
      if (fromLen > length) {
        if (from.charCodeAt(fromStart + i3) === CHAR_BACKWARD_SLASH) {
          lastCommonSep = i3;
        } else if (i3 === 2) {
          lastCommonSep = 3;
        }
      }
      if (lastCommonSep === -1) {
        lastCommonSep = 0;
      }
    }
    let out = "";
    for (i3 = fromStart + lastCommonSep + 1; i3 <= fromEnd; ++i3) {
      if (i3 === fromEnd || from.charCodeAt(i3) === CHAR_BACKWARD_SLASH) {
        out += out.length === 0 ? ".." : "\\..";
      }
    }
    toStart += lastCommonSep;
    if (out.length > 0) {
      return `${out}${toOrig.slice(toStart, toEnd)}`;
    }
    if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
      ++toStart;
    }
    return toOrig.slice(toStart, toEnd);
  },
  toNamespacedPath(path) {
    if (typeof path !== "string") {
      return path;
    }
    if (path.length === 0) {
      return "";
    }
    const resolvedPath = win32.resolve(path);
    if (resolvedPath.length <= 2) {
      return path;
    }
    if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
      if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
        const code2 = resolvedPath.charCodeAt(2);
        if (code2 !== CHAR_QUESTION_MARK && code2 !== CHAR_DOT) {
          return `\\\\?\\UNC\\${resolvedPath.slice(2)}`;
        }
      }
    } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) && resolvedPath.charCodeAt(1) === CHAR_COLON && resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
      return `\\\\?\\${resolvedPath}`;
    }
    return path;
  },
  dirname(path) {
    validateString(path, "path");
    const len2 = path.length;
    if (len2 === 0) {
      return ".";
    }
    let rootEnd = -1;
    let offset2 = 0;
    const code2 = path.charCodeAt(0);
    if (len2 === 1) {
      return isPathSeparator(code2) ? path : ".";
    }
    if (isPathSeparator(code2)) {
      rootEnd = offset2 = 1;
      if (isPathSeparator(path.charCodeAt(1))) {
        let j = 2;
        let last2 = j;
        while (j < len2 && !isPathSeparator(path.charCodeAt(j))) {
          j++;
        }
        if (j < len2 && j !== last2) {
          last2 = j;
          while (j < len2 && isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len2 && j !== last2) {
            last2 = j;
            while (j < len2 && !isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j === len2) {
              return path;
            }
            if (j !== last2) {
              rootEnd = offset2 = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code2) && path.charCodeAt(1) === CHAR_COLON) {
      rootEnd = len2 > 2 && isPathSeparator(path.charCodeAt(2)) ? 3 : 2;
      offset2 = rootEnd;
    }
    let end2 = -1;
    let matchedSlash = true;
    for (let i3 = len2 - 1; i3 >= offset2; --i3) {
      if (isPathSeparator(path.charCodeAt(i3))) {
        if (!matchedSlash) {
          end2 = i3;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end2 === -1) {
      if (rootEnd === -1) {
        return ".";
      }
      end2 = rootEnd;
    }
    return path.slice(0, end2);
  },
  basename(path, ext) {
    if (ext !== void 0) {
      validateString(ext, "ext");
    }
    validateString(path, "path");
    let start3 = 0;
    let end2 = -1;
    let matchedSlash = true;
    let i3;
    if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) {
      start3 = 2;
    }
    if (ext !== void 0 && ext.length > 0 && ext.length <= path.length) {
      if (ext === path) {
        return "";
      }
      let extIdx = ext.length - 1;
      let firstNonSlashEnd = -1;
      for (i3 = path.length - 1; i3 >= start3; --i3) {
        const code2 = path.charCodeAt(i3);
        if (isPathSeparator(code2)) {
          if (!matchedSlash) {
            start3 = i3 + 1;
            break;
          }
        } else {
          if (firstNonSlashEnd === -1) {
            matchedSlash = false;
            firstNonSlashEnd = i3 + 1;
          }
          if (extIdx >= 0) {
            if (code2 === ext.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end2 = i3;
              }
            } else {
              extIdx = -1;
              end2 = firstNonSlashEnd;
            }
          }
        }
      }
      if (start3 === end2) {
        end2 = firstNonSlashEnd;
      } else if (end2 === -1) {
        end2 = path.length;
      }
      return path.slice(start3, end2);
    }
    for (i3 = path.length - 1; i3 >= start3; --i3) {
      if (isPathSeparator(path.charCodeAt(i3))) {
        if (!matchedSlash) {
          start3 = i3 + 1;
          break;
        }
      } else if (end2 === -1) {
        matchedSlash = false;
        end2 = i3 + 1;
      }
    }
    if (end2 === -1) {
      return "";
    }
    return path.slice(start3, end2);
  },
  extname(path) {
    validateString(path, "path");
    let start3 = 0;
    let startDot = -1;
    let startPart = 0;
    let end2 = -1;
    let matchedSlash = true;
    let preDotState = 0;
    if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) {
      start3 = startPart = 2;
    }
    for (let i3 = path.length - 1; i3 >= start3; --i3) {
      const code2 = path.charCodeAt(i3);
      if (isPathSeparator(code2)) {
        if (!matchedSlash) {
          startPart = i3 + 1;
          break;
        }
        continue;
      }
      if (end2 === -1) {
        matchedSlash = false;
        end2 = i3 + 1;
      }
      if (code2 === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i3;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (startDot === -1 || end2 === -1 || preDotState === 0 || preDotState === 1 && startDot === end2 - 1 && startDot === startPart + 1) {
      return "";
    }
    return path.slice(startDot, end2);
  },
  format: _format$1.bind(null, "\\"),
  parse(path) {
    validateString(path, "path");
    const ret = {root: "", dir: "", base: "", ext: "", name: ""};
    if (path.length === 0) {
      return ret;
    }
    const len2 = path.length;
    let rootEnd = 0;
    let code2 = path.charCodeAt(0);
    if (len2 === 1) {
      if (isPathSeparator(code2)) {
        ret.root = ret.dir = path;
        return ret;
      }
      ret.base = ret.name = path;
      return ret;
    }
    if (isPathSeparator(code2)) {
      rootEnd = 1;
      if (isPathSeparator(path.charCodeAt(1))) {
        let j = 2;
        let last2 = j;
        while (j < len2 && !isPathSeparator(path.charCodeAt(j))) {
          j++;
        }
        if (j < len2 && j !== last2) {
          last2 = j;
          while (j < len2 && isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len2 && j !== last2) {
            last2 = j;
            while (j < len2 && !isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j === len2) {
              rootEnd = j;
            } else if (j !== last2) {
              rootEnd = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code2) && path.charCodeAt(1) === CHAR_COLON) {
      if (len2 <= 2) {
        ret.root = ret.dir = path;
        return ret;
      }
      rootEnd = 2;
      if (isPathSeparator(path.charCodeAt(2))) {
        if (len2 === 3) {
          ret.root = ret.dir = path;
          return ret;
        }
        rootEnd = 3;
      }
    }
    if (rootEnd > 0) {
      ret.root = path.slice(0, rootEnd);
    }
    let startDot = -1;
    let startPart = rootEnd;
    let end2 = -1;
    let matchedSlash = true;
    let i3 = path.length - 1;
    let preDotState = 0;
    for (; i3 >= rootEnd; --i3) {
      code2 = path.charCodeAt(i3);
      if (isPathSeparator(code2)) {
        if (!matchedSlash) {
          startPart = i3 + 1;
          break;
        }
        continue;
      }
      if (end2 === -1) {
        matchedSlash = false;
        end2 = i3 + 1;
      }
      if (code2 === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i3;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (end2 !== -1) {
      if (startDot === -1 || preDotState === 0 || preDotState === 1 && startDot === end2 - 1 && startDot === startPart + 1) {
        ret.base = ret.name = path.slice(startPart, end2);
      } else {
        ret.name = path.slice(startPart, startDot);
        ret.base = path.slice(startPart, end2);
        ret.ext = path.slice(startDot, end2);
      }
    }
    if (startPart > 0 && startPart !== rootEnd) {
      ret.dir = path.slice(0, startPart - 1);
    } else {
      ret.dir = ret.root;
    }
    return ret;
  },
  sep: "\\",
  delimiter: ";",
  win32: null,
  posix: null
};
var posix = {
  resolve(...pathSegments) {
    let resolvedPath = "";
    let resolvedAbsolute = false;
    for (let i3 = pathSegments.length - 1; i3 >= -1 && !resolvedAbsolute; i3--) {
      const path = i3 >= 0 ? pathSegments[i3] : cwd2();
      validateString(path, "path");
      if (path.length === 0) {
        continue;
      }
      resolvedPath = `${path}/${resolvedPath}`;
      resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
    }
    resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator);
    if (resolvedAbsolute) {
      return `/${resolvedPath}`;
    }
    return resolvedPath.length > 0 ? resolvedPath : ".";
  },
  normalize(path) {
    validateString(path, "path");
    if (path.length === 0) {
      return ".";
    }
    const isAbsolute2 = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
    const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH;
    path = normalizeString(path, !isAbsolute2, "/", isPosixPathSeparator);
    if (path.length === 0) {
      if (isAbsolute2) {
        return "/";
      }
      return trailingSeparator ? "./" : ".";
    }
    if (trailingSeparator) {
      path += "/";
    }
    return isAbsolute2 ? `/${path}` : path;
  },
  isAbsolute(path) {
    validateString(path, "path");
    return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH;
  },
  join(...paths) {
    if (paths.length === 0) {
      return ".";
    }
    let joined;
    for (let i3 = 0; i3 < paths.length; ++i3) {
      const arg = paths[i3];
      validateString(arg, "path");
      if (arg.length > 0) {
        if (joined === void 0) {
          joined = arg;
        } else {
          joined += `/${arg}`;
        }
      }
    }
    if (joined === void 0) {
      return ".";
    }
    return posix.normalize(joined);
  },
  relative(from, to) {
    validateString(from, "from");
    validateString(to, "to");
    if (from === to) {
      return "";
    }
    from = posix.resolve(from);
    to = posix.resolve(to);
    if (from === to) {
      return "";
    }
    const fromStart = 1;
    const fromEnd = from.length;
    const fromLen = fromEnd - fromStart;
    const toStart = 1;
    const toLen = to.length - toStart;
    const length = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i3 = 0;
    for (; i3 < length; i3++) {
      const fromCode = from.charCodeAt(fromStart + i3);
      if (fromCode !== to.charCodeAt(toStart + i3)) {
        break;
      } else if (fromCode === CHAR_FORWARD_SLASH) {
        lastCommonSep = i3;
      }
    }
    if (i3 === length) {
      if (toLen > length) {
        if (to.charCodeAt(toStart + i3) === CHAR_FORWARD_SLASH) {
          return to.slice(toStart + i3 + 1);
        }
        if (i3 === 0) {
          return to.slice(toStart + i3);
        }
      } else if (fromLen > length) {
        if (from.charCodeAt(fromStart + i3) === CHAR_FORWARD_SLASH) {
          lastCommonSep = i3;
        } else if (i3 === 0) {
          lastCommonSep = 0;
        }
      }
    }
    let out = "";
    for (i3 = fromStart + lastCommonSep + 1; i3 <= fromEnd; ++i3) {
      if (i3 === fromEnd || from.charCodeAt(i3) === CHAR_FORWARD_SLASH) {
        out += out.length === 0 ? ".." : "/..";
      }
    }
    return `${out}${to.slice(toStart + lastCommonSep)}`;
  },
  toNamespacedPath(path) {
    return path;
  },
  dirname(path) {
    validateString(path, "path");
    if (path.length === 0) {
      return ".";
    }
    const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
    let end2 = -1;
    let matchedSlash = true;
    for (let i3 = path.length - 1; i3 >= 1; --i3) {
      if (path.charCodeAt(i3) === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          end2 = i3;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end2 === -1) {
      return hasRoot ? "/" : ".";
    }
    if (hasRoot && end2 === 1) {
      return "//";
    }
    return path.slice(0, end2);
  },
  basename(path, ext) {
    if (ext !== void 0) {
      validateString(ext, "ext");
    }
    validateString(path, "path");
    let start3 = 0;
    let end2 = -1;
    let matchedSlash = true;
    let i3;
    if (ext !== void 0 && ext.length > 0 && ext.length <= path.length) {
      if (ext === path) {
        return "";
      }
      let extIdx = ext.length - 1;
      let firstNonSlashEnd = -1;
      for (i3 = path.length - 1; i3 >= 0; --i3) {
        const code2 = path.charCodeAt(i3);
        if (code2 === CHAR_FORWARD_SLASH) {
          if (!matchedSlash) {
            start3 = i3 + 1;
            break;
          }
        } else {
          if (firstNonSlashEnd === -1) {
            matchedSlash = false;
            firstNonSlashEnd = i3 + 1;
          }
          if (extIdx >= 0) {
            if (code2 === ext.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end2 = i3;
              }
            } else {
              extIdx = -1;
              end2 = firstNonSlashEnd;
            }
          }
        }
      }
      if (start3 === end2) {
        end2 = firstNonSlashEnd;
      } else if (end2 === -1) {
        end2 = path.length;
      }
      return path.slice(start3, end2);
    }
    for (i3 = path.length - 1; i3 >= 0; --i3) {
      if (path.charCodeAt(i3) === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start3 = i3 + 1;
          break;
        }
      } else if (end2 === -1) {
        matchedSlash = false;
        end2 = i3 + 1;
      }
    }
    if (end2 === -1) {
      return "";
    }
    return path.slice(start3, end2);
  },
  extname(path) {
    validateString(path, "path");
    let startDot = -1;
    let startPart = 0;
    let end2 = -1;
    let matchedSlash = true;
    let preDotState = 0;
    for (let i3 = path.length - 1; i3 >= 0; --i3) {
      const code2 = path.charCodeAt(i3);
      if (code2 === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          startPart = i3 + 1;
          break;
        }
        continue;
      }
      if (end2 === -1) {
        matchedSlash = false;
        end2 = i3 + 1;
      }
      if (code2 === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i3;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (startDot === -1 || end2 === -1 || preDotState === 0 || preDotState === 1 && startDot === end2 - 1 && startDot === startPart + 1) {
      return "";
    }
    return path.slice(startDot, end2);
  },
  format: _format$1.bind(null, "/"),
  parse(path) {
    validateString(path, "path");
    const ret = {root: "", dir: "", base: "", ext: "", name: ""};
    if (path.length === 0) {
      return ret;
    }
    const isAbsolute2 = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
    let start3;
    if (isAbsolute2) {
      ret.root = "/";
      start3 = 1;
    } else {
      start3 = 0;
    }
    let startDot = -1;
    let startPart = 0;
    let end2 = -1;
    let matchedSlash = true;
    let i3 = path.length - 1;
    let preDotState = 0;
    for (; i3 >= start3; --i3) {
      const code2 = path.charCodeAt(i3);
      if (code2 === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          startPart = i3 + 1;
          break;
        }
        continue;
      }
      if (end2 === -1) {
        matchedSlash = false;
        end2 = i3 + 1;
      }
      if (code2 === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i3;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (end2 !== -1) {
      const start4 = startPart === 0 && isAbsolute2 ? 1 : startPart;
      if (startDot === -1 || preDotState === 0 || preDotState === 1 && startDot === end2 - 1 && startDot === startPart + 1) {
        ret.base = ret.name = path.slice(start4, end2);
      } else {
        ret.name = path.slice(start4, startDot);
        ret.base = path.slice(start4, end2);
        ret.ext = path.slice(startDot, end2);
      }
    }
    if (startPart > 0) {
      ret.dir = path.slice(0, startPart - 1);
    } else if (isAbsolute2) {
      ret.dir = "/";
    }
    return ret;
  },
  sep: "/",
  delimiter: ":",
  win32: null,
  posix: null
};
posix.win32 = win32.win32 = win32;
posix.posix = win32.posix = posix;
var normalize = platform2 === "win32" ? win32.normalize : posix.normalize;
var resolve = platform2 === "win32" ? win32.resolve : posix.resolve;
var relative = platform2 === "win32" ? win32.relative : posix.relative;
var dirname = platform2 === "win32" ? win32.dirname : posix.dirname;
var basename = platform2 === "win32" ? win32.basename : posix.basename;
var extname = platform2 === "win32" ? win32.extname : posix.extname;
var sep = platform2 === "win32" ? win32.sep : posix.sep;
var _schemePattern = /^\w[\w\d+.-]*$/;
var _singleSlashStart = /^\//;
var _doubleSlashStart = /^\/\//;
function _validateUri(ret, _strict) {
  if (!ret.scheme && _strict) {
    throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`);
  }
  if (ret.scheme && !_schemePattern.test(ret.scheme)) {
    throw new Error("[UriError]: Scheme contains illegal characters.");
  }
  if (ret.path) {
    if (ret.authority) {
      if (!_singleSlashStart.test(ret.path)) {
        throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
      }
    } else {
      if (_doubleSlashStart.test(ret.path)) {
        throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
      }
    }
  }
}
function _schemeFix(scheme, _strict) {
  if (!scheme && !_strict) {
    return "file";
  }
  return scheme;
}
function _referenceResolution(scheme, path) {
  switch (scheme) {
    case "https":
    case "http":
    case "file":
      if (!path) {
        path = _slash;
      } else if (path[0] !== _slash) {
        path = _slash + path;
      }
      break;
  }
  return path;
}
var _empty = "";
var _slash = "/";
var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
var URI = class {
  constructor(schemeOrData, authority, path, query, fragment, _strict = false) {
    if (typeof schemeOrData === "object") {
      this.scheme = schemeOrData.scheme || _empty;
      this.authority = schemeOrData.authority || _empty;
      this.path = schemeOrData.path || _empty;
      this.query = schemeOrData.query || _empty;
      this.fragment = schemeOrData.fragment || _empty;
    } else {
      this.scheme = _schemeFix(schemeOrData, _strict);
      this.authority = authority || _empty;
      this.path = _referenceResolution(this.scheme, path || _empty);
      this.query = query || _empty;
      this.fragment = fragment || _empty;
      _validateUri(this, _strict);
    }
  }
  static isUri(thing) {
    if (thing instanceof URI) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return typeof thing.authority === "string" && typeof thing.fragment === "string" && typeof thing.path === "string" && typeof thing.query === "string" && typeof thing.scheme === "string" && typeof thing.fsPath === "function" && typeof thing.with === "function" && typeof thing.toString === "function";
  }
  get fsPath() {
    return uriToFsPath(this, false);
  }
  with(change) {
    if (!change) {
      return this;
    }
    let {scheme, authority, path, query, fragment} = change;
    if (scheme === void 0) {
      scheme = this.scheme;
    } else if (scheme === null) {
      scheme = _empty;
    }
    if (authority === void 0) {
      authority = this.authority;
    } else if (authority === null) {
      authority = _empty;
    }
    if (path === void 0) {
      path = this.path;
    } else if (path === null) {
      path = _empty;
    }
    if (query === void 0) {
      query = this.query;
    } else if (query === null) {
      query = _empty;
    }
    if (fragment === void 0) {
      fragment = this.fragment;
    } else if (fragment === null) {
      fragment = _empty;
    }
    if (scheme === this.scheme && authority === this.authority && path === this.path && query === this.query && fragment === this.fragment) {
      return this;
    }
    return new Uri(scheme, authority, path, query, fragment);
  }
  static parse(value, _strict = false) {
    const match2 = _regexp.exec(value);
    if (!match2) {
      return new Uri(_empty, _empty, _empty, _empty, _empty);
    }
    return new Uri(match2[2] || _empty, percentDecode(match2[4] || _empty), percentDecode(match2[5] || _empty), percentDecode(match2[7] || _empty), percentDecode(match2[9] || _empty), _strict);
  }
  static file(path) {
    let authority = _empty;
    if (isWindows) {
      path = path.replace(/\\/g, _slash);
    }
    if (path[0] === _slash && path[1] === _slash) {
      const idx = path.indexOf(_slash, 2);
      if (idx === -1) {
        authority = path.substring(2);
        path = _slash;
      } else {
        authority = path.substring(2, idx);
        path = path.substring(idx) || _slash;
      }
    }
    return new Uri("file", authority, path, _empty, _empty);
  }
  static from(components3) {
    return new Uri(components3.scheme, components3.authority, components3.path, components3.query, components3.fragment);
  }
  static joinPath(uri, ...pathFragment) {
    if (!uri.path) {
      throw new Error(`[UriError]: cannot call joinPaths on URI without path`);
    }
    let newPath;
    if (isWindows && uri.scheme === "file") {
      newPath = URI.file(win32.join(uriToFsPath(uri, true), ...pathFragment)).path;
    } else {
      newPath = posix.join(uri.path, ...pathFragment);
    }
    return uri.with({path: newPath});
  }
  toString(skipEncoding = false) {
    return _asFormatted(this, skipEncoding);
  }
  toJSON() {
    return this;
  }
  static revive(data2) {
    if (!data2) {
      return data2;
    } else if (data2 instanceof URI) {
      return data2;
    } else {
      const result = new Uri(data2);
      result._formatted = data2.external;
      result._fsPath = data2._sep === _pathSepMarker ? data2.fsPath : null;
      return result;
    }
  }
};
var _pathSepMarker = isWindows ? 1 : void 0;
var Uri = class extends URI {
  constructor() {
    super(...arguments);
    this._formatted = null;
    this._fsPath = null;
  }
  get fsPath() {
    if (!this._fsPath) {
      this._fsPath = uriToFsPath(this, false);
    }
    return this._fsPath;
  }
  toString(skipEncoding = false) {
    if (!skipEncoding) {
      if (!this._formatted) {
        this._formatted = _asFormatted(this, false);
      }
      return this._formatted;
    } else {
      return _asFormatted(this, true);
    }
  }
  toJSON() {
    const res = {
      $mid: 1
    };
    if (this._fsPath) {
      res.fsPath = this._fsPath;
      res._sep = _pathSepMarker;
    }
    if (this._formatted) {
      res.external = this._formatted;
    }
    if (this.path) {
      res.path = this.path;
    }
    if (this.scheme) {
      res.scheme = this.scheme;
    }
    if (this.authority) {
      res.authority = this.authority;
    }
    if (this.query) {
      res.query = this.query;
    }
    if (this.fragment) {
      res.fragment = this.fragment;
    }
    return res;
  }
};
var encodeTable = {
  [58]: "%3A",
  [47]: "%2F",
  [63]: "%3F",
  [35]: "%23",
  [91]: "%5B",
  [93]: "%5D",
  [64]: "%40",
  [33]: "%21",
  [36]: "%24",
  [38]: "%26",
  [39]: "%27",
  [40]: "%28",
  [41]: "%29",
  [42]: "%2A",
  [43]: "%2B",
  [44]: "%2C",
  [59]: "%3B",
  [61]: "%3D",
  [32]: "%20"
};
function encodeURIComponentFast(uriComponent, allowSlash) {
  let res = void 0;
  let nativeEncodePos = -1;
  for (let pos = 0; pos < uriComponent.length; pos++) {
    const code2 = uriComponent.charCodeAt(pos);
    if (code2 >= 97 && code2 <= 122 || code2 >= 65 && code2 <= 90 || code2 >= 48 && code2 <= 57 || code2 === 45 || code2 === 46 || code2 === 95 || code2 === 126 || allowSlash && code2 === 47) {
      if (nativeEncodePos !== -1) {
        res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
        nativeEncodePos = -1;
      }
      if (res !== void 0) {
        res += uriComponent.charAt(pos);
      }
    } else {
      if (res === void 0) {
        res = uriComponent.substr(0, pos);
      }
      const escaped = encodeTable[code2];
      if (escaped !== void 0) {
        if (nativeEncodePos !== -1) {
          res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
          nativeEncodePos = -1;
        }
        res += escaped;
      } else if (nativeEncodePos === -1) {
        nativeEncodePos = pos;
      }
    }
  }
  if (nativeEncodePos !== -1) {
    res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
  }
  return res !== void 0 ? res : uriComponent;
}
function encodeURIComponentMinimal(path) {
  let res = void 0;
  for (let pos = 0; pos < path.length; pos++) {
    const code2 = path.charCodeAt(pos);
    if (code2 === 35 || code2 === 63) {
      if (res === void 0) {
        res = path.substr(0, pos);
      }
      res += encodeTable[code2];
    } else {
      if (res !== void 0) {
        res += path[pos];
      }
    }
  }
  return res !== void 0 ? res : path;
}
function uriToFsPath(uri, keepDriveLetterCasing) {
  let value;
  if (uri.authority && uri.path.length > 1 && uri.scheme === "file") {
    value = `//${uri.authority}${uri.path}`;
  } else if (uri.path.charCodeAt(0) === 47 && (uri.path.charCodeAt(1) >= 65 && uri.path.charCodeAt(1) <= 90 || uri.path.charCodeAt(1) >= 97 && uri.path.charCodeAt(1) <= 122) && uri.path.charCodeAt(2) === 58) {
    if (!keepDriveLetterCasing) {
      value = uri.path[1].toLowerCase() + uri.path.substr(2);
    } else {
      value = uri.path.substr(1);
    }
  } else {
    value = uri.path;
  }
  if (isWindows) {
    value = value.replace(/\//g, "\\");
  }
  return value;
}
function _asFormatted(uri, skipEncoding) {
  const encoder = !skipEncoding ? encodeURIComponentFast : encodeURIComponentMinimal;
  let res = "";
  let {scheme, authority, path, query, fragment} = uri;
  if (scheme) {
    res += scheme;
    res += ":";
  }
  if (authority || scheme === "file") {
    res += _slash;
    res += _slash;
  }
  if (authority) {
    let idx = authority.indexOf("@");
    if (idx !== -1) {
      const userinfo = authority.substr(0, idx);
      authority = authority.substr(idx + 1);
      idx = userinfo.indexOf(":");
      if (idx === -1) {
        res += encoder(userinfo, false);
      } else {
        res += encoder(userinfo.substr(0, idx), false);
        res += ":";
        res += encoder(userinfo.substr(idx + 1), false);
      }
      res += "@";
    }
    authority = authority.toLowerCase();
    idx = authority.indexOf(":");
    if (idx === -1) {
      res += encoder(authority, false);
    } else {
      res += encoder(authority.substr(0, idx), false);
      res += authority.substr(idx);
    }
  }
  if (path) {
    if (path.length >= 3 && path.charCodeAt(0) === 47 && path.charCodeAt(2) === 58) {
      const code2 = path.charCodeAt(1);
      if (code2 >= 65 && code2 <= 90) {
        path = `/${String.fromCharCode(code2 + 32)}:${path.substr(3)}`;
      }
    } else if (path.length >= 2 && path.charCodeAt(1) === 58) {
      const code2 = path.charCodeAt(0);
      if (code2 >= 65 && code2 <= 90) {
        path = `${String.fromCharCode(code2 + 32)}:${path.substr(2)}`;
      }
    }
    res += encoder(path, true);
  }
  if (query) {
    res += "?";
    res += encoder(query, false);
  }
  if (fragment) {
    res += "#";
    res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment;
  }
  return res;
}
function decodeURIComponentGraceful(str) {
  try {
    return decodeURIComponent(str);
  } catch (_a) {
    if (str.length > 3) {
      return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3));
    } else {
      return str;
    }
  }
}
var _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
function percentDecode(str) {
  if (!str.match(_rEncodedAsHex)) {
    return str;
  }
  return str.replace(_rEncodedAsHex, (match2) => decodeURIComponentGraceful(match2));
}
var Position = class {
  constructor(lineNumber, column) {
    this.lineNumber = lineNumber;
    this.column = column;
  }
  with(newLineNumber = this.lineNumber, newColumn = this.column) {
    if (newLineNumber === this.lineNumber && newColumn === this.column) {
      return this;
    } else {
      return new Position(newLineNumber, newColumn);
    }
  }
  delta(deltaLineNumber = 0, deltaColumn = 0) {
    return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn);
  }
  equals(other) {
    return Position.equals(this, other);
  }
  static equals(a2, b2) {
    if (!a2 && !b2) {
      return true;
    }
    return !!a2 && !!b2 && a2.lineNumber === b2.lineNumber && a2.column === b2.column;
  }
  isBefore(other) {
    return Position.isBefore(this, other);
  }
  static isBefore(a2, b2) {
    if (a2.lineNumber < b2.lineNumber) {
      return true;
    }
    if (b2.lineNumber < a2.lineNumber) {
      return false;
    }
    return a2.column < b2.column;
  }
  isBeforeOrEqual(other) {
    return Position.isBeforeOrEqual(this, other);
  }
  static isBeforeOrEqual(a2, b2) {
    if (a2.lineNumber < b2.lineNumber) {
      return true;
    }
    if (b2.lineNumber < a2.lineNumber) {
      return false;
    }
    return a2.column <= b2.column;
  }
  static compare(a2, b2) {
    let aLineNumber = a2.lineNumber | 0;
    let bLineNumber = b2.lineNumber | 0;
    if (aLineNumber === bLineNumber) {
      let aColumn = a2.column | 0;
      let bColumn = b2.column | 0;
      return aColumn - bColumn;
    }
    return aLineNumber - bLineNumber;
  }
  clone() {
    return new Position(this.lineNumber, this.column);
  }
  toString() {
    return "(" + this.lineNumber + "," + this.column + ")";
  }
  static lift(pos) {
    return new Position(pos.lineNumber, pos.column);
  }
  static isIPosition(obj) {
    return obj && typeof obj.lineNumber === "number" && typeof obj.column === "number";
  }
};
var Range = class {
  constructor(startLineNumber, startColumn, endLineNumber, endColumn) {
    if (startLineNumber > endLineNumber || startLineNumber === endLineNumber && startColumn > endColumn) {
      this.startLineNumber = endLineNumber;
      this.startColumn = endColumn;
      this.endLineNumber = startLineNumber;
      this.endColumn = startColumn;
    } else {
      this.startLineNumber = startLineNumber;
      this.startColumn = startColumn;
      this.endLineNumber = endLineNumber;
      this.endColumn = endColumn;
    }
  }
  isEmpty() {
    return Range.isEmpty(this);
  }
  static isEmpty(range3) {
    return range3.startLineNumber === range3.endLineNumber && range3.startColumn === range3.endColumn;
  }
  containsPosition(position2) {
    return Range.containsPosition(this, position2);
  }
  static containsPosition(range3, position2) {
    if (position2.lineNumber < range3.startLineNumber || position2.lineNumber > range3.endLineNumber) {
      return false;
    }
    if (position2.lineNumber === range3.startLineNumber && position2.column < range3.startColumn) {
      return false;
    }
    if (position2.lineNumber === range3.endLineNumber && position2.column > range3.endColumn) {
      return false;
    }
    return true;
  }
  containsRange(range3) {
    return Range.containsRange(this, range3);
  }
  static containsRange(range3, otherRange) {
    if (otherRange.startLineNumber < range3.startLineNumber || otherRange.endLineNumber < range3.startLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber > range3.endLineNumber || otherRange.endLineNumber > range3.endLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber === range3.startLineNumber && otherRange.startColumn < range3.startColumn) {
      return false;
    }
    if (otherRange.endLineNumber === range3.endLineNumber && otherRange.endColumn > range3.endColumn) {
      return false;
    }
    return true;
  }
  strictContainsRange(range3) {
    return Range.strictContainsRange(this, range3);
  }
  static strictContainsRange(range3, otherRange) {
    if (otherRange.startLineNumber < range3.startLineNumber || otherRange.endLineNumber < range3.startLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber > range3.endLineNumber || otherRange.endLineNumber > range3.endLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber === range3.startLineNumber && otherRange.startColumn <= range3.startColumn) {
      return false;
    }
    if (otherRange.endLineNumber === range3.endLineNumber && otherRange.endColumn >= range3.endColumn) {
      return false;
    }
    return true;
  }
  plusRange(range3) {
    return Range.plusRange(this, range3);
  }
  static plusRange(a2, b2) {
    let startLineNumber;
    let startColumn;
    let endLineNumber;
    let endColumn;
    if (b2.startLineNumber < a2.startLineNumber) {
      startLineNumber = b2.startLineNumber;
      startColumn = b2.startColumn;
    } else if (b2.startLineNumber === a2.startLineNumber) {
      startLineNumber = b2.startLineNumber;
      startColumn = Math.min(b2.startColumn, a2.startColumn);
    } else {
      startLineNumber = a2.startLineNumber;
      startColumn = a2.startColumn;
    }
    if (b2.endLineNumber > a2.endLineNumber) {
      endLineNumber = b2.endLineNumber;
      endColumn = b2.endColumn;
    } else if (b2.endLineNumber === a2.endLineNumber) {
      endLineNumber = b2.endLineNumber;
      endColumn = Math.max(b2.endColumn, a2.endColumn);
    } else {
      endLineNumber = a2.endLineNumber;
      endColumn = a2.endColumn;
    }
    return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
  }
  intersectRanges(range3) {
    return Range.intersectRanges(this, range3);
  }
  static intersectRanges(a2, b2) {
    let resultStartLineNumber = a2.startLineNumber;
    let resultStartColumn = a2.startColumn;
    let resultEndLineNumber = a2.endLineNumber;
    let resultEndColumn = a2.endColumn;
    let otherStartLineNumber = b2.startLineNumber;
    let otherStartColumn = b2.startColumn;
    let otherEndLineNumber = b2.endLineNumber;
    let otherEndColumn = b2.endColumn;
    if (resultStartLineNumber < otherStartLineNumber) {
      resultStartLineNumber = otherStartLineNumber;
      resultStartColumn = otherStartColumn;
    } else if (resultStartLineNumber === otherStartLineNumber) {
      resultStartColumn = Math.max(resultStartColumn, otherStartColumn);
    }
    if (resultEndLineNumber > otherEndLineNumber) {
      resultEndLineNumber = otherEndLineNumber;
      resultEndColumn = otherEndColumn;
    } else if (resultEndLineNumber === otherEndLineNumber) {
      resultEndColumn = Math.min(resultEndColumn, otherEndColumn);
    }
    if (resultStartLineNumber > resultEndLineNumber) {
      return null;
    }
    if (resultStartLineNumber === resultEndLineNumber && resultStartColumn > resultEndColumn) {
      return null;
    }
    return new Range(resultStartLineNumber, resultStartColumn, resultEndLineNumber, resultEndColumn);
  }
  equalsRange(other) {
    return Range.equalsRange(this, other);
  }
  static equalsRange(a2, b2) {
    return !!a2 && !!b2 && a2.startLineNumber === b2.startLineNumber && a2.startColumn === b2.startColumn && a2.endLineNumber === b2.endLineNumber && a2.endColumn === b2.endColumn;
  }
  getEndPosition() {
    return Range.getEndPosition(this);
  }
  static getEndPosition(range3) {
    return new Position(range3.endLineNumber, range3.endColumn);
  }
  getStartPosition() {
    return Range.getStartPosition(this);
  }
  static getStartPosition(range3) {
    return new Position(range3.startLineNumber, range3.startColumn);
  }
  toString() {
    return "[" + this.startLineNumber + "," + this.startColumn + " -> " + this.endLineNumber + "," + this.endColumn + "]";
  }
  setEndPosition(endLineNumber, endColumn) {
    return new Range(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
  }
  setStartPosition(startLineNumber, startColumn) {
    return new Range(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
  }
  collapseToStart() {
    return Range.collapseToStart(this);
  }
  static collapseToStart(range3) {
    return new Range(range3.startLineNumber, range3.startColumn, range3.startLineNumber, range3.startColumn);
  }
  static fromPositions(start3, end2 = start3) {
    return new Range(start3.lineNumber, start3.column, end2.lineNumber, end2.column);
  }
  static lift(range3) {
    if (!range3) {
      return null;
    }
    return new Range(range3.startLineNumber, range3.startColumn, range3.endLineNumber, range3.endColumn);
  }
  static isIRange(obj) {
    return obj && typeof obj.startLineNumber === "number" && typeof obj.startColumn === "number" && typeof obj.endLineNumber === "number" && typeof obj.endColumn === "number";
  }
  static areIntersectingOrTouching(a2, b2) {
    if (a2.endLineNumber < b2.startLineNumber || a2.endLineNumber === b2.startLineNumber && a2.endColumn < b2.startColumn) {
      return false;
    }
    if (b2.endLineNumber < a2.startLineNumber || b2.endLineNumber === a2.startLineNumber && b2.endColumn < a2.startColumn) {
      return false;
    }
    return true;
  }
  static areIntersecting(a2, b2) {
    if (a2.endLineNumber < b2.startLineNumber || a2.endLineNumber === b2.startLineNumber && a2.endColumn <= b2.startColumn) {
      return false;
    }
    if (b2.endLineNumber < a2.startLineNumber || b2.endLineNumber === a2.startLineNumber && b2.endColumn <= a2.startColumn) {
      return false;
    }
    return true;
  }
  static compareRangesUsingStarts(a2, b2) {
    if (a2 && b2) {
      const aStartLineNumber = a2.startLineNumber | 0;
      const bStartLineNumber = b2.startLineNumber | 0;
      if (aStartLineNumber === bStartLineNumber) {
        const aStartColumn = a2.startColumn | 0;
        const bStartColumn = b2.startColumn | 0;
        if (aStartColumn === bStartColumn) {
          const aEndLineNumber = a2.endLineNumber | 0;
          const bEndLineNumber = b2.endLineNumber | 0;
          if (aEndLineNumber === bEndLineNumber) {
            const aEndColumn = a2.endColumn | 0;
            const bEndColumn = b2.endColumn | 0;
            return aEndColumn - bEndColumn;
          }
          return aEndLineNumber - bEndLineNumber;
        }
        return aStartColumn - bStartColumn;
      }
      return aStartLineNumber - bStartLineNumber;
    }
    const aExists = a2 ? 1 : 0;
    const bExists = b2 ? 1 : 0;
    return aExists - bExists;
  }
  static compareRangesUsingEnds(a2, b2) {
    if (a2.endLineNumber === b2.endLineNumber) {
      if (a2.endColumn === b2.endColumn) {
        if (a2.startLineNumber === b2.startLineNumber) {
          return a2.startColumn - b2.startColumn;
        }
        return a2.startLineNumber - b2.startLineNumber;
      }
      return a2.endColumn - b2.endColumn;
    }
    return a2.endLineNumber - b2.endLineNumber;
  }
  static spansMultipleLines(range3) {
    return range3.endLineNumber > range3.startLineNumber;
  }
};
var Selection = class extends Range {
  constructor(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn) {
    super(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn);
    this.selectionStartLineNumber = selectionStartLineNumber;
    this.selectionStartColumn = selectionStartColumn;
    this.positionLineNumber = positionLineNumber;
    this.positionColumn = positionColumn;
  }
  toString() {
    return "[" + this.selectionStartLineNumber + "," + this.selectionStartColumn + " -> " + this.positionLineNumber + "," + this.positionColumn + "]";
  }
  equalsSelection(other) {
    return Selection.selectionsEqual(this, other);
  }
  static selectionsEqual(a2, b2) {
    return a2.selectionStartLineNumber === b2.selectionStartLineNumber && a2.selectionStartColumn === b2.selectionStartColumn && a2.positionLineNumber === b2.positionLineNumber && a2.positionColumn === b2.positionColumn;
  }
  getDirection() {
    if (this.selectionStartLineNumber === this.startLineNumber && this.selectionStartColumn === this.startColumn) {
      return 0;
    }
    return 1;
  }
  setEndPosition(endLineNumber, endColumn) {
    if (this.getDirection() === 0) {
      return new Selection(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
    }
    return new Selection(endLineNumber, endColumn, this.startLineNumber, this.startColumn);
  }
  getPosition() {
    return new Position(this.positionLineNumber, this.positionColumn);
  }
  setStartPosition(startLineNumber, startColumn) {
    if (this.getDirection() === 0) {
      return new Selection(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
    }
    return new Selection(this.endLineNumber, this.endColumn, startLineNumber, startColumn);
  }
  static fromPositions(start3, end2 = start3) {
    return new Selection(start3.lineNumber, start3.column, end2.lineNumber, end2.column);
  }
  static liftSelection(sel) {
    return new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
  }
  static selectionsArrEqual(a2, b2) {
    if (a2 && !b2 || !a2 && b2) {
      return false;
    }
    if (!a2 && !b2) {
      return true;
    }
    if (a2.length !== b2.length) {
      return false;
    }
    for (let i3 = 0, len2 = a2.length; i3 < len2; i3++) {
      if (!this.selectionsEqual(a2[i3], b2[i3])) {
        return false;
      }
    }
    return true;
  }
  static isISelection(obj) {
    return obj && typeof obj.selectionStartLineNumber === "number" && typeof obj.selectionStartColumn === "number" && typeof obj.positionLineNumber === "number" && typeof obj.positionColumn === "number";
  }
  static createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, direction) {
    if (direction === 0) {
      return new Selection(startLineNumber, startColumn, endLineNumber, endColumn);
    }
    return new Selection(endLineNumber, endColumn, startLineNumber, startColumn);
  }
};
var Token = class {
  constructor(offset2, type, language) {
    this.offset = offset2 | 0;
    this.type = type;
    this.language = language;
  }
  toString() {
    return "(" + this.offset + ", " + this.type + ")";
  }
};
var TokenizationResult = class {
  constructor(tokens, endState) {
    this.tokens = tokens;
    this.endState = endState;
  }
};
var TokenizationResult2 = class {
  constructor(tokens, endState) {
    this.tokens = tokens;
    this.endState = endState;
  }
};
var AccessibilitySupport;
(function(AccessibilitySupport2) {
  AccessibilitySupport2[AccessibilitySupport2["Unknown"] = 0] = "Unknown";
  AccessibilitySupport2[AccessibilitySupport2["Disabled"] = 1] = "Disabled";
  AccessibilitySupport2[AccessibilitySupport2["Enabled"] = 2] = "Enabled";
})(AccessibilitySupport || (AccessibilitySupport = {}));
var CompletionItemInsertTextRule;
(function(CompletionItemInsertTextRule2) {
  CompletionItemInsertTextRule2[CompletionItemInsertTextRule2["KeepWhitespace"] = 1] = "KeepWhitespace";
  CompletionItemInsertTextRule2[CompletionItemInsertTextRule2["InsertAsSnippet"] = 4] = "InsertAsSnippet";
})(CompletionItemInsertTextRule || (CompletionItemInsertTextRule = {}));
var CompletionItemKind;
(function(CompletionItemKind2) {
  CompletionItemKind2[CompletionItemKind2["Method"] = 0] = "Method";
  CompletionItemKind2[CompletionItemKind2["Function"] = 1] = "Function";
  CompletionItemKind2[CompletionItemKind2["Constructor"] = 2] = "Constructor";
  CompletionItemKind2[CompletionItemKind2["Field"] = 3] = "Field";
  CompletionItemKind2[CompletionItemKind2["Variable"] = 4] = "Variable";
  CompletionItemKind2[CompletionItemKind2["Class"] = 5] = "Class";
  CompletionItemKind2[CompletionItemKind2["Struct"] = 6] = "Struct";
  CompletionItemKind2[CompletionItemKind2["Interface"] = 7] = "Interface";
  CompletionItemKind2[CompletionItemKind2["Module"] = 8] = "Module";
  CompletionItemKind2[CompletionItemKind2["Property"] = 9] = "Property";
  CompletionItemKind2[CompletionItemKind2["Event"] = 10] = "Event";
  CompletionItemKind2[CompletionItemKind2["Operator"] = 11] = "Operator";
  CompletionItemKind2[CompletionItemKind2["Unit"] = 12] = "Unit";
  CompletionItemKind2[CompletionItemKind2["Value"] = 13] = "Value";
  CompletionItemKind2[CompletionItemKind2["Constant"] = 14] = "Constant";
  CompletionItemKind2[CompletionItemKind2["Enum"] = 15] = "Enum";
  CompletionItemKind2[CompletionItemKind2["EnumMember"] = 16] = "EnumMember";
  CompletionItemKind2[CompletionItemKind2["Keyword"] = 17] = "Keyword";
  CompletionItemKind2[CompletionItemKind2["Text"] = 18] = "Text";
  CompletionItemKind2[CompletionItemKind2["Color"] = 19] = "Color";
  CompletionItemKind2[CompletionItemKind2["File"] = 20] = "File";
  CompletionItemKind2[CompletionItemKind2["Reference"] = 21] = "Reference";
  CompletionItemKind2[CompletionItemKind2["Customcolor"] = 22] = "Customcolor";
  CompletionItemKind2[CompletionItemKind2["Folder"] = 23] = "Folder";
  CompletionItemKind2[CompletionItemKind2["TypeParameter"] = 24] = "TypeParameter";
  CompletionItemKind2[CompletionItemKind2["User"] = 25] = "User";
  CompletionItemKind2[CompletionItemKind2["Issue"] = 26] = "Issue";
  CompletionItemKind2[CompletionItemKind2["Snippet"] = 27] = "Snippet";
})(CompletionItemKind || (CompletionItemKind = {}));
var CompletionItemTag;
(function(CompletionItemTag2) {
  CompletionItemTag2[CompletionItemTag2["Deprecated"] = 1] = "Deprecated";
})(CompletionItemTag || (CompletionItemTag = {}));
var CompletionTriggerKind;
(function(CompletionTriggerKind2) {
  CompletionTriggerKind2[CompletionTriggerKind2["Invoke"] = 0] = "Invoke";
  CompletionTriggerKind2[CompletionTriggerKind2["TriggerCharacter"] = 1] = "TriggerCharacter";
  CompletionTriggerKind2[CompletionTriggerKind2["TriggerForIncompleteCompletions"] = 2] = "TriggerForIncompleteCompletions";
})(CompletionTriggerKind || (CompletionTriggerKind = {}));
var ContentWidgetPositionPreference;
(function(ContentWidgetPositionPreference2) {
  ContentWidgetPositionPreference2[ContentWidgetPositionPreference2["EXACT"] = 0] = "EXACT";
  ContentWidgetPositionPreference2[ContentWidgetPositionPreference2["ABOVE"] = 1] = "ABOVE";
  ContentWidgetPositionPreference2[ContentWidgetPositionPreference2["BELOW"] = 2] = "BELOW";
})(ContentWidgetPositionPreference || (ContentWidgetPositionPreference = {}));
var CursorChangeReason;
(function(CursorChangeReason2) {
  CursorChangeReason2[CursorChangeReason2["NotSet"] = 0] = "NotSet";
  CursorChangeReason2[CursorChangeReason2["ContentFlush"] = 1] = "ContentFlush";
  CursorChangeReason2[CursorChangeReason2["RecoverFromMarkers"] = 2] = "RecoverFromMarkers";
  CursorChangeReason2[CursorChangeReason2["Explicit"] = 3] = "Explicit";
  CursorChangeReason2[CursorChangeReason2["Paste"] = 4] = "Paste";
  CursorChangeReason2[CursorChangeReason2["Undo"] = 5] = "Undo";
  CursorChangeReason2[CursorChangeReason2["Redo"] = 6] = "Redo";
})(CursorChangeReason || (CursorChangeReason = {}));
var DefaultEndOfLine;
(function(DefaultEndOfLine2) {
  DefaultEndOfLine2[DefaultEndOfLine2["LF"] = 1] = "LF";
  DefaultEndOfLine2[DefaultEndOfLine2["CRLF"] = 2] = "CRLF";
})(DefaultEndOfLine || (DefaultEndOfLine = {}));
var DocumentHighlightKind;
(function(DocumentHighlightKind2) {
  DocumentHighlightKind2[DocumentHighlightKind2["Text"] = 0] = "Text";
  DocumentHighlightKind2[DocumentHighlightKind2["Read"] = 1] = "Read";
  DocumentHighlightKind2[DocumentHighlightKind2["Write"] = 2] = "Write";
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
var EditorAutoIndentStrategy;
(function(EditorAutoIndentStrategy2) {
  EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["None"] = 0] = "None";
  EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Keep"] = 1] = "Keep";
  EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Brackets"] = 2] = "Brackets";
  EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Advanced"] = 3] = "Advanced";
  EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Full"] = 4] = "Full";
})(EditorAutoIndentStrategy || (EditorAutoIndentStrategy = {}));
var EditorOption;
(function(EditorOption2) {
  EditorOption2[EditorOption2["acceptSuggestionOnCommitCharacter"] = 0] = "acceptSuggestionOnCommitCharacter";
  EditorOption2[EditorOption2["acceptSuggestionOnEnter"] = 1] = "acceptSuggestionOnEnter";
  EditorOption2[EditorOption2["accessibilitySupport"] = 2] = "accessibilitySupport";
  EditorOption2[EditorOption2["accessibilityPageSize"] = 3] = "accessibilityPageSize";
  EditorOption2[EditorOption2["ariaLabel"] = 4] = "ariaLabel";
  EditorOption2[EditorOption2["autoClosingBrackets"] = 5] = "autoClosingBrackets";
  EditorOption2[EditorOption2["autoClosingOvertype"] = 6] = "autoClosingOvertype";
  EditorOption2[EditorOption2["autoClosingQuotes"] = 7] = "autoClosingQuotes";
  EditorOption2[EditorOption2["autoIndent"] = 8] = "autoIndent";
  EditorOption2[EditorOption2["automaticLayout"] = 9] = "automaticLayout";
  EditorOption2[EditorOption2["autoSurround"] = 10] = "autoSurround";
  EditorOption2[EditorOption2["codeLens"] = 11] = "codeLens";
  EditorOption2[EditorOption2["colorDecorators"] = 12] = "colorDecorators";
  EditorOption2[EditorOption2["columnSelection"] = 13] = "columnSelection";
  EditorOption2[EditorOption2["comments"] = 14] = "comments";
  EditorOption2[EditorOption2["contextmenu"] = 15] = "contextmenu";
  EditorOption2[EditorOption2["copyWithSyntaxHighlighting"] = 16] = "copyWithSyntaxHighlighting";
  EditorOption2[EditorOption2["cursorBlinking"] = 17] = "cursorBlinking";
  EditorOption2[EditorOption2["cursorSmoothCaretAnimation"] = 18] = "cursorSmoothCaretAnimation";
  EditorOption2[EditorOption2["cursorStyle"] = 19] = "cursorStyle";
  EditorOption2[EditorOption2["cursorSurroundingLines"] = 20] = "cursorSurroundingLines";
  EditorOption2[EditorOption2["cursorSurroundingLinesStyle"] = 21] = "cursorSurroundingLinesStyle";
  EditorOption2[EditorOption2["cursorWidth"] = 22] = "cursorWidth";
  EditorOption2[EditorOption2["disableLayerHinting"] = 23] = "disableLayerHinting";
  EditorOption2[EditorOption2["disableMonospaceOptimizations"] = 24] = "disableMonospaceOptimizations";
  EditorOption2[EditorOption2["dragAndDrop"] = 25] = "dragAndDrop";
  EditorOption2[EditorOption2["emptySelectionClipboard"] = 26] = "emptySelectionClipboard";
  EditorOption2[EditorOption2["extraEditorClassName"] = 27] = "extraEditorClassName";
  EditorOption2[EditorOption2["fastScrollSensitivity"] = 28] = "fastScrollSensitivity";
  EditorOption2[EditorOption2["find"] = 29] = "find";
  EditorOption2[EditorOption2["fixedOverflowWidgets"] = 30] = "fixedOverflowWidgets";
  EditorOption2[EditorOption2["folding"] = 31] = "folding";
  EditorOption2[EditorOption2["foldingStrategy"] = 32] = "foldingStrategy";
  EditorOption2[EditorOption2["foldingHighlight"] = 33] = "foldingHighlight";
  EditorOption2[EditorOption2["unfoldOnClickAfterEndOfLine"] = 34] = "unfoldOnClickAfterEndOfLine";
  EditorOption2[EditorOption2["fontFamily"] = 35] = "fontFamily";
  EditorOption2[EditorOption2["fontInfo"] = 36] = "fontInfo";
  EditorOption2[EditorOption2["fontLigatures"] = 37] = "fontLigatures";
  EditorOption2[EditorOption2["fontSize"] = 38] = "fontSize";
  EditorOption2[EditorOption2["fontWeight"] = 39] = "fontWeight";
  EditorOption2[EditorOption2["formatOnPaste"] = 40] = "formatOnPaste";
  EditorOption2[EditorOption2["formatOnType"] = 41] = "formatOnType";
  EditorOption2[EditorOption2["glyphMargin"] = 42] = "glyphMargin";
  EditorOption2[EditorOption2["gotoLocation"] = 43] = "gotoLocation";
  EditorOption2[EditorOption2["hideCursorInOverviewRuler"] = 44] = "hideCursorInOverviewRuler";
  EditorOption2[EditorOption2["highlightActiveIndentGuide"] = 45] = "highlightActiveIndentGuide";
  EditorOption2[EditorOption2["hover"] = 46] = "hover";
  EditorOption2[EditorOption2["inDiffEditor"] = 47] = "inDiffEditor";
  EditorOption2[EditorOption2["letterSpacing"] = 48] = "letterSpacing";
  EditorOption2[EditorOption2["lightbulb"] = 49] = "lightbulb";
  EditorOption2[EditorOption2["lineDecorationsWidth"] = 50] = "lineDecorationsWidth";
  EditorOption2[EditorOption2["lineHeight"] = 51] = "lineHeight";
  EditorOption2[EditorOption2["lineNumbers"] = 52] = "lineNumbers";
  EditorOption2[EditorOption2["lineNumbersMinChars"] = 53] = "lineNumbersMinChars";
  EditorOption2[EditorOption2["links"] = 54] = "links";
  EditorOption2[EditorOption2["matchBrackets"] = 55] = "matchBrackets";
  EditorOption2[EditorOption2["minimap"] = 56] = "minimap";
  EditorOption2[EditorOption2["mouseStyle"] = 57] = "mouseStyle";
  EditorOption2[EditorOption2["mouseWheelScrollSensitivity"] = 58] = "mouseWheelScrollSensitivity";
  EditorOption2[EditorOption2["mouseWheelZoom"] = 59] = "mouseWheelZoom";
  EditorOption2[EditorOption2["multiCursorMergeOverlapping"] = 60] = "multiCursorMergeOverlapping";
  EditorOption2[EditorOption2["multiCursorModifier"] = 61] = "multiCursorModifier";
  EditorOption2[EditorOption2["multiCursorPaste"] = 62] = "multiCursorPaste";
  EditorOption2[EditorOption2["occurrencesHighlight"] = 63] = "occurrencesHighlight";
  EditorOption2[EditorOption2["overviewRulerBorder"] = 64] = "overviewRulerBorder";
  EditorOption2[EditorOption2["overviewRulerLanes"] = 65] = "overviewRulerLanes";
  EditorOption2[EditorOption2["padding"] = 66] = "padding";
  EditorOption2[EditorOption2["parameterHints"] = 67] = "parameterHints";
  EditorOption2[EditorOption2["peekWidgetDefaultFocus"] = 68] = "peekWidgetDefaultFocus";
  EditorOption2[EditorOption2["definitionLinkOpensInPeek"] = 69] = "definitionLinkOpensInPeek";
  EditorOption2[EditorOption2["quickSuggestions"] = 70] = "quickSuggestions";
  EditorOption2[EditorOption2["quickSuggestionsDelay"] = 71] = "quickSuggestionsDelay";
  EditorOption2[EditorOption2["readOnly"] = 72] = "readOnly";
  EditorOption2[EditorOption2["renameOnType"] = 73] = "renameOnType";
  EditorOption2[EditorOption2["renderControlCharacters"] = 74] = "renderControlCharacters";
  EditorOption2[EditorOption2["renderIndentGuides"] = 75] = "renderIndentGuides";
  EditorOption2[EditorOption2["renderFinalNewline"] = 76] = "renderFinalNewline";
  EditorOption2[EditorOption2["renderLineHighlight"] = 77] = "renderLineHighlight";
  EditorOption2[EditorOption2["renderLineHighlightOnlyWhenFocus"] = 78] = "renderLineHighlightOnlyWhenFocus";
  EditorOption2[EditorOption2["renderValidationDecorations"] = 79] = "renderValidationDecorations";
  EditorOption2[EditorOption2["renderWhitespace"] = 80] = "renderWhitespace";
  EditorOption2[EditorOption2["revealHorizontalRightPadding"] = 81] = "revealHorizontalRightPadding";
  EditorOption2[EditorOption2["roundedSelection"] = 82] = "roundedSelection";
  EditorOption2[EditorOption2["rulers"] = 83] = "rulers";
  EditorOption2[EditorOption2["scrollbar"] = 84] = "scrollbar";
  EditorOption2[EditorOption2["scrollBeyondLastColumn"] = 85] = "scrollBeyondLastColumn";
  EditorOption2[EditorOption2["scrollBeyondLastLine"] = 86] = "scrollBeyondLastLine";
  EditorOption2[EditorOption2["scrollPredominantAxis"] = 87] = "scrollPredominantAxis";
  EditorOption2[EditorOption2["selectionClipboard"] = 88] = "selectionClipboard";
  EditorOption2[EditorOption2["selectionHighlight"] = 89] = "selectionHighlight";
  EditorOption2[EditorOption2["selectOnLineNumbers"] = 90] = "selectOnLineNumbers";
  EditorOption2[EditorOption2["showFoldingControls"] = 91] = "showFoldingControls";
  EditorOption2[EditorOption2["showUnused"] = 92] = "showUnused";
  EditorOption2[EditorOption2["snippetSuggestions"] = 93] = "snippetSuggestions";
  EditorOption2[EditorOption2["smoothScrolling"] = 94] = "smoothScrolling";
  EditorOption2[EditorOption2["stopRenderingLineAfter"] = 95] = "stopRenderingLineAfter";
  EditorOption2[EditorOption2["suggest"] = 96] = "suggest";
  EditorOption2[EditorOption2["suggestFontSize"] = 97] = "suggestFontSize";
  EditorOption2[EditorOption2["suggestLineHeight"] = 98] = "suggestLineHeight";
  EditorOption2[EditorOption2["suggestOnTriggerCharacters"] = 99] = "suggestOnTriggerCharacters";
  EditorOption2[EditorOption2["suggestSelection"] = 100] = "suggestSelection";
  EditorOption2[EditorOption2["tabCompletion"] = 101] = "tabCompletion";
  EditorOption2[EditorOption2["tabIndex"] = 102] = "tabIndex";
  EditorOption2[EditorOption2["unusualLineTerminators"] = 103] = "unusualLineTerminators";
  EditorOption2[EditorOption2["useTabStops"] = 104] = "useTabStops";
  EditorOption2[EditorOption2["wordSeparators"] = 105] = "wordSeparators";
  EditorOption2[EditorOption2["wordWrap"] = 106] = "wordWrap";
  EditorOption2[EditorOption2["wordWrapBreakAfterCharacters"] = 107] = "wordWrapBreakAfterCharacters";
  EditorOption2[EditorOption2["wordWrapBreakBeforeCharacters"] = 108] = "wordWrapBreakBeforeCharacters";
  EditorOption2[EditorOption2["wordWrapColumn"] = 109] = "wordWrapColumn";
  EditorOption2[EditorOption2["wordWrapMinified"] = 110] = "wordWrapMinified";
  EditorOption2[EditorOption2["wrappingIndent"] = 111] = "wrappingIndent";
  EditorOption2[EditorOption2["wrappingStrategy"] = 112] = "wrappingStrategy";
  EditorOption2[EditorOption2["showDeprecated"] = 113] = "showDeprecated";
  EditorOption2[EditorOption2["editorClassName"] = 114] = "editorClassName";
  EditorOption2[EditorOption2["pixelRatio"] = 115] = "pixelRatio";
  EditorOption2[EditorOption2["tabFocusMode"] = 116] = "tabFocusMode";
  EditorOption2[EditorOption2["layoutInfo"] = 117] = "layoutInfo";
  EditorOption2[EditorOption2["wrappingInfo"] = 118] = "wrappingInfo";
})(EditorOption || (EditorOption = {}));
var EndOfLinePreference;
(function(EndOfLinePreference2) {
  EndOfLinePreference2[EndOfLinePreference2["TextDefined"] = 0] = "TextDefined";
  EndOfLinePreference2[EndOfLinePreference2["LF"] = 1] = "LF";
  EndOfLinePreference2[EndOfLinePreference2["CRLF"] = 2] = "CRLF";
})(EndOfLinePreference || (EndOfLinePreference = {}));
var EndOfLineSequence;
(function(EndOfLineSequence2) {
  EndOfLineSequence2[EndOfLineSequence2["LF"] = 0] = "LF";
  EndOfLineSequence2[EndOfLineSequence2["CRLF"] = 1] = "CRLF";
})(EndOfLineSequence || (EndOfLineSequence = {}));
var IndentAction;
(function(IndentAction2) {
  IndentAction2[IndentAction2["None"] = 0] = "None";
  IndentAction2[IndentAction2["Indent"] = 1] = "Indent";
  IndentAction2[IndentAction2["IndentOutdent"] = 2] = "IndentOutdent";
  IndentAction2[IndentAction2["Outdent"] = 3] = "Outdent";
})(IndentAction || (IndentAction = {}));
var KeyCode;
(function(KeyCode2) {
  KeyCode2[KeyCode2["Unknown"] = 0] = "Unknown";
  KeyCode2[KeyCode2["Backspace"] = 1] = "Backspace";
  KeyCode2[KeyCode2["Tab"] = 2] = "Tab";
  KeyCode2[KeyCode2["Enter"] = 3] = "Enter";
  KeyCode2[KeyCode2["Shift"] = 4] = "Shift";
  KeyCode2[KeyCode2["Ctrl"] = 5] = "Ctrl";
  KeyCode2[KeyCode2["Alt"] = 6] = "Alt";
  KeyCode2[KeyCode2["PauseBreak"] = 7] = "PauseBreak";
  KeyCode2[KeyCode2["CapsLock"] = 8] = "CapsLock";
  KeyCode2[KeyCode2["Escape"] = 9] = "Escape";
  KeyCode2[KeyCode2["Space"] = 10] = "Space";
  KeyCode2[KeyCode2["PageUp"] = 11] = "PageUp";
  KeyCode2[KeyCode2["PageDown"] = 12] = "PageDown";
  KeyCode2[KeyCode2["End"] = 13] = "End";
  KeyCode2[KeyCode2["Home"] = 14] = "Home";
  KeyCode2[KeyCode2["LeftArrow"] = 15] = "LeftArrow";
  KeyCode2[KeyCode2["UpArrow"] = 16] = "UpArrow";
  KeyCode2[KeyCode2["RightArrow"] = 17] = "RightArrow";
  KeyCode2[KeyCode2["DownArrow"] = 18] = "DownArrow";
  KeyCode2[KeyCode2["Insert"] = 19] = "Insert";
  KeyCode2[KeyCode2["Delete"] = 20] = "Delete";
  KeyCode2[KeyCode2["KEY_0"] = 21] = "KEY_0";
  KeyCode2[KeyCode2["KEY_1"] = 22] = "KEY_1";
  KeyCode2[KeyCode2["KEY_2"] = 23] = "KEY_2";
  KeyCode2[KeyCode2["KEY_3"] = 24] = "KEY_3";
  KeyCode2[KeyCode2["KEY_4"] = 25] = "KEY_4";
  KeyCode2[KeyCode2["KEY_5"] = 26] = "KEY_5";
  KeyCode2[KeyCode2["KEY_6"] = 27] = "KEY_6";
  KeyCode2[KeyCode2["KEY_7"] = 28] = "KEY_7";
  KeyCode2[KeyCode2["KEY_8"] = 29] = "KEY_8";
  KeyCode2[KeyCode2["KEY_9"] = 30] = "KEY_9";
  KeyCode2[KeyCode2["KEY_A"] = 31] = "KEY_A";
  KeyCode2[KeyCode2["KEY_B"] = 32] = "KEY_B";
  KeyCode2[KeyCode2["KEY_C"] = 33] = "KEY_C";
  KeyCode2[KeyCode2["KEY_D"] = 34] = "KEY_D";
  KeyCode2[KeyCode2["KEY_E"] = 35] = "KEY_E";
  KeyCode2[KeyCode2["KEY_F"] = 36] = "KEY_F";
  KeyCode2[KeyCode2["KEY_G"] = 37] = "KEY_G";
  KeyCode2[KeyCode2["KEY_H"] = 38] = "KEY_H";
  KeyCode2[KeyCode2["KEY_I"] = 39] = "KEY_I";
  KeyCode2[KeyCode2["KEY_J"] = 40] = "KEY_J";
  KeyCode2[KeyCode2["KEY_K"] = 41] = "KEY_K";
  KeyCode2[KeyCode2["KEY_L"] = 42] = "KEY_L";
  KeyCode2[KeyCode2["KEY_M"] = 43] = "KEY_M";
  KeyCode2[KeyCode2["KEY_N"] = 44] = "KEY_N";
  KeyCode2[KeyCode2["KEY_O"] = 45] = "KEY_O";
  KeyCode2[KeyCode2["KEY_P"] = 46] = "KEY_P";
  KeyCode2[KeyCode2["KEY_Q"] = 47] = "KEY_Q";
  KeyCode2[KeyCode2["KEY_R"] = 48] = "KEY_R";
  KeyCode2[KeyCode2["KEY_S"] = 49] = "KEY_S";
  KeyCode2[KeyCode2["KEY_T"] = 50] = "KEY_T";
  KeyCode2[KeyCode2["KEY_U"] = 51] = "KEY_U";
  KeyCode2[KeyCode2["KEY_V"] = 52] = "KEY_V";
  KeyCode2[KeyCode2["KEY_W"] = 53] = "KEY_W";
  KeyCode2[KeyCode2["KEY_X"] = 54] = "KEY_X";
  KeyCode2[KeyCode2["KEY_Y"] = 55] = "KEY_Y";
  KeyCode2[KeyCode2["KEY_Z"] = 56] = "KEY_Z";
  KeyCode2[KeyCode2["Meta"] = 57] = "Meta";
  KeyCode2[KeyCode2["ContextMenu"] = 58] = "ContextMenu";
  KeyCode2[KeyCode2["F1"] = 59] = "F1";
  KeyCode2[KeyCode2["F2"] = 60] = "F2";
  KeyCode2[KeyCode2["F3"] = 61] = "F3";
  KeyCode2[KeyCode2["F4"] = 62] = "F4";
  KeyCode2[KeyCode2["F5"] = 63] = "F5";
  KeyCode2[KeyCode2["F6"] = 64] = "F6";
  KeyCode2[KeyCode2["F7"] = 65] = "F7";
  KeyCode2[KeyCode2["F8"] = 66] = "F8";
  KeyCode2[KeyCode2["F9"] = 67] = "F9";
  KeyCode2[KeyCode2["F10"] = 68] = "F10";
  KeyCode2[KeyCode2["F11"] = 69] = "F11";
  KeyCode2[KeyCode2["F12"] = 70] = "F12";
  KeyCode2[KeyCode2["F13"] = 71] = "F13";
  KeyCode2[KeyCode2["F14"] = 72] = "F14";
  KeyCode2[KeyCode2["F15"] = 73] = "F15";
  KeyCode2[KeyCode2["F16"] = 74] = "F16";
  KeyCode2[KeyCode2["F17"] = 75] = "F17";
  KeyCode2[KeyCode2["F18"] = 76] = "F18";
  KeyCode2[KeyCode2["F19"] = 77] = "F19";
  KeyCode2[KeyCode2["NumLock"] = 78] = "NumLock";
  KeyCode2[KeyCode2["ScrollLock"] = 79] = "ScrollLock";
  KeyCode2[KeyCode2["US_SEMICOLON"] = 80] = "US_SEMICOLON";
  KeyCode2[KeyCode2["US_EQUAL"] = 81] = "US_EQUAL";
  KeyCode2[KeyCode2["US_COMMA"] = 82] = "US_COMMA";
  KeyCode2[KeyCode2["US_MINUS"] = 83] = "US_MINUS";
  KeyCode2[KeyCode2["US_DOT"] = 84] = "US_DOT";
  KeyCode2[KeyCode2["US_SLASH"] = 85] = "US_SLASH";
  KeyCode2[KeyCode2["US_BACKTICK"] = 86] = "US_BACKTICK";
  KeyCode2[KeyCode2["US_OPEN_SQUARE_BRACKET"] = 87] = "US_OPEN_SQUARE_BRACKET";
  KeyCode2[KeyCode2["US_BACKSLASH"] = 88] = "US_BACKSLASH";
  KeyCode2[KeyCode2["US_CLOSE_SQUARE_BRACKET"] = 89] = "US_CLOSE_SQUARE_BRACKET";
  KeyCode2[KeyCode2["US_QUOTE"] = 90] = "US_QUOTE";
  KeyCode2[KeyCode2["OEM_8"] = 91] = "OEM_8";
  KeyCode2[KeyCode2["OEM_102"] = 92] = "OEM_102";
  KeyCode2[KeyCode2["NUMPAD_0"] = 93] = "NUMPAD_0";
  KeyCode2[KeyCode2["NUMPAD_1"] = 94] = "NUMPAD_1";
  KeyCode2[KeyCode2["NUMPAD_2"] = 95] = "NUMPAD_2";
  KeyCode2[KeyCode2["NUMPAD_3"] = 96] = "NUMPAD_3";
  KeyCode2[KeyCode2["NUMPAD_4"] = 97] = "NUMPAD_4";
  KeyCode2[KeyCode2["NUMPAD_5"] = 98] = "NUMPAD_5";
  KeyCode2[KeyCode2["NUMPAD_6"] = 99] = "NUMPAD_6";
  KeyCode2[KeyCode2["NUMPAD_7"] = 100] = "NUMPAD_7";
  KeyCode2[KeyCode2["NUMPAD_8"] = 101] = "NUMPAD_8";
  KeyCode2[KeyCode2["NUMPAD_9"] = 102] = "NUMPAD_9";
  KeyCode2[KeyCode2["NUMPAD_MULTIPLY"] = 103] = "NUMPAD_MULTIPLY";
  KeyCode2[KeyCode2["NUMPAD_ADD"] = 104] = "NUMPAD_ADD";
  KeyCode2[KeyCode2["NUMPAD_SEPARATOR"] = 105] = "NUMPAD_SEPARATOR";
  KeyCode2[KeyCode2["NUMPAD_SUBTRACT"] = 106] = "NUMPAD_SUBTRACT";
  KeyCode2[KeyCode2["NUMPAD_DECIMAL"] = 107] = "NUMPAD_DECIMAL";
  KeyCode2[KeyCode2["NUMPAD_DIVIDE"] = 108] = "NUMPAD_DIVIDE";
  KeyCode2[KeyCode2["KEY_IN_COMPOSITION"] = 109] = "KEY_IN_COMPOSITION";
  KeyCode2[KeyCode2["ABNT_C1"] = 110] = "ABNT_C1";
  KeyCode2[KeyCode2["ABNT_C2"] = 111] = "ABNT_C2";
  KeyCode2[KeyCode2["MAX_VALUE"] = 112] = "MAX_VALUE";
})(KeyCode || (KeyCode = {}));
var MarkerSeverity;
(function(MarkerSeverity2) {
  MarkerSeverity2[MarkerSeverity2["Hint"] = 1] = "Hint";
  MarkerSeverity2[MarkerSeverity2["Info"] = 2] = "Info";
  MarkerSeverity2[MarkerSeverity2["Warning"] = 4] = "Warning";
  MarkerSeverity2[MarkerSeverity2["Error"] = 8] = "Error";
})(MarkerSeverity || (MarkerSeverity = {}));
var MarkerTag;
(function(MarkerTag2) {
  MarkerTag2[MarkerTag2["Unnecessary"] = 1] = "Unnecessary";
  MarkerTag2[MarkerTag2["Deprecated"] = 2] = "Deprecated";
})(MarkerTag || (MarkerTag = {}));
var MinimapPosition;
(function(MinimapPosition2) {
  MinimapPosition2[MinimapPosition2["Inline"] = 1] = "Inline";
  MinimapPosition2[MinimapPosition2["Gutter"] = 2] = "Gutter";
})(MinimapPosition || (MinimapPosition = {}));
var MouseTargetType;
(function(MouseTargetType2) {
  MouseTargetType2[MouseTargetType2["UNKNOWN"] = 0] = "UNKNOWN";
  MouseTargetType2[MouseTargetType2["TEXTAREA"] = 1] = "TEXTAREA";
  MouseTargetType2[MouseTargetType2["GUTTER_GLYPH_MARGIN"] = 2] = "GUTTER_GLYPH_MARGIN";
  MouseTargetType2[MouseTargetType2["GUTTER_LINE_NUMBERS"] = 3] = "GUTTER_LINE_NUMBERS";
  MouseTargetType2[MouseTargetType2["GUTTER_LINE_DECORATIONS"] = 4] = "GUTTER_LINE_DECORATIONS";
  MouseTargetType2[MouseTargetType2["GUTTER_VIEW_ZONE"] = 5] = "GUTTER_VIEW_ZONE";
  MouseTargetType2[MouseTargetType2["CONTENT_TEXT"] = 6] = "CONTENT_TEXT";
  MouseTargetType2[MouseTargetType2["CONTENT_EMPTY"] = 7] = "CONTENT_EMPTY";
  MouseTargetType2[MouseTargetType2["CONTENT_VIEW_ZONE"] = 8] = "CONTENT_VIEW_ZONE";
  MouseTargetType2[MouseTargetType2["CONTENT_WIDGET"] = 9] = "CONTENT_WIDGET";
  MouseTargetType2[MouseTargetType2["OVERVIEW_RULER"] = 10] = "OVERVIEW_RULER";
  MouseTargetType2[MouseTargetType2["SCROLLBAR"] = 11] = "SCROLLBAR";
  MouseTargetType2[MouseTargetType2["OVERLAY_WIDGET"] = 12] = "OVERLAY_WIDGET";
  MouseTargetType2[MouseTargetType2["OUTSIDE_EDITOR"] = 13] = "OUTSIDE_EDITOR";
})(MouseTargetType || (MouseTargetType = {}));
var OverlayWidgetPositionPreference;
(function(OverlayWidgetPositionPreference2) {
  OverlayWidgetPositionPreference2[OverlayWidgetPositionPreference2["TOP_RIGHT_CORNER"] = 0] = "TOP_RIGHT_CORNER";
  OverlayWidgetPositionPreference2[OverlayWidgetPositionPreference2["BOTTOM_RIGHT_CORNER"] = 1] = "BOTTOM_RIGHT_CORNER";
  OverlayWidgetPositionPreference2[OverlayWidgetPositionPreference2["TOP_CENTER"] = 2] = "TOP_CENTER";
})(OverlayWidgetPositionPreference || (OverlayWidgetPositionPreference = {}));
var OverviewRulerLane;
(function(OverviewRulerLane2) {
  OverviewRulerLane2[OverviewRulerLane2["Left"] = 1] = "Left";
  OverviewRulerLane2[OverviewRulerLane2["Center"] = 2] = "Center";
  OverviewRulerLane2[OverviewRulerLane2["Right"] = 4] = "Right";
  OverviewRulerLane2[OverviewRulerLane2["Full"] = 7] = "Full";
})(OverviewRulerLane || (OverviewRulerLane = {}));
var RenderLineNumbersType;
(function(RenderLineNumbersType2) {
  RenderLineNumbersType2[RenderLineNumbersType2["Off"] = 0] = "Off";
  RenderLineNumbersType2[RenderLineNumbersType2["On"] = 1] = "On";
  RenderLineNumbersType2[RenderLineNumbersType2["Relative"] = 2] = "Relative";
  RenderLineNumbersType2[RenderLineNumbersType2["Interval"] = 3] = "Interval";
  RenderLineNumbersType2[RenderLineNumbersType2["Custom"] = 4] = "Custom";
})(RenderLineNumbersType || (RenderLineNumbersType = {}));
var RenderMinimap;
(function(RenderMinimap2) {
  RenderMinimap2[RenderMinimap2["None"] = 0] = "None";
  RenderMinimap2[RenderMinimap2["Text"] = 1] = "Text";
  RenderMinimap2[RenderMinimap2["Blocks"] = 2] = "Blocks";
})(RenderMinimap || (RenderMinimap = {}));
var ScrollType;
(function(ScrollType2) {
  ScrollType2[ScrollType2["Smooth"] = 0] = "Smooth";
  ScrollType2[ScrollType2["Immediate"] = 1] = "Immediate";
})(ScrollType || (ScrollType = {}));
var ScrollbarVisibility;
(function(ScrollbarVisibility2) {
  ScrollbarVisibility2[ScrollbarVisibility2["Auto"] = 1] = "Auto";
  ScrollbarVisibility2[ScrollbarVisibility2["Hidden"] = 2] = "Hidden";
  ScrollbarVisibility2[ScrollbarVisibility2["Visible"] = 3] = "Visible";
})(ScrollbarVisibility || (ScrollbarVisibility = {}));
var SelectionDirection;
(function(SelectionDirection2) {
  SelectionDirection2[SelectionDirection2["LTR"] = 0] = "LTR";
  SelectionDirection2[SelectionDirection2["RTL"] = 1] = "RTL";
})(SelectionDirection || (SelectionDirection = {}));
var SignatureHelpTriggerKind;
(function(SignatureHelpTriggerKind2) {
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["Invoke"] = 1] = "Invoke";
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["TriggerCharacter"] = 2] = "TriggerCharacter";
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind || (SignatureHelpTriggerKind = {}));
var SymbolKind;
(function(SymbolKind2) {
  SymbolKind2[SymbolKind2["File"] = 0] = "File";
  SymbolKind2[SymbolKind2["Module"] = 1] = "Module";
  SymbolKind2[SymbolKind2["Namespace"] = 2] = "Namespace";
  SymbolKind2[SymbolKind2["Package"] = 3] = "Package";
  SymbolKind2[SymbolKind2["Class"] = 4] = "Class";
  SymbolKind2[SymbolKind2["Method"] = 5] = "Method";
  SymbolKind2[SymbolKind2["Property"] = 6] = "Property";
  SymbolKind2[SymbolKind2["Field"] = 7] = "Field";
  SymbolKind2[SymbolKind2["Constructor"] = 8] = "Constructor";
  SymbolKind2[SymbolKind2["Enum"] = 9] = "Enum";
  SymbolKind2[SymbolKind2["Interface"] = 10] = "Interface";
  SymbolKind2[SymbolKind2["Function"] = 11] = "Function";
  SymbolKind2[SymbolKind2["Variable"] = 12] = "Variable";
  SymbolKind2[SymbolKind2["Constant"] = 13] = "Constant";
  SymbolKind2[SymbolKind2["String"] = 14] = "String";
  SymbolKind2[SymbolKind2["Number"] = 15] = "Number";
  SymbolKind2[SymbolKind2["Boolean"] = 16] = "Boolean";
  SymbolKind2[SymbolKind2["Array"] = 17] = "Array";
  SymbolKind2[SymbolKind2["Object"] = 18] = "Object";
  SymbolKind2[SymbolKind2["Key"] = 19] = "Key";
  SymbolKind2[SymbolKind2["Null"] = 20] = "Null";
  SymbolKind2[SymbolKind2["EnumMember"] = 21] = "EnumMember";
  SymbolKind2[SymbolKind2["Struct"] = 22] = "Struct";
  SymbolKind2[SymbolKind2["Event"] = 23] = "Event";
  SymbolKind2[SymbolKind2["Operator"] = 24] = "Operator";
  SymbolKind2[SymbolKind2["TypeParameter"] = 25] = "TypeParameter";
})(SymbolKind || (SymbolKind = {}));
var SymbolTag;
(function(SymbolTag2) {
  SymbolTag2[SymbolTag2["Deprecated"] = 1] = "Deprecated";
})(SymbolTag || (SymbolTag = {}));
var TextEditorCursorBlinkingStyle;
(function(TextEditorCursorBlinkingStyle2) {
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Hidden"] = 0] = "Hidden";
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Blink"] = 1] = "Blink";
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Smooth"] = 2] = "Smooth";
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Phase"] = 3] = "Phase";
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Expand"] = 4] = "Expand";
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Solid"] = 5] = "Solid";
})(TextEditorCursorBlinkingStyle || (TextEditorCursorBlinkingStyle = {}));
var TextEditorCursorStyle$1;
(function(TextEditorCursorStyle2) {
  TextEditorCursorStyle2[TextEditorCursorStyle2["Line"] = 1] = "Line";
  TextEditorCursorStyle2[TextEditorCursorStyle2["Block"] = 2] = "Block";
  TextEditorCursorStyle2[TextEditorCursorStyle2["Underline"] = 3] = "Underline";
  TextEditorCursorStyle2[TextEditorCursorStyle2["LineThin"] = 4] = "LineThin";
  TextEditorCursorStyle2[TextEditorCursorStyle2["BlockOutline"] = 5] = "BlockOutline";
  TextEditorCursorStyle2[TextEditorCursorStyle2["UnderlineThin"] = 6] = "UnderlineThin";
})(TextEditorCursorStyle$1 || (TextEditorCursorStyle$1 = {}));
var TrackedRangeStickiness;
(function(TrackedRangeStickiness2) {
  TrackedRangeStickiness2[TrackedRangeStickiness2["AlwaysGrowsWhenTypingAtEdges"] = 0] = "AlwaysGrowsWhenTypingAtEdges";
  TrackedRangeStickiness2[TrackedRangeStickiness2["NeverGrowsWhenTypingAtEdges"] = 1] = "NeverGrowsWhenTypingAtEdges";
  TrackedRangeStickiness2[TrackedRangeStickiness2["GrowsOnlyWhenTypingBefore"] = 2] = "GrowsOnlyWhenTypingBefore";
  TrackedRangeStickiness2[TrackedRangeStickiness2["GrowsOnlyWhenTypingAfter"] = 3] = "GrowsOnlyWhenTypingAfter";
})(TrackedRangeStickiness || (TrackedRangeStickiness = {}));
var WrappingIndent;
(function(WrappingIndent2) {
  WrappingIndent2[WrappingIndent2["None"] = 0] = "None";
  WrappingIndent2[WrappingIndent2["Same"] = 1] = "Same";
  WrappingIndent2[WrappingIndent2["Indent"] = 2] = "Indent";
  WrappingIndent2[WrappingIndent2["DeepIndent"] = 3] = "DeepIndent";
})(WrappingIndent || (WrappingIndent = {}));
var KeyMod = class {
  static chord(firstPart, secondPart) {
    return KeyChord(firstPart, secondPart);
  }
};
KeyMod.CtrlCmd = 2048;
KeyMod.Shift = 1024;
KeyMod.Alt = 512;
KeyMod.WinCtrl = 256;
function createMonacoBaseAPI() {
  return {
    editor: void 0,
    languages: void 0,
    CancellationTokenSource,
    Emitter,
    KeyCode,
    KeyMod,
    Position,
    Range,
    Selection,
    SelectionDirection,
    MarkerSeverity,
    MarkerTag,
    Uri: URI,
    Token
  };
}
function __snowpack__injectStyle(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle('/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n\r\n/* Default standalone editor fonts */\r\n.monaco-editor {\r\n	font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", system-ui, "Ubuntu", "Droid Sans", sans-serif;\r\n	--monaco-monospace-font: "SF Mono", Monaco, Menlo, Consolas, "Ubuntu Mono", "Liberation Mono", "DejaVu Sans Mono", "Courier New", monospace;\r\n}\r\n\r\n.monaco-menu .monaco-action-bar.vertical .action-item .action-menu-item:focus .action-label {\r\n	stroke-width: 1.2px;\r\n}\r\n\r\n.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label,\r\n.monaco-editor.hc-black .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label {\r\n	stroke-width: 1.2px;\r\n}\r\n\r\n.monaco-hover p {\r\n	margin: 0;\r\n}\r\n\r\n/* The hc-black theme is already high contrast optimized */\r\n.monaco-editor.hc-black {\r\n	-ms-high-contrast-adjust: none;\r\n}\r\n/* In case the browser goes into high contrast mode and the editor is not configured with the hc-black theme */\r\n@media screen and (-ms-high-contrast:active) {\r\n\r\n	/* current line highlight */\r\n	.monaco-editor.vs .view-overlays .current-line,\r\n	.monaco-editor.vs-dark .view-overlays .current-line {\r\n		border-color: windowtext !important;\r\n		border-left: 0;\r\n		border-right: 0;\r\n	}\r\n\r\n	/* view cursors */\r\n	.monaco-editor.vs .cursor,\r\n	.monaco-editor.vs-dark .cursor {\r\n		background-color: windowtext !important;\r\n	}\r\n	/* dnd target */\r\n	.monaco-editor.vs .dnd-target,\r\n	.monaco-editor.vs-dark .dnd-target {\r\n		border-color: windowtext !important;\r\n	}\r\n\r\n	/* selected text background */\r\n	.monaco-editor.vs .selected-text,\r\n	.monaco-editor.vs-dark .selected-text {\r\n		background-color: highlight !important;\r\n	}\r\n\r\n	/* allow the text to have a transparent background. */\r\n	.monaco-editor.vs .view-line,\r\n	.monaco-editor.vs-dark .view-line {\r\n		-ms-high-contrast-adjust: none;\r\n	}\r\n\r\n	/* text color */\r\n	.monaco-editor.vs .view-line span,\r\n	.monaco-editor.vs-dark .view-line span {\r\n		color: windowtext !important;\r\n	}\r\n	/* selected text color */\r\n	.monaco-editor.vs .view-line span.inline-selected-text,\r\n	.monaco-editor.vs-dark .view-line span.inline-selected-text {\r\n		color: highlighttext !important;\r\n	}\r\n\r\n	/* allow decorations */\r\n	.monaco-editor.vs .view-overlays,\r\n	.monaco-editor.vs-dark .view-overlays {\r\n		-ms-high-contrast-adjust: none;\r\n	}\r\n\r\n	/* various decorations */\r\n	.monaco-editor.vs .selectionHighlight,\r\n	.monaco-editor.vs-dark .selectionHighlight,\r\n	.monaco-editor.vs .wordHighlight,\r\n	.monaco-editor.vs-dark .wordHighlight,\r\n	.monaco-editor.vs .wordHighlightStrong,\r\n	.monaco-editor.vs-dark .wordHighlightStrong,\r\n	.monaco-editor.vs .reference-decoration,\r\n	.monaco-editor.vs-dark .reference-decoration {\r\n		border: 2px dotted highlight !important;\r\n		background: transparent !important;\r\n		box-sizing: border-box;\r\n	}\r\n	.monaco-editor.vs .rangeHighlight,\r\n	.monaco-editor.vs-dark .rangeHighlight {\r\n		background: transparent !important;\r\n		border: 1px dotted activeborder !important;\r\n		box-sizing: border-box;\r\n	}\r\n	.monaco-editor.vs .bracket-match,\r\n	.monaco-editor.vs-dark .bracket-match {\r\n		border-color: windowtext !important;\r\n		background: transparent !important;\r\n	}\r\n\r\n	/* find widget */\r\n	.monaco-editor.vs .findMatch,\r\n	.monaco-editor.vs-dark .findMatch,\r\n	.monaco-editor.vs .currentFindMatch,\r\n	.monaco-editor.vs-dark .currentFindMatch {\r\n		border: 2px dotted activeborder !important;\r\n		background: transparent !important;\r\n		box-sizing: border-box;\r\n	}\r\n	.monaco-editor.vs .find-widget,\r\n	.monaco-editor.vs-dark .find-widget {\r\n		border: 1px solid windowtext;\r\n	}\r\n\r\n	/* list - used by suggest widget */\r\n	.monaco-editor.vs .monaco-list .monaco-list-row,\r\n	.monaco-editor.vs-dark .monaco-list .monaco-list-row {\r\n		-ms-high-contrast-adjust: none;\r\n		color: windowtext !important;\r\n	}\r\n	.monaco-editor.vs .monaco-list .monaco-list-row.focused,\r\n	.monaco-editor.vs-dark .monaco-list .monaco-list-row.focused {\r\n		color: highlighttext !important;\r\n		background-color: highlight !important;\r\n	}\r\n	.monaco-editor.vs .monaco-list .monaco-list-row:hover,\r\n	.monaco-editor.vs-dark .monaco-list .monaco-list-row:hover {\r\n		background: transparent !important;\r\n		border: 1px solid highlight;\r\n		box-sizing: border-box;\r\n	}\r\n\r\n	/* scrollbars */\r\n	.monaco-editor.vs .monaco-scrollable-element > .scrollbar,\r\n	.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar {\r\n		-ms-high-contrast-adjust: none;\r\n		background: background !important;\r\n		border: 1px solid windowtext;\r\n		box-sizing: border-box;\r\n	}\r\n	.monaco-editor.vs .monaco-scrollable-element > .scrollbar > .slider,\r\n	.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar > .slider {\r\n		background: windowtext !important;\r\n	}\r\n	.monaco-editor.vs .monaco-scrollable-element > .scrollbar > .slider:hover,\r\n	.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar > .slider:hover {\r\n		background: highlight !important;\r\n	}\r\n	.monaco-editor.vs .monaco-scrollable-element > .scrollbar > .slider.active,\r\n	.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar > .slider.active {\r\n		background: highlight !important;\r\n	}\r\n\r\n	/* overview ruler */\r\n	.monaco-editor.vs .decorationsOverviewRuler,\r\n	.monaco-editor.vs-dark .decorationsOverviewRuler {\r\n		opacity: 0;\r\n	}\r\n\r\n	/* minimap */\r\n	.monaco-editor.vs .minimap,\r\n	.monaco-editor.vs-dark .minimap {\r\n		display: none;\r\n	}\r\n\r\n	/* squiggles */\r\n	.monaco-editor.vs .squiggly-d-error,\r\n	.monaco-editor.vs-dark .squiggly-d-error {\r\n		background: transparent !important;\r\n		border-bottom: 4px double #E47777;\r\n	}\r\n	.monaco-editor.vs .squiggly-c-warning,\r\n	.monaco-editor.vs-dark .squiggly-c-warning {\r\n		border-bottom: 4px double #71B771;\r\n	}\r\n	.monaco-editor.vs .squiggly-b-info,\r\n	.monaco-editor.vs-dark .squiggly-b-info {\r\n		border-bottom: 4px double #71B771;\r\n	}\r\n	.monaco-editor.vs .squiggly-a-hint,\r\n	.monaco-editor.vs-dark .squiggly-a-hint {\r\n		border-bottom: 4px double #6c6c6c;\r\n	}\r\n\r\n	/* contextmenu */\r\n	.monaco-editor.vs .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label,\r\n	.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label {\r\n		-ms-high-contrast-adjust: none;\r\n		color: highlighttext !important;\r\n		background-color: highlight !important;\r\n	}\r\n	.monaco-editor.vs .monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .action-label,\r\n	.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .action-label {\r\n		-ms-high-contrast-adjust: none;\r\n		background: transparent !important;\r\n		border: 1px solid highlight;\r\n		box-sizing: border-box;\r\n	}\r\n\r\n	/* diff editor */\r\n	.monaco-diff-editor.vs .diffOverviewRuler,\r\n	.monaco-diff-editor.vs-dark .diffOverviewRuler {\r\n		display: none;\r\n	}\r\n	.monaco-editor.vs .line-insert,\r\n	.monaco-editor.vs-dark .line-insert,\r\n	.monaco-editor.vs .line-delete,\r\n	.monaco-editor.vs-dark .line-delete {\r\n		background: transparent !important;\r\n		border: 1px solid highlight !important;\r\n		box-sizing: border-box;\r\n	}\r\n	.monaco-editor.vs .char-insert,\r\n	.monaco-editor.vs-dark .char-insert,\r\n	.monaco-editor.vs .char-delete,\r\n	.monaco-editor.vs-dark .char-delete {\r\n		background: transparent !important;\r\n	}\r\n}\r\n\r\n/*.monaco-editor.vs [tabindex="0"]:focus {\r\n	outline: 1px solid rgba(0, 122, 204, 0.4);\r\n	outline-offset: -1px;\r\n	opacity: 1 !important;\r\n}\r\n\r\n.monaco-editor.vs-dark [tabindex="0"]:focus {\r\n	outline: 1px solid rgba(14, 99, 156, 0.6);\r\n	outline-offset: -1px;\r\n	opacity: 1 !important;\r\n}*/\r\n');
var _util;
(function(_util2) {
  _util2.serviceIds = new Map();
  _util2.DI_TARGET = "$di$target";
  _util2.DI_DEPENDENCIES = "$di$dependencies";
  function getServiceDependencies(ctor) {
    return ctor[_util2.DI_DEPENDENCIES] || [];
  }
  _util2.getServiceDependencies = getServiceDependencies;
})(_util || (_util = {}));
var IInstantiationService = createDecorator("instantiationService");
function storeServiceDependency(id3, target, index3, optional2) {
  if (target[_util.DI_TARGET] === target) {
    target[_util.DI_DEPENDENCIES].push({id: id3, index: index3, optional: optional2});
  } else {
    target[_util.DI_DEPENDENCIES] = [{id: id3, index: index3, optional: optional2}];
    target[_util.DI_TARGET] = target;
  }
}
function createDecorator(serviceId) {
  if (_util.serviceIds.has(serviceId)) {
    return _util.serviceIds.get(serviceId);
  }
  const id3 = function(target, key, index3) {
    if (arguments.length !== 3) {
      throw new Error("@IServiceName-decorator can only be used to decorate a parameter");
    }
    storeServiceDependency(id3, target, index3, false);
  };
  id3.toString = () => serviceId;
  _util.serviceIds.set(serviceId, id3);
  return id3;
}
function optional(serviceIdentifier) {
  return function(target, key, index3) {
    if (arguments.length !== 3) {
      throw new Error("@optional-decorator can only be used to decorate a parameter");
    }
    storeServiceDependency(serviceIdentifier, target, index3, true);
  };
}
var ICodeEditorService = createDecorator("codeEditorService");
var WindowManager = class {
  constructor() {
    this._zoomLevel = 0;
    this._lastZoomLevelChangeTime = 0;
    this._onDidChangeZoomLevel = new Emitter();
    this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;
    this._zoomFactor = 1;
  }
  getZoomLevel() {
    return this._zoomLevel;
  }
  getTimeSinceLastZoomLevelChanged() {
    return Date.now() - this._lastZoomLevelChangeTime;
  }
  getZoomFactor() {
    return this._zoomFactor;
  }
  getPixelRatio() {
    let ctx = document.createElement("canvas").getContext("2d");
    let dpr = window.devicePixelRatio || 1;
    let bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
    return dpr / bsr;
  }
};
WindowManager.INSTANCE = new WindowManager();
function getZoomLevel() {
  return WindowManager.INSTANCE.getZoomLevel();
}
function getTimeSinceLastZoomLevelChanged() {
  return WindowManager.INSTANCE.getTimeSinceLastZoomLevelChanged();
}
function onDidChangeZoomLevel(callback) {
  return WindowManager.INSTANCE.onDidChangeZoomLevel(callback);
}
function getZoomFactor() {
  return WindowManager.INSTANCE.getZoomFactor();
}
function getPixelRatio() {
  return WindowManager.INSTANCE.getPixelRatio();
}
var userAgent = navigator.userAgent;
var isEdge2 = userAgent.indexOf("Edge/") >= 0;
var isFirefox = userAgent.indexOf("Firefox") >= 0;
var isWebKit = userAgent.indexOf("AppleWebKit") >= 0;
var isChrome = userAgent.indexOf("Chrome") >= 0;
var isSafari = !isChrome && userAgent.indexOf("Safari") >= 0;
var isWebkitWebView = !isChrome && !isSafari && isWebKit;
var isIPad = userAgent.indexOf("iPad") >= 0 || isSafari && navigator.maxTouchPoints > 0;
var isEdgeWebView = isEdge2 && userAgent.indexOf("WebView/") >= 0;
var isStandalone = window.matchMedia && window.matchMedia("(display-mode: standalone)").matches;
var domEvent = (element, type, useCapture) => {
  const fn = (e2) => emitter.fire(e2);
  const emitter = new Emitter({
    onFirstListenerAdd: () => {
      element.addEventListener(type, fn, useCapture);
    },
    onLastListenerRemove: () => {
      element.removeEventListener(type, fn, useCapture);
    }
  });
  return emitter.event;
};
var KEY_CODE_MAP = new Array(230);
var INVERSE_KEY_CODE_MAP = new Array(112);
(function() {
  for (let i3 = 0; i3 < INVERSE_KEY_CODE_MAP.length; i3++) {
    INVERSE_KEY_CODE_MAP[i3] = -1;
  }
  function define2(code2, keyCode) {
    KEY_CODE_MAP[code2] = keyCode;
    INVERSE_KEY_CODE_MAP[keyCode] = code2;
  }
  define2(3, 7);
  define2(8, 1);
  define2(9, 2);
  define2(13, 3);
  define2(16, 4);
  define2(17, 5);
  define2(18, 6);
  define2(19, 7);
  define2(20, 8);
  define2(27, 9);
  define2(32, 10);
  define2(33, 11);
  define2(34, 12);
  define2(35, 13);
  define2(36, 14);
  define2(37, 15);
  define2(38, 16);
  define2(39, 17);
  define2(40, 18);
  define2(45, 19);
  define2(46, 20);
  define2(48, 21);
  define2(49, 22);
  define2(50, 23);
  define2(51, 24);
  define2(52, 25);
  define2(53, 26);
  define2(54, 27);
  define2(55, 28);
  define2(56, 29);
  define2(57, 30);
  define2(65, 31);
  define2(66, 32);
  define2(67, 33);
  define2(68, 34);
  define2(69, 35);
  define2(70, 36);
  define2(71, 37);
  define2(72, 38);
  define2(73, 39);
  define2(74, 40);
  define2(75, 41);
  define2(76, 42);
  define2(77, 43);
  define2(78, 44);
  define2(79, 45);
  define2(80, 46);
  define2(81, 47);
  define2(82, 48);
  define2(83, 49);
  define2(84, 50);
  define2(85, 51);
  define2(86, 52);
  define2(87, 53);
  define2(88, 54);
  define2(89, 55);
  define2(90, 56);
  define2(93, 58);
  define2(96, 93);
  define2(97, 94);
  define2(98, 95);
  define2(99, 96);
  define2(100, 97);
  define2(101, 98);
  define2(102, 99);
  define2(103, 100);
  define2(104, 101);
  define2(105, 102);
  define2(106, 103);
  define2(107, 104);
  define2(108, 105);
  define2(109, 106);
  define2(110, 107);
  define2(111, 108);
  define2(112, 59);
  define2(113, 60);
  define2(114, 61);
  define2(115, 62);
  define2(116, 63);
  define2(117, 64);
  define2(118, 65);
  define2(119, 66);
  define2(120, 67);
  define2(121, 68);
  define2(122, 69);
  define2(123, 70);
  define2(124, 71);
  define2(125, 72);
  define2(126, 73);
  define2(127, 74);
  define2(128, 75);
  define2(129, 76);
  define2(130, 77);
  define2(144, 78);
  define2(145, 79);
  define2(186, 80);
  define2(187, 81);
  define2(188, 82);
  define2(189, 83);
  define2(190, 84);
  define2(191, 85);
  define2(192, 86);
  define2(193, 110);
  define2(194, 111);
  define2(219, 87);
  define2(220, 88);
  define2(221, 89);
  define2(222, 90);
  define2(223, 91);
  define2(226, 92);
  define2(229, 109);
  if (isFirefox) {
    define2(59, 80);
    define2(107, 81);
    define2(109, 83);
    if (isMacintosh) {
      define2(224, 57);
    }
  } else if (isWebKit) {
    define2(91, 57);
    if (isMacintosh) {
      define2(93, 57);
    } else {
      define2(92, 57);
    }
  }
})();
function extractKeyCode(e2) {
  if (e2.charCode) {
    let char = String.fromCharCode(e2.charCode).toUpperCase();
    return KeyCodeUtils.fromString(char);
  }
  return KEY_CODE_MAP[e2.keyCode] || 0;
}
var ctrlKeyMod = isMacintosh ? 256 : 2048;
var altKeyMod = 512;
var shiftKeyMod = 1024;
var metaKeyMod = isMacintosh ? 2048 : 256;
var StandardKeyboardEvent = class {
  constructor(source2) {
    this._standardKeyboardEventBrand = true;
    let e2 = source2;
    this.browserEvent = e2;
    this.target = e2.target;
    this.ctrlKey = e2.ctrlKey;
    this.shiftKey = e2.shiftKey;
    this.altKey = e2.altKey;
    this.metaKey = e2.metaKey;
    this.keyCode = extractKeyCode(e2);
    this.code = e2.code;
    this.ctrlKey = this.ctrlKey || this.keyCode === 5;
    this.altKey = this.altKey || this.keyCode === 6;
    this.shiftKey = this.shiftKey || this.keyCode === 4;
    this.metaKey = this.metaKey || this.keyCode === 57;
    this._asKeybinding = this._computeKeybinding();
    this._asRuntimeKeybinding = this._computeRuntimeKeybinding();
  }
  preventDefault() {
    if (this.browserEvent && this.browserEvent.preventDefault) {
      this.browserEvent.preventDefault();
    }
  }
  stopPropagation() {
    if (this.browserEvent && this.browserEvent.stopPropagation) {
      this.browserEvent.stopPropagation();
    }
  }
  toKeybinding() {
    return this._asRuntimeKeybinding;
  }
  equals(other) {
    return this._asKeybinding === other;
  }
  _computeKeybinding() {
    let key = 0;
    if (this.keyCode !== 5 && this.keyCode !== 4 && this.keyCode !== 6 && this.keyCode !== 57) {
      key = this.keyCode;
    }
    let result = 0;
    if (this.ctrlKey) {
      result |= ctrlKeyMod;
    }
    if (this.altKey) {
      result |= altKeyMod;
    }
    if (this.shiftKey) {
      result |= shiftKeyMod;
    }
    if (this.metaKey) {
      result |= metaKeyMod;
    }
    result |= key;
    return result;
  }
  _computeRuntimeKeybinding() {
    let key = 0;
    if (this.keyCode !== 5 && this.keyCode !== 4 && this.keyCode !== 6 && this.keyCode !== 57) {
      key = this.keyCode;
    }
    return new SimpleKeybinding(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key);
  }
};
var hasDifferentOriginAncestorFlag = false;
var sameOriginWindowChainCache = null;
function getParentWindowIfSameOrigin(w2) {
  if (!w2.parent || w2.parent === w2) {
    return null;
  }
  try {
    let location2 = w2.location;
    let parentLocation = w2.parent.location;
    if (location2.origin !== "null" && parentLocation.origin !== "null") {
      if (location2.protocol !== parentLocation.protocol || location2.hostname !== parentLocation.hostname || location2.port !== parentLocation.port) {
        hasDifferentOriginAncestorFlag = true;
        return null;
      }
    }
  } catch (e2) {
    hasDifferentOriginAncestorFlag = true;
    return null;
  }
  return w2.parent;
}
var IframeUtils = class {
  static getSameOriginWindowChain() {
    if (!sameOriginWindowChainCache) {
      sameOriginWindowChainCache = [];
      let w2 = window;
      let parent;
      do {
        parent = getParentWindowIfSameOrigin(w2);
        if (parent) {
          sameOriginWindowChainCache.push({
            window: w2,
            iframeElement: w2.frameElement || null
          });
        } else {
          sameOriginWindowChainCache.push({
            window: w2,
            iframeElement: null
          });
        }
        w2 = parent;
      } while (w2);
    }
    return sameOriginWindowChainCache.slice(0);
  }
  static hasDifferentOriginAncestor() {
    if (!sameOriginWindowChainCache) {
      this.getSameOriginWindowChain();
    }
    return hasDifferentOriginAncestorFlag;
  }
  static getPositionOfChildWindowRelativeToAncestorWindow(childWindow, ancestorWindow) {
    if (!ancestorWindow || childWindow === ancestorWindow) {
      return {
        top: 0,
        left: 0
      };
    }
    let top2 = 0, left2 = 0;
    let windowChain = this.getSameOriginWindowChain();
    for (const windowChainEl of windowChain) {
      top2 += windowChainEl.window.scrollY;
      left2 += windowChainEl.window.scrollX;
      if (windowChainEl.window === ancestorWindow) {
        break;
      }
      if (!windowChainEl.iframeElement) {
        break;
      }
      let boundingRect = windowChainEl.iframeElement.getBoundingClientRect();
      top2 += boundingRect.top;
      left2 += boundingRect.left;
    }
    return {
      top: top2,
      left: left2
    };
  }
};
var StandardMouseEvent = class {
  constructor(e2) {
    this.timestamp = Date.now();
    this.browserEvent = e2;
    this.leftButton = e2.button === 0;
    this.middleButton = e2.button === 1;
    this.rightButton = e2.button === 2;
    this.buttons = e2.buttons;
    this.target = e2.target;
    this.detail = e2.detail || 1;
    if (e2.type === "dblclick") {
      this.detail = 2;
    }
    this.ctrlKey = e2.ctrlKey;
    this.shiftKey = e2.shiftKey;
    this.altKey = e2.altKey;
    this.metaKey = e2.metaKey;
    if (typeof e2.pageX === "number") {
      this.posx = e2.pageX;
      this.posy = e2.pageY;
    } else {
      this.posx = e2.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      this.posy = e2.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    let iframeOffsets = IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(self, e2.view);
    this.posx -= iframeOffsets.left;
    this.posy -= iframeOffsets.top;
  }
  preventDefault() {
    this.browserEvent.preventDefault();
  }
  stopPropagation() {
    this.browserEvent.stopPropagation();
  }
};
var StandardWheelEvent = class {
  constructor(e2, deltaX = 0, deltaY = 0) {
    this.browserEvent = e2 || null;
    this.target = e2 ? e2.target || e2.targetNode || e2.srcElement : null;
    this.deltaY = deltaY;
    this.deltaX = deltaX;
    if (e2) {
      let e1 = e2;
      let e22 = e2;
      if (typeof e1.wheelDeltaY !== "undefined") {
        this.deltaY = e1.wheelDeltaY / 120;
      } else if (typeof e22.VERTICAL_AXIS !== "undefined" && e22.axis === e22.VERTICAL_AXIS) {
        this.deltaY = -e22.detail / 3;
      } else if (e2.type === "wheel") {
        const ev = e2;
        if (ev.deltaMode === ev.DOM_DELTA_LINE) {
          if (isFirefox && !isMacintosh) {
            this.deltaY = -e2.deltaY / 3;
          } else {
            this.deltaY = -e2.deltaY;
          }
        } else {
          this.deltaY = -e2.deltaY / 40;
        }
      }
      if (typeof e1.wheelDeltaX !== "undefined") {
        if (isSafari && isWindows) {
          this.deltaX = -(e1.wheelDeltaX / 120);
        } else {
          this.deltaX = e1.wheelDeltaX / 120;
        }
      } else if (typeof e22.HORIZONTAL_AXIS !== "undefined" && e22.axis === e22.HORIZONTAL_AXIS) {
        this.deltaX = -e2.detail / 3;
      } else if (e2.type === "wheel") {
        const ev = e2;
        if (ev.deltaMode === ev.DOM_DELTA_LINE) {
          if (isFirefox && !isMacintosh) {
            this.deltaX = -e2.deltaX / 3;
          } else {
            this.deltaX = -e2.deltaX;
          }
        } else {
          this.deltaX = -e2.deltaX / 40;
        }
      }
      if (this.deltaY === 0 && this.deltaX === 0 && e2.wheelDelta) {
        this.deltaY = e2.wheelDelta / 120;
      }
    }
  }
  preventDefault() {
    if (this.browserEvent) {
      this.browserEvent.preventDefault();
    }
  }
  stopPropagation() {
    if (this.browserEvent) {
      this.browserEvent.stopPropagation();
    }
  }
};
function isThenable(obj) {
  return obj && typeof obj.then === "function";
}
function createCancelablePromise(callback) {
  const source2 = new CancellationTokenSource();
  const thenable = callback(source2.token);
  const promise = new Promise((resolve2, reject) => {
    source2.token.onCancellationRequested(() => {
      reject(canceled());
    });
    Promise.resolve(thenable).then((value) => {
      source2.dispose();
      resolve2(value);
    }, (err) => {
      source2.dispose();
      reject(err);
    });
  });
  return new class {
    cancel() {
      source2.cancel();
    }
    then(resolve2, reject) {
      return promise.then(resolve2, reject);
    }
    catch(reject) {
      return this.then(void 0, reject);
    }
    finally(onfinally) {
      return promise.finally(onfinally);
    }
  }();
}
var Delayer = class {
  constructor(defaultDelay) {
    this.defaultDelay = defaultDelay;
    this.timeout = null;
    this.completionPromise = null;
    this.doResolve = null;
    this.doReject = null;
    this.task = null;
  }
  trigger(task, delay3 = this.defaultDelay) {
    this.task = task;
    this.cancelTimeout();
    if (!this.completionPromise) {
      this.completionPromise = new Promise((c3, e2) => {
        this.doResolve = c3;
        this.doReject = e2;
      }).then(() => {
        this.completionPromise = null;
        this.doResolve = null;
        if (this.task) {
          const task2 = this.task;
          this.task = null;
          return task2();
        }
        return void 0;
      });
    }
    this.timeout = setTimeout(() => {
      this.timeout = null;
      if (this.doResolve) {
        this.doResolve(null);
      }
    }, delay3);
    return this.completionPromise;
  }
  isTriggered() {
    return this.timeout !== null;
  }
  cancel() {
    this.cancelTimeout();
    if (this.completionPromise) {
      if (this.doReject) {
        this.doReject(canceled());
      }
      this.completionPromise = null;
    }
  }
  cancelTimeout() {
    if (this.timeout !== null) {
      clearTimeout(this.timeout);
      this.timeout = null;
    }
  }
  dispose() {
    this.cancelTimeout();
  }
};
function timeout(millis, token2) {
  if (!token2) {
    return createCancelablePromise((token3) => timeout(millis, token3));
  }
  return new Promise((resolve2, reject) => {
    const handle2 = setTimeout(resolve2, millis);
    token2.onCancellationRequested(() => {
      clearTimeout(handle2);
      reject(canceled());
    });
  });
}
function disposableTimeout(handler, timeout3 = 0) {
  const timer2 = setTimeout(handler, timeout3);
  return toDisposable(() => clearTimeout(timer2));
}
var TimeoutTimer = class {
  constructor(runner, timeout3) {
    this._token = -1;
    if (typeof runner === "function" && typeof timeout3 === "number") {
      this.setIfNotSet(runner, timeout3);
    }
  }
  dispose() {
    this.cancel();
  }
  cancel() {
    if (this._token !== -1) {
      clearTimeout(this._token);
      this._token = -1;
    }
  }
  cancelAndSet(runner, timeout3) {
    this.cancel();
    this._token = setTimeout(() => {
      this._token = -1;
      runner();
    }, timeout3);
  }
  setIfNotSet(runner, timeout3) {
    if (this._token !== -1) {
      return;
    }
    this._token = setTimeout(() => {
      this._token = -1;
      runner();
    }, timeout3);
  }
};
var IntervalTimer = class {
  constructor() {
    this._token = -1;
  }
  dispose() {
    this.cancel();
  }
  cancel() {
    if (this._token !== -1) {
      clearInterval(this._token);
      this._token = -1;
    }
  }
  cancelAndSet(runner, interval2) {
    this.cancel();
    this._token = setInterval(() => {
      runner();
    }, interval2);
  }
};
var RunOnceScheduler = class {
  constructor(runner, timeout3) {
    this.timeoutToken = -1;
    this.runner = runner;
    this.timeout = timeout3;
    this.timeoutHandler = this.onTimeout.bind(this);
  }
  dispose() {
    this.cancel();
    this.runner = null;
  }
  cancel() {
    if (this.isScheduled()) {
      clearTimeout(this.timeoutToken);
      this.timeoutToken = -1;
    }
  }
  schedule(delay3 = this.timeout) {
    this.cancel();
    this.timeoutToken = setTimeout(this.timeoutHandler, delay3);
  }
  isScheduled() {
    return this.timeoutToken !== -1;
  }
  onTimeout() {
    this.timeoutToken = -1;
    if (this.runner) {
      this.doRun();
    }
  }
  doRun() {
    if (this.runner) {
      this.runner();
    }
  }
};
var runWhenIdle;
(function() {
  if (typeof requestIdleCallback !== "function" || typeof cancelIdleCallback !== "function") {
    const dummyIdle = Object.freeze({
      didTimeout: true,
      timeRemaining() {
        return 15;
      }
    });
    runWhenIdle = (runner) => {
      const handle2 = setTimeout(() => runner(dummyIdle));
      let disposed = false;
      return {
        dispose() {
          if (disposed) {
            return;
          }
          disposed = true;
          clearTimeout(handle2);
        }
      };
    };
  } else {
    runWhenIdle = (runner, timeout3) => {
      const handle2 = requestIdleCallback(runner, typeof timeout3 === "number" ? {timeout: timeout3} : void 0);
      let disposed = false;
      return {
        dispose() {
          if (disposed) {
            return;
          }
          disposed = true;
          cancelIdleCallback(handle2);
        }
      };
    };
  }
})();
var IdleValue = class {
  constructor(executor) {
    this._didRun = false;
    this._executor = () => {
      try {
        this._value = executor();
      } catch (err) {
        this._error = err;
      } finally {
        this._didRun = true;
      }
    };
    this._handle = runWhenIdle(() => this._executor());
  }
  dispose() {
    this._handle.dispose();
  }
  get value() {
    if (!this._didRun) {
      this._handle.dispose();
      this._executor();
    }
    if (this._error) {
      throw this._error;
    }
    return this._value;
  }
};
function tail(array2, n3 = 0) {
  return array2[array2.length - (1 + n3)];
}
function tail2(arr) {
  if (arr.length === 0) {
    throw new Error("Invalid tail call");
  }
  return [arr.slice(0, arr.length - 1), arr[arr.length - 1]];
}
function equals(one2, other, itemEquals = (a2, b2) => a2 === b2) {
  if (one2 === other) {
    return true;
  }
  if (!one2 || !other) {
    return false;
  }
  if (one2.length !== other.length) {
    return false;
  }
  for (let i3 = 0, len2 = one2.length; i3 < len2; i3++) {
    if (!itemEquals(one2[i3], other[i3])) {
      return false;
    }
  }
  return true;
}
function binarySearch(array2, key, comparator) {
  let low = 0, high = array2.length - 1;
  while (low <= high) {
    const mid = (low + high) / 2 | 0;
    const comp = comparator(array2[mid], key);
    if (comp < 0) {
      low = mid + 1;
    } else if (comp > 0) {
      high = mid - 1;
    } else {
      return mid;
    }
  }
  return -(low + 1);
}
function mergeSort(data2, compare2) {
  _sort(data2, compare2, 0, data2.length - 1, []);
  return data2;
}
function _merge(a2, compare2, lo, mid, hi2, aux) {
  let leftIdx = lo, rightIdx = mid + 1;
  for (let i3 = lo; i3 <= hi2; i3++) {
    aux[i3] = a2[i3];
  }
  for (let i3 = lo; i3 <= hi2; i3++) {
    if (leftIdx > mid) {
      a2[i3] = aux[rightIdx++];
    } else if (rightIdx > hi2) {
      a2[i3] = aux[leftIdx++];
    } else if (compare2(aux[rightIdx], aux[leftIdx]) < 0) {
      a2[i3] = aux[rightIdx++];
    } else {
      a2[i3] = aux[leftIdx++];
    }
  }
}
function _sort(a2, compare2, lo, hi2, aux) {
  if (hi2 <= lo) {
    return;
  }
  const mid = lo + (hi2 - lo) / 2 | 0;
  _sort(a2, compare2, lo, mid, aux);
  _sort(a2, compare2, mid + 1, hi2, aux);
  if (compare2(a2[mid], a2[mid + 1]) <= 0) {
    return;
  }
  _merge(a2, compare2, lo, mid, hi2, aux);
}
function coalesce(array2) {
  return array2.filter((e2) => !!e2);
}
function isFalsyOrEmpty(obj) {
  return !Array.isArray(obj) || obj.length === 0;
}
function isNonEmptyArray(obj) {
  return Array.isArray(obj) && obj.length > 0;
}
function distinct(array2, keyFn) {
  if (!keyFn) {
    return array2.filter((element, position2) => {
      return array2.indexOf(element) === position2;
    });
  }
  const seen = Object.create(null);
  return array2.filter((elem) => {
    const key = keyFn(elem);
    if (seen[key]) {
      return false;
    }
    seen[key] = true;
    return true;
  });
}
function distinctES6(array2) {
  const seen = new Set();
  return array2.filter((element) => {
    if (seen.has(element)) {
      return false;
    }
    seen.add(element);
    return true;
  });
}
function firstIndex(array2, fn) {
  for (let i3 = 0; i3 < array2.length; i3++) {
    const element = array2[i3];
    if (fn(element)) {
      return i3;
    }
  }
  return -1;
}
function first(array2, fn, notFoundValue = void 0) {
  const index3 = firstIndex(array2, fn);
  return index3 < 0 ? notFoundValue : array2[index3];
}
function firstOrDefault(array2, notFoundValue) {
  return array2.length > 0 ? array2[0] : notFoundValue;
}
function range(arg, to) {
  let from = typeof to === "number" ? arg : 0;
  if (typeof to === "number") {
    from = arg;
  } else {
    from = 0;
    to = arg;
  }
  const result = [];
  if (from <= to) {
    for (let i3 = from; i3 < to; i3++) {
      result.push(i3);
    }
  } else {
    for (let i3 = from; i3 > to; i3--) {
      result.push(i3);
    }
  }
  return result;
}
function arrayInsert(target, insertIndex, insertArr) {
  const before = target.slice(0, insertIndex);
  const after = target.slice(insertIndex);
  return before.concat(insertArr, after);
}
var Schemas;
(function(Schemas2) {
  Schemas2.inMemory = "inmemory";
  Schemas2.vscode = "vscode";
  Schemas2.internal = "private";
  Schemas2.walkThrough = "walkThrough";
  Schemas2.walkThroughSnippet = "walkThroughSnippet";
  Schemas2.http = "http";
  Schemas2.https = "https";
  Schemas2.file = "file";
  Schemas2.mailto = "mailto";
  Schemas2.untitled = "untitled";
  Schemas2.data = "data";
  Schemas2.command = "command";
  Schemas2.vscodeRemote = "vscode-remote";
  Schemas2.vscodeRemoteResource = "vscode-remote-resource";
  Schemas2.userData = "vscode-userdata";
  Schemas2.vscodeCustomEditor = "vscode-custom-editor";
  Schemas2.vscodeNotebook = "vscode-notebook";
  Schemas2.vscodeNotebookCell = "vscode-notebook-cell";
  Schemas2.vscodeSettings = "vscode-settings";
  Schemas2.webviewPanel = "webview-panel";
  Schemas2.vscodeWebview = "vscode-webview";
  Schemas2.vscodeWebviewResource = "vscode-webview-resource";
  Schemas2.extension = "extension";
})(Schemas || (Schemas = {}));
var RemoteAuthoritiesImpl = class {
  constructor() {
    this._hosts = Object.create(null);
    this._ports = Object.create(null);
    this._connectionTokens = Object.create(null);
    this._preferredWebSchema = "http";
    this._delegate = null;
  }
  setPreferredWebSchema(schema) {
    this._preferredWebSchema = schema;
  }
  rewrite(uri) {
    if (this._delegate) {
      return this._delegate(uri);
    }
    const authority = uri.authority;
    let host = this._hosts[authority];
    if (host && host.indexOf(":") !== -1) {
      host = `[${host}]`;
    }
    const port = this._ports[authority];
    const connectionToken = this._connectionTokens[authority];
    let query = `path=${encodeURIComponent(uri.path)}`;
    if (typeof connectionToken === "string") {
      query += `&tkn=${encodeURIComponent(connectionToken)}`;
    }
    return URI.from({
      scheme: isWeb2 ? this._preferredWebSchema : Schemas.vscodeRemoteResource,
      authority: `${host}:${port}`,
      path: `/vscode-remote-resource`,
      query
    });
  }
};
var RemoteAuthorities = new RemoteAuthoritiesImpl();
var BrowserFeatures = {
  clipboard: {
    writeText: isNative || document.queryCommandSupported && document.queryCommandSupported("copy") || !!(navigator && navigator.clipboard && navigator.clipboard.writeText),
    readText: isNative || !!(navigator && navigator.clipboard && navigator.clipboard.readText),
    richText: (() => {
      if (isEdge2) {
        let index3 = navigator.userAgent.indexOf("Edge/");
        let version4 = parseInt(navigator.userAgent.substring(index3 + 5, navigator.userAgent.indexOf(".", index3)), 10);
        if (!version4 || version4 >= 12 && version4 <= 16) {
          return false;
        }
      }
      return true;
    })()
  },
  keyboard: (() => {
    if (isNative || isStandalone) {
      return 0;
    }
    if (navigator.keyboard || isSafari) {
      return 1;
    }
    return 2;
  })(),
  touch: "ontouchstart" in window || navigator.maxTouchPoints > 0 || window.navigator.msMaxTouchPoints > 0,
  pointerEvents: window.PointerEvent && ("ontouchstart" in window || window.navigator.maxTouchPoints > 0 || navigator.maxTouchPoints > 0 || window.navigator.msMaxTouchPoints > 0)
};
function clearNode(node) {
  while (node.firstChild) {
    node.removeChild(node.firstChild);
  }
}
function removeNode(node) {
  if (node.parentNode) {
    node.parentNode.removeChild(node);
  }
}
function isInDOM(node) {
  while (node) {
    if (node === document.body) {
      return true;
    }
    node = node.parentNode || node.host;
  }
  return false;
}
var _classList = new class {
  hasClass(node, className) {
    return Boolean(className) && node.classList && node.classList.contains(className);
  }
  addClasses(node, ...classNames2) {
    classNames2.forEach((nameValue) => nameValue.split(" ").forEach((name) => this.addClass(node, name)));
  }
  addClass(node, className) {
    if (className && node.classList) {
      node.classList.add(className);
    }
  }
  removeClass(node, className) {
    if (className && node.classList) {
      node.classList.remove(className);
    }
  }
  removeClasses(node, ...classNames2) {
    classNames2.forEach((nameValue) => nameValue.split(" ").forEach((name) => this.removeClass(node, name)));
  }
  toggleClass(node, className, shouldHaveIt) {
    if (node.classList) {
      node.classList.toggle(className, shouldHaveIt);
    }
  }
}();
var hasClass = _classList.hasClass.bind(_classList);
var addClass = _classList.addClass.bind(_classList);
var addClasses = _classList.addClasses.bind(_classList);
var removeClass = _classList.removeClass.bind(_classList);
var removeClasses = _classList.removeClasses.bind(_classList);
var toggleClass = _classList.toggleClass.bind(_classList);
var DomListener = class {
  constructor(node, type, handler, options) {
    this._node = node;
    this._type = type;
    this._handler = handler;
    this._options = options || false;
    this._node.addEventListener(this._type, this._handler, this._options);
  }
  dispose() {
    if (!this._handler) {
      return;
    }
    this._node.removeEventListener(this._type, this._handler, this._options);
    this._node = null;
    this._handler = null;
  }
};
function addDisposableListener(node, type, handler, useCaptureOrOptions) {
  return new DomListener(node, type, handler, useCaptureOrOptions);
}
function _wrapAsStandardMouseEvent(handler) {
  return function(e2) {
    return handler(new StandardMouseEvent(e2));
  };
}
function _wrapAsStandardKeyboardEvent(handler) {
  return function(e2) {
    return handler(new StandardKeyboardEvent(e2));
  };
}
var addStandardDisposableListener = function addStandardDisposableListener2(node, type, handler, useCapture) {
  let wrapHandler = handler;
  if (type === "click" || type === "mousedown") {
    wrapHandler = _wrapAsStandardMouseEvent(handler);
  } else if (type === "keydown" || type === "keypress" || type === "keyup") {
    wrapHandler = _wrapAsStandardKeyboardEvent(handler);
  }
  return addDisposableListener(node, type, wrapHandler, useCapture);
};
function addDisposableNonBubblingMouseOutListener(node, handler) {
  return addDisposableListener(node, "mouseout", (e2) => {
    let toElement = e2.relatedTarget;
    while (toElement && toElement !== node) {
      toElement = toElement.parentNode;
    }
    if (toElement === node) {
      return;
    }
    handler(e2);
  });
}
function addDisposableNonBubblingPointerOutListener(node, handler) {
  return addDisposableListener(node, "pointerout", (e2) => {
    let toElement = e2.relatedTarget;
    while (toElement && toElement !== node) {
      toElement = toElement.parentNode;
    }
    if (toElement === node) {
      return;
    }
    handler(e2);
  });
}
var _animationFrame = null;
function doRequestAnimationFrame(callback) {
  if (!_animationFrame) {
    const emulatedRequestAnimationFrame = (callback2) => {
      return setTimeout(() => callback2(new Date().getTime()), 0);
    };
    _animationFrame = self.requestAnimationFrame || self.msRequestAnimationFrame || self.webkitRequestAnimationFrame || self.mozRequestAnimationFrame || self.oRequestAnimationFrame || emulatedRequestAnimationFrame;
  }
  return _animationFrame.call(self, callback);
}
var runAtThisOrScheduleAtNextAnimationFrame;
var scheduleAtNextAnimationFrame;
var AnimationFrameQueueItem = class {
  constructor(runner, priority = 0) {
    this._runner = runner;
    this.priority = priority;
    this._canceled = false;
  }
  dispose() {
    this._canceled = true;
  }
  execute() {
    if (this._canceled) {
      return;
    }
    try {
      this._runner();
    } catch (e2) {
      onUnexpectedError(e2);
    }
  }
  static sort(a2, b2) {
    return b2.priority - a2.priority;
  }
};
(function() {
  let NEXT_QUEUE = [];
  let CURRENT_QUEUE = null;
  let animFrameRequested = false;
  let inAnimationFrameRunner = false;
  let animationFrameRunner = () => {
    animFrameRequested = false;
    CURRENT_QUEUE = NEXT_QUEUE;
    NEXT_QUEUE = [];
    inAnimationFrameRunner = true;
    while (CURRENT_QUEUE.length > 0) {
      CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort);
      let top2 = CURRENT_QUEUE.shift();
      top2.execute();
    }
    inAnimationFrameRunner = false;
  };
  scheduleAtNextAnimationFrame = (runner, priority = 0) => {
    let item = new AnimationFrameQueueItem(runner, priority);
    NEXT_QUEUE.push(item);
    if (!animFrameRequested) {
      animFrameRequested = true;
      doRequestAnimationFrame(animationFrameRunner);
    }
    return item;
  };
  runAtThisOrScheduleAtNextAnimationFrame = (runner, priority) => {
    if (inAnimationFrameRunner) {
      let item = new AnimationFrameQueueItem(runner, priority);
      CURRENT_QUEUE.push(item);
      return item;
    } else {
      return scheduleAtNextAnimationFrame(runner, priority);
    }
  };
})();
var MINIMUM_TIME_MS = 16;
var DEFAULT_EVENT_MERGER = function(lastEvent, currentEvent) {
  return currentEvent;
};
var TimeoutThrottledDomListener = class extends Disposable {
  constructor(node, type, handler, eventMerger = DEFAULT_EVENT_MERGER, minimumTimeMs = MINIMUM_TIME_MS) {
    super();
    let lastEvent = null;
    let lastHandlerTime = 0;
    let timeout3 = this._register(new TimeoutTimer());
    let invokeHandler = () => {
      lastHandlerTime = new Date().getTime();
      handler(lastEvent);
      lastEvent = null;
    };
    this._register(addDisposableListener(node, type, (e2) => {
      lastEvent = eventMerger(lastEvent, e2);
      let elapsedTime = new Date().getTime() - lastHandlerTime;
      if (elapsedTime >= minimumTimeMs) {
        timeout3.cancel();
        invokeHandler();
      } else {
        timeout3.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime);
      }
    }));
  }
};
function addDisposableThrottledListener(node, type, handler, eventMerger, minimumTimeMs) {
  return new TimeoutThrottledDomListener(node, type, handler, eventMerger, minimumTimeMs);
}
function getComputedStyle$12(el) {
  return document.defaultView.getComputedStyle(el, null);
}
function getClientArea(element) {
  if (element !== document.body) {
    return new Dimension(element.clientWidth, element.clientHeight);
  }
  if (isIOS && window.visualViewport) {
    const width2 = window.visualViewport.width;
    const height = window.visualViewport.height - (isStandalone ? 20 + 4 : 0);
    return new Dimension(width2, height);
  }
  if (window.innerWidth && window.innerHeight) {
    return new Dimension(window.innerWidth, window.innerHeight);
  }
  if (document.body && document.body.clientWidth && document.body.clientHeight) {
    return new Dimension(document.body.clientWidth, document.body.clientHeight);
  }
  if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) {
    return new Dimension(document.documentElement.clientWidth, document.documentElement.clientHeight);
  }
  throw new Error("Unable to figure out browser width and height");
}
var SizeUtils = class {
  static convertToPixels(element, value) {
    return parseFloat(value) || 0;
  }
  static getDimension(element, cssPropertyName, jsPropertyName) {
    let computedStyle = getComputedStyle$12(element);
    let value = "0";
    if (computedStyle) {
      if (computedStyle.getPropertyValue) {
        value = computedStyle.getPropertyValue(cssPropertyName);
      } else {
        value = computedStyle.getAttribute(jsPropertyName);
      }
    }
    return SizeUtils.convertToPixels(element, value);
  }
  static getBorderLeftWidth(element) {
    return SizeUtils.getDimension(element, "border-left-width", "borderLeftWidth");
  }
  static getBorderRightWidth(element) {
    return SizeUtils.getDimension(element, "border-right-width", "borderRightWidth");
  }
  static getBorderTopWidth(element) {
    return SizeUtils.getDimension(element, "border-top-width", "borderTopWidth");
  }
  static getBorderBottomWidth(element) {
    return SizeUtils.getDimension(element, "border-bottom-width", "borderBottomWidth");
  }
  static getPaddingLeft(element) {
    return SizeUtils.getDimension(element, "padding-left", "paddingLeft");
  }
  static getPaddingRight(element) {
    return SizeUtils.getDimension(element, "padding-right", "paddingRight");
  }
  static getPaddingTop(element) {
    return SizeUtils.getDimension(element, "padding-top", "paddingTop");
  }
  static getPaddingBottom(element) {
    return SizeUtils.getDimension(element, "padding-bottom", "paddingBottom");
  }
  static getMarginLeft(element) {
    return SizeUtils.getDimension(element, "margin-left", "marginLeft");
  }
  static getMarginTop(element) {
    return SizeUtils.getDimension(element, "margin-top", "marginTop");
  }
  static getMarginRight(element) {
    return SizeUtils.getDimension(element, "margin-right", "marginRight");
  }
  static getMarginBottom(element) {
    return SizeUtils.getDimension(element, "margin-bottom", "marginBottom");
  }
};
var Dimension = class {
  constructor(width2, height) {
    this.width = width2;
    this.height = height;
  }
};
function getTopLeftOffset(element) {
  let offsetParent2 = element.offsetParent;
  let top2 = element.offsetTop;
  let left2 = element.offsetLeft;
  while ((element = element.parentNode) !== null && element !== document.body && element !== document.documentElement) {
    top2 -= element.scrollTop;
    const c3 = isShadowRoot(element) ? null : getComputedStyle$12(element);
    if (c3) {
      left2 -= c3.direction !== "rtl" ? element.scrollLeft : -element.scrollLeft;
    }
    if (element === offsetParent2) {
      left2 += SizeUtils.getBorderLeftWidth(element);
      top2 += SizeUtils.getBorderTopWidth(element);
      top2 += element.offsetTop;
      left2 += element.offsetLeft;
      offsetParent2 = element.offsetParent;
    }
  }
  return {
    left: left2,
    top: top2
  };
}
function getDomNodePagePosition(domNode) {
  let bb2 = domNode.getBoundingClientRect();
  return {
    left: bb2.left + StandardWindow.scrollX,
    top: bb2.top + StandardWindow.scrollY,
    width: bb2.width,
    height: bb2.height
  };
}
var StandardWindow = new class {
  get scrollX() {
    if (typeof window.scrollX === "number") {
      return window.scrollX;
    } else {
      return document.body.scrollLeft + document.documentElement.scrollLeft;
    }
  }
  get scrollY() {
    if (typeof window.scrollY === "number") {
      return window.scrollY;
    } else {
      return document.body.scrollTop + document.documentElement.scrollTop;
    }
  }
}();
function getTotalWidth(element) {
  let margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
  return element.offsetWidth + margin;
}
function getContentWidth(element) {
  let border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);
  let padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);
  return element.offsetWidth - border - padding;
}
function getContentHeight(element) {
  let border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);
  let padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);
  return element.offsetHeight - border - padding;
}
function getTotalHeight(element) {
  let margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);
  return element.offsetHeight + margin;
}
function isAncestor(testChild, testAncestor) {
  while (testChild) {
    if (testChild === testAncestor) {
      return true;
    }
    testChild = testChild.parentNode;
  }
  return false;
}
function findParentWithClass(node, clazz, stopAtClazzOrNode) {
  while (node && node.nodeType === node.ELEMENT_NODE) {
    if (hasClass(node, clazz)) {
      return node;
    }
    if (stopAtClazzOrNode) {
      if (typeof stopAtClazzOrNode === "string") {
        if (hasClass(node, stopAtClazzOrNode)) {
          return null;
        }
      } else {
        if (node === stopAtClazzOrNode) {
          return null;
        }
      }
    }
    node = node.parentNode;
  }
  return null;
}
function hasParentWithClass(node, clazz, stopAtClazzOrNode) {
  return !!findParentWithClass(node, clazz, stopAtClazzOrNode);
}
function isShadowRoot(node) {
  return node && !!node.host && !!node.mode;
}
function isInShadowDOM(domNode) {
  return !!getShadowRoot(domNode);
}
function getShadowRoot(domNode) {
  while (domNode.parentNode) {
    if (domNode === document.body) {
      return null;
    }
    domNode = domNode.parentNode;
  }
  return isShadowRoot(domNode) ? domNode : null;
}
function getActiveElement() {
  let result = document.activeElement;
  while (result === null || result === void 0 ? void 0 : result.shadowRoot) {
    result = result.shadowRoot.activeElement;
  }
  return result;
}
function createStyleSheet(container = document.getElementsByTagName("head")[0]) {
  let style = document.createElement("style");
  style.type = "text/css";
  style.media = "screen";
  container.appendChild(style);
  return style;
}
var _sharedStyleSheet = null;
function getSharedStyleSheet() {
  if (!_sharedStyleSheet) {
    _sharedStyleSheet = createStyleSheet();
  }
  return _sharedStyleSheet;
}
function getDynamicStyleSheetRules(style) {
  if (style && style.sheet && style.sheet.rules) {
    return style.sheet.rules;
  }
  if (style && style.sheet && style.sheet.cssRules) {
    return style.sheet.cssRules;
  }
  return [];
}
function createCSSRule(selector2, cssText, style = getSharedStyleSheet()) {
  if (!style || !cssText) {
    return;
  }
  style.sheet.insertRule(selector2 + "{" + cssText + "}", 0);
}
function removeCSSRulesContainingSelector(ruleName, style = getSharedStyleSheet()) {
  if (!style) {
    return;
  }
  let rules = getDynamicStyleSheetRules(style);
  let toDelete = [];
  for (let i3 = 0; i3 < rules.length; i3++) {
    let rule = rules[i3];
    if (rule.selectorText.indexOf(ruleName) !== -1) {
      toDelete.push(i3);
    }
  }
  for (let i3 = toDelete.length - 1; i3 >= 0; i3--) {
    style.sheet.deleteRule(toDelete[i3]);
  }
}
function isHTMLElement3(o) {
  if (typeof HTMLElement === "object") {
    return o instanceof HTMLElement;
  }
  return o && typeof o === "object" && o.nodeType === 1 && typeof o.nodeName === "string";
}
var EventType = {
  CLICK: "click",
  AUXCLICK: "auxclick",
  DBLCLICK: "dblclick",
  MOUSE_UP: "mouseup",
  MOUSE_DOWN: "mousedown",
  MOUSE_OVER: "mouseover",
  MOUSE_MOVE: "mousemove",
  MOUSE_OUT: "mouseout",
  MOUSE_ENTER: "mouseenter",
  MOUSE_LEAVE: "mouseleave",
  MOUSE_WHEEL: isEdge2 ? "mousewheel" : "wheel",
  POINTER_UP: "pointerup",
  POINTER_DOWN: "pointerdown",
  POINTER_MOVE: "pointermove",
  CONTEXT_MENU: "contextmenu",
  WHEEL: "wheel",
  KEY_DOWN: "keydown",
  KEY_PRESS: "keypress",
  KEY_UP: "keyup",
  LOAD: "load",
  BEFORE_UNLOAD: "beforeunload",
  UNLOAD: "unload",
  ABORT: "abort",
  ERROR: "error",
  RESIZE: "resize",
  SCROLL: "scroll",
  FULLSCREEN_CHANGE: "fullscreenchange",
  WK_FULLSCREEN_CHANGE: "webkitfullscreenchange",
  SELECT: "select",
  CHANGE: "change",
  SUBMIT: "submit",
  RESET: "reset",
  FOCUS: "focus",
  FOCUS_IN: "focusin",
  FOCUS_OUT: "focusout",
  BLUR: "blur",
  INPUT: "input",
  STORAGE: "storage",
  DRAG_START: "dragstart",
  DRAG: "drag",
  DRAG_ENTER: "dragenter",
  DRAG_LEAVE: "dragleave",
  DRAG_OVER: "dragover",
  DROP: "drop",
  DRAG_END: "dragend",
  ANIMATION_START: isWebKit ? "webkitAnimationStart" : "animationstart",
  ANIMATION_END: isWebKit ? "webkitAnimationEnd" : "animationend",
  ANIMATION_ITERATION: isWebKit ? "webkitAnimationIteration" : "animationiteration"
};
var EventHelper = {
  stop: function(e2, cancelBubble) {
    if (e2.preventDefault) {
      e2.preventDefault();
    } else {
      e2.returnValue = false;
    }
    if (cancelBubble) {
      if (e2.stopPropagation) {
        e2.stopPropagation();
      } else {
        e2.cancelBubble = true;
      }
    }
  }
};
function saveParentsScrollTop(node) {
  let r3 = [];
  for (let i3 = 0; node && node.nodeType === node.ELEMENT_NODE; i3++) {
    r3[i3] = node.scrollTop;
    node = node.parentNode;
  }
  return r3;
}
function restoreParentsScrollTop(node, state) {
  for (let i3 = 0; node && node.nodeType === node.ELEMENT_NODE; i3++) {
    if (node.scrollTop !== state[i3]) {
      node.scrollTop = state[i3];
    }
    node = node.parentNode;
  }
}
var FocusTracker = class extends Disposable {
  constructor(element) {
    super();
    this._onDidFocus = this._register(new Emitter());
    this.onDidFocus = this._onDidFocus.event;
    this._onDidBlur = this._register(new Emitter());
    this.onDidBlur = this._onDidBlur.event;
    let hasFocus = isAncestor(document.activeElement, element);
    let loosingFocus = false;
    const onFocus = () => {
      loosingFocus = false;
      if (!hasFocus) {
        hasFocus = true;
        this._onDidFocus.fire();
      }
    };
    const onBlur = () => {
      if (hasFocus) {
        loosingFocus = true;
        window.setTimeout(() => {
          if (loosingFocus) {
            loosingFocus = false;
            hasFocus = false;
            this._onDidBlur.fire();
          }
        }, 0);
      }
    };
    this._refreshStateHandler = () => {
      let currentNodeHasFocus = isAncestor(document.activeElement, element);
      if (currentNodeHasFocus !== hasFocus) {
        if (hasFocus) {
          onBlur();
        } else {
          onFocus();
        }
      }
    };
    this._register(domEvent(element, EventType.FOCUS, true)(onFocus));
    this._register(domEvent(element, EventType.BLUR, true)(onBlur));
  }
};
function trackFocus(element) {
  return new FocusTracker(element);
}
function append(parent, ...children2) {
  children2.forEach((child) => parent.appendChild(child));
  return children2[children2.length - 1];
}
var SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;
function reset(parent, ...children2) {
  parent.innerText = "";
  coalesce(children2).forEach((child) => {
    if (child instanceof Node) {
      parent.appendChild(child);
    } else {
      parent.appendChild(document.createTextNode(child));
    }
  });
}
var Namespace;
(function(Namespace2) {
  Namespace2["HTML"] = "http://www.w3.org/1999/xhtml";
  Namespace2["SVG"] = "http://www.w3.org/2000/svg";
})(Namespace || (Namespace = {}));
function _$(namespace2, description, attrs, ...children2) {
  let match2 = SELECTOR_REGEX.exec(description);
  if (!match2) {
    throw new Error("Bad use of emmet");
  }
  attrs = Object.assign({}, attrs || {});
  let tagName = match2[1] || "div";
  let result;
  if (namespace2 !== Namespace.HTML) {
    result = document.createElementNS(namespace2, tagName);
  } else {
    result = document.createElement(tagName);
  }
  if (match2[3]) {
    result.id = match2[3];
  }
  if (match2[4]) {
    result.className = match2[4].replace(/\./g, " ").trim();
  }
  Object.keys(attrs).forEach((name) => {
    const value = attrs[name];
    if (typeof value === "undefined") {
      return;
    }
    if (/^on\w+$/.test(name)) {
      result[name] = value;
    } else if (name === "selected") {
      if (value) {
        result.setAttribute(name, "true");
      }
    } else {
      result.setAttribute(name, value);
    }
  });
  coalesce(children2).forEach((child) => {
    if (child instanceof Node) {
      result.appendChild(child);
    } else {
      result.appendChild(document.createTextNode(child));
    }
  });
  return result;
}
function $(description, attrs, ...children2) {
  return _$(Namespace.HTML, description, attrs, ...children2);
}
$.SVG = function(description, attrs, ...children2) {
  return _$(Namespace.SVG, description, attrs, ...children2);
};
function show(...elements) {
  for (let element of elements) {
    element.style.display = "";
    element.removeAttribute("aria-hidden");
  }
}
function hide2(...elements) {
  for (let element of elements) {
    element.style.display = "none";
    element.setAttribute("aria-hidden", "true");
  }
}
function findParentWithAttribute(node, attribute) {
  while (node && node.nodeType === node.ELEMENT_NODE) {
    if (node instanceof HTMLElement && node.hasAttribute(attribute)) {
      return node;
    }
    node = node.parentNode;
  }
  return null;
}
function removeTabIndexAndUpdateFocus(node) {
  if (!node || !node.hasAttribute("tabIndex")) {
    return;
  }
  if (document.activeElement === node) {
    let parentFocusable = findParentWithAttribute(node.parentElement, "tabIndex");
    if (parentFocusable) {
      parentFocusable.focus();
    }
  }
  node.removeAttribute("tabindex");
}
function getElementsByTagName(tag) {
  return Array.prototype.slice.call(document.getElementsByTagName(tag), 0);
}
function computeScreenAwareSize(cssPx) {
  const screenPx = window.devicePixelRatio * cssPx;
  return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio;
}
function windowOpenNoOpener(url) {
  if (isNative || isEdgeWebView) {
    window.open(url);
  } else {
    let newTab = window.open();
    if (newTab) {
      newTab.opener = null;
      newTab.location.href = url;
    }
  }
}
function animate(fn) {
  const step = () => {
    fn();
    stepDisposable = scheduleAtNextAnimationFrame(step);
  };
  let stepDisposable = scheduleAtNextAnimationFrame(step);
  return toDisposable(() => stepDisposable.dispose());
}
RemoteAuthorities.setPreferredWebSchema(/^https:/.test(window.location.href) ? "https" : "http");
function asDomUri(uri) {
  if (!uri) {
    return uri;
  }
  if (Schemas.vscodeRemote === uri.scheme) {
    return RemoteAuthorities.rewrite(uri);
  }
  return uri;
}
function asCSSUrl(uri) {
  if (!uri) {
    return `url('')`;
  }
  return `url('${asDomUri(uri).toString(true).replace(/'/g, "%27")}')`;
}
function isFalsyOrWhitespace(str) {
  if (!str || typeof str !== "string") {
    return true;
  }
  return str.trim().length === 0;
}
var _formatRegexp = /{(\d+)}/g;
function format(value, ...args) {
  if (args.length === 0) {
    return value;
  }
  return value.replace(_formatRegexp, function(match2, group) {
    const idx = parseInt(group, 10);
    return isNaN(idx) || idx < 0 || idx >= args.length ? match2 : args[idx];
  });
}
function escape3(html) {
  return html.replace(/[<>&]/g, function(match2) {
    switch (match2) {
      case "<":
        return "&lt;";
      case ">":
        return "&gt;";
      case "&":
        return "&amp;";
      default:
        return match2;
    }
  });
}
function escapeRegExpCharacters(value) {
  return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, "\\$&");
}
function ltrim(haystack, needle) {
  if (!haystack || !needle) {
    return haystack;
  }
  const needleLen = needle.length;
  if (needleLen === 0 || haystack.length === 0) {
    return haystack;
  }
  let offset2 = 0;
  while (haystack.indexOf(needle, offset2) === offset2) {
    offset2 = offset2 + needleLen;
  }
  return haystack.substring(offset2);
}
function rtrim(haystack, needle) {
  if (!haystack || !needle) {
    return haystack;
  }
  const needleLen = needle.length, haystackLen = haystack.length;
  if (needleLen === 0 || haystackLen === 0) {
    return haystack;
  }
  let offset2 = haystackLen, idx = -1;
  while (true) {
    idx = haystack.lastIndexOf(needle, offset2 - 1);
    if (idx === -1 || idx + needleLen !== offset2) {
      break;
    }
    if (idx === 0) {
      return "";
    }
    offset2 = idx;
  }
  return haystack.substring(0, offset2);
}
function convertSimple2RegExpPattern(pattern) {
  return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, "\\$&").replace(/[\*]/g, ".*");
}
function startsWith(haystack, needle) {
  if (haystack.length < needle.length) {
    return false;
  }
  if (haystack === needle) {
    return true;
  }
  for (let i3 = 0; i3 < needle.length; i3++) {
    if (haystack[i3] !== needle[i3]) {
      return false;
    }
  }
  return true;
}
function endsWith(haystack, needle) {
  const diff = haystack.length - needle.length;
  if (diff > 0) {
    return haystack.indexOf(needle, diff) === diff;
  } else if (diff === 0) {
    return haystack === needle;
  } else {
    return false;
  }
}
function createRegExp(searchString, isRegex2, options = {}) {
  if (!searchString) {
    throw new Error("Cannot create regex from empty string");
  }
  if (!isRegex2) {
    searchString = escapeRegExpCharacters(searchString);
  }
  if (options.wholeWord) {
    if (!/\B/.test(searchString.charAt(0))) {
      searchString = "\\b" + searchString;
    }
    if (!/\B/.test(searchString.charAt(searchString.length - 1))) {
      searchString = searchString + "\\b";
    }
  }
  let modifiers = "";
  if (options.global) {
    modifiers += "g";
  }
  if (!options.matchCase) {
    modifiers += "i";
  }
  if (options.multiline) {
    modifiers += "m";
  }
  if (options.unicode) {
    modifiers += "u";
  }
  return new RegExp(searchString, modifiers);
}
function regExpLeadsToEndlessLoop(regexp) {
  if (regexp.source === "^" || regexp.source === "^$" || regexp.source === "$" || regexp.source === "^\\s*$") {
    return false;
  }
  const match2 = regexp.exec("");
  return !!(match2 && regexp.lastIndex === 0);
}
function regExpFlags(regexp) {
  return (regexp.global ? "g" : "") + (regexp.ignoreCase ? "i" : "") + (regexp.multiline ? "m" : "") + (regexp.unicode ? "u" : "");
}
function firstNonWhitespaceIndex(str) {
  for (let i3 = 0, len2 = str.length; i3 < len2; i3++) {
    const chCode = str.charCodeAt(i3);
    if (chCode !== 32 && chCode !== 9) {
      return i3;
    }
  }
  return -1;
}
function getLeadingWhitespace(str, start3 = 0, end2 = str.length) {
  for (let i3 = start3; i3 < end2; i3++) {
    const chCode = str.charCodeAt(i3);
    if (chCode !== 32 && chCode !== 9) {
      return str.substring(start3, i3);
    }
  }
  return str.substring(start3, end2);
}
function lastNonWhitespaceIndex(str, startIndex = str.length - 1) {
  for (let i3 = startIndex; i3 >= 0; i3--) {
    const chCode = str.charCodeAt(i3);
    if (chCode !== 32 && chCode !== 9) {
      return i3;
    }
  }
  return -1;
}
function compare(a2, b2) {
  if (a2 < b2) {
    return -1;
  } else if (a2 > b2) {
    return 1;
  } else {
    return 0;
  }
}
function isLowerAsciiLetter(code2) {
  return code2 >= 97 && code2 <= 122;
}
function isUpperAsciiLetter(code2) {
  return code2 >= 65 && code2 <= 90;
}
function isAsciiLetter(code2) {
  return isLowerAsciiLetter(code2) || isUpperAsciiLetter(code2);
}
function equalsIgnoreCase(a2, b2) {
  return a2.length === b2.length && doEqualsIgnoreCase(a2, b2);
}
function doEqualsIgnoreCase(a2, b2, stopAt = a2.length) {
  for (let i3 = 0; i3 < stopAt; i3++) {
    const codeA = a2.charCodeAt(i3);
    const codeB = b2.charCodeAt(i3);
    if (codeA === codeB) {
      continue;
    }
    if (isAsciiLetter(codeA) && isAsciiLetter(codeB)) {
      const diff = Math.abs(codeA - codeB);
      if (diff !== 0 && diff !== 32) {
        return false;
      }
    } else {
      if (String.fromCharCode(codeA).toLowerCase() !== String.fromCharCode(codeB).toLowerCase()) {
        return false;
      }
    }
  }
  return true;
}
function startsWithIgnoreCase(str, candidate) {
  const candidateLength = candidate.length;
  if (candidate.length > str.length) {
    return false;
  }
  return doEqualsIgnoreCase(str, candidate, candidateLength);
}
function commonPrefixLength(a2, b2) {
  let i3, len2 = Math.min(a2.length, b2.length);
  for (i3 = 0; i3 < len2; i3++) {
    if (a2.charCodeAt(i3) !== b2.charCodeAt(i3)) {
      return i3;
    }
  }
  return len2;
}
function commonSuffixLength(a2, b2) {
  let i3, len2 = Math.min(a2.length, b2.length);
  const aLastIndex = a2.length - 1;
  const bLastIndex = b2.length - 1;
  for (i3 = 0; i3 < len2; i3++) {
    if (a2.charCodeAt(aLastIndex - i3) !== b2.charCodeAt(bLastIndex - i3)) {
      return i3;
    }
  }
  return len2;
}
function isHighSurrogate(charCode) {
  return 55296 <= charCode && charCode <= 56319;
}
function isLowSurrogate(charCode) {
  return 56320 <= charCode && charCode <= 57343;
}
function computeCodePoint(highSurrogate, lowSurrogate) {
  return (highSurrogate - 55296 << 10) + (lowSurrogate - 56320) + 65536;
}
function getNextCodePoint(str, len2, offset2) {
  const charCode = str.charCodeAt(offset2);
  if (isHighSurrogate(charCode) && offset2 + 1 < len2) {
    const nextCharCode = str.charCodeAt(offset2 + 1);
    if (isLowSurrogate(nextCharCode)) {
      return computeCodePoint(charCode, nextCharCode);
    }
  }
  return charCode;
}
function getPrevCodePoint(str, offset2) {
  const charCode = str.charCodeAt(offset2 - 1);
  if (isLowSurrogate(charCode) && offset2 > 1) {
    const prevCharCode = str.charCodeAt(offset2 - 2);
    if (isHighSurrogate(prevCharCode)) {
      return computeCodePoint(prevCharCode, charCode);
    }
  }
  return charCode;
}
function nextCharLength(str, offset2) {
  const graphemeBreakTree = GraphemeBreakTree.getInstance();
  const initialOffset = offset2;
  const len2 = str.length;
  const initialCodePoint = getNextCodePoint(str, len2, offset2);
  offset2 += initialCodePoint >= 65536 ? 2 : 1;
  let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(initialCodePoint);
  while (offset2 < len2) {
    const nextCodePoint = getNextCodePoint(str, len2, offset2);
    const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(nextCodePoint);
    if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
      break;
    }
    offset2 += nextCodePoint >= 65536 ? 2 : 1;
    graphemeBreakType = nextGraphemeBreakType;
  }
  return offset2 - initialOffset;
}
function prevCharLength(str, offset2) {
  const graphemeBreakTree = GraphemeBreakTree.getInstance();
  const initialOffset = offset2;
  const initialCodePoint = getPrevCodePoint(str, offset2);
  offset2 -= initialCodePoint >= 65536 ? 2 : 1;
  let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(initialCodePoint);
  while (offset2 > 0) {
    const prevCodePoint = getPrevCodePoint(str, offset2);
    const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(prevCodePoint);
    if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) {
      break;
    }
    offset2 -= prevCodePoint >= 65536 ? 2 : 1;
    graphemeBreakType = prevGraphemeBreakType;
  }
  return initialOffset - offset2;
}
function decodeUTF8(buffer) {
  const len2 = buffer.byteLength;
  const result = [];
  let offset2 = 0;
  while (offset2 < len2) {
    const v0 = buffer[offset2];
    let codePoint;
    if (v0 >= 240 && offset2 + 3 < len2) {
      codePoint = (buffer[offset2++] & 7) << 18 >>> 0 | (buffer[offset2++] & 63) << 12 >>> 0 | (buffer[offset2++] & 63) << 6 >>> 0 | (buffer[offset2++] & 63) << 0 >>> 0;
    } else if (v0 >= 224 && offset2 + 2 < len2) {
      codePoint = (buffer[offset2++] & 15) << 12 >>> 0 | (buffer[offset2++] & 63) << 6 >>> 0 | (buffer[offset2++] & 63) << 0 >>> 0;
    } else if (v0 >= 192 && offset2 + 1 < len2) {
      codePoint = (buffer[offset2++] & 31) << 6 >>> 0 | (buffer[offset2++] & 63) << 0 >>> 0;
    } else {
      codePoint = buffer[offset2++];
    }
    if (codePoint >= 0 && codePoint <= 55295 || codePoint >= 57344 && codePoint <= 65535) {
      result.push(String.fromCharCode(codePoint));
    } else if (codePoint >= 65536 && codePoint <= 1114111) {
      const uPrime = codePoint - 65536;
      const w1 = 55296 + ((uPrime & 1047552) >>> 10);
      const w2 = 56320 + ((uPrime & 1023) >>> 0);
      result.push(String.fromCharCode(w1));
      result.push(String.fromCharCode(w2));
    } else {
      result.push(String.fromCharCode(65533));
    }
  }
  return result.join("");
}
var CONTAINS_RTL = /(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u08BD\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE33\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDCFF]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD50-\uDFFF]|\uD83B[\uDC00-\uDEBB])/;
function containsRTL(str) {
  return CONTAINS_RTL.test(str);
}
var CONTAINS_EMOJI = /(?:[\u231A\u231B\u23F0\u23F3\u2600-\u27BF\u2B50\u2B55]|\uD83C[\uDDE6-\uDDFF\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F\uDE80-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD00-\uDDFF\uDE70-\uDE73\uDE78-\uDE82\uDE90-\uDE95])/;
function containsEmoji(str) {
  return CONTAINS_EMOJI.test(str);
}
var IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/;
function isBasicASCII(str) {
  return IS_BASIC_ASCII.test(str);
}
var UNUSUAL_LINE_TERMINATORS = /[\u2028\u2029]/;
function containsUnusualLineTerminators(str) {
  return UNUSUAL_LINE_TERMINATORS.test(str);
}
function containsFullWidthCharacter(str) {
  for (let i3 = 0, len2 = str.length; i3 < len2; i3++) {
    if (isFullWidthCharacter(str.charCodeAt(i3))) {
      return true;
    }
  }
  return false;
}
function isFullWidthCharacter(charCode) {
  charCode = +charCode;
  return charCode >= 11904 && charCode <= 55215 || charCode >= 63744 && charCode <= 64255 || charCode >= 65281 && charCode <= 65374;
}
function isEmojiImprecise(x2) {
  return x2 >= 127462 && x2 <= 127487 || x2 >= 9728 && x2 <= 10175 || x2 >= 127744 && x2 <= 128591 || x2 >= 128640 && x2 <= 128764 || x2 >= 128992 && x2 <= 129003 || x2 >= 129280 && x2 <= 129535 || x2 >= 129648 && x2 <= 129651 || x2 >= 129656 && x2 <= 129666 || x2 >= 129680 && x2 <= 129685;
}
var UTF8_BOM_CHARACTER = String.fromCharCode(65279);
function startsWithUTF8BOM(str) {
  return !!(str && str.length > 0 && str.charCodeAt(0) === 65279);
}
function singleLetterHash(n3) {
  const LETTERS_CNT = 90 - 65 + 1;
  n3 = n3 % (2 * LETTERS_CNT);
  if (n3 < LETTERS_CNT) {
    return String.fromCharCode(97 + n3);
  }
  return String.fromCharCode(65 + n3 - LETTERS_CNT);
}
function getGraphemeBreakType(codePoint) {
  const graphemeBreakTree = GraphemeBreakTree.getInstance();
  return graphemeBreakTree.getGraphemeBreakType(codePoint);
}
function breakBetweenGraphemeBreakType(breakTypeA, breakTypeB) {
  if (breakTypeA === 0) {
    return breakTypeB !== 5 && breakTypeB !== 7;
  }
  if (breakTypeA === 2) {
    if (breakTypeB === 3) {
      return false;
    }
  }
  if (breakTypeA === 4 || breakTypeA === 2 || breakTypeA === 3) {
    return true;
  }
  if (breakTypeB === 4 || breakTypeB === 2 || breakTypeB === 3) {
    return true;
  }
  if (breakTypeA === 8) {
    if (breakTypeB === 8 || breakTypeB === 9 || breakTypeB === 11 || breakTypeB === 12) {
      return false;
    }
  }
  if (breakTypeA === 11 || breakTypeA === 9) {
    if (breakTypeB === 9 || breakTypeB === 10) {
      return false;
    }
  }
  if (breakTypeA === 12 || breakTypeA === 10) {
    if (breakTypeB === 10) {
      return false;
    }
  }
  if (breakTypeB === 5 || breakTypeB === 13) {
    return false;
  }
  if (breakTypeB === 7) {
    return false;
  }
  if (breakTypeA === 1) {
    return false;
  }
  if (breakTypeA === 13 && breakTypeB === 14) {
    return false;
  }
  if (breakTypeA === 6 && breakTypeB === 6) {
    return false;
  }
  return true;
}
var GraphemeBreakTree = class {
  constructor() {
    this._data = getGraphemeBreakRawData();
  }
  static getInstance() {
    if (!GraphemeBreakTree._INSTANCE) {
      GraphemeBreakTree._INSTANCE = new GraphemeBreakTree();
    }
    return GraphemeBreakTree._INSTANCE;
  }
  getGraphemeBreakType(codePoint) {
    if (codePoint < 32) {
      if (codePoint === 10) {
        return 3;
      }
      if (codePoint === 13) {
        return 2;
      }
      return 4;
    }
    if (codePoint < 127) {
      return 0;
    }
    const data2 = this._data;
    const nodeCount = data2.length / 3;
    let nodeIndex = 1;
    while (nodeIndex <= nodeCount) {
      if (codePoint < data2[3 * nodeIndex]) {
        nodeIndex = 2 * nodeIndex;
      } else if (codePoint > data2[3 * nodeIndex + 1]) {
        nodeIndex = 2 * nodeIndex + 1;
      } else {
        return data2[3 * nodeIndex + 2];
      }
    }
    return 0;
  }
};
GraphemeBreakTree._INSTANCE = null;
function getGraphemeBreakRawData() {
  return JSON.parse("[0,0,0,51592,51592,11,44424,44424,11,72251,72254,5,7150,7150,7,48008,48008,11,55176,55176,11,128420,128420,14,3276,3277,5,9979,9980,14,46216,46216,11,49800,49800,11,53384,53384,11,70726,70726,5,122915,122916,5,129320,129327,14,2558,2558,5,5906,5908,5,9762,9763,14,43360,43388,8,45320,45320,11,47112,47112,11,48904,48904,11,50696,50696,11,52488,52488,11,54280,54280,11,70082,70083,1,71350,71350,7,73111,73111,5,127892,127893,14,128726,128727,14,129473,129474,14,2027,2035,5,2901,2902,5,3784,3789,5,6754,6754,5,8418,8420,5,9877,9877,14,11088,11088,14,44008,44008,5,44872,44872,11,45768,45768,11,46664,46664,11,47560,47560,11,48456,48456,11,49352,49352,11,50248,50248,11,51144,51144,11,52040,52040,11,52936,52936,11,53832,53832,11,54728,54728,11,69811,69814,5,70459,70460,5,71096,71099,7,71998,71998,5,72874,72880,5,119149,119149,7,127374,127374,14,128335,128335,14,128482,128482,14,128765,128767,14,129399,129400,14,129680,129685,14,1476,1477,5,2377,2380,7,2759,2760,5,3137,3140,7,3458,3459,7,4153,4154,5,6432,6434,5,6978,6978,5,7675,7679,5,9723,9726,14,9823,9823,14,9919,9923,14,10035,10036,14,42736,42737,5,43596,43596,5,44200,44200,11,44648,44648,11,45096,45096,11,45544,45544,11,45992,45992,11,46440,46440,11,46888,46888,11,47336,47336,11,47784,47784,11,48232,48232,11,48680,48680,11,49128,49128,11,49576,49576,11,50024,50024,11,50472,50472,11,50920,50920,11,51368,51368,11,51816,51816,11,52264,52264,11,52712,52712,11,53160,53160,11,53608,53608,11,54056,54056,11,54504,54504,11,54952,54952,11,68108,68111,5,69933,69940,5,70197,70197,7,70498,70499,7,70845,70845,5,71229,71229,5,71727,71735,5,72154,72155,5,72344,72345,5,73023,73029,5,94095,94098,5,121403,121452,5,126981,127182,14,127538,127546,14,127990,127990,14,128391,128391,14,128445,128449,14,128500,128505,14,128752,128752,14,129160,129167,14,129356,129356,14,129432,129442,14,129648,129651,14,129751,131069,14,173,173,4,1757,1757,1,2274,2274,1,2494,2494,5,2641,2641,5,2876,2876,5,3014,3016,7,3262,3262,7,3393,3396,5,3570,3571,7,3968,3972,5,4228,4228,7,6086,6086,5,6679,6680,5,6912,6915,5,7080,7081,5,7380,7392,5,8252,8252,14,9096,9096,14,9748,9749,14,9784,9786,14,9833,9850,14,9890,9894,14,9938,9938,14,9999,9999,14,10085,10087,14,12349,12349,14,43136,43137,7,43454,43456,7,43755,43755,7,44088,44088,11,44312,44312,11,44536,44536,11,44760,44760,11,44984,44984,11,45208,45208,11,45432,45432,11,45656,45656,11,45880,45880,11,46104,46104,11,46328,46328,11,46552,46552,11,46776,46776,11,47000,47000,11,47224,47224,11,47448,47448,11,47672,47672,11,47896,47896,11,48120,48120,11,48344,48344,11,48568,48568,11,48792,48792,11,49016,49016,11,49240,49240,11,49464,49464,11,49688,49688,11,49912,49912,11,50136,50136,11,50360,50360,11,50584,50584,11,50808,50808,11,51032,51032,11,51256,51256,11,51480,51480,11,51704,51704,11,51928,51928,11,52152,52152,11,52376,52376,11,52600,52600,11,52824,52824,11,53048,53048,11,53272,53272,11,53496,53496,11,53720,53720,11,53944,53944,11,54168,54168,11,54392,54392,11,54616,54616,11,54840,54840,11,55064,55064,11,65438,65439,5,69633,69633,5,69837,69837,1,70018,70018,7,70188,70190,7,70368,70370,7,70465,70468,7,70712,70719,5,70835,70840,5,70850,70851,5,71132,71133,5,71340,71340,7,71458,71461,5,71985,71989,7,72002,72002,7,72193,72202,5,72281,72283,5,72766,72766,7,72885,72886,5,73104,73105,5,92912,92916,5,113824,113827,4,119173,119179,5,121505,121519,5,125136,125142,5,127279,127279,14,127489,127490,14,127570,127743,14,127900,127901,14,128254,128254,14,128369,128370,14,128400,128400,14,128425,128432,14,128468,128475,14,128489,128494,14,128715,128720,14,128745,128745,14,128759,128760,14,129004,129023,14,129296,129304,14,129340,129342,14,129388,129392,14,129404,129407,14,129454,129455,14,129485,129487,14,129659,129663,14,129719,129727,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2363,2363,7,2402,2403,5,2507,2508,7,2622,2624,7,2691,2691,7,2786,2787,5,2881,2884,5,3006,3006,5,3072,3072,5,3170,3171,5,3267,3268,7,3330,3331,7,3406,3406,1,3538,3540,5,3655,3662,5,3897,3897,5,4038,4038,5,4184,4185,5,4352,4447,8,6068,6069,5,6155,6157,5,6448,6449,7,6742,6742,5,6783,6783,5,6966,6970,5,7042,7042,7,7143,7143,7,7212,7219,5,7412,7412,5,8206,8207,4,8294,8303,4,8596,8601,14,9410,9410,14,9742,9742,14,9757,9757,14,9770,9770,14,9794,9794,14,9828,9828,14,9855,9855,14,9882,9882,14,9900,9903,14,9929,9933,14,9963,9967,14,9987,9988,14,10006,10006,14,10062,10062,14,10175,10175,14,11744,11775,5,42607,42607,5,43043,43044,7,43263,43263,5,43444,43445,7,43569,43570,5,43698,43700,5,43766,43766,5,44032,44032,11,44144,44144,11,44256,44256,11,44368,44368,11,44480,44480,11,44592,44592,11,44704,44704,11,44816,44816,11,44928,44928,11,45040,45040,11,45152,45152,11,45264,45264,11,45376,45376,11,45488,45488,11,45600,45600,11,45712,45712,11,45824,45824,11,45936,45936,11,46048,46048,11,46160,46160,11,46272,46272,11,46384,46384,11,46496,46496,11,46608,46608,11,46720,46720,11,46832,46832,11,46944,46944,11,47056,47056,11,47168,47168,11,47280,47280,11,47392,47392,11,47504,47504,11,47616,47616,11,47728,47728,11,47840,47840,11,47952,47952,11,48064,48064,11,48176,48176,11,48288,48288,11,48400,48400,11,48512,48512,11,48624,48624,11,48736,48736,11,48848,48848,11,48960,48960,11,49072,49072,11,49184,49184,11,49296,49296,11,49408,49408,11,49520,49520,11,49632,49632,11,49744,49744,11,49856,49856,11,49968,49968,11,50080,50080,11,50192,50192,11,50304,50304,11,50416,50416,11,50528,50528,11,50640,50640,11,50752,50752,11,50864,50864,11,50976,50976,11,51088,51088,11,51200,51200,11,51312,51312,11,51424,51424,11,51536,51536,11,51648,51648,11,51760,51760,11,51872,51872,11,51984,51984,11,52096,52096,11,52208,52208,11,52320,52320,11,52432,52432,11,52544,52544,11,52656,52656,11,52768,52768,11,52880,52880,11,52992,52992,11,53104,53104,11,53216,53216,11,53328,53328,11,53440,53440,11,53552,53552,11,53664,53664,11,53776,53776,11,53888,53888,11,54000,54000,11,54112,54112,11,54224,54224,11,54336,54336,11,54448,54448,11,54560,54560,11,54672,54672,11,54784,54784,11,54896,54896,11,55008,55008,11,55120,55120,11,64286,64286,5,66272,66272,5,68900,68903,5,69762,69762,7,69817,69818,5,69927,69931,5,70003,70003,5,70070,70078,5,70094,70094,7,70194,70195,7,70206,70206,5,70400,70401,5,70463,70463,7,70475,70477,7,70512,70516,5,70722,70724,5,70832,70832,5,70842,70842,5,70847,70848,5,71088,71089,7,71102,71102,7,71219,71226,5,71231,71232,5,71342,71343,7,71453,71455,5,71463,71467,5,71737,71738,5,71995,71996,5,72000,72000,7,72145,72147,7,72160,72160,5,72249,72249,7,72273,72278,5,72330,72342,5,72752,72758,5,72850,72871,5,72882,72883,5,73018,73018,5,73031,73031,5,73109,73109,5,73461,73462,7,94031,94031,5,94192,94193,7,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,126976,126979,14,127184,127231,14,127344,127345,14,127405,127461,14,127514,127514,14,127561,127567,14,127778,127779,14,127896,127896,14,127985,127986,14,127995,127999,5,128326,128328,14,128360,128366,14,128378,128378,14,128394,128397,14,128405,128406,14,128422,128423,14,128435,128443,14,128453,128464,14,128479,128480,14,128484,128487,14,128496,128498,14,128640,128709,14,128723,128724,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129096,129103,14,129292,129292,14,129311,129311,14,129329,129330,14,129344,129349,14,129360,129374,14,129394,129394,14,129402,129402,14,129413,129425,14,129445,129450,14,129466,129471,14,129483,129483,14,129511,129535,14,129653,129655,14,129667,129670,14,129705,129711,14,129731,129743,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2307,2307,7,2366,2368,7,2382,2383,7,2434,2435,7,2497,2500,5,2519,2519,5,2563,2563,7,2631,2632,5,2677,2677,5,2750,2752,7,2763,2764,7,2817,2817,5,2879,2879,5,2891,2892,7,2914,2915,5,3008,3008,5,3021,3021,5,3076,3076,5,3146,3149,5,3202,3203,7,3264,3265,7,3271,3272,7,3298,3299,5,3390,3390,5,3402,3404,7,3426,3427,5,3535,3535,5,3544,3550,7,3635,3635,7,3763,3763,7,3893,3893,5,3953,3966,5,3981,3991,5,4145,4145,7,4157,4158,5,4209,4212,5,4237,4237,5,4520,4607,10,5970,5971,5,6071,6077,5,6089,6099,5,6277,6278,5,6439,6440,5,6451,6456,7,6683,6683,5,6744,6750,5,6765,6770,7,6846,6846,5,6964,6964,5,6972,6972,5,7019,7027,5,7074,7077,5,7083,7085,5,7146,7148,7,7154,7155,7,7222,7223,5,7394,7400,5,7416,7417,5,8204,8204,5,8233,8233,4,8288,8292,4,8413,8416,5,8482,8482,14,8986,8987,14,9193,9203,14,9654,9654,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9775,14,9792,9792,14,9800,9811,14,9825,9826,14,9831,9831,14,9852,9853,14,9872,9873,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9936,9936,14,9941,9960,14,9974,9974,14,9982,9985,14,9992,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10145,10145,14,11013,11015,14,11503,11505,5,12334,12335,5,12951,12951,14,42612,42621,5,43014,43014,5,43047,43047,7,43204,43205,5,43335,43345,5,43395,43395,7,43450,43451,7,43561,43566,5,43573,43574,5,43644,43644,5,43710,43711,5,43758,43759,7,44005,44005,5,44012,44012,7,44060,44060,11,44116,44116,11,44172,44172,11,44228,44228,11,44284,44284,11,44340,44340,11,44396,44396,11,44452,44452,11,44508,44508,11,44564,44564,11,44620,44620,11,44676,44676,11,44732,44732,11,44788,44788,11,44844,44844,11,44900,44900,11,44956,44956,11,45012,45012,11,45068,45068,11,45124,45124,11,45180,45180,11,45236,45236,11,45292,45292,11,45348,45348,11,45404,45404,11,45460,45460,11,45516,45516,11,45572,45572,11,45628,45628,11,45684,45684,11,45740,45740,11,45796,45796,11,45852,45852,11,45908,45908,11,45964,45964,11,46020,46020,11,46076,46076,11,46132,46132,11,46188,46188,11,46244,46244,11,46300,46300,11,46356,46356,11,46412,46412,11,46468,46468,11,46524,46524,11,46580,46580,11,46636,46636,11,46692,46692,11,46748,46748,11,46804,46804,11,46860,46860,11,46916,46916,11,46972,46972,11,47028,47028,11,47084,47084,11,47140,47140,11,47196,47196,11,47252,47252,11,47308,47308,11,47364,47364,11,47420,47420,11,47476,47476,11,47532,47532,11,47588,47588,11,47644,47644,11,47700,47700,11,47756,47756,11,47812,47812,11,47868,47868,11,47924,47924,11,47980,47980,11,48036,48036,11,48092,48092,11,48148,48148,11,48204,48204,11,48260,48260,11,48316,48316,11,48372,48372,11,48428,48428,11,48484,48484,11,48540,48540,11,48596,48596,11,48652,48652,11,48708,48708,11,48764,48764,11,48820,48820,11,48876,48876,11,48932,48932,11,48988,48988,11,49044,49044,11,49100,49100,11,49156,49156,11,49212,49212,11,49268,49268,11,49324,49324,11,49380,49380,11,49436,49436,11,49492,49492,11,49548,49548,11,49604,49604,11,49660,49660,11,49716,49716,11,49772,49772,11,49828,49828,11,49884,49884,11,49940,49940,11,49996,49996,11,50052,50052,11,50108,50108,11,50164,50164,11,50220,50220,11,50276,50276,11,50332,50332,11,50388,50388,11,50444,50444,11,50500,50500,11,50556,50556,11,50612,50612,11,50668,50668,11,50724,50724,11,50780,50780,11,50836,50836,11,50892,50892,11,50948,50948,11,51004,51004,11,51060,51060,11,51116,51116,11,51172,51172,11,51228,51228,11,51284,51284,11,51340,51340,11,51396,51396,11,51452,51452,11,51508,51508,11,51564,51564,11,51620,51620,11,51676,51676,11,51732,51732,11,51788,51788,11,51844,51844,11,51900,51900,11,51956,51956,11,52012,52012,11,52068,52068,11,52124,52124,11,52180,52180,11,52236,52236,11,52292,52292,11,52348,52348,11,52404,52404,11,52460,52460,11,52516,52516,11,52572,52572,11,52628,52628,11,52684,52684,11,52740,52740,11,52796,52796,11,52852,52852,11,52908,52908,11,52964,52964,11,53020,53020,11,53076,53076,11,53132,53132,11,53188,53188,11,53244,53244,11,53300,53300,11,53356,53356,11,53412,53412,11,53468,53468,11,53524,53524,11,53580,53580,11,53636,53636,11,53692,53692,11,53748,53748,11,53804,53804,11,53860,53860,11,53916,53916,11,53972,53972,11,54028,54028,11,54084,54084,11,54140,54140,11,54196,54196,11,54252,54252,11,54308,54308,11,54364,54364,11,54420,54420,11,54476,54476,11,54532,54532,11,54588,54588,11,54644,54644,11,54700,54700,11,54756,54756,11,54812,54812,11,54868,54868,11,54924,54924,11,54980,54980,11,55036,55036,11,55092,55092,11,55148,55148,11,55216,55238,9,65056,65071,5,65529,65531,4,68097,68099,5,68159,68159,5,69446,69456,5,69688,69702,5,69808,69810,7,69815,69816,7,69821,69821,1,69888,69890,5,69932,69932,7,69957,69958,7,70016,70017,5,70067,70069,7,70079,70080,7,70089,70092,5,70095,70095,5,70191,70193,5,70196,70196,5,70198,70199,5,70367,70367,5,70371,70378,5,70402,70403,7,70462,70462,5,70464,70464,5,70471,70472,7,70487,70487,5,70502,70508,5,70709,70711,7,70720,70721,7,70725,70725,7,70750,70750,5,70833,70834,7,70841,70841,7,70843,70844,7,70846,70846,7,70849,70849,7,71087,71087,5,71090,71093,5,71100,71101,5,71103,71104,5,71216,71218,7,71227,71228,7,71230,71230,7,71339,71339,5,71341,71341,5,71344,71349,5,71351,71351,5,71456,71457,7,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123628,123631,5,125252,125258,5,126980,126980,14,127183,127183,14,127245,127247,14,127340,127343,14,127358,127359,14,127377,127386,14,127462,127487,6,127491,127503,14,127535,127535,14,127548,127551,14,127568,127569,14,127744,127777,14,127780,127891,14,127894,127895,14,127897,127899,14,127902,127984,14,127987,127989,14,127991,127994,14,128000,128253,14,128255,128317,14,128329,128334,14,128336,128359,14,128367,128368,14,128371,128377,14,128379,128390,14,128392,128393,14,128398,128399,14,128401,128404,14,128407,128419,14,128421,128421,14,128424,128424,14,128433,128434,14,128444,128444,14,128450,128452,14,128465,128467,14,128476,128478,14,128481,128481,14,128483,128483,14,128488,128488,14,128495,128495,14,128499,128499,14,128506,128591,14,128710,128714,14,128721,128722,14,128725,128725,14,128728,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129664,129666,14,129671,129679,14,129686,129704,14,129712,129718,14,129728,129730,14,129744,129750,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2259,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3134,3136,5,3142,3144,5,3157,3158,5,3201,3201,5,3260,3260,5,3263,3263,5,3266,3266,5,3270,3270,5,3274,3275,7,3285,3286,5,3328,3329,5,3387,3388,5,3391,3392,7,3398,3400,7,3405,3405,5,3415,3415,5,3457,3457,5,3530,3530,5,3536,3537,7,3542,3542,5,3551,3551,5,3633,3633,5,3636,3642,5,3761,3761,5,3764,3772,5,3864,3865,5,3895,3895,5,3902,3903,7,3967,3967,7,3974,3975,5,3993,4028,5,4141,4144,5,4146,4151,5,4155,4156,7,4182,4183,7,4190,4192,5,4226,4226,5,4229,4230,5,4253,4253,5,4448,4519,9,4957,4959,5,5938,5940,5,6002,6003,5,6070,6070,7,6078,6085,7,6087,6088,7,6109,6109,5,6158,6158,4,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6848,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7673,5,8203,8203,4,8205,8205,13,8232,8232,4,8234,8238,4,8265,8265,14,8293,8293,4,8400,8412,5,8417,8417,5,8421,8432,5,8505,8505,14,8617,8618,14,9000,9000,14,9167,9167,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9776,9783,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9935,14,9937,9937,14,9939,9940,14,9961,9962,14,9968,9973,14,9975,9978,14,9981,9981,14,9986,9986,14,9989,9989,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10084,14,10133,10135,14,10160,10160,14,10548,10549,14,11035,11036,14,11093,11093,14,11647,11647,5,12330,12333,5,12336,12336,14,12441,12442,5,12953,12953,14,42608,42610,5,42654,42655,5,43010,43010,5,43019,43019,5,43045,43046,5,43052,43052,5,43188,43203,7,43232,43249,5,43302,43309,5,43346,43347,7,43392,43394,5,43443,43443,5,43446,43449,5,43452,43453,5,43493,43493,5,43567,43568,7,43571,43572,7,43587,43587,5,43597,43597,7,43696,43696,5,43703,43704,5,43713,43713,5,43756,43757,5,43765,43765,7,44003,44004,7,44006,44007,7,44009,44010,7,44013,44013,5,44033,44059,12,44061,44087,12,44089,44115,12,44117,44143,12,44145,44171,12,44173,44199,12,44201,44227,12,44229,44255,12,44257,44283,12,44285,44311,12,44313,44339,12,44341,44367,12,44369,44395,12,44397,44423,12,44425,44451,12,44453,44479,12,44481,44507,12,44509,44535,12,44537,44563,12,44565,44591,12,44593,44619,12,44621,44647,12,44649,44675,12,44677,44703,12,44705,44731,12,44733,44759,12,44761,44787,12,44789,44815,12,44817,44843,12,44845,44871,12,44873,44899,12,44901,44927,12,44929,44955,12,44957,44983,12,44985,45011,12,45013,45039,12,45041,45067,12,45069,45095,12,45097,45123,12,45125,45151,12,45153,45179,12,45181,45207,12,45209,45235,12,45237,45263,12,45265,45291,12,45293,45319,12,45321,45347,12,45349,45375,12,45377,45403,12,45405,45431,12,45433,45459,12,45461,45487,12,45489,45515,12,45517,45543,12,45545,45571,12,45573,45599,12,45601,45627,12,45629,45655,12,45657,45683,12,45685,45711,12,45713,45739,12,45741,45767,12,45769,45795,12,45797,45823,12,45825,45851,12,45853,45879,12,45881,45907,12,45909,45935,12,45937,45963,12,45965,45991,12,45993,46019,12,46021,46047,12,46049,46075,12,46077,46103,12,46105,46131,12,46133,46159,12,46161,46187,12,46189,46215,12,46217,46243,12,46245,46271,12,46273,46299,12,46301,46327,12,46329,46355,12,46357,46383,12,46385,46411,12,46413,46439,12,46441,46467,12,46469,46495,12,46497,46523,12,46525,46551,12,46553,46579,12,46581,46607,12,46609,46635,12,46637,46663,12,46665,46691,12,46693,46719,12,46721,46747,12,46749,46775,12,46777,46803,12,46805,46831,12,46833,46859,12,46861,46887,12,46889,46915,12,46917,46943,12,46945,46971,12,46973,46999,12,47001,47027,12,47029,47055,12,47057,47083,12,47085,47111,12,47113,47139,12,47141,47167,12,47169,47195,12,47197,47223,12,47225,47251,12,47253,47279,12,47281,47307,12,47309,47335,12,47337,47363,12,47365,47391,12,47393,47419,12,47421,47447,12,47449,47475,12,47477,47503,12,47505,47531,12,47533,47559,12,47561,47587,12,47589,47615,12,47617,47643,12,47645,47671,12,47673,47699,12,47701,47727,12,47729,47755,12,47757,47783,12,47785,47811,12,47813,47839,12,47841,47867,12,47869,47895,12,47897,47923,12,47925,47951,12,47953,47979,12,47981,48007,12,48009,48035,12,48037,48063,12,48065,48091,12,48093,48119,12,48121,48147,12,48149,48175,12,48177,48203,12,48205,48231,12,48233,48259,12,48261,48287,12,48289,48315,12,48317,48343,12,48345,48371,12,48373,48399,12,48401,48427,12,48429,48455,12,48457,48483,12,48485,48511,12,48513,48539,12,48541,48567,12,48569,48595,12,48597,48623,12,48625,48651,12,48653,48679,12,48681,48707,12,48709,48735,12,48737,48763,12,48765,48791,12,48793,48819,12,48821,48847,12,48849,48875,12,48877,48903,12,48905,48931,12,48933,48959,12,48961,48987,12,48989,49015,12,49017,49043,12,49045,49071,12,49073,49099,12,49101,49127,12,49129,49155,12,49157,49183,12,49185,49211,12,49213,49239,12,49241,49267,12,49269,49295,12,49297,49323,12,49325,49351,12,49353,49379,12,49381,49407,12,49409,49435,12,49437,49463,12,49465,49491,12,49493,49519,12,49521,49547,12,49549,49575,12,49577,49603,12,49605,49631,12,49633,49659,12,49661,49687,12,49689,49715,12,49717,49743,12,49745,49771,12,49773,49799,12,49801,49827,12,49829,49855,12,49857,49883,12,49885,49911,12,49913,49939,12,49941,49967,12,49969,49995,12,49997,50023,12,50025,50051,12,50053,50079,12,50081,50107,12,50109,50135,12,50137,50163,12,50165,50191,12,50193,50219,12,50221,50247,12,50249,50275,12,50277,50303,12,50305,50331,12,50333,50359,12,50361,50387,12,50389,50415,12,50417,50443,12,50445,50471,12,50473,50499,12,50501,50527,12,50529,50555,12,50557,50583,12,50585,50611,12,50613,50639,12,50641,50667,12,50669,50695,12,50697,50723,12,50725,50751,12,50753,50779,12,50781,50807,12,50809,50835,12,50837,50863,12,50865,50891,12,50893,50919,12,50921,50947,12,50949,50975,12,50977,51003,12,51005,51031,12,51033,51059,12,51061,51087,12,51089,51115,12,51117,51143,12,51145,51171,12,51173,51199,12,51201,51227,12,51229,51255,12,51257,51283,12,51285,51311,12,51313,51339,12,51341,51367,12,51369,51395,12,51397,51423,12,51425,51451,12,51453,51479,12,51481,51507,12,51509,51535,12,51537,51563,12,51565,51591,12,51593,51619,12,51621,51647,12,51649,51675,12,51677,51703,12,51705,51731,12,51733,51759,12,51761,51787,12,51789,51815,12,51817,51843,12,51845,51871,12,51873,51899,12,51901,51927,12,51929,51955,12,51957,51983,12,51985,52011,12,52013,52039,12,52041,52067,12,52069,52095,12,52097,52123,12,52125,52151,12,52153,52179,12,52181,52207,12,52209,52235,12,52237,52263,12,52265,52291,12,52293,52319,12,52321,52347,12,52349,52375,12,52377,52403,12,52405,52431,12,52433,52459,12,52461,52487,12,52489,52515,12,52517,52543,12,52545,52571,12,52573,52599,12,52601,52627,12,52629,52655,12,52657,52683,12,52685,52711,12,52713,52739,12,52741,52767,12,52769,52795,12,52797,52823,12,52825,52851,12,52853,52879,12,52881,52907,12,52909,52935,12,52937,52963,12,52965,52991,12,52993,53019,12,53021,53047,12,53049,53075,12,53077,53103,12,53105,53131,12,53133,53159,12,53161,53187,12,53189,53215,12,53217,53243,12,53245,53271,12,53273,53299,12,53301,53327,12,53329,53355,12,53357,53383,12,53385,53411,12,53413,53439,12,53441,53467,12,53469,53495,12,53497,53523,12,53525,53551,12,53553,53579,12,53581,53607,12,53609,53635,12,53637,53663,12,53665,53691,12,53693,53719,12,53721,53747,12,53749,53775,12,53777,53803,12,53805,53831,12,53833,53859,12,53861,53887,12,53889,53915,12,53917,53943,12,53945,53971,12,53973,53999,12,54001,54027,12,54029,54055,12,54057,54083,12,54085,54111,12,54113,54139,12,54141,54167,12,54169,54195,12,54197,54223,12,54225,54251,12,54253,54279,12,54281,54307,12,54309,54335,12,54337,54363,12,54365,54391,12,54393,54419,12,54421,54447,12,54449,54475,12,54477,54503,12,54505,54531,12,54533,54559,12,54561,54587,12,54589,54615,12,54617,54643,12,54645,54671,12,54673,54699,12,54701,54727,12,54729,54755,12,54757,54783,12,54785,54811,12,54813,54839,12,54841,54867,12,54869,54895,12,54897,54923,12,54925,54951,12,54953,54979,12,54981,55007,12,55009,55035,12,55037,55063,12,55065,55091,12,55093,55119,12,55121,55147,12,55149,55175,12,55177,55203,12,55243,55291,10,65024,65039,5,65279,65279,4,65520,65528,4,66045,66045,5,66422,66426,5,68101,68102,5,68152,68154,5,68325,68326,5,69291,69292,5,69632,69632,7,69634,69634,7,69759,69761,5]");
}
var hasBuffer = typeof Buffer !== "undefined";
var hasTextDecoder = typeof TextDecoder !== "undefined";
var textDecoder;
var VSBuffer = class {
  constructor(buffer) {
    this.buffer = buffer;
    this.byteLength = this.buffer.byteLength;
  }
  toString() {
    if (hasBuffer) {
      return this.buffer.toString();
    } else if (hasTextDecoder) {
      if (!textDecoder) {
        textDecoder = new TextDecoder();
      }
      return textDecoder.decode(this.buffer);
    } else {
      return decodeUTF8(this.buffer);
    }
  }
};
function readUInt16LE(source2, offset2) {
  return source2[offset2 + 0] << 0 >>> 0 | source2[offset2 + 1] << 8 >>> 0;
}
function writeUInt16LE(destination, value, offset2) {
  destination[offset2 + 0] = value & 255;
  value = value >>> 8;
  destination[offset2 + 1] = value & 255;
}
function readUInt32BE(source2, offset2) {
  return source2[offset2] * Math.pow(2, 24) + source2[offset2 + 1] * Math.pow(2, 16) + source2[offset2 + 2] * Math.pow(2, 8) + source2[offset2 + 3];
}
function writeUInt32BE(destination, value, offset2) {
  destination[offset2 + 3] = value;
  value = value >>> 8;
  destination[offset2 + 2] = value;
  value = value >>> 8;
  destination[offset2 + 1] = value;
  value = value >>> 8;
  destination[offset2] = value;
}
function readUInt8(source2, offset2) {
  return source2[offset2];
}
function writeUInt8(destination, value, offset2) {
  destination[offset2] = value;
}
function parse2(text) {
  let data2 = JSON.parse(text);
  data2 = revive(data2);
  return data2;
}
function revive(obj, depth = 0) {
  if (!obj || depth > 200) {
    return obj;
  }
  if (typeof obj === "object") {
    switch (obj.$mid) {
      case 1:
        return URI.revive(obj);
      case 2:
        return new RegExp(obj.source, obj.flags);
    }
    if (obj instanceof VSBuffer || obj instanceof Uint8Array) {
      return obj;
    }
    if (Array.isArray(obj)) {
      for (let i3 = 0; i3 < obj.length; ++i3) {
        obj[i3] = revive(obj[i3], depth + 1);
      }
    } else {
      for (const key in obj) {
        if (Object.hasOwnProperty.call(obj, key)) {
          obj[key] = revive(obj[key], depth + 1);
        }
      }
    }
  }
  return obj;
}
function toSlashes(osPath) {
  return osPath.replace(/[\\/]/g, posix.sep);
}
function isEqualOrParent(path, candidate, ignoreCase, separator = sep) {
  if (path === candidate) {
    return true;
  }
  if (!path || !candidate) {
    return false;
  }
  if (candidate.length > path.length) {
    return false;
  }
  if (ignoreCase) {
    const beginsWith = startsWithIgnoreCase(path, candidate);
    if (!beginsWith) {
      return false;
    }
    if (candidate.length === path.length) {
      return true;
    }
    let sepOffset = candidate.length;
    if (candidate.charAt(candidate.length - 1) === separator) {
      sepOffset--;
    }
    return path.charAt(sepOffset) === separator;
  }
  if (candidate.charAt(candidate.length - 1) !== separator) {
    candidate += separator;
  }
  return path.indexOf(candidate) === 0;
}
function originalFSPath(uri) {
  return uriToFsPath(uri, true);
}
var ExtUri = class {
  constructor(_ignorePathCasing) {
    this._ignorePathCasing = _ignorePathCasing;
  }
  compare(uri1, uri2, ignoreFragment = false) {
    if (uri1 === uri2) {
      return 0;
    }
    return compare(this.getComparisonKey(uri1, ignoreFragment), this.getComparisonKey(uri2, ignoreFragment));
  }
  isEqual(uri1, uri2, ignoreFragment = false) {
    if (uri1 === uri2) {
      return true;
    }
    if (!uri1 || !uri2) {
      return false;
    }
    return this.getComparisonKey(uri1, ignoreFragment) === this.getComparisonKey(uri2, ignoreFragment);
  }
  getComparisonKey(uri, ignoreFragment = false) {
    return uri.with({
      path: this._ignorePathCasing(uri) ? uri.path.toLowerCase() : void 0,
      fragment: ignoreFragment ? null : void 0
    }).toString();
  }
  joinPath(resource2, ...pathFragment) {
    return URI.joinPath(resource2, ...pathFragment);
  }
  basenameOrAuthority(resource2) {
    return basename$1(resource2) || resource2.authority;
  }
  basename(resource2) {
    return posix.basename(resource2.path);
  }
  dirname(resource2) {
    if (resource2.path.length === 0) {
      return resource2;
    }
    let dirname$12;
    if (resource2.scheme === Schemas.file) {
      dirname$12 = URI.file(dirname(originalFSPath(resource2))).path;
    } else {
      dirname$12 = posix.dirname(resource2.path);
      if (resource2.authority && dirname$12.length && dirname$12.charCodeAt(0) !== 47) {
        console.error(`dirname("${resource2.toString})) resulted in a relative path`);
        dirname$12 = "/";
      }
    }
    return resource2.with({
      path: dirname$12
    });
  }
  normalizePath(resource2) {
    if (!resource2.path.length) {
      return resource2;
    }
    let normalizedPath;
    if (resource2.scheme === Schemas.file) {
      normalizedPath = URI.file(normalize(originalFSPath(resource2))).path;
    } else {
      normalizedPath = posix.normalize(resource2.path);
    }
    return resource2.with({
      path: normalizedPath
    });
  }
  relativePath(from, to) {
    if (from.scheme !== to.scheme || !isEqualAuthority(from.authority, to.authority)) {
      return void 0;
    }
    if (from.scheme === Schemas.file) {
      const relativePath2 = relative(originalFSPath(from), originalFSPath(to));
      return isWindows ? toSlashes(relativePath2) : relativePath2;
    }
    let fromPath = from.path || "/", toPath = to.path || "/";
    if (this._ignorePathCasing(from)) {
      let i3 = 0;
      for (const len2 = Math.min(fromPath.length, toPath.length); i3 < len2; i3++) {
        if (fromPath.charCodeAt(i3) !== toPath.charCodeAt(i3)) {
          if (fromPath.charAt(i3).toLowerCase() !== toPath.charAt(i3).toLowerCase()) {
            break;
          }
        }
      }
      fromPath = toPath.substr(0, i3) + fromPath.substr(i3);
    }
    return posix.relative(fromPath, toPath);
  }
  resolvePath(base, path) {
    if (base.scheme === Schemas.file) {
      const newURI = URI.file(resolve(originalFSPath(base), path));
      return base.with({
        authority: newURI.authority,
        path: newURI.path
      });
    }
    if (path.indexOf("/") === -1) {
      path = toSlashes(path);
      if (/^[a-zA-Z]:(\/|$)/.test(path)) {
        path = "/" + path;
      }
    }
    return base.with({
      path: posix.resolve(base.path, path)
    });
  }
  isEqualAuthority(a1, a2) {
    return a1 === a2 || equalsIgnoreCase(a1, a2);
  }
};
var extUri = new ExtUri(() => false);
var isEqual2 = extUri.isEqual.bind(extUri);
var basenameOrAuthority = extUri.basenameOrAuthority.bind(extUri);
var basename$1 = extUri.basename.bind(extUri);
var dirname$1 = extUri.dirname.bind(extUri);
var joinPath = extUri.joinPath.bind(extUri);
var normalizePath = extUri.normalizePath.bind(extUri);
var relativePath = extUri.relativePath.bind(extUri);
var resolvePath = extUri.resolvePath.bind(extUri);
var isEqualAuthority = extUri.isEqualAuthority.bind(extUri);
var DataUri;
(function(DataUri2) {
  DataUri2.META_DATA_LABEL = "label";
  DataUri2.META_DATA_DESCRIPTION = "description";
  DataUri2.META_DATA_SIZE = "size";
  DataUri2.META_DATA_MIME = "mime";
  function parseMetaData(dataUri) {
    const metadata = new Map();
    const meta = dataUri.path.substring(dataUri.path.indexOf(";") + 1, dataUri.path.lastIndexOf(";"));
    meta.split(";").forEach((property2) => {
      const [key, value] = property2.split(":");
      if (key && value) {
        metadata.set(key, value);
      }
    });
    const mime = dataUri.path.substring(0, dataUri.path.indexOf(";"));
    if (mime) {
      metadata.set(DataUri2.META_DATA_MIME, mime);
    }
    return metadata;
  }
  DataUri2.parseMetaData = parseMetaData;
})(DataUri || (DataUri = {}));
function isString3(str) {
  return typeof str === "string";
}
function isObject3(obj) {
  return typeof obj === "object" && obj !== null && !Array.isArray(obj) && !(obj instanceof RegExp) && !(obj instanceof Date);
}
function isNumber2(obj) {
  return typeof obj === "number" && !isNaN(obj);
}
function isBoolean2(obj) {
  return obj === true || obj === false;
}
function isUndefined3(obj) {
  return typeof obj === "undefined";
}
function isUndefinedOrNull(obj) {
  return isUndefined3(obj) || obj === null;
}
function isFunction3(obj) {
  return typeof obj === "function";
}
function validateConstraints(args, constraints) {
  const len2 = Math.min(args.length, constraints.length);
  for (let i3 = 0; i3 < len2; i3++) {
    validateConstraint(args[i3], constraints[i3]);
  }
}
function validateConstraint(arg, constraint) {
  if (isString3(constraint)) {
    if (typeof arg !== constraint) {
      throw new Error(`argument does not match constraint: typeof ${constraint}`);
    }
  } else if (isFunction3(constraint)) {
    try {
      if (arg instanceof constraint) {
        return;
      }
    } catch (_a) {
    }
    if (!isUndefinedOrNull(arg) && arg.constructor === constraint) {
      return;
    }
    if (constraint.length === 1 && constraint.call(void 0, arg) === true) {
      return;
    }
    throw new Error(`argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true`);
  }
}
function getAllPropertyNames(obj) {
  let res = [];
  let proto = Object.getPrototypeOf(obj);
  while (Object.prototype !== proto) {
    res = res.concat(Object.getOwnPropertyNames(proto));
    proto = Object.getPrototypeOf(proto);
  }
  return res;
}
function getAllMethodNames(obj) {
  const methods = [];
  for (const prop of getAllPropertyNames(obj)) {
    if (typeof obj[prop] === "function") {
      methods.push(prop);
    }
  }
  return methods;
}
function createProxyObject(methodNames, invoke) {
  const createProxyMethod = (method) => {
    return function() {
      const args = Array.prototype.slice.call(arguments, 0);
      return invoke(method, args);
    };
  };
  let result = {};
  for (const methodName of methodNames) {
    result[methodName] = createProxyMethod(methodName);
  }
  return result;
}
function withNullAsUndefined(x2) {
  return x2 === null ? void 0 : x2;
}
var ICommandService = createDecorator("commandService");
var CommandsRegistry = new class {
  constructor() {
    this._commands = new Map();
    this._onDidRegisterCommand = new Emitter();
    this.onDidRegisterCommand = this._onDidRegisterCommand.event;
  }
  registerCommand(idOrCommand, handler) {
    if (!idOrCommand) {
      throw new Error(`invalid command`);
    }
    if (typeof idOrCommand === "string") {
      if (!handler) {
        throw new Error(`invalid command`);
      }
      return this.registerCommand({id: idOrCommand, handler});
    }
    if (idOrCommand.description) {
      const constraints = [];
      for (let arg of idOrCommand.description.args) {
        constraints.push(arg.constraint);
      }
      const actualHandler = idOrCommand.handler;
      idOrCommand.handler = function(accessor, ...args) {
        validateConstraints(args, constraints);
        return actualHandler(accessor, ...args);
      };
    }
    const {id: id3} = idOrCommand;
    let commands = this._commands.get(id3);
    if (!commands) {
      commands = new LinkedList();
      this._commands.set(id3, commands);
    }
    let removeFn = commands.unshift(idOrCommand);
    let ret = toDisposable(() => {
      removeFn();
      const command = this._commands.get(id3);
      if (command === null || command === void 0 ? void 0 : command.isEmpty()) {
        this._commands.delete(id3);
      }
    });
    this._onDidRegisterCommand.fire(id3);
    return ret;
  }
  registerCommandAlias(oldId, newId3) {
    return CommandsRegistry.registerCommand(oldId, (accessor, ...args) => accessor.get(ICommandService).executeCommand(newId3, ...args));
  }
  getCommand(id3) {
    const list3 = this._commands.get(id3);
    if (!list3 || list3.isEmpty()) {
      return void 0;
    }
    return Iterable.first(list3);
  }
  getCommands() {
    const result = new Map();
    for (const key of this._commands.keys()) {
      const command = this.getCommand(key);
      if (command) {
        result.set(key, command);
      }
    }
    return result;
  }
}();
var __awaiter2 = function(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var IOpenerService = createDecorator("openerService");
var NullOpenerService = Object.freeze({
  _serviceBrand: void 0,
  registerOpener() {
    return Disposable.None;
  },
  registerValidator() {
    return Disposable.None;
  },
  registerExternalUriResolver() {
    return Disposable.None;
  },
  setExternalOpener() {
  },
  open() {
    return __awaiter2(this, void 0, void 0, function* () {
      return false;
    });
  },
  resolveExternalUri(uri) {
    return __awaiter2(this, void 0, void 0, function* () {
      return {resolved: uri, dispose() {
      }};
    });
  }
});
function matchesScheme(target, scheme) {
  if (URI.isUri(target)) {
    return equalsIgnoreCase(target.scheme, scheme);
  } else {
    return startsWithIgnoreCase(target, scheme + ":");
  }
}
var EditorOpenContext;
(function(EditorOpenContext2) {
  EditorOpenContext2[EditorOpenContext2["API"] = 0] = "API";
  EditorOpenContext2[EditorOpenContext2["USER"] = 1] = "USER";
})(EditorOpenContext || (EditorOpenContext = {}));
var __decorate = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1 = function(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var CommandOpener = class CommandOpener2 {
  constructor(_commandService) {
    this._commandService = _commandService;
  }
  open(target) {
    return __awaiter$1(this, void 0, void 0, function* () {
      if (!matchesScheme(target, Schemas.command)) {
        return false;
      }
      if (typeof target === "string") {
        target = URI.parse(target);
      }
      let args = [];
      try {
        args = parse2(decodeURIComponent(target.query));
      } catch (_a) {
        try {
          args = parse2(target.query);
        } catch (_b) {
        }
      }
      if (!Array.isArray(args)) {
        args = [args];
      }
      yield this._commandService.executeCommand(target.path, ...args);
      return true;
    });
  }
};
CommandOpener = __decorate([
  __param(0, ICommandService)
], CommandOpener);
var EditorOpener = class EditorOpener2 {
  constructor(_editorService) {
    this._editorService = _editorService;
  }
  open(target, options) {
    return __awaiter$1(this, void 0, void 0, function* () {
      if (typeof target === "string") {
        target = URI.parse(target);
      }
      let selection2 = void 0;
      const match2 = /^L?(\d+)(?:,(\d+))?/.exec(target.fragment);
      if (match2) {
        selection2 = {
          startLineNumber: parseInt(match2[1]),
          startColumn: match2[2] ? parseInt(match2[2]) : 1
        };
        target = target.with({fragment: ""});
      }
      if (target.scheme === Schemas.file) {
        target = normalizePath(target);
      }
      yield this._editorService.openCodeEditor({resource: target, options: {selection: selection2, context: (options === null || options === void 0 ? void 0 : options.fromUserGesture) ? EditorOpenContext.USER : EditorOpenContext.API}}, this._editorService.getFocusedCodeEditor(), options === null || options === void 0 ? void 0 : options.openToSide);
      return true;
    });
  }
};
EditorOpener = __decorate([
  __param(0, ICodeEditorService)
], EditorOpener);
var OpenerService = class OpenerService2 {
  constructor(editorService, commandService) {
    this._openers = new LinkedList();
    this._validators = new LinkedList();
    this._resolvers = new LinkedList();
    this._externalOpener = {
      openExternal: (href) => {
        if (matchesScheme(href, Schemas.http) || matchesScheme(href, Schemas.https)) {
          windowOpenNoOpener(href);
        } else {
          window.location.href = href;
        }
        return Promise.resolve(true);
      }
    };
    this._openers.push({
      open: (target, options) => __awaiter$1(this, void 0, void 0, function* () {
        if ((options === null || options === void 0 ? void 0 : options.openExternal) || matchesScheme(target, Schemas.mailto) || matchesScheme(target, Schemas.http) || matchesScheme(target, Schemas.https)) {
          yield this._doOpenExternal(target, options);
          return true;
        }
        return false;
      })
    });
    this._openers.push(new CommandOpener(commandService));
    this._openers.push(new EditorOpener(editorService));
  }
  open(target, options) {
    return __awaiter$1(this, void 0, void 0, function* () {
      for (const validator2 of this._validators.toArray()) {
        if (!(yield validator2.shouldOpen(target))) {
          return false;
        }
      }
      for (const opener of this._openers.toArray()) {
        const handled = yield opener.open(target, options);
        if (handled) {
          return true;
        }
      }
      return false;
    });
  }
  resolveExternalUri(resource2, options) {
    return __awaiter$1(this, void 0, void 0, function* () {
      for (const resolver of this._resolvers.toArray()) {
        const result = yield resolver.resolveExternalUri(resource2, options);
        if (result) {
          return result;
        }
      }
      return {resolved: resource2, dispose: () => {
      }};
    });
  }
  _doOpenExternal(resource2, options) {
    return __awaiter$1(this, void 0, void 0, function* () {
      const uri = typeof resource2 === "string" ? URI.parse(resource2) : resource2;
      const {resolved} = yield this.resolveExternalUri(uri, options);
      if (typeof resource2 === "string" && uri.toString() === resolved.toString()) {
        return this._externalOpener.openExternal(resource2);
      } else {
        return this._externalOpener.openExternal(encodeURI(resolved.toString(true)));
      }
    });
  }
  dispose() {
    this._validators.clear();
  }
};
OpenerService = __decorate([
  __param(0, ICodeEditorService),
  __param(1, ICommandService)
], OpenerService);
function ok2(value, message) {
  if (!value) {
    throw new Error(message ? `Assertion failed (${message})` : "Assertion Failed");
  }
}
function deepClone(obj) {
  if (!obj || typeof obj !== "object") {
    return obj;
  }
  if (obj instanceof RegExp) {
    return obj;
  }
  const result = Array.isArray(obj) ? [] : {};
  Object.keys(obj).forEach((key) => {
    if (obj[key] && typeof obj[key] === "object") {
      result[key] = deepClone(obj[key]);
    } else {
      result[key] = obj[key];
    }
  });
  return result;
}
function deepFreeze(obj) {
  if (!obj || typeof obj !== "object") {
    return obj;
  }
  const stack2 = [obj];
  while (stack2.length > 0) {
    const obj2 = stack2.shift();
    Object.freeze(obj2);
    for (const key in obj2) {
      if (_hasOwnProperty.call(obj2, key)) {
        const prop = obj2[key];
        if (typeof prop === "object" && !Object.isFrozen(prop)) {
          stack2.push(prop);
        }
      }
    }
  }
  return obj;
}
var _hasOwnProperty = Object.prototype.hasOwnProperty;
function mixin(destination, source2, overwrite = true) {
  if (!isObject3(destination)) {
    return source2;
  }
  if (isObject3(source2)) {
    Object.keys(source2).forEach((key) => {
      if (key in destination) {
        if (overwrite) {
          if (isObject3(destination[key]) && isObject3(source2[key])) {
            mixin(destination[key], source2[key], overwrite);
          } else {
            destination[key] = source2[key];
          }
        }
      } else {
        destination[key] = source2[key];
      }
    });
  }
  return destination;
}
function assign(destination, ...sources) {
  sources.forEach((source2) => Object.keys(source2).forEach((key) => destination[key] = source2[key]));
  return destination;
}
function equals$1(one2, other) {
  if (one2 === other) {
    return true;
  }
  if (one2 === null || one2 === void 0 || other === null || other === void 0) {
    return false;
  }
  if (typeof one2 !== typeof other) {
    return false;
  }
  if (typeof one2 !== "object") {
    return false;
  }
  if (Array.isArray(one2) !== Array.isArray(other)) {
    return false;
  }
  let i3;
  let key;
  if (Array.isArray(one2)) {
    if (one2.length !== other.length) {
      return false;
    }
    for (i3 = 0; i3 < one2.length; i3++) {
      if (!equals$1(one2[i3], other[i3])) {
        return false;
      }
    }
  } else {
    const oneKeys = [];
    for (key in one2) {
      oneKeys.push(key);
    }
    oneKeys.sort();
    const otherKeys = [];
    for (key in other) {
      otherKeys.push(key);
    }
    otherKeys.sort();
    if (!equals$1(oneKeys, otherKeys)) {
      return false;
    }
    for (i3 = 0; i3 < oneKeys.length; i3++) {
      if (!equals$1(one2[oneKeys[i3]], other[oneKeys[i3]])) {
        return false;
      }
    }
  }
  return true;
}
function getOrDefault(obj, fn, defaultValue) {
  const result = fn(obj);
  return typeof result === "undefined" ? defaultValue : result;
}
var defaultOptions2 = {
  followsCaret: true,
  ignoreCharChanges: true,
  alwaysRevealFirst: true
};
var DiffNavigator = class extends Disposable {
  constructor(editor2, options = {}) {
    super();
    this._onDidUpdate = this._register(new Emitter());
    this._editor = editor2;
    this._options = mixin(options, defaultOptions2, false);
    this.disposed = false;
    this.nextIdx = -1;
    this.ranges = [];
    this.ignoreSelectionChange = false;
    this.revealFirst = Boolean(this._options.alwaysRevealFirst);
    this._register(this._editor.onDidDispose(() => this.dispose()));
    this._register(this._editor.onDidUpdateDiff(() => this._onDiffUpdated()));
    if (this._options.followsCaret) {
      this._register(this._editor.getModifiedEditor().onDidChangeCursorPosition((e2) => {
        if (this.ignoreSelectionChange) {
          return;
        }
        this.nextIdx = -1;
      }));
    }
    if (this._options.alwaysRevealFirst) {
      this._register(this._editor.getModifiedEditor().onDidChangeModel((e2) => {
        this.revealFirst = true;
      }));
    }
    this._init();
  }
  _init() {
    let changes = this._editor.getLineChanges();
    if (!changes) {
      return;
    }
  }
  _onDiffUpdated() {
    this._init();
    this._compute(this._editor.getLineChanges());
    if (this.revealFirst) {
      if (this._editor.getLineChanges() !== null) {
        this.revealFirst = false;
        this.nextIdx = -1;
        this.next(1);
      }
    }
  }
  _compute(lineChanges) {
    this.ranges = [];
    if (lineChanges) {
      lineChanges.forEach((lineChange) => {
        if (!this._options.ignoreCharChanges && lineChange.charChanges) {
          lineChange.charChanges.forEach((charChange) => {
            this.ranges.push({
              rhs: true,
              range: new Range(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn)
            });
          });
        } else {
          this.ranges.push({
            rhs: true,
            range: new Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedStartLineNumber, 1)
          });
        }
      });
    }
    this.ranges.sort((left2, right2) => {
      if (left2.range.getStartPosition().isBeforeOrEqual(right2.range.getStartPosition())) {
        return -1;
      } else if (right2.range.getStartPosition().isBeforeOrEqual(left2.range.getStartPosition())) {
        return 1;
      } else {
        return 0;
      }
    });
    this._onDidUpdate.fire(this);
  }
  _initIdx(fwd) {
    let found = false;
    let position2 = this._editor.getPosition();
    if (!position2) {
      this.nextIdx = 0;
      return;
    }
    for (let i3 = 0, len2 = this.ranges.length; i3 < len2 && !found; i3++) {
      let range3 = this.ranges[i3].range;
      if (position2.isBeforeOrEqual(range3.getStartPosition())) {
        this.nextIdx = i3 + (fwd ? 0 : -1);
        found = true;
      }
    }
    if (!found) {
      this.nextIdx = fwd ? 0 : this.ranges.length - 1;
    }
    if (this.nextIdx < 0) {
      this.nextIdx = this.ranges.length - 1;
    }
  }
  _move(fwd, scrollType) {
    ok2(!this.disposed, "Illegal State - diff navigator has been disposed");
    if (!this.canNavigate()) {
      return;
    }
    if (this.nextIdx === -1) {
      this._initIdx(fwd);
    } else if (fwd) {
      this.nextIdx += 1;
      if (this.nextIdx >= this.ranges.length) {
        this.nextIdx = 0;
      }
    } else {
      this.nextIdx -= 1;
      if (this.nextIdx < 0) {
        this.nextIdx = this.ranges.length - 1;
      }
    }
    let info2 = this.ranges[this.nextIdx];
    this.ignoreSelectionChange = true;
    try {
      let pos = info2.range.getStartPosition();
      this._editor.setPosition(pos);
      this._editor.revealPositionInCenter(pos, scrollType);
    } finally {
      this.ignoreSelectionChange = false;
    }
  }
  canNavigate() {
    return this.ranges && this.ranges.length > 0;
  }
  next(scrollType = 0) {
    this._move(true, scrollType);
  }
  previous(scrollType = 0) {
    this._move(false, scrollType);
  }
  dispose() {
    super.dispose();
    this.ranges = [];
    this.disposed = true;
  }
};
var EditorZoom = new class {
  constructor() {
    this._zoomLevel = 0;
    this._onDidChangeZoomLevel = new Emitter();
    this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;
  }
  getZoomLevel() {
    return this._zoomLevel;
  }
  setZoomLevel(zoomLevel) {
    zoomLevel = Math.min(Math.max(-5, zoomLevel), 20);
    if (this._zoomLevel === zoomLevel) {
      return;
    }
    this._zoomLevel = zoomLevel;
    this._onDidChangeZoomLevel.fire(this._zoomLevel);
  }
}();
var GOLDEN_LINE_HEIGHT_RATIO = isMacintosh ? 1.5 : 1.35;
var MINIMUM_LINE_HEIGHT = 8;
var BareFontInfo = class {
  constructor(opts) {
    this.zoomLevel = opts.zoomLevel;
    this.fontFamily = String(opts.fontFamily);
    this.fontWeight = String(opts.fontWeight);
    this.fontSize = opts.fontSize;
    this.fontFeatureSettings = opts.fontFeatureSettings;
    this.lineHeight = opts.lineHeight | 0;
    this.letterSpacing = opts.letterSpacing;
  }
  static createFromValidatedSettings(options, zoomLevel, ignoreEditorZoom) {
    const fontFamily = options.get(35);
    const fontWeight = options.get(39);
    const fontSize = options.get(38);
    const fontFeatureSettings = options.get(37);
    const lineHeight = options.get(51);
    const letterSpacing = options.get(48);
    return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, zoomLevel, ignoreEditorZoom);
  }
  static _create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, zoomLevel, ignoreEditorZoom) {
    if (lineHeight === 0) {
      lineHeight = Math.round(GOLDEN_LINE_HEIGHT_RATIO * fontSize);
    } else if (lineHeight < MINIMUM_LINE_HEIGHT) {
      lineHeight = MINIMUM_LINE_HEIGHT;
    }
    const editorZoomLevelMultiplier = 1 + (ignoreEditorZoom ? 0 : EditorZoom.getZoomLevel() * 0.1);
    fontSize *= editorZoomLevelMultiplier;
    lineHeight *= editorZoomLevelMultiplier;
    return new BareFontInfo({
      zoomLevel,
      fontFamily,
      fontWeight,
      fontSize,
      fontFeatureSettings,
      lineHeight,
      letterSpacing
    });
  }
  getId() {
    return this.zoomLevel + "-" + this.fontFamily + "-" + this.fontWeight + "-" + this.fontSize + "-" + this.fontFeatureSettings + "-" + this.lineHeight + "-" + this.letterSpacing;
  }
  getMassagedFontFamily() {
    if (/[,"']/.test(this.fontFamily)) {
      return this.fontFamily;
    }
    if (/[+ ]/.test(this.fontFamily)) {
      return `"${this.fontFamily}"`;
    }
    return this.fontFamily;
  }
};
var FontInfo = class extends BareFontInfo {
  constructor(opts, isTrusted) {
    super(opts);
    this.isTrusted = isTrusted;
    this.isMonospace = opts.isMonospace;
    this.typicalHalfwidthCharacterWidth = opts.typicalHalfwidthCharacterWidth;
    this.typicalFullwidthCharacterWidth = opts.typicalFullwidthCharacterWidth;
    this.canUseHalfwidthRightwardsArrow = opts.canUseHalfwidthRightwardsArrow;
    this.spaceWidth = opts.spaceWidth;
    this.middotWidth = opts.middotWidth;
    this.wsmiddotWidth = opts.wsmiddotWidth;
    this.maxDigitWidth = opts.maxDigitWidth;
  }
  equals(other) {
    return this.fontFamily === other.fontFamily && this.fontWeight === other.fontWeight && this.fontSize === other.fontSize && this.fontFeatureSettings === other.fontFeatureSettings && this.lineHeight === other.lineHeight && this.letterSpacing === other.letterSpacing && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth && this.typicalFullwidthCharacterWidth === other.typicalFullwidthCharacterWidth && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.maxDigitWidth === other.maxDigitWidth;
  }
};
function isThemeColor(o) {
  return o && typeof o.id === "string";
}
var EditorType = {
  ICodeEditor: "vs.editor.ICodeEditor",
  IDiffEditor: "vs.editor.IDiffEditor"
};
var OverviewRulerLane$1;
(function(OverviewRulerLane2) {
  OverviewRulerLane2[OverviewRulerLane2["Left"] = 1] = "Left";
  OverviewRulerLane2[OverviewRulerLane2["Center"] = 2] = "Center";
  OverviewRulerLane2[OverviewRulerLane2["Right"] = 4] = "Right";
  OverviewRulerLane2[OverviewRulerLane2["Full"] = 7] = "Full";
})(OverviewRulerLane$1 || (OverviewRulerLane$1 = {}));
var MinimapPosition$1;
(function(MinimapPosition2) {
  MinimapPosition2[MinimapPosition2["Inline"] = 1] = "Inline";
  MinimapPosition2[MinimapPosition2["Gutter"] = 2] = "Gutter";
})(MinimapPosition$1 || (MinimapPosition$1 = {}));
var TextModelResolvedOptions = class {
  constructor(src) {
    this.tabSize = Math.max(1, src.tabSize | 0);
    this.indentSize = src.tabSize | 0;
    this.insertSpaces = Boolean(src.insertSpaces);
    this.defaultEOL = src.defaultEOL | 0;
    this.trimAutoWhitespace = Boolean(src.trimAutoWhitespace);
  }
  equals(other) {
    return this.tabSize === other.tabSize && this.indentSize === other.indentSize && this.insertSpaces === other.insertSpaces && this.defaultEOL === other.defaultEOL && this.trimAutoWhitespace === other.trimAutoWhitespace;
  }
  createChangeEvent(newOpts) {
    return {
      tabSize: this.tabSize !== newOpts.tabSize,
      indentSize: this.indentSize !== newOpts.indentSize,
      insertSpaces: this.insertSpaces !== newOpts.insertSpaces,
      trimAutoWhitespace: this.trimAutoWhitespace !== newOpts.trimAutoWhitespace
    };
  }
};
var FindMatch = class {
  constructor(range3, matches2) {
    this.range = range3;
    this.matches = matches2;
  }
};
var ValidAnnotatedEditOperation = class {
  constructor(identifier, range3, text, forceMoveMarkers, isAutoWhitespaceEdit, _isTracked) {
    this.identifier = identifier;
    this.range = range3;
    this.text = text;
    this.forceMoveMarkers = forceMoveMarkers;
    this.isAutoWhitespaceEdit = isAutoWhitespaceEdit;
    this._isTracked = _isTracked;
  }
};
var ApplyEditsResult = class {
  constructor(reverseEdits, changes, trimAutoWhitespaceLineNumbers) {
    this.reverseEdits = reverseEdits;
    this.changes = changes;
    this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers;
  }
};
var ResourceMap = class {
  constructor(mapOrKeyFn, toKey2) {
    this[Symbol.toStringTag] = "ResourceMap";
    if (mapOrKeyFn instanceof ResourceMap) {
      this.map = new Map(mapOrKeyFn.map);
      this.toKey = toKey2 !== null && toKey2 !== void 0 ? toKey2 : ResourceMap.defaultToKey;
    } else {
      this.map = new Map();
      this.toKey = mapOrKeyFn !== null && mapOrKeyFn !== void 0 ? mapOrKeyFn : ResourceMap.defaultToKey;
    }
  }
  set(resource2, value) {
    this.map.set(this.toKey(resource2), value);
    return this;
  }
  get(resource2) {
    return this.map.get(this.toKey(resource2));
  }
  has(resource2) {
    return this.map.has(this.toKey(resource2));
  }
  get size() {
    return this.map.size;
  }
  clear() {
    this.map.clear();
  }
  delete(resource2) {
    return this.map.delete(this.toKey(resource2));
  }
  forEach(clb, thisArg) {
    if (typeof thisArg !== "undefined") {
      clb = clb.bind(thisArg);
    }
    for (let [index3, value] of this.map) {
      clb(value, URI.parse(index3), this);
    }
  }
  values() {
    return this.map.values();
  }
  *keys() {
    for (let key of this.map.keys()) {
      yield URI.parse(key);
    }
  }
  *entries() {
    for (let tuple of this.map.entries()) {
      yield [URI.parse(tuple[0]), tuple[1]];
    }
  }
  *[Symbol.iterator]() {
    for (let item of this.map) {
      yield [URI.parse(item[0]), item[1]];
    }
  }
};
ResourceMap.defaultToKey = (resource2) => resource2.toString();
var LinkedMap = class {
  constructor() {
    this[Symbol.toStringTag] = "LinkedMap";
    this._map = new Map();
    this._head = void 0;
    this._tail = void 0;
    this._size = 0;
    this._state = 0;
  }
  clear() {
    this._map.clear();
    this._head = void 0;
    this._tail = void 0;
    this._size = 0;
    this._state++;
  }
  isEmpty() {
    return !this._head && !this._tail;
  }
  get size() {
    return this._size;
  }
  get first() {
    var _a;
    return (_a = this._head) === null || _a === void 0 ? void 0 : _a.value;
  }
  get last() {
    var _a;
    return (_a = this._tail) === null || _a === void 0 ? void 0 : _a.value;
  }
  has(key) {
    return this._map.has(key);
  }
  get(key, touch = 0) {
    const item = this._map.get(key);
    if (!item) {
      return void 0;
    }
    if (touch !== 0) {
      this.touch(item, touch);
    }
    return item.value;
  }
  set(key, value, touch = 0) {
    let item = this._map.get(key);
    if (item) {
      item.value = value;
      if (touch !== 0) {
        this.touch(item, touch);
      }
    } else {
      item = {key, value, next: void 0, previous: void 0};
      switch (touch) {
        case 0:
          this.addItemLast(item);
          break;
        case 1:
          this.addItemFirst(item);
          break;
        case 2:
          this.addItemLast(item);
          break;
        default:
          this.addItemLast(item);
          break;
      }
      this._map.set(key, item);
      this._size++;
    }
    return this;
  }
  delete(key) {
    return !!this.remove(key);
  }
  remove(key) {
    const item = this._map.get(key);
    if (!item) {
      return void 0;
    }
    this._map.delete(key);
    this.removeItem(item);
    this._size--;
    return item.value;
  }
  shift() {
    if (!this._head && !this._tail) {
      return void 0;
    }
    if (!this._head || !this._tail) {
      throw new Error("Invalid list");
    }
    const item = this._head;
    this._map.delete(item.key);
    this.removeItem(item);
    this._size--;
    return item.value;
  }
  forEach(callbackfn, thisArg) {
    const state = this._state;
    let current = this._head;
    while (current) {
      if (thisArg) {
        callbackfn.bind(thisArg)(current.value, current.key, this);
      } else {
        callbackfn(current.value, current.key, this);
      }
      if (this._state !== state) {
        throw new Error(`LinkedMap got modified during iteration.`);
      }
      current = current.next;
    }
  }
  keys() {
    const map2 = this;
    const state = this._state;
    let current = this._head;
    const iterator = {
      [Symbol.iterator]() {
        return iterator;
      },
      next() {
        if (map2._state !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = {value: current.key, done: false};
          current = current.next;
          return result;
        } else {
          return {value: void 0, done: true};
        }
      }
    };
    return iterator;
  }
  values() {
    const map2 = this;
    const state = this._state;
    let current = this._head;
    const iterator = {
      [Symbol.iterator]() {
        return iterator;
      },
      next() {
        if (map2._state !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = {value: current.value, done: false};
          current = current.next;
          return result;
        } else {
          return {value: void 0, done: true};
        }
      }
    };
    return iterator;
  }
  entries() {
    const map2 = this;
    const state = this._state;
    let current = this._head;
    const iterator = {
      [Symbol.iterator]() {
        return iterator;
      },
      next() {
        if (map2._state !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = {value: [current.key, current.value], done: false};
          current = current.next;
          return result;
        } else {
          return {value: void 0, done: true};
        }
      }
    };
    return iterator;
  }
  [Symbol.iterator]() {
    return this.entries();
  }
  trimOld(newSize2) {
    if (newSize2 >= this.size) {
      return;
    }
    if (newSize2 === 0) {
      this.clear();
      return;
    }
    let current = this._head;
    let currentSize = this.size;
    while (current && currentSize > newSize2) {
      this._map.delete(current.key);
      current = current.next;
      currentSize--;
    }
    this._head = current;
    this._size = currentSize;
    if (current) {
      current.previous = void 0;
    }
    this._state++;
  }
  addItemFirst(item) {
    if (!this._head && !this._tail) {
      this._tail = item;
    } else if (!this._head) {
      throw new Error("Invalid list");
    } else {
      item.next = this._head;
      this._head.previous = item;
    }
    this._head = item;
    this._state++;
  }
  addItemLast(item) {
    if (!this._head && !this._tail) {
      this._head = item;
    } else if (!this._tail) {
      throw new Error("Invalid list");
    } else {
      item.previous = this._tail;
      this._tail.next = item;
    }
    this._tail = item;
    this._state++;
  }
  removeItem(item) {
    if (item === this._head && item === this._tail) {
      this._head = void 0;
      this._tail = void 0;
    } else if (item === this._head) {
      if (!item.next) {
        throw new Error("Invalid list");
      }
      item.next.previous = void 0;
      this._head = item.next;
    } else if (item === this._tail) {
      if (!item.previous) {
        throw new Error("Invalid list");
      }
      item.previous.next = void 0;
      this._tail = item.previous;
    } else {
      const next = item.next;
      const previous = item.previous;
      if (!next || !previous) {
        throw new Error("Invalid list");
      }
      next.previous = previous;
      previous.next = next;
    }
    item.next = void 0;
    item.previous = void 0;
    this._state++;
  }
  touch(item, touch) {
    if (!this._head || !this._tail) {
      throw new Error("Invalid list");
    }
    if (touch !== 1 && touch !== 2) {
      return;
    }
    if (touch === 1) {
      if (item === this._head) {
        return;
      }
      const next = item.next;
      const previous = item.previous;
      if (item === this._tail) {
        previous.next = void 0;
        this._tail = previous;
      } else {
        next.previous = previous;
        previous.next = next;
      }
      item.previous = void 0;
      item.next = this._head;
      this._head.previous = item;
      this._head = item;
      this._state++;
    } else if (touch === 2) {
      if (item === this._tail) {
        return;
      }
      const next = item.next;
      const previous = item.previous;
      if (item === this._head) {
        next.previous = void 0;
        this._head = next;
      } else {
        next.previous = previous;
        previous.next = next;
      }
      item.next = void 0;
      item.previous = this._tail;
      this._tail.next = item;
      this._tail = item;
      this._state++;
    }
  }
  toJSON() {
    const data2 = [];
    this.forEach((value, key) => {
      data2.push([key, value]);
    });
    return data2;
  }
  fromJSON(data2) {
    this.clear();
    for (const [key, value] of data2) {
      this.set(key, value);
    }
  }
};
var LRUCache = class extends LinkedMap {
  constructor(limit, ratio = 1) {
    super();
    this._limit = limit;
    this._ratio = Math.min(Math.max(0, ratio), 1);
  }
  get limit() {
    return this._limit;
  }
  set limit(limit) {
    this._limit = limit;
    this.checkTrim();
  }
  get(key, touch = 2) {
    return super.get(key, touch);
  }
  peek(key) {
    return super.get(key, 0);
  }
  set(key, value) {
    super.set(key, value, 2);
    this.checkTrim();
    return this;
  }
  checkTrim() {
    if (this.size > this._limit) {
      this.trimOld(Math.round(this._limit * this._ratio));
    }
  }
};
var GLOBSTAR = "**";
var GLOB_SPLIT = "/";
var PATH_REGEX = "[/\\\\]";
var NO_PATH_REGEX = "[^/\\\\]";
var ALL_FORWARD_SLASHES = /\//g;
function starsToRegExp(starCount) {
  switch (starCount) {
    case 0:
      return "";
    case 1:
      return `${NO_PATH_REGEX}*?`;
    default:
      return `(?:${PATH_REGEX}|${NO_PATH_REGEX}+${PATH_REGEX}|${PATH_REGEX}${NO_PATH_REGEX}+)*?`;
  }
}
function splitGlobAware(pattern, splitChar) {
  if (!pattern) {
    return [];
  }
  const segments = [];
  let inBraces = false;
  let inBrackets = false;
  let curVal = "";
  for (const char of pattern) {
    switch (char) {
      case splitChar:
        if (!inBraces && !inBrackets) {
          segments.push(curVal);
          curVal = "";
          continue;
        }
        break;
      case "{":
        inBraces = true;
        break;
      case "}":
        inBraces = false;
        break;
      case "[":
        inBrackets = true;
        break;
      case "]":
        inBrackets = false;
        break;
    }
    curVal += char;
  }
  if (curVal) {
    segments.push(curVal);
  }
  return segments;
}
function parseRegExp(pattern) {
  if (!pattern) {
    return "";
  }
  let regEx = "";
  const segments = splitGlobAware(pattern, GLOB_SPLIT);
  if (segments.every((s2) => s2 === GLOBSTAR)) {
    regEx = ".*";
  } else {
    let previousSegmentWasGlobStar = false;
    segments.forEach((segment, index3) => {
      if (segment === GLOBSTAR) {
        if (!previousSegmentWasGlobStar) {
          regEx += starsToRegExp(2);
          previousSegmentWasGlobStar = true;
        }
        return;
      }
      let inBraces = false;
      let braceVal = "";
      let inBrackets = false;
      let bracketVal = "";
      for (const char of segment) {
        if (char !== "}" && inBraces) {
          braceVal += char;
          continue;
        }
        if (inBrackets && (char !== "]" || !bracketVal)) {
          let res;
          if (char === "-") {
            res = char;
          } else if ((char === "^" || char === "!") && !bracketVal) {
            res = "^";
          } else if (char === GLOB_SPLIT) {
            res = "";
          } else {
            res = escapeRegExpCharacters(char);
          }
          bracketVal += res;
          continue;
        }
        switch (char) {
          case "{":
            inBraces = true;
            continue;
          case "[":
            inBrackets = true;
            continue;
          case "}":
            const choices = splitGlobAware(braceVal, ",");
            const braceRegExp = `(?:${choices.map((c3) => parseRegExp(c3)).join("|")})`;
            regEx += braceRegExp;
            inBraces = false;
            braceVal = "";
            break;
          case "]":
            regEx += "[" + bracketVal + "]";
            inBrackets = false;
            bracketVal = "";
            break;
          case "?":
            regEx += NO_PATH_REGEX;
            continue;
          case "*":
            regEx += starsToRegExp(1);
            continue;
          default:
            regEx += escapeRegExpCharacters(char);
        }
      }
      if (index3 < segments.length - 1 && (segments[index3 + 1] !== GLOBSTAR || index3 + 2 < segments.length)) {
        regEx += PATH_REGEX;
      }
      previousSegmentWasGlobStar = false;
    });
  }
  return regEx;
}
var T1 = /^\*\*\/\*\.[\w\.-]+$/;
var T2 = /^\*\*\/([\w\.-]+)\/?$/;
var T3 = /^{\*\*\/[\*\.]?[\w\.-]+\/?(,\*\*\/[\*\.]?[\w\.-]+\/?)*}$/;
var T3_2 = /^{\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?(,\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?)*}$/;
var T4 = /^\*\*((\/[\w\.-]+)+)\/?$/;
var T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/;
var CACHE = new LRUCache(1e4);
var FALSE = function() {
  return false;
};
var NULL = function() {
  return null;
};
function parsePattern(arg1, options) {
  if (!arg1) {
    return NULL;
  }
  let pattern;
  if (typeof arg1 !== "string") {
    pattern = arg1.pattern;
  } else {
    pattern = arg1;
  }
  pattern = pattern.trim();
  const patternKey = `${pattern}_${!!options.trimForExclusions}`;
  let parsedPattern = CACHE.get(patternKey);
  if (parsedPattern) {
    return wrapRelativePattern(parsedPattern, arg1);
  }
  let match2;
  if (T1.test(pattern)) {
    const base = pattern.substr(4);
    parsedPattern = function(path, basename2) {
      return typeof path === "string" && path.endsWith(base) ? pattern : null;
    };
  } else if (match2 = T2.exec(trimForExclusions(pattern, options))) {
    parsedPattern = trivia2(match2[1], pattern);
  } else if ((options.trimForExclusions ? T3_2 : T3).test(pattern)) {
    parsedPattern = trivia3(pattern, options);
  } else if (match2 = T4.exec(trimForExclusions(pattern, options))) {
    parsedPattern = trivia4and5(match2[1].substr(1), pattern, true);
  } else if (match2 = T5.exec(trimForExclusions(pattern, options))) {
    parsedPattern = trivia4and5(match2[1], pattern, false);
  } else {
    parsedPattern = toRegExp(pattern);
  }
  CACHE.set(patternKey, parsedPattern);
  return wrapRelativePattern(parsedPattern, arg1);
}
function wrapRelativePattern(parsedPattern, arg2) {
  if (typeof arg2 === "string") {
    return parsedPattern;
  }
  return function(path, basename2) {
    if (!isEqualOrParent(path, arg2.base)) {
      return null;
    }
    return parsedPattern(relative(arg2.base, path), basename2);
  };
}
function trimForExclusions(pattern, options) {
  return options.trimForExclusions && pattern.endsWith("/**") ? pattern.substr(0, pattern.length - 2) : pattern;
}
function trivia2(base, originalPattern) {
  const slashBase = `/${base}`;
  const backslashBase = `\\${base}`;
  const parsedPattern = function(path, basename2) {
    if (typeof path !== "string") {
      return null;
    }
    if (basename2) {
      return basename2 === base ? originalPattern : null;
    }
    return path === base || path.endsWith(slashBase) || path.endsWith(backslashBase) ? originalPattern : null;
  };
  const basenames = [base];
  parsedPattern.basenames = basenames;
  parsedPattern.patterns = [originalPattern];
  parsedPattern.allBasenames = basenames;
  return parsedPattern;
}
function trivia3(pattern, options) {
  const parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1).split(",").map((pattern2) => parsePattern(pattern2, options)).filter((pattern2) => pattern2 !== NULL), pattern);
  const n3 = parsedPatterns.length;
  if (!n3) {
    return NULL;
  }
  if (n3 === 1) {
    return parsedPatterns[0];
  }
  const parsedPattern = function(path, basename2) {
    for (let i3 = 0, n4 = parsedPatterns.length; i3 < n4; i3++) {
      if (parsedPatterns[i3](path, basename2)) {
        return pattern;
      }
    }
    return null;
  };
  const withBasenames = first(parsedPatterns, (pattern2) => !!pattern2.allBasenames);
  if (withBasenames) {
    parsedPattern.allBasenames = withBasenames.allBasenames;
  }
  const allPaths = parsedPatterns.reduce((all2, current) => current.allPaths ? all2.concat(current.allPaths) : all2, []);
  if (allPaths.length) {
    parsedPattern.allPaths = allPaths;
  }
  return parsedPattern;
}
function trivia4and5(path, pattern, matchPathEnds) {
  const nativePath = sep !== posix.sep ? path.replace(ALL_FORWARD_SLASHES, sep) : path;
  const nativePathEnd = sep + nativePath;
  const parsedPattern = matchPathEnds ? function(path2, basename2) {
    return typeof path2 === "string" && (path2 === nativePath || path2.endsWith(nativePathEnd)) ? pattern : null;
  } : function(path2, basename2) {
    return typeof path2 === "string" && path2 === nativePath ? pattern : null;
  };
  parsedPattern.allPaths = [(matchPathEnds ? "*/" : "./") + path];
  return parsedPattern;
}
function toRegExp(pattern) {
  try {
    const regExp = new RegExp(`^${parseRegExp(pattern)}$`);
    return function(path) {
      regExp.lastIndex = 0;
      return typeof path === "string" && regExp.test(path) ? pattern : null;
    };
  } catch (error2) {
    return NULL;
  }
}
function match(arg1, path, hasSibling) {
  if (!arg1 || typeof path !== "string") {
    return false;
  }
  return parse$1(arg1)(path, void 0, hasSibling);
}
function parse$1(arg1, options = {}) {
  if (!arg1) {
    return FALSE;
  }
  if (typeof arg1 === "string" || isRelativePattern(arg1)) {
    const parsedPattern = parsePattern(arg1, options);
    if (parsedPattern === NULL) {
      return FALSE;
    }
    const resultPattern = function(path, basename2) {
      return !!parsedPattern(path, basename2);
    };
    if (parsedPattern.allBasenames) {
      resultPattern.allBasenames = parsedPattern.allBasenames;
    }
    if (parsedPattern.allPaths) {
      resultPattern.allPaths = parsedPattern.allPaths;
    }
    return resultPattern;
  }
  return parsedExpression(arg1, options);
}
function isRelativePattern(obj) {
  const rp = obj;
  return rp && typeof rp.base === "string" && typeof rp.pattern === "string";
}
function parsedExpression(expression, options) {
  const parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression).map((pattern) => parseExpressionPattern(pattern, expression[pattern], options)).filter((pattern) => pattern !== NULL));
  const n3 = parsedPatterns.length;
  if (!n3) {
    return NULL;
  }
  if (!parsedPatterns.some((parsedPattern) => !!parsedPattern.requiresSiblings)) {
    if (n3 === 1) {
      return parsedPatterns[0];
    }
    const resultExpression2 = function(path, basename2) {
      for (let i3 = 0, n4 = parsedPatterns.length; i3 < n4; i3++) {
        const result = parsedPatterns[i3](path, basename2);
        if (result) {
          return result;
        }
      }
      return null;
    };
    const withBasenames2 = first(parsedPatterns, (pattern) => !!pattern.allBasenames);
    if (withBasenames2) {
      resultExpression2.allBasenames = withBasenames2.allBasenames;
    }
    const allPaths2 = parsedPatterns.reduce((all2, current) => current.allPaths ? all2.concat(current.allPaths) : all2, []);
    if (allPaths2.length) {
      resultExpression2.allPaths = allPaths2;
    }
    return resultExpression2;
  }
  const resultExpression = function(path, basename$12, hasSibling) {
    let name = void 0;
    for (let i3 = 0, n4 = parsedPatterns.length; i3 < n4; i3++) {
      const parsedPattern = parsedPatterns[i3];
      if (parsedPattern.requiresSiblings && hasSibling) {
        if (!basename$12) {
          basename$12 = basename(path);
        }
        if (!name) {
          name = basename$12.substr(0, basename$12.length - extname(path).length);
        }
      }
      const result = parsedPattern(path, basename$12, name, hasSibling);
      if (result) {
        return result;
      }
    }
    return null;
  };
  const withBasenames = first(parsedPatterns, (pattern) => !!pattern.allBasenames);
  if (withBasenames) {
    resultExpression.allBasenames = withBasenames.allBasenames;
  }
  const allPaths = parsedPatterns.reduce((all2, current) => current.allPaths ? all2.concat(current.allPaths) : all2, []);
  if (allPaths.length) {
    resultExpression.allPaths = allPaths;
  }
  return resultExpression;
}
function parseExpressionPattern(pattern, value, options) {
  if (value === false) {
    return NULL;
  }
  const parsedPattern = parsePattern(pattern, options);
  if (parsedPattern === NULL) {
    return NULL;
  }
  if (typeof value === "boolean") {
    return parsedPattern;
  }
  if (value) {
    const when = value.when;
    if (typeof when === "string") {
      const result = (path, basename2, name, hasSibling) => {
        if (!hasSibling || !parsedPattern(path, basename2)) {
          return null;
        }
        const clausePattern = when.replace("$(basename)", name);
        const matched = hasSibling(clausePattern);
        return isThenable(matched) ? matched.then((m2) => m2 ? pattern : null) : matched ? pattern : null;
      };
      result.requiresSiblings = true;
      return result;
    }
  }
  return parsedPattern;
}
function aggregateBasenameMatches(parsedPatterns, result) {
  const basenamePatterns = parsedPatterns.filter((parsedPattern) => !!parsedPattern.basenames);
  if (basenamePatterns.length < 2) {
    return parsedPatterns;
  }
  const basenames = basenamePatterns.reduce((all2, current) => {
    const basenames2 = current.basenames;
    return basenames2 ? all2.concat(basenames2) : all2;
  }, []);
  let patterns;
  if (result) {
    patterns = [];
    for (let i3 = 0, n3 = basenames.length; i3 < n3; i3++) {
      patterns.push(result);
    }
  } else {
    patterns = basenamePatterns.reduce((all2, current) => {
      const patterns2 = current.patterns;
      return patterns2 ? all2.concat(patterns2) : all2;
    }, []);
  }
  const aggregate = function(path, basename2) {
    if (typeof path !== "string") {
      return null;
    }
    if (!basename2) {
      let i3;
      for (i3 = path.length; i3 > 0; i3--) {
        const ch2 = path.charCodeAt(i3 - 1);
        if (ch2 === 47 || ch2 === 92) {
          break;
        }
      }
      basename2 = path.substr(i3);
    }
    const index3 = basenames.indexOf(basename2);
    return index3 !== -1 ? patterns[index3] : null;
  };
  aggregate.basenames = basenames;
  aggregate.patterns = patterns;
  aggregate.allBasenames = basenames;
  const aggregatedPatterns = parsedPatterns.filter((parsedPattern) => !parsedPattern.basenames);
  aggregatedPatterns.push(aggregate);
  return aggregatedPatterns;
}
function score(selector2, candidateUri, candidateLanguage, candidateIsSynchronized) {
  if (Array.isArray(selector2)) {
    let ret = 0;
    for (const filter3 of selector2) {
      const value = score(filter3, candidateUri, candidateLanguage, candidateIsSynchronized);
      if (value === 10) {
        return value;
      }
      if (value > ret) {
        ret = value;
      }
    }
    return ret;
  } else if (typeof selector2 === "string") {
    if (!candidateIsSynchronized) {
      return 0;
    }
    if (selector2 === "*") {
      return 5;
    } else if (selector2 === candidateLanguage) {
      return 10;
    } else {
      return 0;
    }
  } else if (selector2) {
    const {language, pattern, scheme, hasAccessToAllModels} = selector2;
    if (!candidateIsSynchronized && !hasAccessToAllModels) {
      return 0;
    }
    let ret = 0;
    if (scheme) {
      if (scheme === candidateUri.scheme) {
        ret = 10;
      } else if (scheme === "*") {
        ret = 5;
      } else {
        return 0;
      }
    }
    if (language) {
      if (language === candidateLanguage) {
        ret = 10;
      } else if (language === "*") {
        ret = Math.max(ret, 5);
      } else {
        return 0;
      }
    }
    if (pattern) {
      let normalizedPattern;
      if (typeof pattern === "string") {
        normalizedPattern = pattern;
      } else {
        normalizedPattern = Object.assign(Object.assign({}, pattern), {base: normalize(pattern.base)});
      }
      if (normalizedPattern === candidateUri.fsPath || match(normalizedPattern, candidateUri.fsPath)) {
        ret = 10;
      } else {
        return 0;
      }
    }
    return ret;
  } else {
    return 0;
  }
}
var IModelService = createDecorator("modelService");
function shouldSynchronizeModel(model) {
  return !model.isTooLargeForSyncing() && !model.isForSimpleWidget;
}
function isExclusive(selector2) {
  if (typeof selector2 === "string") {
    return false;
  } else if (Array.isArray(selector2)) {
    return selector2.every(isExclusive);
  } else {
    return !!selector2.exclusive;
  }
}
var LanguageFeatureRegistry = class {
  constructor() {
    this._clock = 0;
    this._entries = [];
    this._onDidChange = new Emitter();
  }
  get onDidChange() {
    return this._onDidChange.event;
  }
  register(selector2, provider) {
    let entry = {
      selector: selector2,
      provider,
      _score: -1,
      _time: this._clock++
    };
    this._entries.push(entry);
    this._lastCandidate = void 0;
    this._onDidChange.fire(this._entries.length);
    return toDisposable(() => {
      if (entry) {
        let idx = this._entries.indexOf(entry);
        if (idx >= 0) {
          this._entries.splice(idx, 1);
          this._lastCandidate = void 0;
          this._onDidChange.fire(this._entries.length);
          entry = void 0;
        }
      }
    });
  }
  has(model) {
    return this.all(model).length > 0;
  }
  all(model) {
    if (!model) {
      return [];
    }
    this._updateScores(model);
    const result = [];
    for (let entry of this._entries) {
      if (entry._score > 0) {
        result.push(entry.provider);
      }
    }
    return result;
  }
  ordered(model) {
    const result = [];
    this._orderedForEach(model, (entry) => result.push(entry.provider));
    return result;
  }
  orderedGroups(model) {
    const result = [];
    let lastBucket;
    let lastBucketScore;
    this._orderedForEach(model, (entry) => {
      if (lastBucket && lastBucketScore === entry._score) {
        lastBucket.push(entry.provider);
      } else {
        lastBucketScore = entry._score;
        lastBucket = [entry.provider];
        result.push(lastBucket);
      }
    });
    return result;
  }
  _orderedForEach(model, callback) {
    if (!model) {
      return;
    }
    this._updateScores(model);
    for (const entry of this._entries) {
      if (entry._score > 0) {
        callback(entry);
      }
    }
  }
  _updateScores(model) {
    let candidate = {
      uri: model.uri.toString(),
      language: model.getLanguageIdentifier().language
    };
    if (this._lastCandidate && this._lastCandidate.language === candidate.language && this._lastCandidate.uri === candidate.uri) {
      return;
    }
    this._lastCandidate = candidate;
    for (let entry of this._entries) {
      entry._score = score(entry.selector, model.uri, model.getLanguageIdentifier().language, shouldSynchronizeModel(model));
      if (isExclusive(entry.selector) && entry._score > 0) {
        for (let entry2 of this._entries) {
          entry2._score = 0;
        }
        entry._score = 1e3;
        break;
      }
    }
    this._entries.sort(LanguageFeatureRegistry._compareByScoreAndTime);
  }
  static _compareByScoreAndTime(a2, b2) {
    if (a2._score < b2._score) {
      return 1;
    } else if (a2._score > b2._score) {
      return -1;
    } else if (a2._time < b2._time) {
      return 1;
    } else if (a2._time > b2._time) {
      return -1;
    } else {
      return 0;
    }
  }
};
var TokenizationRegistryImpl = class {
  constructor() {
    this._map = new Map();
    this._promises = new Map();
    this._onDidChange = new Emitter();
    this.onDidChange = this._onDidChange.event;
    this._colorMap = null;
  }
  fire(languages2) {
    this._onDidChange.fire({
      changedLanguages: languages2,
      changedColorMap: false
    });
  }
  register(language, support) {
    this._map.set(language, support);
    this.fire([language]);
    return toDisposable(() => {
      if (this._map.get(language) !== support) {
        return;
      }
      this._map.delete(language);
      this.fire([language]);
    });
  }
  registerPromise(language, supportPromise) {
    let registration = null;
    let isDisposed = false;
    this._promises.set(language, supportPromise.then((support) => {
      this._promises.delete(language);
      if (isDisposed || !support) {
        return;
      }
      registration = this.register(language, support);
    }));
    return toDisposable(() => {
      isDisposed = true;
      if (registration) {
        registration.dispose();
      }
    });
  }
  getPromise(language) {
    const support = this.get(language);
    if (support) {
      return Promise.resolve(support);
    }
    const promise = this._promises.get(language);
    if (promise) {
      return promise.then((_23) => this.get(language));
    }
    return null;
  }
  get(language) {
    return this._map.get(language) || null;
  }
  setColorMap(colorMap) {
    this._colorMap = colorMap;
    this._onDidChange.fire({
      changedLanguages: Array.from(this._map.keys()),
      changedColorMap: true
    });
  }
  getColorMap() {
    return this._colorMap;
  }
  getDefaultBackground() {
    if (this._colorMap && this._colorMap.length > 2) {
      return this._colorMap[2];
    }
    return null;
  }
};
function or(...filter3) {
  return function(word, wordToMatchAgainst) {
    for (let i3 = 0, len2 = filter3.length; i3 < len2; i3++) {
      const match2 = filter3[i3](word, wordToMatchAgainst);
      if (match2) {
        return match2;
      }
    }
    return null;
  };
}
var matchesPrefix = _matchesPrefix.bind(void 0, true);
function _matchesPrefix(ignoreCase, word, wordToMatchAgainst) {
  if (!wordToMatchAgainst || wordToMatchAgainst.length < word.length) {
    return null;
  }
  let matches2;
  if (ignoreCase) {
    matches2 = startsWithIgnoreCase(wordToMatchAgainst, word);
  } else {
    matches2 = wordToMatchAgainst.indexOf(word) === 0;
  }
  if (!matches2) {
    return null;
  }
  return word.length > 0 ? [{start: 0, end: word.length}] : [];
}
function matchesContiguousSubString(word, wordToMatchAgainst) {
  const index3 = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
  if (index3 === -1) {
    return null;
  }
  return [{start: index3, end: index3 + word.length}];
}
function matchesSubString(word, wordToMatchAgainst) {
  return _matchesSubString(word.toLowerCase(), wordToMatchAgainst.toLowerCase(), 0, 0);
}
function _matchesSubString(word, wordToMatchAgainst, i3, j) {
  if (i3 === word.length) {
    return [];
  } else if (j === wordToMatchAgainst.length) {
    return null;
  } else {
    if (word[i3] === wordToMatchAgainst[j]) {
      let result = null;
      if (result = _matchesSubString(word, wordToMatchAgainst, i3 + 1, j + 1)) {
        return join({start: j, end: j + 1}, result);
      }
      return null;
    }
    return _matchesSubString(word, wordToMatchAgainst, i3, j + 1);
  }
}
function isLower(code2) {
  return 97 <= code2 && code2 <= 122;
}
function isUpper(code2) {
  return 65 <= code2 && code2 <= 90;
}
function isNumber$1(code2) {
  return 48 <= code2 && code2 <= 57;
}
function isWhitespace(code2) {
  return code2 === 32 || code2 === 9 || code2 === 10 || code2 === 13;
}
var wordSeparators = new Set();
"`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?".split("").forEach((s2) => wordSeparators.add(s2.charCodeAt(0)));
function isAlphanumeric(code2) {
  return isLower(code2) || isUpper(code2) || isNumber$1(code2);
}
function join(head, tail3) {
  if (tail3.length === 0) {
    tail3 = [head];
  } else if (head.end === tail3[0].start) {
    tail3[0].start = head.start;
  } else {
    tail3.unshift(head);
  }
  return tail3;
}
function nextAnchor(camelCaseWord, start3) {
  for (let i3 = start3; i3 < camelCaseWord.length; i3++) {
    const c3 = camelCaseWord.charCodeAt(i3);
    if (isUpper(c3) || isNumber$1(c3) || i3 > 0 && !isAlphanumeric(camelCaseWord.charCodeAt(i3 - 1))) {
      return i3;
    }
  }
  return camelCaseWord.length;
}
function _matchesCamelCase(word, camelCaseWord, i3, j) {
  if (i3 === word.length) {
    return [];
  } else if (j === camelCaseWord.length) {
    return null;
  } else if (word[i3] !== camelCaseWord[j].toLowerCase()) {
    return null;
  } else {
    let result = null;
    let nextUpperIndex = j + 1;
    result = _matchesCamelCase(word, camelCaseWord, i3 + 1, j + 1);
    while (!result && (nextUpperIndex = nextAnchor(camelCaseWord, nextUpperIndex)) < camelCaseWord.length) {
      result = _matchesCamelCase(word, camelCaseWord, i3 + 1, nextUpperIndex);
      nextUpperIndex++;
    }
    return result === null ? null : join({start: j, end: j + 1}, result);
  }
}
function analyzeCamelCaseWord(word) {
  let upper = 0, lower2 = 0, alpha = 0, numeric = 0, code2 = 0;
  for (let i3 = 0; i3 < word.length; i3++) {
    code2 = word.charCodeAt(i3);
    if (isUpper(code2)) {
      upper++;
    }
    if (isLower(code2)) {
      lower2++;
    }
    if (isAlphanumeric(code2)) {
      alpha++;
    }
    if (isNumber$1(code2)) {
      numeric++;
    }
  }
  const upperPercent = upper / word.length;
  const lowerPercent = lower2 / word.length;
  const alphaPercent = alpha / word.length;
  const numericPercent = numeric / word.length;
  return {upperPercent, lowerPercent, alphaPercent, numericPercent};
}
function isUpperCaseWord(analysis) {
  const {upperPercent, lowerPercent} = analysis;
  return lowerPercent === 0 && upperPercent > 0.6;
}
function isCamelCaseWord(analysis) {
  const {upperPercent, lowerPercent, alphaPercent, numericPercent} = analysis;
  return lowerPercent > 0.2 && upperPercent < 0.8 && alphaPercent > 0.6 && numericPercent < 0.2;
}
function isCamelCasePattern(word) {
  let upper = 0, lower2 = 0, code2 = 0, whitespace = 0;
  for (let i3 = 0; i3 < word.length; i3++) {
    code2 = word.charCodeAt(i3);
    if (isUpper(code2)) {
      upper++;
    }
    if (isLower(code2)) {
      lower2++;
    }
    if (isWhitespace(code2)) {
      whitespace++;
    }
  }
  if ((upper === 0 || lower2 === 0) && whitespace === 0) {
    return word.length <= 30;
  } else {
    return upper <= 5;
  }
}
function matchesCamelCase(word, camelCaseWord) {
  if (!camelCaseWord) {
    return null;
  }
  camelCaseWord = camelCaseWord.trim();
  if (camelCaseWord.length === 0) {
    return null;
  }
  if (!isCamelCasePattern(word)) {
    return null;
  }
  if (camelCaseWord.length > 60) {
    return null;
  }
  const analysis = analyzeCamelCaseWord(camelCaseWord);
  if (!isCamelCaseWord(analysis)) {
    if (!isUpperCaseWord(analysis)) {
      return null;
    }
    camelCaseWord = camelCaseWord.toLowerCase();
  }
  let result = null;
  let i3 = 0;
  word = word.toLowerCase();
  while (i3 < camelCaseWord.length && (result = _matchesCamelCase(word, camelCaseWord, 0, i3)) === null) {
    i3 = nextAnchor(camelCaseWord, i3 + 1);
  }
  return result;
}
var fuzzyContiguousFilter = or(matchesPrefix, matchesCamelCase, matchesContiguousSubString);
var fuzzySeparateFilter = or(matchesPrefix, matchesCamelCase, matchesSubString);
var fuzzyRegExpCache = new LRUCache(1e4);
function matchesFuzzy(word, wordToMatchAgainst, enableSeparateSubstringMatching = false) {
  if (typeof word !== "string" || typeof wordToMatchAgainst !== "string") {
    return null;
  }
  let regexp = fuzzyRegExpCache.get(word);
  if (!regexp) {
    regexp = new RegExp(convertSimple2RegExpPattern(word), "i");
    fuzzyRegExpCache.set(word, regexp);
  }
  const match2 = regexp.exec(wordToMatchAgainst);
  if (match2) {
    return [{start: match2.index, end: match2.index + match2[0].length}];
  }
  return enableSeparateSubstringMatching ? fuzzySeparateFilter(word, wordToMatchAgainst) : fuzzyContiguousFilter(word, wordToMatchAgainst);
}
var _maxLen = 128;
function initTable() {
  const table2 = [];
  const row = [0];
  for (let i3 = 1; i3 <= _maxLen; i3++) {
    row.push(-i3);
  }
  for (let i3 = 0; i3 <= _maxLen; i3++) {
    const thisRow = row.slice(0);
    thisRow[0] = -i3;
    table2.push(thisRow);
  }
  return table2;
}
var _table = initTable();
var _scores = initTable();
var _arrows = initTable();
function isSeparatorAtPos(value, index3) {
  if (index3 < 0 || index3 >= value.length) {
    return false;
  }
  const code2 = value.charCodeAt(index3);
  switch (code2) {
    case 95:
    case 45:
    case 46:
    case 32:
    case 47:
    case 92:
    case 39:
    case 34:
    case 58:
    case 36:
      return true;
    default:
      return false;
  }
}
function isWhitespaceAtPos(value, index3) {
  if (index3 < 0 || index3 >= value.length) {
    return false;
  }
  const code2 = value.charCodeAt(index3);
  switch (code2) {
    case 32:
    case 9:
      return true;
    default:
      return false;
  }
}
function isUpperCaseAtPos(pos, word, wordLow) {
  return word[pos] !== wordLow[pos];
}
function isPatternInWord(patternLow, patternPos, patternLen, wordLow, wordPos, wordLen) {
  while (patternPos < patternLen && wordPos < wordLen) {
    if (patternLow[patternPos] === wordLow[wordPos]) {
      patternPos += 1;
    }
    wordPos += 1;
  }
  return patternPos === patternLen;
}
var FuzzyScore;
(function(FuzzyScore2) {
  FuzzyScore2.Default = Object.freeze([-100, 0, 0]);
  function isDefault(score2) {
    return !score2 || score2[0] === -100 && score2[1] === 0 && score2[2] === 0;
  }
  FuzzyScore2.isDefault = isDefault;
})(FuzzyScore || (FuzzyScore = {}));
function fuzzyScore(pattern, patternLow, patternStart, word, wordLow, wordStart, firstMatchCanBeWeak) {
  const patternLen = pattern.length > _maxLen ? _maxLen : pattern.length;
  const wordLen = word.length > _maxLen ? _maxLen : word.length;
  if (patternStart >= patternLen || wordStart >= wordLen || patternLen - patternStart > wordLen - wordStart) {
    return void 0;
  }
  if (!isPatternInWord(patternLow, patternStart, patternLen, wordLow, wordStart, wordLen)) {
    return void 0;
  }
  let row = 1;
  let column = 1;
  let patternPos = patternStart;
  let wordPos = wordStart;
  let hasStrongFirstMatch = false;
  for (row = 1, patternPos = patternStart; patternPos < patternLen; row++, patternPos++) {
    for (column = 1, wordPos = wordStart; wordPos < wordLen; column++, wordPos++) {
      const score2 = _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos);
      if (patternPos === patternStart && score2 > 1) {
        hasStrongFirstMatch = true;
      }
      _scores[row][column] = score2;
      const diag = _table[row - 1][column - 1] + (score2 > 1 ? 1 : score2);
      const top2 = _table[row - 1][column] + -1;
      const left2 = _table[row][column - 1] + -1;
      if (left2 >= top2) {
        if (left2 > diag) {
          _table[row][column] = left2;
          _arrows[row][column] = 4;
        } else if (left2 === diag) {
          _table[row][column] = left2;
          _arrows[row][column] = 4 | 2;
        } else {
          _table[row][column] = diag;
          _arrows[row][column] = 2;
        }
      } else {
        if (top2 > diag) {
          _table[row][column] = top2;
          _arrows[row][column] = 1;
        } else if (top2 === diag) {
          _table[row][column] = top2;
          _arrows[row][column] = 1 | 2;
        } else {
          _table[row][column] = diag;
          _arrows[row][column] = 2;
        }
      }
    }
  }
  if (!hasStrongFirstMatch && !firstMatchCanBeWeak) {
    return void 0;
  }
  _matchesCount = 0;
  _topScore = -100;
  _wordStart = wordStart;
  _firstMatchCanBeWeak = firstMatchCanBeWeak;
  _findAllMatches2(row - 1, column - 1, patternLen === wordLen ? 1 : 0, 0, false);
  if (_matchesCount === 0) {
    return void 0;
  }
  return [_topScore, _topMatch2, wordStart];
}
function _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos) {
  if (patternLow[patternPos] !== wordLow[wordPos]) {
    return -1;
  }
  if (wordPos === patternPos - patternStart) {
    if (pattern[patternPos] === word[wordPos]) {
      return 7;
    } else {
      return 5;
    }
  } else if (isUpperCaseAtPos(wordPos, word, wordLow) && (wordPos === 0 || !isUpperCaseAtPos(wordPos - 1, word, wordLow))) {
    if (pattern[patternPos] === word[wordPos]) {
      return 7;
    } else {
      return 5;
    }
  } else if (isSeparatorAtPos(wordLow, wordPos) && (wordPos === 0 || !isSeparatorAtPos(wordLow, wordPos - 1))) {
    return 5;
  } else if (isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1)) {
    return 5;
  } else {
    return 1;
  }
}
var _matchesCount = 0;
var _topMatch2 = 0;
var _topScore = 0;
var _wordStart = 0;
var _firstMatchCanBeWeak = false;
function _findAllMatches2(row, column, total, matches2, lastMatched) {
  if (_matchesCount >= 10 || total < -25) {
    return;
  }
  let simpleMatchCount = 0;
  while (row > 0 && column > 0) {
    const score2 = _scores[row][column];
    const arrow2 = _arrows[row][column];
    if (arrow2 === 4) {
      column -= 1;
      if (lastMatched) {
        total -= 5;
      } else if (matches2 !== 0) {
        total -= 1;
      }
      lastMatched = false;
      simpleMatchCount = 0;
    } else if (arrow2 & 2) {
      if (arrow2 & 4) {
        _findAllMatches2(row, column - 1, matches2 !== 0 ? total - 1 : total, matches2, lastMatched);
      }
      total += score2;
      row -= 1;
      column -= 1;
      lastMatched = true;
      matches2 += Math.pow(2, column + _wordStart);
      if (score2 === 1) {
        simpleMatchCount += 1;
        if (row === 0 && !_firstMatchCanBeWeak) {
          return void 0;
        }
      } else {
        total += 1 + simpleMatchCount * (score2 - 1);
        simpleMatchCount = 0;
      }
    } else {
      return void 0;
    }
  }
  total -= column >= 3 ? 9 : column * 3;
  _matchesCount += 1;
  if (total > _topScore) {
    _topScore = total;
    _topMatch2 = matches2;
  }
}
var codiconStartMarker = "$(";
function parseCodicons(text) {
  const firstCodiconIndex = text.indexOf(codiconStartMarker);
  if (firstCodiconIndex === -1) {
    return {text};
  }
  return doParseCodicons(text, firstCodiconIndex);
}
function doParseCodicons(text, firstCodiconIndex) {
  const codiconOffsets = [];
  let textWithoutCodicons = "";
  function appendChars(chars2) {
    if (chars2) {
      textWithoutCodicons += chars2;
      for (const _23 of chars2) {
        codiconOffsets.push(codiconsOffset);
      }
    }
  }
  let currentCodiconStart = -1;
  let currentCodiconValue = "";
  let codiconsOffset = 0;
  let char;
  let nextChar;
  let offset2 = firstCodiconIndex;
  const length = text.length;
  appendChars(text.substr(0, firstCodiconIndex));
  while (offset2 < length) {
    char = text[offset2];
    nextChar = text[offset2 + 1];
    if (char === codiconStartMarker[0] && nextChar === codiconStartMarker[1]) {
      currentCodiconStart = offset2;
      appendChars(currentCodiconValue);
      currentCodiconValue = codiconStartMarker;
      offset2++;
    } else if (char === ")" && currentCodiconStart !== -1) {
      const currentCodiconLength = offset2 - currentCodiconStart + 1;
      codiconsOffset += currentCodiconLength;
      currentCodiconStart = -1;
      currentCodiconValue = "";
    } else if (currentCodiconStart !== -1) {
      if (/^[a-z0-9\-]$/i.test(char)) {
        currentCodiconValue += char;
      } else {
        appendChars(currentCodiconValue);
        currentCodiconStart = -1;
        currentCodiconValue = "";
      }
    } else {
      appendChars(char);
    }
    offset2++;
  }
  appendChars(currentCodiconValue);
  return {text: textWithoutCodicons, codiconOffsets};
}
function matchesFuzzyCodiconAware(query, target, enableSeparateSubstringMatching = false) {
  const {text, codiconOffsets} = target;
  if (!codiconOffsets || codiconOffsets.length === 0) {
    return matchesFuzzy(query, text, enableSeparateSubstringMatching);
  }
  const wordToMatchAgainstWithoutCodiconsTrimmed = ltrim(text, " ");
  const leadingWhitespaceOffset = text.length - wordToMatchAgainstWithoutCodiconsTrimmed.length;
  const matches2 = matchesFuzzy(query, wordToMatchAgainstWithoutCodiconsTrimmed, enableSeparateSubstringMatching);
  if (matches2) {
    for (const match2 of matches2) {
      const codiconOffset = codiconOffsets[match2.start + leadingWhitespaceOffset] + leadingWhitespaceOffset;
      match2.start += codiconOffset;
      match2.end += codiconOffset;
    }
  }
  return matches2;
}
var Registry = class {
  constructor() {
    this._icons = new Map();
    this._onDidRegister = new Emitter();
  }
  add(icon) {
    if (!this._icons.has(icon.id)) {
      this._icons.set(icon.id, icon);
      this._onDidRegister.fire(icon);
    } else {
      console.error(`Duplicate registration of codicon ${icon.id}`);
    }
  }
  get(id3) {
    return this._icons.get(id3);
  }
  get all() {
    return this._icons.values();
  }
  get onDidRegister() {
    return this._onDidRegister.event;
  }
};
var _registry = new Registry();
var iconRegistry = _registry;
function registerIcon(id3, def, description) {
  return new Codicon(id3, def);
}
var Codicon = class {
  constructor(id3, definition, description) {
    this.id = id3;
    this.definition = definition;
    this.description = description;
    _registry.add(this);
  }
  get classNames() {
    return "codicon codicon-" + this.id;
  }
  get cssSelector() {
    return ".codicon.codicon-" + this.id;
  }
};
(function(Codicon2) {
  Codicon2.add = new Codicon2("add", {character: "\\ea60"});
  Codicon2.plus = new Codicon2("plus", {character: "\\ea60"});
  Codicon2.gistNew = new Codicon2("gist-new", {character: "\\ea60"});
  Codicon2.repoCreate = new Codicon2("repo-create", {character: "\\ea60"});
  Codicon2.lightbulb = new Codicon2("lightbulb", {character: "\\ea61"});
  Codicon2.lightBulb = new Codicon2("light-bulb", {character: "\\ea61"});
  Codicon2.repo = new Codicon2("repo", {character: "\\ea62"});
  Codicon2.repoDelete = new Codicon2("repo-delete", {character: "\\ea62"});
  Codicon2.gistFork = new Codicon2("gist-fork", {character: "\\ea63"});
  Codicon2.repoForked = new Codicon2("repo-forked", {character: "\\ea63"});
  Codicon2.gitPullRequest = new Codicon2("git-pull-request", {character: "\\ea64"});
  Codicon2.gitPullRequestAbandoned = new Codicon2("git-pull-request-abandoned", {character: "\\ea64"});
  Codicon2.recordKeys = new Codicon2("record-keys", {character: "\\ea65"});
  Codicon2.keyboard = new Codicon2("keyboard", {character: "\\ea65"});
  Codicon2.tag = new Codicon2("tag", {character: "\\ea66"});
  Codicon2.tagAdd = new Codicon2("tag-add", {character: "\\ea66"});
  Codicon2.tagRemove = new Codicon2("tag-remove", {character: "\\ea66"});
  Codicon2.person = new Codicon2("person", {character: "\\ea67"});
  Codicon2.personAdd = new Codicon2("person-add", {character: "\\ea67"});
  Codicon2.personFollow = new Codicon2("person-follow", {character: "\\ea67"});
  Codicon2.personOutline = new Codicon2("person-outline", {character: "\\ea67"});
  Codicon2.personFilled = new Codicon2("person-filled", {character: "\\ea67"});
  Codicon2.gitBranch = new Codicon2("git-branch", {character: "\\ea68"});
  Codicon2.gitBranchCreate = new Codicon2("git-branch-create", {character: "\\ea68"});
  Codicon2.gitBranchDelete = new Codicon2("git-branch-delete", {character: "\\ea68"});
  Codicon2.sourceControl = new Codicon2("source-control", {character: "\\ea68"});
  Codicon2.mirror = new Codicon2("mirror", {character: "\\ea69"});
  Codicon2.mirrorPublic = new Codicon2("mirror-public", {character: "\\ea69"});
  Codicon2.star = new Codicon2("star", {character: "\\ea6a"});
  Codicon2.starAdd = new Codicon2("star-add", {character: "\\ea6a"});
  Codicon2.starDelete = new Codicon2("star-delete", {character: "\\ea6a"});
  Codicon2.starEmpty = new Codicon2("star-empty", {character: "\\ea6a"});
  Codicon2.comment = new Codicon2("comment", {character: "\\ea6b"});
  Codicon2.commentAdd = new Codicon2("comment-add", {character: "\\ea6b"});
  Codicon2.alert = new Codicon2("alert", {character: "\\ea6c"});
  Codicon2.warning = new Codicon2("warning", {character: "\\ea6c"});
  Codicon2.search = new Codicon2("search", {character: "\\ea6d"});
  Codicon2.searchSave = new Codicon2("search-save", {character: "\\ea6d"});
  Codicon2.logOut = new Codicon2("log-out", {character: "\\ea6e"});
  Codicon2.signOut = new Codicon2("sign-out", {character: "\\ea6e"});
  Codicon2.logIn = new Codicon2("log-in", {character: "\\ea6f"});
  Codicon2.signIn = new Codicon2("sign-in", {character: "\\ea6f"});
  Codicon2.eye = new Codicon2("eye", {character: "\\ea70"});
  Codicon2.eyeUnwatch = new Codicon2("eye-unwatch", {character: "\\ea70"});
  Codicon2.eyeWatch = new Codicon2("eye-watch", {character: "\\ea70"});
  Codicon2.circleFilled = new Codicon2("circle-filled", {character: "\\ea71"});
  Codicon2.primitiveDot = new Codicon2("primitive-dot", {character: "\\ea71"});
  Codicon2.closeDirty = new Codicon2("close-dirty", {character: "\\ea71"});
  Codicon2.debugBreakpoint = new Codicon2("debug-breakpoint", {character: "\\ea71"});
  Codicon2.debugBreakpointDisabled = new Codicon2("debug-breakpoint-disabled", {character: "\\ea71"});
  Codicon2.debugHint = new Codicon2("debug-hint", {character: "\\ea71"});
  Codicon2.primitiveSquare = new Codicon2("primitive-square", {character: "\\ea72"});
  Codicon2.edit = new Codicon2("edit", {character: "\\ea73"});
  Codicon2.pencil = new Codicon2("pencil", {character: "\\ea73"});
  Codicon2.info = new Codicon2("info", {character: "\\ea74"});
  Codicon2.issueOpened = new Codicon2("issue-opened", {character: "\\ea74"});
  Codicon2.gistPrivate = new Codicon2("gist-private", {character: "\\ea75"});
  Codicon2.gitForkPrivate = new Codicon2("git-fork-private", {character: "\\ea75"});
  Codicon2.lock = new Codicon2("lock", {character: "\\ea75"});
  Codicon2.mirrorPrivate = new Codicon2("mirror-private", {character: "\\ea75"});
  Codicon2.close = new Codicon2("close", {character: "\\ea76"});
  Codicon2.removeClose = new Codicon2("remove-close", {character: "\\ea76"});
  Codicon2.x = new Codicon2("x", {character: "\\ea76"});
  Codicon2.repoSync = new Codicon2("repo-sync", {character: "\\ea77"});
  Codicon2.sync = new Codicon2("sync", {character: "\\ea77"});
  Codicon2.clone = new Codicon2("clone", {character: "\\ea78"});
  Codicon2.desktopDownload = new Codicon2("desktop-download", {character: "\\ea78"});
  Codicon2.beaker = new Codicon2("beaker", {character: "\\ea79"});
  Codicon2.microscope = new Codicon2("microscope", {character: "\\ea79"});
  Codicon2.vm = new Codicon2("vm", {character: "\\ea7a"});
  Codicon2.deviceDesktop = new Codicon2("device-desktop", {character: "\\ea7a"});
  Codicon2.file = new Codicon2("file", {character: "\\ea7b"});
  Codicon2.fileText = new Codicon2("file-text", {character: "\\ea7b"});
  Codicon2.more = new Codicon2("more", {character: "\\ea7c"});
  Codicon2.ellipsis = new Codicon2("ellipsis", {character: "\\ea7c"});
  Codicon2.kebabHorizontal = new Codicon2("kebab-horizontal", {character: "\\ea7c"});
  Codicon2.mailReply = new Codicon2("mail-reply", {character: "\\ea7d"});
  Codicon2.reply = new Codicon2("reply", {character: "\\ea7d"});
  Codicon2.organization = new Codicon2("organization", {character: "\\ea7e"});
  Codicon2.organizationFilled = new Codicon2("organization-filled", {character: "\\ea7e"});
  Codicon2.organizationOutline = new Codicon2("organization-outline", {character: "\\ea7e"});
  Codicon2.newFile = new Codicon2("new-file", {character: "\\ea7f"});
  Codicon2.fileAdd = new Codicon2("file-add", {character: "\\ea7f"});
  Codicon2.newFolder = new Codicon2("new-folder", {character: "\\ea80"});
  Codicon2.fileDirectoryCreate = new Codicon2("file-directory-create", {character: "\\ea80"});
  Codicon2.trash = new Codicon2("trash", {character: "\\ea81"});
  Codicon2.trashcan = new Codicon2("trashcan", {character: "\\ea81"});
  Codicon2.history = new Codicon2("history", {character: "\\ea82"});
  Codicon2.clock = new Codicon2("clock", {character: "\\ea82"});
  Codicon2.folder = new Codicon2("folder", {character: "\\ea83"});
  Codicon2.fileDirectory = new Codicon2("file-directory", {character: "\\ea83"});
  Codicon2.symbolFolder = new Codicon2("symbol-folder", {character: "\\ea83"});
  Codicon2.logoGithub = new Codicon2("logo-github", {character: "\\ea84"});
  Codicon2.markGithub = new Codicon2("mark-github", {character: "\\ea84"});
  Codicon2.github = new Codicon2("github", {character: "\\ea84"});
  Codicon2.terminal = new Codicon2("terminal", {character: "\\ea85"});
  Codicon2.console = new Codicon2("console", {character: "\\ea85"});
  Codicon2.repl = new Codicon2("repl", {character: "\\ea85"});
  Codicon2.zap = new Codicon2("zap", {character: "\\ea86"});
  Codicon2.symbolEvent = new Codicon2("symbol-event", {character: "\\ea86"});
  Codicon2.error = new Codicon2("error", {character: "\\ea87"});
  Codicon2.stop = new Codicon2("stop", {character: "\\ea87"});
  Codicon2.variable = new Codicon2("variable", {character: "\\ea88"});
  Codicon2.symbolVariable = new Codicon2("symbol-variable", {character: "\\ea88"});
  Codicon2.array = new Codicon2("array", {character: "\\ea8a"});
  Codicon2.symbolArray = new Codicon2("symbol-array", {character: "\\ea8a"});
  Codicon2.symbolModule = new Codicon2("symbol-module", {character: "\\ea8b"});
  Codicon2.symbolPackage = new Codicon2("symbol-package", {character: "\\ea8b"});
  Codicon2.symbolNamespace = new Codicon2("symbol-namespace", {character: "\\ea8b"});
  Codicon2.symbolObject = new Codicon2("symbol-object", {character: "\\ea8b"});
  Codicon2.symbolMethod = new Codicon2("symbol-method", {character: "\\ea8c"});
  Codicon2.symbolFunction = new Codicon2("symbol-function", {character: "\\ea8c"});
  Codicon2.symbolConstructor = new Codicon2("symbol-constructor", {character: "\\ea8c"});
  Codicon2.symbolBoolean = new Codicon2("symbol-boolean", {character: "\\ea8f"});
  Codicon2.symbolNull = new Codicon2("symbol-null", {character: "\\ea8f"});
  Codicon2.symbolNumeric = new Codicon2("symbol-numeric", {character: "\\ea90"});
  Codicon2.symbolNumber = new Codicon2("symbol-number", {character: "\\ea90"});
  Codicon2.symbolStructure = new Codicon2("symbol-structure", {character: "\\ea91"});
  Codicon2.symbolStruct = new Codicon2("symbol-struct", {character: "\\ea91"});
  Codicon2.symbolParameter = new Codicon2("symbol-parameter", {character: "\\ea92"});
  Codicon2.symbolTypeParameter = new Codicon2("symbol-type-parameter", {character: "\\ea92"});
  Codicon2.symbolKey = new Codicon2("symbol-key", {character: "\\ea93"});
  Codicon2.symbolText = new Codicon2("symbol-text", {character: "\\ea93"});
  Codicon2.symbolReference = new Codicon2("symbol-reference", {character: "\\ea94"});
  Codicon2.goToFile = new Codicon2("go-to-file", {character: "\\ea94"});
  Codicon2.symbolEnum = new Codicon2("symbol-enum", {character: "\\ea95"});
  Codicon2.symbolValue = new Codicon2("symbol-value", {character: "\\ea95"});
  Codicon2.symbolRuler = new Codicon2("symbol-ruler", {character: "\\ea96"});
  Codicon2.symbolUnit = new Codicon2("symbol-unit", {character: "\\ea96"});
  Codicon2.activateBreakpoints = new Codicon2("activate-breakpoints", {character: "\\ea97"});
  Codicon2.archive = new Codicon2("archive", {character: "\\ea98"});
  Codicon2.arrowBoth = new Codicon2("arrow-both", {character: "\\ea99"});
  Codicon2.arrowDown = new Codicon2("arrow-down", {character: "\\ea9a"});
  Codicon2.arrowLeft = new Codicon2("arrow-left", {character: "\\ea9b"});
  Codicon2.arrowRight = new Codicon2("arrow-right", {character: "\\ea9c"});
  Codicon2.arrowSmallDown = new Codicon2("arrow-small-down", {character: "\\ea9d"});
  Codicon2.arrowSmallLeft = new Codicon2("arrow-small-left", {character: "\\ea9e"});
  Codicon2.arrowSmallRight = new Codicon2("arrow-small-right", {character: "\\ea9f"});
  Codicon2.arrowSmallUp = new Codicon2("arrow-small-up", {character: "\\eaa0"});
  Codicon2.arrowUp = new Codicon2("arrow-up", {character: "\\eaa1"});
  Codicon2.bell = new Codicon2("bell", {character: "\\eaa2"});
  Codicon2.bold = new Codicon2("bold", {character: "\\eaa3"});
  Codicon2.book = new Codicon2("book", {character: "\\eaa4"});
  Codicon2.bookmark = new Codicon2("bookmark", {character: "\\eaa5"});
  Codicon2.debugBreakpointConditionalUnverified = new Codicon2("debug-breakpoint-conditional-unverified", {character: "\\eaa6"});
  Codicon2.debugBreakpointConditional = new Codicon2("debug-breakpoint-conditional", {character: "\\eaa7"});
  Codicon2.debugBreakpointConditionalDisabled = new Codicon2("debug-breakpoint-conditional-disabled", {character: "\\eaa7"});
  Codicon2.debugBreakpointDataUnverified = new Codicon2("debug-breakpoint-data-unverified", {character: "\\eaa8"});
  Codicon2.debugBreakpointData = new Codicon2("debug-breakpoint-data", {character: "\\eaa9"});
  Codicon2.debugBreakpointDataDisabled = new Codicon2("debug-breakpoint-data-disabled", {character: "\\eaa9"});
  Codicon2.debugBreakpointLogUnverified = new Codicon2("debug-breakpoint-log-unverified", {character: "\\eaaa"});
  Codicon2.debugBreakpointLog = new Codicon2("debug-breakpoint-log", {character: "\\eaab"});
  Codicon2.debugBreakpointLogDisabled = new Codicon2("debug-breakpoint-log-disabled", {character: "\\eaab"});
  Codicon2.briefcase = new Codicon2("briefcase", {character: "\\eaac"});
  Codicon2.broadcast = new Codicon2("broadcast", {character: "\\eaad"});
  Codicon2.browser = new Codicon2("browser", {character: "\\eaae"});
  Codicon2.bug = new Codicon2("bug", {character: "\\eaaf"});
  Codicon2.calendar = new Codicon2("calendar", {character: "\\eab0"});
  Codicon2.caseSensitive = new Codicon2("case-sensitive", {character: "\\eab1"});
  Codicon2.check = new Codicon2("check", {character: "\\eab2"});
  Codicon2.checklist = new Codicon2("checklist", {character: "\\eab3"});
  Codicon2.chevronDown = new Codicon2("chevron-down", {character: "\\eab4"});
  Codicon2.chevronLeft = new Codicon2("chevron-left", {character: "\\eab5"});
  Codicon2.chevronRight = new Codicon2("chevron-right", {character: "\\eab6"});
  Codicon2.chevronUp = new Codicon2("chevron-up", {character: "\\eab7"});
  Codicon2.chromeClose = new Codicon2("chrome-close", {character: "\\eab8"});
  Codicon2.chromeMaximize = new Codicon2("chrome-maximize", {character: "\\eab9"});
  Codicon2.chromeMinimize = new Codicon2("chrome-minimize", {character: "\\eaba"});
  Codicon2.chromeRestore = new Codicon2("chrome-restore", {character: "\\eabb"});
  Codicon2.circleOutline = new Codicon2("circle-outline", {character: "\\eabc"});
  Codicon2.debugBreakpointUnverified = new Codicon2("debug-breakpoint-unverified", {character: "\\eabc"});
  Codicon2.circleSlash = new Codicon2("circle-slash", {character: "\\eabd"});
  Codicon2.circuitBoard = new Codicon2("circuit-board", {character: "\\eabe"});
  Codicon2.clearAll = new Codicon2("clear-all", {character: "\\eabf"});
  Codicon2.clippy = new Codicon2("clippy", {character: "\\eac0"});
  Codicon2.closeAll = new Codicon2("close-all", {character: "\\eac1"});
  Codicon2.cloudDownload = new Codicon2("cloud-download", {character: "\\eac2"});
  Codicon2.cloudUpload = new Codicon2("cloud-upload", {character: "\\eac3"});
  Codicon2.code = new Codicon2("code", {character: "\\eac4"});
  Codicon2.collapseAll = new Codicon2("collapse-all", {character: "\\eac5"});
  Codicon2.colorMode = new Codicon2("color-mode", {character: "\\eac6"});
  Codicon2.commentDiscussion = new Codicon2("comment-discussion", {character: "\\eac7"});
  Codicon2.compareChanges = new Codicon2("compare-changes", {character: "\\eafd"});
  Codicon2.creditCard = new Codicon2("credit-card", {character: "\\eac9"});
  Codicon2.dash = new Codicon2("dash", {character: "\\eacc"});
  Codicon2.dashboard = new Codicon2("dashboard", {character: "\\eacd"});
  Codicon2.database = new Codicon2("database", {character: "\\eace"});
  Codicon2.debugContinue = new Codicon2("debug-continue", {character: "\\eacf"});
  Codicon2.debugDisconnect = new Codicon2("debug-disconnect", {character: "\\ead0"});
  Codicon2.debugPause = new Codicon2("debug-pause", {character: "\\ead1"});
  Codicon2.debugRestart = new Codicon2("debug-restart", {character: "\\ead2"});
  Codicon2.debugStart = new Codicon2("debug-start", {character: "\\ead3"});
  Codicon2.debugStepInto = new Codicon2("debug-step-into", {character: "\\ead4"});
  Codicon2.debugStepOut = new Codicon2("debug-step-out", {character: "\\ead5"});
  Codicon2.debugStepOver = new Codicon2("debug-step-over", {character: "\\ead6"});
  Codicon2.debugStop = new Codicon2("debug-stop", {character: "\\ead7"});
  Codicon2.debug = new Codicon2("debug", {character: "\\ead8"});
  Codicon2.deviceCameraVideo = new Codicon2("device-camera-video", {character: "\\ead9"});
  Codicon2.deviceCamera = new Codicon2("device-camera", {character: "\\eada"});
  Codicon2.deviceMobile = new Codicon2("device-mobile", {character: "\\eadb"});
  Codicon2.diffAdded = new Codicon2("diff-added", {character: "\\eadc"});
  Codicon2.diffIgnored = new Codicon2("diff-ignored", {character: "\\eadd"});
  Codicon2.diffModified = new Codicon2("diff-modified", {character: "\\eade"});
  Codicon2.diffRemoved = new Codicon2("diff-removed", {character: "\\eadf"});
  Codicon2.diffRenamed = new Codicon2("diff-renamed", {character: "\\eae0"});
  Codicon2.diff = new Codicon2("diff", {character: "\\eae1"});
  Codicon2.discard = new Codicon2("discard", {character: "\\eae2"});
  Codicon2.editorLayout = new Codicon2("editor-layout", {character: "\\eae3"});
  Codicon2.emptyWindow = new Codicon2("empty-window", {character: "\\eae4"});
  Codicon2.exclude = new Codicon2("exclude", {character: "\\eae5"});
  Codicon2.extensions = new Codicon2("extensions", {character: "\\eae6"});
  Codicon2.eyeClosed = new Codicon2("eye-closed", {character: "\\eae7"});
  Codicon2.fileBinary = new Codicon2("file-binary", {character: "\\eae8"});
  Codicon2.fileCode = new Codicon2("file-code", {character: "\\eae9"});
  Codicon2.fileMedia = new Codicon2("file-media", {character: "\\eaea"});
  Codicon2.filePdf = new Codicon2("file-pdf", {character: "\\eaeb"});
  Codicon2.fileSubmodule = new Codicon2("file-submodule", {character: "\\eaec"});
  Codicon2.fileSymlinkDirectory = new Codicon2("file-symlink-directory", {character: "\\eaed"});
  Codicon2.fileSymlinkFile = new Codicon2("file-symlink-file", {character: "\\eaee"});
  Codicon2.fileZip = new Codicon2("file-zip", {character: "\\eaef"});
  Codicon2.files = new Codicon2("files", {character: "\\eaf0"});
  Codicon2.filter = new Codicon2("filter", {character: "\\eaf1"});
  Codicon2.flame = new Codicon2("flame", {character: "\\eaf2"});
  Codicon2.foldDown = new Codicon2("fold-down", {character: "\\eaf3"});
  Codicon2.foldUp = new Codicon2("fold-up", {character: "\\eaf4"});
  Codicon2.fold = new Codicon2("fold", {character: "\\eaf5"});
  Codicon2.folderActive = new Codicon2("folder-active", {character: "\\eaf6"});
  Codicon2.folderOpened = new Codicon2("folder-opened", {character: "\\eaf7"});
  Codicon2.gear = new Codicon2("gear", {character: "\\eaf8"});
  Codicon2.gift = new Codicon2("gift", {character: "\\eaf9"});
  Codicon2.gistSecret = new Codicon2("gist-secret", {character: "\\eafa"});
  Codicon2.gist = new Codicon2("gist", {character: "\\eafb"});
  Codicon2.gitCommit = new Codicon2("git-commit", {character: "\\eafc"});
  Codicon2.gitCompare = new Codicon2("git-compare", {character: "\\eafd"});
  Codicon2.gitMerge = new Codicon2("git-merge", {character: "\\eafe"});
  Codicon2.githubAction = new Codicon2("github-action", {character: "\\eaff"});
  Codicon2.githubAlt = new Codicon2("github-alt", {character: "\\eb00"});
  Codicon2.globe = new Codicon2("globe", {character: "\\eb01"});
  Codicon2.grabber = new Codicon2("grabber", {character: "\\eb02"});
  Codicon2.graph = new Codicon2("graph", {character: "\\eb03"});
  Codicon2.gripper = new Codicon2("gripper", {character: "\\eb04"});
  Codicon2.heart = new Codicon2("heart", {character: "\\eb05"});
  Codicon2.home = new Codicon2("home", {character: "\\eb06"});
  Codicon2.horizontalRule = new Codicon2("horizontal-rule", {character: "\\eb07"});
  Codicon2.hubot = new Codicon2("hubot", {character: "\\eb08"});
  Codicon2.inbox = new Codicon2("inbox", {character: "\\eb09"});
  Codicon2.issueClosed = new Codicon2("issue-closed", {character: "\\eb0a"});
  Codicon2.issueReopened = new Codicon2("issue-reopened", {character: "\\eb0b"});
  Codicon2.issues = new Codicon2("issues", {character: "\\eb0c"});
  Codicon2.italic = new Codicon2("italic", {character: "\\eb0d"});
  Codicon2.jersey = new Codicon2("jersey", {character: "\\eb0e"});
  Codicon2.json = new Codicon2("json", {character: "\\eb0f"});
  Codicon2.kebabVertical = new Codicon2("kebab-vertical", {character: "\\eb10"});
  Codicon2.key = new Codicon2("key", {character: "\\eb11"});
  Codicon2.law = new Codicon2("law", {character: "\\eb12"});
  Codicon2.lightbulbAutofix = new Codicon2("lightbulb-autofix", {character: "\\eb13"});
  Codicon2.linkExternal = new Codicon2("link-external", {character: "\\eb14"});
  Codicon2.link = new Codicon2("link", {character: "\\eb15"});
  Codicon2.listOrdered = new Codicon2("list-ordered", {character: "\\eb16"});
  Codicon2.listUnordered = new Codicon2("list-unordered", {character: "\\eb17"});
  Codicon2.liveShare = new Codicon2("live-share", {character: "\\eb18"});
  Codicon2.loading = new Codicon2("loading", {character: "\\eb19"});
  Codicon2.location = new Codicon2("location", {character: "\\eb1a"});
  Codicon2.mailRead = new Codicon2("mail-read", {character: "\\eb1b"});
  Codicon2.mail = new Codicon2("mail", {character: "\\eb1c"});
  Codicon2.markdown = new Codicon2("markdown", {character: "\\eb1d"});
  Codicon2.megaphone = new Codicon2("megaphone", {character: "\\eb1e"});
  Codicon2.mention = new Codicon2("mention", {character: "\\eb1f"});
  Codicon2.milestone = new Codicon2("milestone", {character: "\\eb20"});
  Codicon2.mortarBoard = new Codicon2("mortar-board", {character: "\\eb21"});
  Codicon2.move = new Codicon2("move", {character: "\\eb22"});
  Codicon2.multipleWindows = new Codicon2("multiple-windows", {character: "\\eb23"});
  Codicon2.mute = new Codicon2("mute", {character: "\\eb24"});
  Codicon2.noNewline = new Codicon2("no-newline", {character: "\\eb25"});
  Codicon2.note = new Codicon2("note", {character: "\\eb26"});
  Codicon2.octoface = new Codicon2("octoface", {character: "\\eb27"});
  Codicon2.openPreview = new Codicon2("open-preview", {character: "\\eb28"});
  Codicon2.package_ = new Codicon2("package", {character: "\\eb29"});
  Codicon2.paintcan = new Codicon2("paintcan", {character: "\\eb2a"});
  Codicon2.pin = new Codicon2("pin", {character: "\\eb2b"});
  Codicon2.play = new Codicon2("play", {character: "\\eb2c"});
  Codicon2.run = new Codicon2("run", {character: "\\eb2c"});
  Codicon2.plug = new Codicon2("plug", {character: "\\eb2d"});
  Codicon2.preserveCase = new Codicon2("preserve-case", {character: "\\eb2e"});
  Codicon2.preview = new Codicon2("preview", {character: "\\eb2f"});
  Codicon2.project = new Codicon2("project", {character: "\\eb30"});
  Codicon2.pulse = new Codicon2("pulse", {character: "\\eb31"});
  Codicon2.question = new Codicon2("question", {character: "\\eb32"});
  Codicon2.quote = new Codicon2("quote", {character: "\\eb33"});
  Codicon2.radioTower = new Codicon2("radio-tower", {character: "\\eb34"});
  Codicon2.reactions = new Codicon2("reactions", {character: "\\eb35"});
  Codicon2.references = new Codicon2("references", {character: "\\eb36"});
  Codicon2.refresh = new Codicon2("refresh", {character: "\\eb37"});
  Codicon2.regex = new Codicon2("regex", {character: "\\eb38"});
  Codicon2.remoteExplorer = new Codicon2("remote-explorer", {character: "\\eb39"});
  Codicon2.remote = new Codicon2("remote", {character: "\\eb3a"});
  Codicon2.remove = new Codicon2("remove", {character: "\\eb3b"});
  Codicon2.replaceAll = new Codicon2("replace-all", {character: "\\eb3c"});
  Codicon2.replace = new Codicon2("replace", {character: "\\eb3d"});
  Codicon2.repoClone = new Codicon2("repo-clone", {character: "\\eb3e"});
  Codicon2.repoForcePush = new Codicon2("repo-force-push", {character: "\\eb3f"});
  Codicon2.repoPull = new Codicon2("repo-pull", {character: "\\eb40"});
  Codicon2.repoPush = new Codicon2("repo-push", {character: "\\eb41"});
  Codicon2.report = new Codicon2("report", {character: "\\eb42"});
  Codicon2.requestChanges = new Codicon2("request-changes", {character: "\\eb43"});
  Codicon2.rocket = new Codicon2("rocket", {character: "\\eb44"});
  Codicon2.rootFolderOpened = new Codicon2("root-folder-opened", {character: "\\eb45"});
  Codicon2.rootFolder = new Codicon2("root-folder", {character: "\\eb46"});
  Codicon2.rss = new Codicon2("rss", {character: "\\eb47"});
  Codicon2.ruby = new Codicon2("ruby", {character: "\\eb48"});
  Codicon2.saveAll = new Codicon2("save-all", {character: "\\eb49"});
  Codicon2.saveAs = new Codicon2("save-as", {character: "\\eb4a"});
  Codicon2.save = new Codicon2("save", {character: "\\eb4b"});
  Codicon2.screenFull = new Codicon2("screen-full", {character: "\\eb4c"});
  Codicon2.screenNormal = new Codicon2("screen-normal", {character: "\\eb4d"});
  Codicon2.searchStop = new Codicon2("search-stop", {character: "\\eb4e"});
  Codicon2.server = new Codicon2("server", {character: "\\eb50"});
  Codicon2.settingsGear = new Codicon2("settings-gear", {character: "\\eb51"});
  Codicon2.settings = new Codicon2("settings", {character: "\\eb52"});
  Codicon2.shield = new Codicon2("shield", {character: "\\eb53"});
  Codicon2.smiley = new Codicon2("smiley", {character: "\\eb54"});
  Codicon2.sortPrecedence = new Codicon2("sort-precedence", {character: "\\eb55"});
  Codicon2.splitHorizontal = new Codicon2("split-horizontal", {character: "\\eb56"});
  Codicon2.splitVertical = new Codicon2("split-vertical", {character: "\\eb57"});
  Codicon2.squirrel = new Codicon2("squirrel", {character: "\\eb58"});
  Codicon2.starFull = new Codicon2("star-full", {character: "\\eb59"});
  Codicon2.starHalf = new Codicon2("star-half", {character: "\\eb5a"});
  Codicon2.symbolClass = new Codicon2("symbol-class", {character: "\\eb5b"});
  Codicon2.symbolColor = new Codicon2("symbol-color", {character: "\\eb5c"});
  Codicon2.symbolConstant = new Codicon2("symbol-constant", {character: "\\eb5d"});
  Codicon2.symbolEnumMember = new Codicon2("symbol-enum-member", {character: "\\eb5e"});
  Codicon2.symbolField = new Codicon2("symbol-field", {character: "\\eb5f"});
  Codicon2.symbolFile = new Codicon2("symbol-file", {character: "\\eb60"});
  Codicon2.symbolInterface = new Codicon2("symbol-interface", {character: "\\eb61"});
  Codicon2.symbolKeyword = new Codicon2("symbol-keyword", {character: "\\eb62"});
  Codicon2.symbolMisc = new Codicon2("symbol-misc", {character: "\\eb63"});
  Codicon2.symbolOperator = new Codicon2("symbol-operator", {character: "\\eb64"});
  Codicon2.symbolProperty = new Codicon2("symbol-property", {character: "\\eb65"});
  Codicon2.wrench = new Codicon2("wrench", {character: "\\eb65"});
  Codicon2.wrenchSubaction = new Codicon2("wrench-subaction", {character: "\\eb65"});
  Codicon2.symbolSnippet = new Codicon2("symbol-snippet", {character: "\\eb66"});
  Codicon2.tasklist = new Codicon2("tasklist", {character: "\\eb67"});
  Codicon2.telescope = new Codicon2("telescope", {character: "\\eb68"});
  Codicon2.textSize = new Codicon2("text-size", {character: "\\eb69"});
  Codicon2.threeBars = new Codicon2("three-bars", {character: "\\eb6a"});
  Codicon2.thumbsdown = new Codicon2("thumbsdown", {character: "\\eb6b"});
  Codicon2.thumbsup = new Codicon2("thumbsup", {character: "\\eb6c"});
  Codicon2.tools = new Codicon2("tools", {character: "\\eb6d"});
  Codicon2.triangleDown = new Codicon2("triangle-down", {character: "\\eb6e"});
  Codicon2.triangleLeft = new Codicon2("triangle-left", {character: "\\eb6f"});
  Codicon2.triangleRight = new Codicon2("triangle-right", {character: "\\eb70"});
  Codicon2.triangleUp = new Codicon2("triangle-up", {character: "\\eb71"});
  Codicon2.twitter = new Codicon2("twitter", {character: "\\eb72"});
  Codicon2.unfold = new Codicon2("unfold", {character: "\\eb73"});
  Codicon2.unlock = new Codicon2("unlock", {character: "\\eb74"});
  Codicon2.unmute = new Codicon2("unmute", {character: "\\eb75"});
  Codicon2.unverified = new Codicon2("unverified", {character: "\\eb76"});
  Codicon2.verified = new Codicon2("verified", {character: "\\eb77"});
  Codicon2.versions = new Codicon2("versions", {character: "\\eb78"});
  Codicon2.vmActive = new Codicon2("vm-active", {character: "\\eb79"});
  Codicon2.vmOutline = new Codicon2("vm-outline", {character: "\\eb7a"});
  Codicon2.vmRunning = new Codicon2("vm-running", {character: "\\eb7b"});
  Codicon2.watch = new Codicon2("watch", {character: "\\eb7c"});
  Codicon2.whitespace = new Codicon2("whitespace", {character: "\\eb7d"});
  Codicon2.wholeWord = new Codicon2("whole-word", {character: "\\eb7e"});
  Codicon2.window = new Codicon2("window", {character: "\\eb7f"});
  Codicon2.wordWrap = new Codicon2("word-wrap", {character: "\\eb80"});
  Codicon2.zoomIn = new Codicon2("zoom-in", {character: "\\eb81"});
  Codicon2.zoomOut = new Codicon2("zoom-out", {character: "\\eb82"});
  Codicon2.listFilter = new Codicon2("list-filter", {character: "\\eb83"});
  Codicon2.listFlat = new Codicon2("list-flat", {character: "\\eb84"});
  Codicon2.listSelection = new Codicon2("list-selection", {character: "\\eb85"});
  Codicon2.selection = new Codicon2("selection", {character: "\\eb85"});
  Codicon2.listTree = new Codicon2("list-tree", {character: "\\eb86"});
  Codicon2.debugBreakpointFunctionUnverified = new Codicon2("debug-breakpoint-function-unverified", {character: "\\eb87"});
  Codicon2.debugBreakpointFunction = new Codicon2("debug-breakpoint-function", {character: "\\eb88"});
  Codicon2.debugBreakpointFunctionDisabled = new Codicon2("debug-breakpoint-function-disabled", {character: "\\eb88"});
  Codicon2.debugStackframeActive = new Codicon2("debug-stackframe-active", {character: "\\eb89"});
  Codicon2.debugStackframeDot = new Codicon2("debug-stackframe-dot", {character: "\\eb8a"});
  Codicon2.debugStackframe = new Codicon2("debug-stackframe", {character: "\\eb8b"});
  Codicon2.debugStackframeFocused = new Codicon2("debug-stackframe-focused", {character: "\\eb8b"});
  Codicon2.debugBreakpointUnsupported = new Codicon2("debug-breakpoint-unsupported", {character: "\\eb8c"});
  Codicon2.symbolString = new Codicon2("symbol-string", {character: "\\eb8d"});
  Codicon2.debugReverseContinue = new Codicon2("debug-reverse-continue", {character: "\\eb8e"});
  Codicon2.debugStepBack = new Codicon2("debug-step-back", {character: "\\eb8f"});
  Codicon2.debugRestartFrame = new Codicon2("debug-restart-frame", {character: "\\eb90"});
  Codicon2.callIncoming = new Codicon2("call-incoming", {character: "\\eb92"});
  Codicon2.callOutgoing = new Codicon2("call-outgoing", {character: "\\eb93"});
  Codicon2.menu = new Codicon2("menu", {character: "\\eb94"});
  Codicon2.expandAll = new Codicon2("expand-all", {character: "\\eb95"});
  Codicon2.feedback = new Codicon2("feedback", {character: "\\eb96"});
  Codicon2.groupByRefType = new Codicon2("group-by-ref-type", {character: "\\eb97"});
  Codicon2.ungroupByRefType = new Codicon2("ungroup-by-ref-type", {character: "\\eb98"});
  Codicon2.account = new Codicon2("account", {character: "\\eb99"});
  Codicon2.bellDot = new Codicon2("bell-dot", {character: "\\eb9a"});
  Codicon2.debugConsole = new Codicon2("debug-console", {character: "\\eb9b"});
  Codicon2.library = new Codicon2("library", {character: "\\eb9c"});
  Codicon2.output = new Codicon2("output", {character: "\\eb9d"});
  Codicon2.runAll = new Codicon2("run-all", {character: "\\eb9e"});
  Codicon2.syncIgnored = new Codicon2("sync-ignored", {character: "\\eb9f"});
  Codicon2.pinned = new Codicon2("pinned", {character: "\\eba0"});
  Codicon2.githubInverted = new Codicon2("github-inverted", {character: "\\eba1"});
  Codicon2.debugAlt = new Codicon2("debug-alt", {character: "\\eb91"});
  Codicon2.serverProcess = new Codicon2("server-process", {character: "\\eba2"});
  Codicon2.serverEnvironment = new Codicon2("server-environment", {character: "\\eba3"});
  Codicon2.pass = new Codicon2("pass", {character: "\\eba4"});
  Codicon2.stopCircle = new Codicon2("stop-circle", {character: "\\eba5"});
  Codicon2.playCircle = new Codicon2("play-circle", {character: "\\eba6"});
  Codicon2.record = new Codicon2("record", {character: "\\eba7"});
  Codicon2.debugAltSmall = new Codicon2("debug-alt-small", {character: "\\eba8"});
  Codicon2.vmConnect = new Codicon2("vm-connect", {character: "\\eba9"});
  Codicon2.cloud = new Codicon2("cloud", {character: "\\ebaa"});
  Codicon2.merge = new Codicon2("merge", {character: "\\ebab"});
})(Codicon || (Codicon = {}));
var renderCodiconsRegex = /(\\)?\$\((([a-z0-9\-]+?)(?:~([a-z0-9\-]*?))?)\)/gi;
function renderCodicons(text) {
  return text.replace(renderCodiconsRegex, (_23, escaped, codicon, name, animation) => {
    return escaped ? `$(${codicon})` : `<span class="codicon codicon-${name}${animation ? ` codicon-animation-${animation}` : ""}"></span>`;
  });
}
var stripCodiconsRegex = /(\s)?(\\)?\$\([a-z0-9\-]+?(?:~[a-z0-9\-]*?)?\)(\s)?/gi;
function stripCodicons(text) {
  if (text.indexOf(codiconStartMarker) === -1) {
    return text;
  }
  return text.replace(stripCodiconsRegex, (match2, preWhitespace, escaped, postWhitespace) => escaped ? match2 : preWhitespace || postWhitespace || "");
}
var LanguageIdentifier = class {
  constructor(language, id3) {
    this.language = language;
    this.id = id3;
  }
};
var TokenMetadata = class {
  static getLanguageId(metadata) {
    return (metadata & 255) >>> 0;
  }
  static getTokenType(metadata) {
    return (metadata & 1792) >>> 8;
  }
  static getFontStyle(metadata) {
    return (metadata & 14336) >>> 11;
  }
  static getForeground(metadata) {
    return (metadata & 8372224) >>> 14;
  }
  static getBackground(metadata) {
    return (metadata & 4286578688) >>> 23;
  }
  static getClassNameFromMetadata(metadata) {
    let foreground2 = this.getForeground(metadata);
    let className = "mtk" + foreground2;
    let fontStyle = this.getFontStyle(metadata);
    if (fontStyle & 1) {
      className += " mtki";
    }
    if (fontStyle & 2) {
      className += " mtkb";
    }
    if (fontStyle & 4) {
      className += " mtku";
    }
    return className;
  }
  static getInlineStyleFromMetadata(metadata, colorMap) {
    const foreground2 = this.getForeground(metadata);
    const fontStyle = this.getFontStyle(metadata);
    let result = `color: ${colorMap[foreground2]};`;
    if (fontStyle & 1) {
      result += "font-style: italic;";
    }
    if (fontStyle & 2) {
      result += "font-weight: bold;";
    }
    if (fontStyle & 4) {
      result += "text-decoration: underline;";
    }
    return result;
  }
};
var completionKindToCssClass = function() {
  let data2 = Object.create(null);
  data2[0] = "symbol-method";
  data2[1] = "symbol-function";
  data2[2] = "symbol-constructor";
  data2[3] = "symbol-field";
  data2[4] = "symbol-variable";
  data2[5] = "symbol-class";
  data2[6] = "symbol-struct";
  data2[7] = "symbol-interface";
  data2[8] = "symbol-module";
  data2[9] = "symbol-property";
  data2[10] = "symbol-event";
  data2[11] = "symbol-operator";
  data2[12] = "symbol-unit";
  data2[13] = "symbol-value";
  data2[14] = "symbol-constant";
  data2[15] = "symbol-enum";
  data2[16] = "symbol-enum-member";
  data2[17] = "symbol-keyword";
  data2[27] = "symbol-snippet";
  data2[18] = "symbol-text";
  data2[19] = "symbol-color";
  data2[20] = "symbol-file";
  data2[21] = "symbol-reference";
  data2[22] = "symbol-customcolor";
  data2[23] = "symbol-folder";
  data2[24] = "symbol-type-parameter";
  data2[25] = "account";
  data2[26] = "issues";
  return function(kind) {
    const name = data2[kind];
    let codicon = name && iconRegistry.get(name);
    if (!codicon) {
      console.info("No codicon found for CompletionItemKind " + kind);
      codicon = Codicon.symbolProperty;
    }
    return codicon.classNames;
  };
}();
var completionKindFromString = function() {
  let data2 = Object.create(null);
  data2["method"] = 0;
  data2["function"] = 1;
  data2["constructor"] = 2;
  data2["field"] = 3;
  data2["variable"] = 4;
  data2["class"] = 5;
  data2["struct"] = 6;
  data2["interface"] = 7;
  data2["module"] = 8;
  data2["property"] = 9;
  data2["event"] = 10;
  data2["operator"] = 11;
  data2["unit"] = 12;
  data2["value"] = 13;
  data2["constant"] = 14;
  data2["enum"] = 15;
  data2["enum-member"] = 16;
  data2["enumMember"] = 16;
  data2["keyword"] = 17;
  data2["snippet"] = 27;
  data2["text"] = 18;
  data2["color"] = 19;
  data2["file"] = 20;
  data2["reference"] = 21;
  data2["customcolor"] = 22;
  data2["folder"] = 23;
  data2["type-parameter"] = 24;
  data2["typeParameter"] = 24;
  data2["account"] = 25;
  data2["issue"] = 26;
  return function(value, strict) {
    let res = data2[value];
    if (typeof res === "undefined" && !strict) {
      res = 9;
    }
    return res;
  };
}();
var SignatureHelpTriggerKind$1;
(function(SignatureHelpTriggerKind2) {
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["Invoke"] = 1] = "Invoke";
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["TriggerCharacter"] = 2] = "TriggerCharacter";
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind$1 || (SignatureHelpTriggerKind$1 = {}));
var DocumentHighlightKind$1;
(function(DocumentHighlightKind2) {
  DocumentHighlightKind2[DocumentHighlightKind2["Text"] = 0] = "Text";
  DocumentHighlightKind2[DocumentHighlightKind2["Read"] = 1] = "Read";
  DocumentHighlightKind2[DocumentHighlightKind2["Write"] = 2] = "Write";
})(DocumentHighlightKind$1 || (DocumentHighlightKind$1 = {}));
var SymbolKinds;
(function(SymbolKinds2) {
  const byName = new Map();
  byName.set("file", 0);
  byName.set("module", 1);
  byName.set("namespace", 2);
  byName.set("package", 3);
  byName.set("class", 4);
  byName.set("method", 5);
  byName.set("property", 6);
  byName.set("field", 7);
  byName.set("constructor", 8);
  byName.set("enum", 9);
  byName.set("interface", 10);
  byName.set("function", 11);
  byName.set("variable", 12);
  byName.set("constant", 13);
  byName.set("string", 14);
  byName.set("number", 15);
  byName.set("boolean", 16);
  byName.set("array", 17);
  byName.set("object", 18);
  byName.set("key", 19);
  byName.set("null", 20);
  byName.set("enum-member", 21);
  byName.set("struct", 22);
  byName.set("event", 23);
  byName.set("operator", 24);
  byName.set("type-parameter", 25);
  const byKind = new Map();
  byKind.set(0, "file");
  byKind.set(1, "module");
  byKind.set(2, "namespace");
  byKind.set(3, "package");
  byKind.set(4, "class");
  byKind.set(5, "method");
  byKind.set(6, "property");
  byKind.set(7, "field");
  byKind.set(8, "constructor");
  byKind.set(9, "enum");
  byKind.set(10, "interface");
  byKind.set(11, "function");
  byKind.set(12, "variable");
  byKind.set(13, "constant");
  byKind.set(14, "string");
  byKind.set(15, "number");
  byKind.set(16, "boolean");
  byKind.set(17, "array");
  byKind.set(18, "object");
  byKind.set(19, "key");
  byKind.set(20, "null");
  byKind.set(21, "enum-member");
  byKind.set(22, "struct");
  byKind.set(23, "event");
  byKind.set(24, "operator");
  byKind.set(25, "type-parameter");
  function fromString(value) {
    return byName.get(value);
  }
  SymbolKinds2.fromString = fromString;
  function toString5(kind) {
    return byKind.get(kind);
  }
  SymbolKinds2.toString = toString5;
  function toCssClassName(kind, inline) {
    const symbolName = byKind.get(kind);
    let codicon = symbolName && iconRegistry.get("symbol-" + symbolName);
    if (!codicon) {
      console.info("No codicon found for SymbolKind " + kind);
      codicon = Codicon.symbolProperty;
    }
    return `${inline ? "inline" : "block"} ${codicon.classNames}`;
  }
  SymbolKinds2.toCssClassName = toCssClassName;
})(SymbolKinds || (SymbolKinds = {}));
var FoldingRangeKind = class {
  constructor(value) {
    this.value = value;
  }
};
FoldingRangeKind.Comment = new FoldingRangeKind("comment");
FoldingRangeKind.Imports = new FoldingRangeKind("imports");
FoldingRangeKind.Region = new FoldingRangeKind("region");
var ReferenceProviderRegistry = new LanguageFeatureRegistry();
var RenameProviderRegistry = new LanguageFeatureRegistry();
var CompletionProviderRegistry = new LanguageFeatureRegistry();
var SignatureHelpProviderRegistry = new LanguageFeatureRegistry();
var HoverProviderRegistry = new LanguageFeatureRegistry();
var DocumentSymbolProviderRegistry = new LanguageFeatureRegistry();
var DocumentHighlightProviderRegistry = new LanguageFeatureRegistry();
var OnTypeRenameProviderRegistry = new LanguageFeatureRegistry();
var DefinitionProviderRegistry = new LanguageFeatureRegistry();
var DeclarationProviderRegistry = new LanguageFeatureRegistry();
var ImplementationProviderRegistry = new LanguageFeatureRegistry();
var TypeDefinitionProviderRegistry = new LanguageFeatureRegistry();
var CodeLensProviderRegistry = new LanguageFeatureRegistry();
var CodeActionProviderRegistry = new LanguageFeatureRegistry();
var DocumentFormattingEditProviderRegistry = new LanguageFeatureRegistry();
var DocumentRangeFormattingEditProviderRegistry = new LanguageFeatureRegistry();
var OnTypeFormattingEditProviderRegistry = new LanguageFeatureRegistry();
var LinkProviderRegistry = new LanguageFeatureRegistry();
var ColorProviderRegistry = new LanguageFeatureRegistry();
var SelectionRangeRegistry = new LanguageFeatureRegistry();
var FoldingRangeProviderRegistry = new LanguageFeatureRegistry();
var DocumentSemanticTokensProviderRegistry = new LanguageFeatureRegistry();
var DocumentRangeSemanticTokensProviderRegistry = new LanguageFeatureRegistry();
var TokenizationRegistry = new TokenizationRegistryImpl();
var NullStateImpl = class {
  clone() {
    return this;
  }
  equals(other) {
    return this === other;
  }
};
var NULL_STATE = new NullStateImpl();
var NULL_MODE_ID = "vs.editor.nullMode";
var NULL_LANGUAGE_IDENTIFIER = new LanguageIdentifier(NULL_MODE_ID, 0);
function nullTokenize(modeId, buffer, state, deltaOffset) {
  return new TokenizationResult([new Token(deltaOffset, "", modeId)], state);
}
function nullTokenize2(languageId, buffer, state, deltaOffset) {
  let tokens = new Uint32Array(2);
  tokens[0] = deltaOffset;
  tokens[1] = (languageId << 0 | 0 << 8 | 0 << 11 | 1 << 14 | 2 << 23) >>> 0;
  return new TokenizationResult2(tokens, state === null ? NULL_STATE : state);
}
var ID_EDITOR_WORKER_SERVICE = "editorWorkerService";
var IEditorWorkerService = createDecorator(ID_EDITOR_WORKER_SERVICE);
var ITextModelService = createDecorator("textModelService");
var INITIALIZE = "$initialize";
var webWorkerWarningLogged = false;
function logOnceWebWorkerWarning(err) {
  if (!isWeb2) {
    return;
  }
  if (!webWorkerWarningLogged) {
    webWorkerWarningLogged = true;
    console.warn("Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/Microsoft/monaco-editor#faq");
  }
  console.warn(err.message);
}
var SimpleWorkerProtocol = class {
  constructor(handler) {
    this._workerId = -1;
    this._handler = handler;
    this._lastSentReq = 0;
    this._pendingReplies = Object.create(null);
  }
  setWorkerId(workerId) {
    this._workerId = workerId;
  }
  sendMessage(method, args) {
    let req = String(++this._lastSentReq);
    return new Promise((resolve2, reject) => {
      this._pendingReplies[req] = {
        resolve: resolve2,
        reject
      };
      this._send({
        vsWorker: this._workerId,
        req,
        method,
        args
      });
    });
  }
  handleMessage(message) {
    if (!message || !message.vsWorker) {
      return;
    }
    if (this._workerId !== -1 && message.vsWorker !== this._workerId) {
      return;
    }
    this._handleMessage(message);
  }
  _handleMessage(msg) {
    if (msg.seq) {
      let replyMessage = msg;
      if (!this._pendingReplies[replyMessage.seq]) {
        console.warn("Got reply to unknown seq");
        return;
      }
      let reply = this._pendingReplies[replyMessage.seq];
      delete this._pendingReplies[replyMessage.seq];
      if (replyMessage.err) {
        let err = replyMessage.err;
        if (replyMessage.err.$isError) {
          err = new Error();
          err.name = replyMessage.err.name;
          err.message = replyMessage.err.message;
          err.stack = replyMessage.err.stack;
        }
        reply.reject(err);
        return;
      }
      reply.resolve(replyMessage.res);
      return;
    }
    let requestMessage = msg;
    let req = requestMessage.req;
    let result = this._handler.handleMessage(requestMessage.method, requestMessage.args);
    result.then((r3) => {
      this._send({
        vsWorker: this._workerId,
        seq: req,
        res: r3,
        err: void 0
      });
    }, (e2) => {
      if (e2.detail instanceof Error) {
        e2.detail = transformErrorForSerialization(e2.detail);
      }
      this._send({
        vsWorker: this._workerId,
        seq: req,
        res: void 0,
        err: transformErrorForSerialization(e2)
      });
    });
  }
  _send(msg) {
    let transfer = [];
    if (msg.req) {
      const m2 = msg;
      for (let i3 = 0; i3 < m2.args.length; i3++) {
        if (m2.args[i3] instanceof ArrayBuffer) {
          transfer.push(m2.args[i3]);
        }
      }
    } else {
      const m2 = msg;
      if (m2.res instanceof ArrayBuffer) {
        transfer.push(m2.res);
      }
    }
    this._handler.sendMessage(msg, transfer);
  }
};
var SimpleWorkerClient = class extends Disposable {
  constructor(workerFactory, moduleId, host) {
    super();
    let lazyProxyReject = null;
    this._worker = this._register(workerFactory.create("vs/base/common/worker/simpleWorker", (msg) => {
      this._protocol.handleMessage(msg);
    }, (err) => {
      if (lazyProxyReject) {
        lazyProxyReject(err);
      }
    }));
    this._protocol = new SimpleWorkerProtocol({
      sendMessage: (msg, transfer) => {
        this._worker.postMessage(msg, transfer);
      },
      handleMessage: (method, args) => {
        if (typeof host[method] !== "function") {
          return Promise.reject(new Error("Missing method " + method + " on main thread host."));
        }
        try {
          return Promise.resolve(host[method].apply(host, args));
        } catch (e2) {
          return Promise.reject(e2);
        }
      }
    });
    this._protocol.setWorkerId(this._worker.getId());
    let loaderConfiguration = null;
    if (typeof self.require !== "undefined" && typeof self.require.getConfig === "function") {
      loaderConfiguration = self.require.getConfig();
    } else if (typeof self.requirejs !== "undefined") {
      loaderConfiguration = self.requirejs.s.contexts._.config;
    }
    const hostMethods = getAllMethodNames(host);
    this._onModuleLoaded = this._protocol.sendMessage(INITIALIZE, [
      this._worker.getId(),
      JSON.parse(JSON.stringify(loaderConfiguration)),
      moduleId,
      hostMethods
    ]);
    const proxyMethodRequest = (method, args) => {
      return this._request(method, args);
    };
    this._lazyProxy = new Promise((resolve2, reject) => {
      lazyProxyReject = reject;
      this._onModuleLoaded.then((availableMethods) => {
        resolve2(createProxyObject(availableMethods, proxyMethodRequest));
      }, (e2) => {
        reject(e2);
        this._onError("Worker failed to load " + moduleId, e2);
      });
    });
  }
  getProxyObject() {
    return this._lazyProxy;
  }
  _request(method, args) {
    return new Promise((resolve2, reject) => {
      this._onModuleLoaded.then(() => {
        this._protocol.sendMessage(method, args).then(resolve2, reject);
      }, reject);
    });
  }
  _onError(message, error2) {
    console.error(message);
    console.info(error2);
  }
};
function getWorker(workerId, label2) {
  if (globals.MonacoEnvironment) {
    if (typeof globals.MonacoEnvironment.getWorker === "function") {
      return globals.MonacoEnvironment.getWorker(workerId, label2);
    }
    if (typeof globals.MonacoEnvironment.getWorkerUrl === "function") {
      return new Worker(globals.MonacoEnvironment.getWorkerUrl(workerId, label2));
    }
  }
  throw new Error(`You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker`);
}
function isPromiseLike(obj) {
  if (typeof obj.then === "function") {
    return true;
  }
  return false;
}
var WebWorker = class {
  constructor(moduleId, id3, label2, onMessageCallback, onErrorCallback) {
    this.id = id3;
    const workerOrPromise = getWorker("workerMain.js", label2);
    if (isPromiseLike(workerOrPromise)) {
      this.worker = workerOrPromise;
    } else {
      this.worker = Promise.resolve(workerOrPromise);
    }
    this.postMessage(moduleId, []);
    this.worker.then((w2) => {
      w2.onmessage = function(ev) {
        onMessageCallback(ev.data);
      };
      w2.onmessageerror = onErrorCallback;
      if (typeof w2.addEventListener === "function") {
        w2.addEventListener("error", onErrorCallback);
      }
    });
  }
  getId() {
    return this.id;
  }
  postMessage(message, transfer) {
    if (this.worker) {
      this.worker.then((w2) => w2.postMessage(message, transfer));
    }
  }
  dispose() {
    if (this.worker) {
      this.worker.then((w2) => w2.terminate());
    }
    this.worker = null;
  }
};
var DefaultWorkerFactory = class {
  constructor(label2) {
    this._label = label2;
    this._webWorkerFailedBeforeError = false;
  }
  create(moduleId, onMessageCallback, onErrorCallback) {
    let workerId = ++DefaultWorkerFactory.LAST_WORKER_ID;
    if (this._webWorkerFailedBeforeError) {
      throw this._webWorkerFailedBeforeError;
    }
    return new WebWorker(moduleId, workerId, this._label || "anonymous" + workerId, onMessageCallback, (err) => {
      logOnceWebWorkerWarning(err);
      this._webWorkerFailedBeforeError = err;
      onErrorCallback(err);
    });
  }
};
DefaultWorkerFactory.LAST_WORKER_ID = 0;
var IndentAction$1;
(function(IndentAction2) {
  IndentAction2[IndentAction2["None"] = 0] = "None";
  IndentAction2[IndentAction2["Indent"] = 1] = "Indent";
  IndentAction2[IndentAction2["IndentOutdent"] = 2] = "IndentOutdent";
  IndentAction2[IndentAction2["Outdent"] = 3] = "Outdent";
})(IndentAction$1 || (IndentAction$1 = {}));
var StandardAutoClosingPairConditional = class {
  constructor(source2) {
    this.open = source2.open;
    this.close = source2.close;
    this._standardTokenMask = 0;
    if (Array.isArray(source2.notIn)) {
      for (let i3 = 0, len2 = source2.notIn.length; i3 < len2; i3++) {
        const notIn = source2.notIn[i3];
        switch (notIn) {
          case "string":
            this._standardTokenMask |= 2;
            break;
          case "comment":
            this._standardTokenMask |= 1;
            break;
          case "regex":
            this._standardTokenMask |= 4;
            break;
        }
      }
    }
  }
  isOK(standardToken) {
    return (this._standardTokenMask & standardToken) === 0;
  }
};
function createScopedLineTokens(context2, offset2) {
  let tokenCount = context2.getCount();
  let tokenIndex = context2.findTokenIndexAtOffset(offset2);
  let desiredLanguageId = context2.getLanguageId(tokenIndex);
  let lastTokenIndex = tokenIndex;
  while (lastTokenIndex + 1 < tokenCount && context2.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) {
    lastTokenIndex++;
  }
  let firstTokenIndex = tokenIndex;
  while (firstTokenIndex > 0 && context2.getLanguageId(firstTokenIndex - 1) === desiredLanguageId) {
    firstTokenIndex--;
  }
  return new ScopedLineTokens(context2, desiredLanguageId, firstTokenIndex, lastTokenIndex + 1, context2.getStartOffset(firstTokenIndex), context2.getEndOffset(lastTokenIndex));
}
var ScopedLineTokens = class {
  constructor(actual, languageId, firstTokenIndex, lastTokenIndex, firstCharOffset, lastCharOffset) {
    this._actual = actual;
    this.languageId = languageId;
    this._firstTokenIndex = firstTokenIndex;
    this._lastTokenIndex = lastTokenIndex;
    this.firstCharOffset = firstCharOffset;
    this._lastCharOffset = lastCharOffset;
  }
  getLineContent() {
    const actualLineContent = this._actual.getLineContent();
    return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset);
  }
  getActualLineContentBefore(offset2) {
    const actualLineContent = this._actual.getLineContent();
    return actualLineContent.substring(0, this.firstCharOffset + offset2);
  }
  getTokenCount() {
    return this._lastTokenIndex - this._firstTokenIndex;
  }
  findTokenIndexAtOffset(offset2) {
    return this._actual.findTokenIndexAtOffset(offset2 + this.firstCharOffset) - this._firstTokenIndex;
  }
  getStandardTokenType(tokenIndex) {
    return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex);
  }
};
function ignoreBracketsInToken(standardTokenType) {
  return (standardTokenType & 7) !== 0;
}
var CharacterPairSupport = class {
  constructor(config2) {
    if (config2.autoClosingPairs) {
      this._autoClosingPairs = config2.autoClosingPairs.map((el) => new StandardAutoClosingPairConditional(el));
    } else if (config2.brackets) {
      this._autoClosingPairs = config2.brackets.map((b2) => new StandardAutoClosingPairConditional({open: b2[0], close: b2[1]}));
    } else {
      this._autoClosingPairs = [];
    }
    if (config2.__electricCharacterSupport && config2.__electricCharacterSupport.docComment) {
      const docComment = config2.__electricCharacterSupport.docComment;
      this._autoClosingPairs.push(new StandardAutoClosingPairConditional({open: docComment.open, close: docComment.close || ""}));
    }
    this._autoCloseBefore = typeof config2.autoCloseBefore === "string" ? config2.autoCloseBefore : CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED;
    this._surroundingPairs = config2.surroundingPairs || this._autoClosingPairs;
  }
  getAutoClosingPairs() {
    return this._autoClosingPairs;
  }
  getAutoCloseBeforeSet() {
    return this._autoCloseBefore;
  }
  static shouldAutoClosePair(autoClosingPair, context2, column) {
    if (context2.getTokenCount() === 0) {
      return true;
    }
    const tokenIndex = context2.findTokenIndexAtOffset(column - 2);
    const standardTokenType = context2.getStandardTokenType(tokenIndex);
    return autoClosingPair.isOK(standardTokenType);
  }
  getSurroundingPairs() {
    return this._surroundingPairs;
  }
};
CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED = ";:.,=}])> \n	";
var _platformTextDecoder;
function getPlatformTextDecoder() {
  if (!_platformTextDecoder) {
    _platformTextDecoder = new TextDecoder(isLittleEndian() ? "UTF-16LE" : "UTF-16BE");
  }
  return _platformTextDecoder;
}
var hasTextDecoder$1 = typeof TextDecoder !== "undefined";
var createStringBuilder;
var decodeUTF16LE;
if (hasTextDecoder$1) {
  createStringBuilder = (capacity) => new StringBuilder(capacity);
  decodeUTF16LE = standardDecodeUTF16LE;
} else {
  createStringBuilder = (capacity) => new CompatStringBuilder();
  decodeUTF16LE = compatDecodeUTF16LE;
}
function standardDecodeUTF16LE(source2, offset2, len2) {
  const view = new Uint16Array(source2.buffer, offset2, len2);
  return getPlatformTextDecoder().decode(view);
}
function compatDecodeUTF16LE(source2, offset2, len2) {
  let result = [];
  let resultLen = 0;
  for (let i3 = 0; i3 < len2; i3++) {
    const charCode = readUInt16LE(source2, offset2);
    offset2 += 2;
    result[resultLen++] = String.fromCharCode(charCode);
  }
  return result.join("");
}
var StringBuilder = class {
  constructor(capacity) {
    this._capacity = capacity | 0;
    this._buffer = new Uint16Array(this._capacity);
    this._completedStrings = null;
    this._bufferLength = 0;
  }
  reset() {
    this._completedStrings = null;
    this._bufferLength = 0;
  }
  build() {
    if (this._completedStrings !== null) {
      this._flushBuffer();
      return this._completedStrings.join("");
    }
    return this._buildBuffer();
  }
  _buildBuffer() {
    if (this._bufferLength === 0) {
      return "";
    }
    const view = new Uint16Array(this._buffer.buffer, 0, this._bufferLength);
    return getPlatformTextDecoder().decode(view);
  }
  _flushBuffer() {
    const bufferString = this._buildBuffer();
    this._bufferLength = 0;
    if (this._completedStrings === null) {
      this._completedStrings = [bufferString];
    } else {
      this._completedStrings[this._completedStrings.length] = bufferString;
    }
  }
  write1(charCode) {
    const remainingSpace = this._capacity - this._bufferLength;
    if (remainingSpace <= 1) {
      if (remainingSpace === 0 || isHighSurrogate(charCode)) {
        this._flushBuffer();
      }
    }
    this._buffer[this._bufferLength++] = charCode;
  }
  appendASCII(charCode) {
    if (this._bufferLength === this._capacity) {
      this._flushBuffer();
    }
    this._buffer[this._bufferLength++] = charCode;
  }
  appendASCIIString(str) {
    const strLen = str.length;
    if (this._bufferLength + strLen >= this._capacity) {
      this._flushBuffer();
      this._completedStrings[this._completedStrings.length] = str;
      return;
    }
    for (let i3 = 0; i3 < strLen; i3++) {
      this._buffer[this._bufferLength++] = str.charCodeAt(i3);
    }
  }
};
var CompatStringBuilder = class {
  constructor() {
    this._pieces = [];
    this._piecesLen = 0;
  }
  reset() {
    this._pieces = [];
    this._piecesLen = 0;
  }
  build() {
    return this._pieces.join("");
  }
  write1(charCode) {
    this._pieces[this._piecesLen++] = String.fromCharCode(charCode);
  }
  appendASCII(charCode) {
    this._pieces[this._piecesLen++] = String.fromCharCode(charCode);
  }
  appendASCIIString(str) {
    this._pieces[this._piecesLen++] = str;
  }
};
var RichEditBracket = class {
  constructor(languageIdentifier, index3, open2, close, forwardRegex, reversedRegex) {
    this.languageIdentifier = languageIdentifier;
    this.index = index3;
    this.open = open2;
    this.close = close;
    this.forwardRegex = forwardRegex;
    this.reversedRegex = reversedRegex;
    this._openSet = RichEditBracket._toSet(this.open);
    this._closeSet = RichEditBracket._toSet(this.close);
  }
  isOpen(text) {
    return this._openSet.has(text);
  }
  isClose(text) {
    return this._closeSet.has(text);
  }
  static _toSet(arr) {
    const result = new Set();
    for (const element of arr) {
      result.add(element);
    }
    return result;
  }
};
function groupFuzzyBrackets(brackets) {
  const N2 = brackets.length;
  brackets = brackets.map((b2) => [b2[0].toLowerCase(), b2[1].toLowerCase()]);
  const group = [];
  for (let i3 = 0; i3 < N2; i3++) {
    group[i3] = i3;
  }
  const areOverlapping = (a2, b2) => {
    const [aOpen, aClose] = a2;
    const [bOpen, bClose] = b2;
    return aOpen === bOpen || aOpen === bClose || aClose === bOpen || aClose === bClose;
  };
  const mergeGroups = (g1, g2) => {
    const newG = Math.min(g1, g2);
    const oldG = Math.max(g1, g2);
    for (let i3 = 0; i3 < N2; i3++) {
      if (group[i3] === oldG) {
        group[i3] = newG;
      }
    }
  };
  for (let i3 = 0; i3 < N2; i3++) {
    const a2 = brackets[i3];
    for (let j = i3 + 1; j < N2; j++) {
      const b2 = brackets[j];
      if (areOverlapping(a2, b2)) {
        mergeGroups(group[i3], group[j]);
      }
    }
  }
  const result = [];
  for (let g2 = 0; g2 < N2; g2++) {
    let currentOpen = [];
    let currentClose = [];
    for (let i3 = 0; i3 < N2; i3++) {
      if (group[i3] === g2) {
        const [open2, close] = brackets[i3];
        currentOpen.push(open2);
        currentClose.push(close);
      }
    }
    if (currentOpen.length > 0) {
      result.push({
        open: currentOpen,
        close: currentClose
      });
    }
  }
  return result;
}
var RichEditBrackets = class {
  constructor(languageIdentifier, _brackets) {
    const brackets = groupFuzzyBrackets(_brackets);
    this.brackets = brackets.map((b2, index3) => {
      return new RichEditBracket(languageIdentifier, index3, b2.open, b2.close, getRegexForBracketPair(b2.open, b2.close, brackets, index3), getReversedRegexForBracketPair(b2.open, b2.close, brackets, index3));
    });
    this.forwardRegex = getRegexForBrackets(this.brackets);
    this.reversedRegex = getReversedRegexForBrackets(this.brackets);
    this.textIsBracket = {};
    this.textIsOpenBracket = {};
    this.maxBracketLength = 0;
    for (const bracket of this.brackets) {
      for (const open2 of bracket.open) {
        this.textIsBracket[open2] = bracket;
        this.textIsOpenBracket[open2] = true;
        this.maxBracketLength = Math.max(this.maxBracketLength, open2.length);
      }
      for (const close of bracket.close) {
        this.textIsBracket[close] = bracket;
        this.textIsOpenBracket[close] = false;
        this.maxBracketLength = Math.max(this.maxBracketLength, close.length);
      }
    }
  }
};
function collectSuperstrings(str, brackets, currentIndex, dest) {
  for (let i3 = 0, len2 = brackets.length; i3 < len2; i3++) {
    if (i3 === currentIndex) {
      continue;
    }
    const bracket = brackets[i3];
    for (const open2 of bracket.open) {
      if (open2.indexOf(str) >= 0) {
        dest.push(open2);
      }
    }
    for (const close of bracket.close) {
      if (close.indexOf(str) >= 0) {
        dest.push(close);
      }
    }
  }
}
function lengthcmp(a2, b2) {
  return a2.length - b2.length;
}
function unique(arr) {
  if (arr.length <= 1) {
    return arr;
  }
  const result = [];
  const seen = new Set();
  for (const element of arr) {
    if (seen.has(element)) {
      continue;
    }
    result.push(element);
    seen.add(element);
  }
  return result;
}
function getRegexForBracketPair(open2, close, brackets, currentIndex) {
  let pieces = [];
  pieces = pieces.concat(open2);
  pieces = pieces.concat(close);
  for (let i3 = 0, len2 = pieces.length; i3 < len2; i3++) {
    collectSuperstrings(pieces[i3], brackets, currentIndex, pieces);
  }
  pieces = unique(pieces);
  pieces.sort(lengthcmp);
  pieces.reverse();
  return createBracketOrRegExp(pieces);
}
function getReversedRegexForBracketPair(open2, close, brackets, currentIndex) {
  let pieces = [];
  pieces = pieces.concat(open2);
  pieces = pieces.concat(close);
  for (let i3 = 0, len2 = pieces.length; i3 < len2; i3++) {
    collectSuperstrings(pieces[i3], brackets, currentIndex, pieces);
  }
  pieces = unique(pieces);
  pieces.sort(lengthcmp);
  pieces.reverse();
  return createBracketOrRegExp(pieces.map(toReversedString));
}
function getRegexForBrackets(brackets) {
  let pieces = [];
  for (const bracket of brackets) {
    for (const open2 of bracket.open) {
      pieces.push(open2);
    }
    for (const close of bracket.close) {
      pieces.push(close);
    }
  }
  pieces = unique(pieces);
  return createBracketOrRegExp(pieces);
}
function getReversedRegexForBrackets(brackets) {
  let pieces = [];
  for (const bracket of brackets) {
    for (const open2 of bracket.open) {
      pieces.push(open2);
    }
    for (const close of bracket.close) {
      pieces.push(close);
    }
  }
  pieces = unique(pieces);
  return createBracketOrRegExp(pieces.map(toReversedString));
}
function prepareBracketForRegExp(str) {
  const insertWordBoundaries = /^[\w ]+$/.test(str);
  str = escapeRegExpCharacters(str);
  return insertWordBoundaries ? `\\b${str}\\b` : str;
}
function createBracketOrRegExp(pieces) {
  let regexStr = `(${pieces.map(prepareBracketForRegExp).join(")|(")})`;
  return createRegExp(regexStr, true);
}
var toReversedString = function() {
  function reverse(str) {
    if (hasTextDecoder$1) {
      const arr = new Uint16Array(str.length);
      let offset2 = 0;
      for (let i3 = str.length - 1; i3 >= 0; i3--) {
        arr[offset2++] = str.charCodeAt(i3);
      }
      return getPlatformTextDecoder().decode(arr);
    } else {
      let result = [], resultLen = 0;
      for (let i3 = str.length - 1; i3 >= 0; i3--) {
        result[resultLen++] = str.charAt(i3);
      }
      return result.join("");
    }
  }
  let lastInput = null;
  let lastOutput = null;
  return function toReversedString2(str) {
    if (lastInput !== str) {
      lastInput = str;
      lastOutput = reverse(lastInput);
    }
    return lastOutput;
  };
}();
var BracketsUtils = class {
  static _findPrevBracketInText(reversedBracketRegex, lineNumber, reversedText, offset2) {
    let m2 = reversedText.match(reversedBracketRegex);
    if (!m2) {
      return null;
    }
    let matchOffset = reversedText.length - (m2.index || 0);
    let matchLength = m2[0].length;
    let absoluteMatchOffset = offset2 + matchOffset;
    return new Range(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1);
  }
  static findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, startOffset, endOffset) {
    const reversedLineText = toReversedString(lineText);
    const reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset);
    return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedSubstr, startOffset);
  }
  static findNextBracketInText(bracketRegex, lineNumber, text, offset2) {
    let m2 = text.match(bracketRegex);
    if (!m2) {
      return null;
    }
    let matchOffset = m2.index || 0;
    let matchLength = m2[0].length;
    if (matchLength === 0) {
      return null;
    }
    let absoluteMatchOffset = offset2 + matchOffset;
    return new Range(lineNumber, absoluteMatchOffset + 1, lineNumber, absoluteMatchOffset + 1 + matchLength);
  }
  static findNextBracketInRange(bracketRegex, lineNumber, lineText, startOffset, endOffset) {
    const substr = lineText.substring(startOffset, endOffset);
    return this.findNextBracketInText(bracketRegex, lineNumber, substr, startOffset);
  }
};
var BracketElectricCharacterSupport = class {
  constructor(richEditBrackets) {
    this._richEditBrackets = richEditBrackets;
  }
  getElectricCharacters() {
    let result = [];
    if (this._richEditBrackets) {
      for (const bracket of this._richEditBrackets.brackets) {
        for (const close of bracket.close) {
          const lastChar = close.charAt(close.length - 1);
          result.push(lastChar);
        }
      }
    }
    result = result.filter((item, pos, array2) => {
      return array2.indexOf(item) === pos;
    });
    return result;
  }
  onElectricCharacter(character, context2, column) {
    if (!this._richEditBrackets || this._richEditBrackets.brackets.length === 0) {
      return null;
    }
    const tokenIndex = context2.findTokenIndexAtOffset(column - 1);
    if (ignoreBracketsInToken(context2.getStandardTokenType(tokenIndex))) {
      return null;
    }
    const reversedBracketRegex = this._richEditBrackets.reversedRegex;
    const text = context2.getLineContent().substring(0, column - 1) + character;
    const r3 = BracketsUtils.findPrevBracketInRange(reversedBracketRegex, 1, text, 0, text.length);
    if (!r3) {
      return null;
    }
    const bracketText = text.substring(r3.startColumn - 1, r3.endColumn - 1).toLowerCase();
    const isOpen = this._richEditBrackets.textIsOpenBracket[bracketText];
    if (isOpen) {
      return null;
    }
    const textBeforeBracket = context2.getActualLineContentBefore(r3.startColumn - 1);
    if (!/^\s*$/.test(textBeforeBracket)) {
      return null;
    }
    return {
      matchOpenBracket: bracketText
    };
  }
};
var IndentRulesSupport = class {
  constructor(indentationRules) {
    this._indentationRules = indentationRules;
  }
  shouldIncrease(text) {
    if (this._indentationRules) {
      if (this._indentationRules.increaseIndentPattern && this._indentationRules.increaseIndentPattern.test(text)) {
        return true;
      }
    }
    return false;
  }
  shouldDecrease(text) {
    if (this._indentationRules && this._indentationRules.decreaseIndentPattern && this._indentationRules.decreaseIndentPattern.test(text)) {
      return true;
    }
    return false;
  }
  shouldIndentNextLine(text) {
    if (this._indentationRules && this._indentationRules.indentNextLinePattern && this._indentationRules.indentNextLinePattern.test(text)) {
      return true;
    }
    return false;
  }
  shouldIgnore(text) {
    if (this._indentationRules && this._indentationRules.unIndentedLinePattern && this._indentationRules.unIndentedLinePattern.test(text)) {
      return true;
    }
    return false;
  }
  getIndentMetadata(text) {
    let ret = 0;
    if (this.shouldIncrease(text)) {
      ret += 1;
    }
    if (this.shouldDecrease(text)) {
      ret += 2;
    }
    if (this.shouldIndentNextLine(text)) {
      ret += 4;
    }
    if (this.shouldIgnore(text)) {
      ret += 8;
    }
    return ret;
  }
};
var OnEnterSupport = class {
  constructor(opts) {
    opts = opts || {};
    opts.brackets = opts.brackets || [
      ["(", ")"],
      ["{", "}"],
      ["[", "]"]
    ];
    this._brackets = [];
    opts.brackets.forEach((bracket) => {
      const openRegExp = OnEnterSupport._createOpenBracketRegExp(bracket[0]);
      const closeRegExp = OnEnterSupport._createCloseBracketRegExp(bracket[1]);
      if (openRegExp && closeRegExp) {
        this._brackets.push({
          open: bracket[0],
          openRegExp,
          close: bracket[1],
          closeRegExp
        });
      }
    });
    this._regExpRules = opts.onEnterRules || [];
  }
  onEnter(autoIndent, oneLineAboveText, beforeEnterText, afterEnterText) {
    if (autoIndent >= 3) {
      for (let i3 = 0, len2 = this._regExpRules.length; i3 < len2; i3++) {
        let rule = this._regExpRules[i3];
        const regResult = [{
          reg: rule.beforeText,
          text: beforeEnterText
        }, {
          reg: rule.afterText,
          text: afterEnterText
        }, {
          reg: rule.oneLineAboveText,
          text: oneLineAboveText
        }].every((obj) => {
          return obj.reg ? obj.reg.test(obj.text) : true;
        });
        if (regResult) {
          return rule.action;
        }
      }
    }
    if (autoIndent >= 2) {
      if (beforeEnterText.length > 0 && afterEnterText.length > 0) {
        for (let i3 = 0, len2 = this._brackets.length; i3 < len2; i3++) {
          let bracket = this._brackets[i3];
          if (bracket.openRegExp.test(beforeEnterText) && bracket.closeRegExp.test(afterEnterText)) {
            return {indentAction: IndentAction$1.IndentOutdent};
          }
        }
      }
    }
    if (autoIndent >= 2) {
      if (beforeEnterText.length > 0) {
        for (let i3 = 0, len2 = this._brackets.length; i3 < len2; i3++) {
          let bracket = this._brackets[i3];
          if (bracket.openRegExp.test(beforeEnterText)) {
            return {indentAction: IndentAction$1.Indent};
          }
        }
      }
    }
    return null;
  }
  static _createOpenBracketRegExp(bracket) {
    let str = escapeRegExpCharacters(bracket);
    if (!/\B/.test(str.charAt(0))) {
      str = "\\b" + str;
    }
    str += "\\s*$";
    return OnEnterSupport._safeRegExp(str);
  }
  static _createCloseBracketRegExp(bracket) {
    let str = escapeRegExpCharacters(bracket);
    if (!/\B/.test(str.charAt(str.length - 1))) {
      str = str + "\\b";
    }
    str = "^\\s*" + str;
    return OnEnterSupport._safeRegExp(str);
  }
  static _safeRegExp(def) {
    try {
      return new RegExp(def);
    } catch (err) {
      onUnexpectedError(err);
      return null;
    }
  }
};
var RichEditSupport = class {
  constructor(languageIdentifier, previous, rawConf) {
    this._languageIdentifier = languageIdentifier;
    this._brackets = null;
    this._electricCharacter = null;
    let prev = null;
    if (previous) {
      prev = previous._conf;
    }
    this._conf = RichEditSupport._mergeConf(prev, rawConf);
    this._onEnterSupport = this._conf.brackets || this._conf.indentationRules || this._conf.onEnterRules ? new OnEnterSupport(this._conf) : null;
    this.comments = RichEditSupport._handleComments(this._conf);
    this.characterPair = new CharacterPairSupport(this._conf);
    this.wordDefinition = this._conf.wordPattern || DEFAULT_WORD_REGEXP;
    this.indentationRules = this._conf.indentationRules;
    if (this._conf.indentationRules) {
      this.indentRulesSupport = new IndentRulesSupport(this._conf.indentationRules);
    } else {
      this.indentRulesSupport = null;
    }
    this.foldingRules = this._conf.folding || {};
  }
  get brackets() {
    if (!this._brackets && this._conf.brackets) {
      this._brackets = new RichEditBrackets(this._languageIdentifier, this._conf.brackets);
    }
    return this._brackets;
  }
  get electricCharacter() {
    if (!this._electricCharacter) {
      this._electricCharacter = new BracketElectricCharacterSupport(this.brackets);
    }
    return this._electricCharacter;
  }
  onEnter(autoIndent, oneLineAboveText, beforeEnterText, afterEnterText) {
    if (!this._onEnterSupport) {
      return null;
    }
    return this._onEnterSupport.onEnter(autoIndent, oneLineAboveText, beforeEnterText, afterEnterText);
  }
  static _mergeConf(prev, current) {
    return {
      comments: prev ? current.comments || prev.comments : current.comments,
      brackets: prev ? current.brackets || prev.brackets : current.brackets,
      wordPattern: prev ? current.wordPattern || prev.wordPattern : current.wordPattern,
      indentationRules: prev ? current.indentationRules || prev.indentationRules : current.indentationRules,
      onEnterRules: prev ? current.onEnterRules || prev.onEnterRules : current.onEnterRules,
      autoClosingPairs: prev ? current.autoClosingPairs || prev.autoClosingPairs : current.autoClosingPairs,
      surroundingPairs: prev ? current.surroundingPairs || prev.surroundingPairs : current.surroundingPairs,
      autoCloseBefore: prev ? current.autoCloseBefore || prev.autoCloseBefore : current.autoCloseBefore,
      folding: prev ? current.folding || prev.folding : current.folding,
      __electricCharacterSupport: prev ? current.__electricCharacterSupport || prev.__electricCharacterSupport : current.__electricCharacterSupport
    };
  }
  static _handleComments(conf) {
    let commentRule = conf.comments;
    if (!commentRule) {
      return null;
    }
    let comments = {};
    if (commentRule.lineComment) {
      comments.lineCommentToken = commentRule.lineComment;
    }
    if (commentRule.blockComment) {
      let [blockStart, blockEnd] = commentRule.blockComment;
      comments.blockCommentStartToken = blockStart;
      comments.blockCommentEndToken = blockEnd;
    }
    return comments;
  }
};
var LanguageConfigurationChangeEvent = class {
  constructor(languageIdentifier) {
    this.languageIdentifier = languageIdentifier;
  }
};
var LanguageConfigurationRegistryImpl = class {
  constructor() {
    this._entries = new Map();
    this._onDidChange = new Emitter();
    this.onDidChange = this._onDidChange.event;
  }
  register(languageIdentifier, configuration) {
    let previous = this._getRichEditSupport(languageIdentifier.id);
    let current = new RichEditSupport(languageIdentifier, previous, configuration);
    this._entries.set(languageIdentifier.id, current);
    this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageIdentifier));
    return toDisposable(() => {
      if (this._entries.get(languageIdentifier.id) === current) {
        this._entries.set(languageIdentifier.id, previous);
        this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageIdentifier));
      }
    });
  }
  _getRichEditSupport(languageId) {
    return this._entries.get(languageId);
  }
  getIndentationRules(languageId) {
    const value = this._entries.get(languageId);
    if (!value) {
      return null;
    }
    return value.indentationRules || null;
  }
  _getElectricCharacterSupport(languageId) {
    let value = this._getRichEditSupport(languageId);
    if (!value) {
      return null;
    }
    return value.electricCharacter || null;
  }
  getElectricCharacters(languageId) {
    let electricCharacterSupport = this._getElectricCharacterSupport(languageId);
    if (!electricCharacterSupport) {
      return [];
    }
    return electricCharacterSupport.getElectricCharacters();
  }
  onElectricCharacter(character, context2, column) {
    let scopedLineTokens = createScopedLineTokens(context2, column - 1);
    let electricCharacterSupport = this._getElectricCharacterSupport(scopedLineTokens.languageId);
    if (!electricCharacterSupport) {
      return null;
    }
    return electricCharacterSupport.onElectricCharacter(character, scopedLineTokens, column - scopedLineTokens.firstCharOffset);
  }
  getComments(languageId) {
    let value = this._getRichEditSupport(languageId);
    if (!value) {
      return null;
    }
    return value.comments || null;
  }
  _getCharacterPairSupport(languageId) {
    let value = this._getRichEditSupport(languageId);
    if (!value) {
      return null;
    }
    return value.characterPair || null;
  }
  getAutoClosingPairs(languageId) {
    let characterPairSupport = this._getCharacterPairSupport(languageId);
    if (!characterPairSupport) {
      return [];
    }
    return characterPairSupport.getAutoClosingPairs();
  }
  getAutoCloseBeforeSet(languageId) {
    let characterPairSupport = this._getCharacterPairSupport(languageId);
    if (!characterPairSupport) {
      return CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED;
    }
    return characterPairSupport.getAutoCloseBeforeSet();
  }
  getSurroundingPairs(languageId) {
    let characterPairSupport = this._getCharacterPairSupport(languageId);
    if (!characterPairSupport) {
      return [];
    }
    return characterPairSupport.getSurroundingPairs();
  }
  shouldAutoClosePair(autoClosingPair, context2, column) {
    const scopedLineTokens = createScopedLineTokens(context2, column - 1);
    return CharacterPairSupport.shouldAutoClosePair(autoClosingPair, scopedLineTokens, column - scopedLineTokens.firstCharOffset);
  }
  getWordDefinition(languageId) {
    let value = this._getRichEditSupport(languageId);
    if (!value) {
      return ensureValidWordDefinition(null);
    }
    return ensureValidWordDefinition(value.wordDefinition || null);
  }
  getFoldingRules(languageId) {
    let value = this._getRichEditSupport(languageId);
    if (!value) {
      return {};
    }
    return value.foldingRules;
  }
  getIndentRulesSupport(languageId) {
    let value = this._getRichEditSupport(languageId);
    if (!value) {
      return null;
    }
    return value.indentRulesSupport || null;
  }
  getPrecedingValidLine(model, lineNumber, indentRulesSupport) {
    let languageID = model.getLanguageIdAtPosition(lineNumber, 0);
    if (lineNumber > 1) {
      let lastLineNumber;
      let resultLineNumber = -1;
      for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
        if (model.getLanguageIdAtPosition(lastLineNumber, 0) !== languageID) {
          return resultLineNumber;
        }
        let text = model.getLineContent(lastLineNumber);
        if (indentRulesSupport.shouldIgnore(text) || /^\s+$/.test(text) || text === "") {
          resultLineNumber = lastLineNumber;
          continue;
        }
        return lastLineNumber;
      }
    }
    return -1;
  }
  getInheritIndentForLine(autoIndent, model, lineNumber, honorIntentialIndent = true) {
    if (autoIndent < 4) {
      return null;
    }
    const indentRulesSupport = this.getIndentRulesSupport(model.getLanguageIdentifier().id);
    if (!indentRulesSupport) {
      return null;
    }
    if (lineNumber <= 1) {
      return {
        indentation: "",
        action: null
      };
    }
    const precedingUnIgnoredLine = this.getPrecedingValidLine(model, lineNumber, indentRulesSupport);
    if (precedingUnIgnoredLine < 0) {
      return null;
    } else if (precedingUnIgnoredLine < 1) {
      return {
        indentation: "",
        action: null
      };
    }
    const precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine);
    if (indentRulesSupport.shouldIncrease(precedingUnIgnoredLineContent) || indentRulesSupport.shouldIndentNextLine(precedingUnIgnoredLineContent)) {
      return {
        indentation: getLeadingWhitespace(precedingUnIgnoredLineContent),
        action: IndentAction$1.Indent,
        line: precedingUnIgnoredLine
      };
    } else if (indentRulesSupport.shouldDecrease(precedingUnIgnoredLineContent)) {
      return {
        indentation: getLeadingWhitespace(precedingUnIgnoredLineContent),
        action: null,
        line: precedingUnIgnoredLine
      };
    } else {
      if (precedingUnIgnoredLine === 1) {
        return {
          indentation: getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
          action: null,
          line: precedingUnIgnoredLine
        };
      }
      const previousLine = precedingUnIgnoredLine - 1;
      const previousLineIndentMetadata = indentRulesSupport.getIndentMetadata(model.getLineContent(previousLine));
      if (!(previousLineIndentMetadata & (1 | 2)) && previousLineIndentMetadata & 4) {
        let stopLine = 0;
        for (let i3 = previousLine - 1; i3 > 0; i3--) {
          if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(i3))) {
            continue;
          }
          stopLine = i3;
          break;
        }
        return {
          indentation: getLeadingWhitespace(model.getLineContent(stopLine + 1)),
          action: null,
          line: stopLine + 1
        };
      }
      if (honorIntentialIndent) {
        return {
          indentation: getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
          action: null,
          line: precedingUnIgnoredLine
        };
      } else {
        for (let i3 = precedingUnIgnoredLine; i3 > 0; i3--) {
          const lineContent = model.getLineContent(i3);
          if (indentRulesSupport.shouldIncrease(lineContent)) {
            return {
              indentation: getLeadingWhitespace(lineContent),
              action: IndentAction$1.Indent,
              line: i3
            };
          } else if (indentRulesSupport.shouldIndentNextLine(lineContent)) {
            let stopLine = 0;
            for (let j = i3 - 1; j > 0; j--) {
              if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(i3))) {
                continue;
              }
              stopLine = j;
              break;
            }
            return {
              indentation: getLeadingWhitespace(model.getLineContent(stopLine + 1)),
              action: null,
              line: stopLine + 1
            };
          } else if (indentRulesSupport.shouldDecrease(lineContent)) {
            return {
              indentation: getLeadingWhitespace(lineContent),
              action: null,
              line: i3
            };
          }
        }
        return {
          indentation: getLeadingWhitespace(model.getLineContent(1)),
          action: null,
          line: 1
        };
      }
    }
  }
  getGoodIndentForLine(autoIndent, virtualModel, languageId, lineNumber, indentConverter) {
    if (autoIndent < 4) {
      return null;
    }
    const richEditSupport = this._getRichEditSupport(languageId);
    if (!richEditSupport) {
      return null;
    }
    const indentRulesSupport = this.getIndentRulesSupport(languageId);
    if (!indentRulesSupport) {
      return null;
    }
    const indent = this.getInheritIndentForLine(autoIndent, virtualModel, lineNumber);
    const lineContent = virtualModel.getLineContent(lineNumber);
    if (indent) {
      const inheritLine = indent.line;
      if (inheritLine !== void 0) {
        const enterResult = richEditSupport.onEnter(autoIndent, "", virtualModel.getLineContent(inheritLine), "");
        if (enterResult) {
          let indentation = getLeadingWhitespace(virtualModel.getLineContent(inheritLine));
          if (enterResult.removeText) {
            indentation = indentation.substring(0, indentation.length - enterResult.removeText);
          }
          if (enterResult.indentAction === IndentAction$1.Indent || enterResult.indentAction === IndentAction$1.IndentOutdent) {
            indentation = indentConverter.shiftIndent(indentation);
          } else if (enterResult.indentAction === IndentAction$1.Outdent) {
            indentation = indentConverter.unshiftIndent(indentation);
          }
          if (indentRulesSupport.shouldDecrease(lineContent)) {
            indentation = indentConverter.unshiftIndent(indentation);
          }
          if (enterResult.appendText) {
            indentation += enterResult.appendText;
          }
          return getLeadingWhitespace(indentation);
        }
      }
      if (indentRulesSupport.shouldDecrease(lineContent)) {
        if (indent.action === IndentAction$1.Indent) {
          return indent.indentation;
        } else {
          return indentConverter.unshiftIndent(indent.indentation);
        }
      } else {
        if (indent.action === IndentAction$1.Indent) {
          return indentConverter.shiftIndent(indent.indentation);
        } else {
          return indent.indentation;
        }
      }
    }
    return null;
  }
  getIndentForEnter(autoIndent, model, range3, indentConverter) {
    if (autoIndent < 4) {
      return null;
    }
    model.forceTokenization(range3.startLineNumber);
    const lineTokens = model.getLineTokens(range3.startLineNumber);
    const scopedLineTokens = createScopedLineTokens(lineTokens, range3.startColumn - 1);
    const scopedLineText = scopedLineTokens.getLineContent();
    let embeddedLanguage = false;
    let beforeEnterText;
    if (scopedLineTokens.firstCharOffset > 0 && lineTokens.getLanguageId(0) !== scopedLineTokens.languageId) {
      embeddedLanguage = true;
      beforeEnterText = scopedLineText.substr(0, range3.startColumn - 1 - scopedLineTokens.firstCharOffset);
    } else {
      beforeEnterText = lineTokens.getLineContent().substring(0, range3.startColumn - 1);
    }
    let afterEnterText;
    if (range3.isEmpty()) {
      afterEnterText = scopedLineText.substr(range3.startColumn - 1 - scopedLineTokens.firstCharOffset);
    } else {
      const endScopedLineTokens = this.getScopedLineTokens(model, range3.endLineNumber, range3.endColumn);
      afterEnterText = endScopedLineTokens.getLineContent().substr(range3.endColumn - 1 - scopedLineTokens.firstCharOffset);
    }
    const indentRulesSupport = this.getIndentRulesSupport(scopedLineTokens.languageId);
    if (!indentRulesSupport) {
      return null;
    }
    const beforeEnterResult = beforeEnterText;
    const beforeEnterIndent = getLeadingWhitespace(beforeEnterText);
    const virtualModel = {
      getLineTokens: (lineNumber) => {
        return model.getLineTokens(lineNumber);
      },
      getLanguageIdentifier: () => {
        return model.getLanguageIdentifier();
      },
      getLanguageIdAtPosition: (lineNumber, column) => {
        return model.getLanguageIdAtPosition(lineNumber, column);
      },
      getLineContent: (lineNumber) => {
        if (lineNumber === range3.startLineNumber) {
          return beforeEnterResult;
        } else {
          return model.getLineContent(lineNumber);
        }
      }
    };
    const currentLineIndent = getLeadingWhitespace(lineTokens.getLineContent());
    const afterEnterAction = this.getInheritIndentForLine(autoIndent, virtualModel, range3.startLineNumber + 1);
    if (!afterEnterAction) {
      const beforeEnter = embeddedLanguage ? currentLineIndent : beforeEnterIndent;
      return {
        beforeEnter,
        afterEnter: beforeEnter
      };
    }
    let afterEnterIndent = embeddedLanguage ? currentLineIndent : afterEnterAction.indentation;
    if (afterEnterAction.action === IndentAction$1.Indent) {
      afterEnterIndent = indentConverter.shiftIndent(afterEnterIndent);
    }
    if (indentRulesSupport.shouldDecrease(afterEnterText)) {
      afterEnterIndent = indentConverter.unshiftIndent(afterEnterIndent);
    }
    return {
      beforeEnter: embeddedLanguage ? currentLineIndent : beforeEnterIndent,
      afterEnter: afterEnterIndent
    };
  }
  getIndentActionForType(autoIndent, model, range3, ch2, indentConverter) {
    if (autoIndent < 4) {
      return null;
    }
    const scopedLineTokens = this.getScopedLineTokens(model, range3.startLineNumber, range3.startColumn);
    const indentRulesSupport = this.getIndentRulesSupport(scopedLineTokens.languageId);
    if (!indentRulesSupport) {
      return null;
    }
    const scopedLineText = scopedLineTokens.getLineContent();
    const beforeTypeText = scopedLineText.substr(0, range3.startColumn - 1 - scopedLineTokens.firstCharOffset);
    let afterTypeText;
    if (range3.isEmpty()) {
      afterTypeText = scopedLineText.substr(range3.startColumn - 1 - scopedLineTokens.firstCharOffset);
    } else {
      const endScopedLineTokens = this.getScopedLineTokens(model, range3.endLineNumber, range3.endColumn);
      afterTypeText = endScopedLineTokens.getLineContent().substr(range3.endColumn - 1 - scopedLineTokens.firstCharOffset);
    }
    if (!indentRulesSupport.shouldDecrease(beforeTypeText + afterTypeText) && indentRulesSupport.shouldDecrease(beforeTypeText + ch2 + afterTypeText)) {
      const r3 = this.getInheritIndentForLine(autoIndent, model, range3.startLineNumber, false);
      if (!r3) {
        return null;
      }
      let indentation = r3.indentation;
      if (r3.action !== IndentAction$1.Indent) {
        indentation = indentConverter.unshiftIndent(indentation);
      }
      return indentation;
    }
    return null;
  }
  getIndentMetadata(model, lineNumber) {
    const indentRulesSupport = this.getIndentRulesSupport(model.getLanguageIdentifier().id);
    if (!indentRulesSupport) {
      return null;
    }
    if (lineNumber < 1 || lineNumber > model.getLineCount()) {
      return null;
    }
    return indentRulesSupport.getIndentMetadata(model.getLineContent(lineNumber));
  }
  getEnterAction(autoIndent, model, range3) {
    const scopedLineTokens = this.getScopedLineTokens(model, range3.startLineNumber, range3.startColumn);
    const richEditSupport = this._getRichEditSupport(scopedLineTokens.languageId);
    if (!richEditSupport) {
      return null;
    }
    const scopedLineText = scopedLineTokens.getLineContent();
    const beforeEnterText = scopedLineText.substr(0, range3.startColumn - 1 - scopedLineTokens.firstCharOffset);
    let afterEnterText;
    if (range3.isEmpty()) {
      afterEnterText = scopedLineText.substr(range3.startColumn - 1 - scopedLineTokens.firstCharOffset);
    } else {
      const endScopedLineTokens = this.getScopedLineTokens(model, range3.endLineNumber, range3.endColumn);
      afterEnterText = endScopedLineTokens.getLineContent().substr(range3.endColumn - 1 - scopedLineTokens.firstCharOffset);
    }
    let oneLineAboveText = "";
    if (range3.startLineNumber > 1 && scopedLineTokens.firstCharOffset === 0) {
      const oneLineAboveScopedLineTokens = this.getScopedLineTokens(model, range3.startLineNumber - 1);
      if (oneLineAboveScopedLineTokens.languageId === scopedLineTokens.languageId) {
        oneLineAboveText = oneLineAboveScopedLineTokens.getLineContent();
      }
    }
    const enterResult = richEditSupport.onEnter(autoIndent, oneLineAboveText, beforeEnterText, afterEnterText);
    if (!enterResult) {
      return null;
    }
    const indentAction = enterResult.indentAction;
    let appendText = enterResult.appendText;
    const removeText = enterResult.removeText || 0;
    if (!appendText) {
      if (indentAction === IndentAction$1.Indent || indentAction === IndentAction$1.IndentOutdent) {
        appendText = "	";
      } else {
        appendText = "";
      }
    }
    let indentation = this.getIndentationAtPosition(model, range3.startLineNumber, range3.startColumn);
    if (removeText) {
      indentation = indentation.substring(0, indentation.length - removeText);
    }
    return {
      indentAction,
      appendText,
      removeText,
      indentation
    };
  }
  getIndentationAtPosition(model, lineNumber, column) {
    const lineText = model.getLineContent(lineNumber);
    let indentation = getLeadingWhitespace(lineText);
    if (indentation.length > column - 1) {
      indentation = indentation.substring(0, column - 1);
    }
    return indentation;
  }
  getScopedLineTokens(model, lineNumber, columnNumber) {
    model.forceTokenization(lineNumber);
    const lineTokens = model.getLineTokens(lineNumber);
    const column = typeof columnNumber === "undefined" ? model.getLineMaxColumn(lineNumber) - 1 : columnNumber - 1;
    return createScopedLineTokens(lineTokens, column);
  }
  getBracketsSupport(languageId) {
    const value = this._getRichEditSupport(languageId);
    if (!value) {
      return null;
    }
    return value.brackets || null;
  }
};
var LanguageConfigurationRegistry = new LanguageConfigurationRegistryImpl();
var DiffChange = class {
  constructor(originalStart, originalLength, modifiedStart, modifiedLength) {
    this.originalStart = originalStart;
    this.originalLength = originalLength;
    this.modifiedStart = modifiedStart;
    this.modifiedLength = modifiedLength;
  }
  getOriginalEnd() {
    return this.originalStart + this.originalLength;
  }
  getModifiedEnd() {
    return this.modifiedStart + this.modifiedLength;
  }
};
function numberHash(val, initialHashVal) {
  return (initialHashVal << 5) - initialHashVal + val | 0;
}
function stringHash(s2, hashVal) {
  hashVal = numberHash(149417, hashVal);
  for (let i3 = 0, length = s2.length; i3 < length; i3++) {
    hashVal = numberHash(s2.charCodeAt(i3), hashVal);
  }
  return hashVal;
}
function leftRotate(value, bits, totalBits = 32) {
  const delta = totalBits - bits;
  const mask = ~((1 << delta) - 1);
  return (value << bits | (mask & value) >>> delta) >>> 0;
}
function fill(dest, index3 = 0, count = dest.byteLength, value = 0) {
  for (let i3 = 0; i3 < count; i3++) {
    dest[index3 + i3] = value;
  }
}
function leftPad(value, length, char = "0") {
  while (value.length < length) {
    value = char + value;
  }
  return value;
}
function toHexString(value, bitsize = 32) {
  return leftPad((value >>> 0).toString(16), bitsize / 4);
}
var StringSHA1 = class {
  constructor() {
    this._h0 = 1732584193;
    this._h1 = 4023233417;
    this._h2 = 2562383102;
    this._h3 = 271733878;
    this._h4 = 3285377520;
    this._buff = new Uint8Array(64 + 3);
    this._buffDV = new DataView(this._buff.buffer);
    this._buffLen = 0;
    this._totalLen = 0;
    this._leftoverHighSurrogate = 0;
    this._finished = false;
  }
  update(str) {
    const strLen = str.length;
    if (strLen === 0) {
      return;
    }
    const buff = this._buff;
    let buffLen = this._buffLen;
    let leftoverHighSurrogate = this._leftoverHighSurrogate;
    let charCode;
    let offset2;
    if (leftoverHighSurrogate !== 0) {
      charCode = leftoverHighSurrogate;
      offset2 = -1;
      leftoverHighSurrogate = 0;
    } else {
      charCode = str.charCodeAt(0);
      offset2 = 0;
    }
    while (true) {
      let codePoint = charCode;
      if (isHighSurrogate(charCode)) {
        if (offset2 + 1 < strLen) {
          const nextCharCode = str.charCodeAt(offset2 + 1);
          if (isLowSurrogate(nextCharCode)) {
            offset2++;
            codePoint = computeCodePoint(charCode, nextCharCode);
          } else {
            codePoint = 65533;
          }
        } else {
          leftoverHighSurrogate = charCode;
          break;
        }
      } else if (isLowSurrogate(charCode)) {
        codePoint = 65533;
      }
      buffLen = this._push(buff, buffLen, codePoint);
      offset2++;
      if (offset2 < strLen) {
        charCode = str.charCodeAt(offset2);
      } else {
        break;
      }
    }
    this._buffLen = buffLen;
    this._leftoverHighSurrogate = leftoverHighSurrogate;
  }
  _push(buff, buffLen, codePoint) {
    if (codePoint < 128) {
      buff[buffLen++] = codePoint;
    } else if (codePoint < 2048) {
      buff[buffLen++] = 192 | (codePoint & 1984) >>> 6;
      buff[buffLen++] = 128 | (codePoint & 63) >>> 0;
    } else if (codePoint < 65536) {
      buff[buffLen++] = 224 | (codePoint & 61440) >>> 12;
      buff[buffLen++] = 128 | (codePoint & 4032) >>> 6;
      buff[buffLen++] = 128 | (codePoint & 63) >>> 0;
    } else {
      buff[buffLen++] = 240 | (codePoint & 1835008) >>> 18;
      buff[buffLen++] = 128 | (codePoint & 258048) >>> 12;
      buff[buffLen++] = 128 | (codePoint & 4032) >>> 6;
      buff[buffLen++] = 128 | (codePoint & 63) >>> 0;
    }
    if (buffLen >= 64) {
      this._step();
      buffLen -= 64;
      this._totalLen += 64;
      buff[0] = buff[64 + 0];
      buff[1] = buff[64 + 1];
      buff[2] = buff[64 + 2];
    }
    return buffLen;
  }
  digest() {
    if (!this._finished) {
      this._finished = true;
      if (this._leftoverHighSurrogate) {
        this._leftoverHighSurrogate = 0;
        this._buffLen = this._push(this._buff, this._buffLen, 65533);
      }
      this._totalLen += this._buffLen;
      this._wrapUp();
    }
    return toHexString(this._h0) + toHexString(this._h1) + toHexString(this._h2) + toHexString(this._h3) + toHexString(this._h4);
  }
  _wrapUp() {
    this._buff[this._buffLen++] = 128;
    fill(this._buff, this._buffLen);
    if (this._buffLen > 56) {
      this._step();
      fill(this._buff);
    }
    const ml = 8 * this._totalLen;
    this._buffDV.setUint32(56, Math.floor(ml / 4294967296), false);
    this._buffDV.setUint32(60, ml % 4294967296, false);
    this._step();
  }
  _step() {
    const bigBlock32 = StringSHA1._bigBlock32;
    const data2 = this._buffDV;
    for (let j = 0; j < 64; j += 4) {
      bigBlock32.setUint32(j, data2.getUint32(j, false), false);
    }
    for (let j = 64; j < 320; j += 4) {
      bigBlock32.setUint32(j, leftRotate(bigBlock32.getUint32(j - 12, false) ^ bigBlock32.getUint32(j - 32, false) ^ bigBlock32.getUint32(j - 56, false) ^ bigBlock32.getUint32(j - 64, false), 1), false);
    }
    let a2 = this._h0;
    let b2 = this._h1;
    let c3 = this._h2;
    let d2 = this._h3;
    let e2 = this._h4;
    let f2, k2;
    let temp;
    for (let j = 0; j < 80; j++) {
      if (j < 20) {
        f2 = b2 & c3 | ~b2 & d2;
        k2 = 1518500249;
      } else if (j < 40) {
        f2 = b2 ^ c3 ^ d2;
        k2 = 1859775393;
      } else if (j < 60) {
        f2 = b2 & c3 | b2 & d2 | c3 & d2;
        k2 = 2400959708;
      } else {
        f2 = b2 ^ c3 ^ d2;
        k2 = 3395469782;
      }
      temp = leftRotate(a2, 5) + f2 + e2 + k2 + bigBlock32.getUint32(j * 4, false) & 4294967295;
      e2 = d2;
      d2 = c3;
      c3 = leftRotate(b2, 30);
      b2 = a2;
      a2 = temp;
    }
    this._h0 = this._h0 + a2 & 4294967295;
    this._h1 = this._h1 + b2 & 4294967295;
    this._h2 = this._h2 + c3 & 4294967295;
    this._h3 = this._h3 + d2 & 4294967295;
    this._h4 = this._h4 + e2 & 4294967295;
  }
};
StringSHA1._bigBlock32 = new DataView(new ArrayBuffer(320));
var StringDiffSequence = class {
  constructor(source2) {
    this.source = source2;
  }
  getElements() {
    const source2 = this.source;
    const characters = new Int32Array(source2.length);
    for (let i3 = 0, len2 = source2.length; i3 < len2; i3++) {
      characters[i3] = source2.charCodeAt(i3);
    }
    return characters;
  }
};
function stringDiff(original, modified, pretty) {
  return new LcsDiff(new StringDiffSequence(original), new StringDiffSequence(modified)).ComputeDiff(pretty).changes;
}
var Debug = class {
  static Assert(condition, message) {
    if (!condition) {
      throw new Error(message);
    }
  }
};
var MyArray = class {
  static Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
    for (let i3 = 0; i3 < length; i3++) {
      destinationArray[destinationIndex + i3] = sourceArray[sourceIndex + i3];
    }
  }
  static Copy2(sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
    for (let i3 = 0; i3 < length; i3++) {
      destinationArray[destinationIndex + i3] = sourceArray[sourceIndex + i3];
    }
  }
};
var DiffChangeHelper = class {
  constructor() {
    this.m_changes = [];
    this.m_originalStart = 1073741824;
    this.m_modifiedStart = 1073741824;
    this.m_originalCount = 0;
    this.m_modifiedCount = 0;
  }
  MarkNextChange() {
    if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
      this.m_changes.push(new DiffChange(this.m_originalStart, this.m_originalCount, this.m_modifiedStart, this.m_modifiedCount));
    }
    this.m_originalCount = 0;
    this.m_modifiedCount = 0;
    this.m_originalStart = 1073741824;
    this.m_modifiedStart = 1073741824;
  }
  AddOriginalElement(originalIndex, modifiedIndex) {
    this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
    this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
    this.m_originalCount++;
  }
  AddModifiedElement(originalIndex, modifiedIndex) {
    this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
    this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
    this.m_modifiedCount++;
  }
  getChanges() {
    if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
      this.MarkNextChange();
    }
    return this.m_changes;
  }
  getReverseChanges() {
    if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
      this.MarkNextChange();
    }
    this.m_changes.reverse();
    return this.m_changes;
  }
};
var LcsDiff = class {
  constructor(originalSequence, modifiedSequence, continueProcessingPredicate = null) {
    this.ContinueProcessingPredicate = continueProcessingPredicate;
    const [originalStringElements, originalElementsOrHash, originalHasStrings] = LcsDiff._getElements(originalSequence);
    const [modifiedStringElements, modifiedElementsOrHash, modifiedHasStrings] = LcsDiff._getElements(modifiedSequence);
    this._hasStrings = originalHasStrings && modifiedHasStrings;
    this._originalStringElements = originalStringElements;
    this._originalElementsOrHash = originalElementsOrHash;
    this._modifiedStringElements = modifiedStringElements;
    this._modifiedElementsOrHash = modifiedElementsOrHash;
    this.m_forwardHistory = [];
    this.m_reverseHistory = [];
  }
  static _isStringArray(arr) {
    return arr.length > 0 && typeof arr[0] === "string";
  }
  static _getElements(sequence) {
    const elements = sequence.getElements();
    if (LcsDiff._isStringArray(elements)) {
      const hashes = new Int32Array(elements.length);
      for (let i3 = 0, len2 = elements.length; i3 < len2; i3++) {
        hashes[i3] = stringHash(elements[i3], 0);
      }
      return [elements, hashes, true];
    }
    if (elements instanceof Int32Array) {
      return [[], elements, false];
    }
    return [[], new Int32Array(elements), false];
  }
  ElementsAreEqual(originalIndex, newIndex) {
    if (this._originalElementsOrHash[originalIndex] !== this._modifiedElementsOrHash[newIndex]) {
      return false;
    }
    return this._hasStrings ? this._originalStringElements[originalIndex] === this._modifiedStringElements[newIndex] : true;
  }
  OriginalElementsAreEqual(index1, index22) {
    if (this._originalElementsOrHash[index1] !== this._originalElementsOrHash[index22]) {
      return false;
    }
    return this._hasStrings ? this._originalStringElements[index1] === this._originalStringElements[index22] : true;
  }
  ModifiedElementsAreEqual(index1, index22) {
    if (this._modifiedElementsOrHash[index1] !== this._modifiedElementsOrHash[index22]) {
      return false;
    }
    return this._hasStrings ? this._modifiedStringElements[index1] === this._modifiedStringElements[index22] : true;
  }
  ComputeDiff(pretty) {
    return this._ComputeDiff(0, this._originalElementsOrHash.length - 1, 0, this._modifiedElementsOrHash.length - 1, pretty);
  }
  _ComputeDiff(originalStart, originalEnd, modifiedStart, modifiedEnd, pretty) {
    const quitEarlyArr = [false];
    let changes = this.ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr);
    if (pretty) {
      changes = this.PrettifyChanges(changes);
    }
    return {
      quitEarly: quitEarlyArr[0],
      changes
    };
  }
  ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr) {
    quitEarlyArr[0] = false;
    while (originalStart <= originalEnd && modifiedStart <= modifiedEnd && this.ElementsAreEqual(originalStart, modifiedStart)) {
      originalStart++;
      modifiedStart++;
    }
    while (originalEnd >= originalStart && modifiedEnd >= modifiedStart && this.ElementsAreEqual(originalEnd, modifiedEnd)) {
      originalEnd--;
      modifiedEnd--;
    }
    if (originalStart > originalEnd || modifiedStart > modifiedEnd) {
      let changes;
      if (modifiedStart <= modifiedEnd) {
        Debug.Assert(originalStart === originalEnd + 1, "originalStart should only be one more than originalEnd");
        changes = [
          new DiffChange(originalStart, 0, modifiedStart, modifiedEnd - modifiedStart + 1)
        ];
      } else if (originalStart <= originalEnd) {
        Debug.Assert(modifiedStart === modifiedEnd + 1, "modifiedStart should only be one more than modifiedEnd");
        changes = [
          new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, 0)
        ];
      } else {
        Debug.Assert(originalStart === originalEnd + 1, "originalStart should only be one more than originalEnd");
        Debug.Assert(modifiedStart === modifiedEnd + 1, "modifiedStart should only be one more than modifiedEnd");
        changes = [];
      }
      return changes;
    }
    const midOriginalArr = [0];
    const midModifiedArr = [0];
    const result = this.ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr);
    const midOriginal = midOriginalArr[0];
    const midModified = midModifiedArr[0];
    if (result !== null) {
      return result;
    } else if (!quitEarlyArr[0]) {
      const leftChanges = this.ComputeDiffRecursive(originalStart, midOriginal, modifiedStart, midModified, quitEarlyArr);
      let rightChanges = [];
      if (!quitEarlyArr[0]) {
        rightChanges = this.ComputeDiffRecursive(midOriginal + 1, originalEnd, midModified + 1, modifiedEnd, quitEarlyArr);
      } else {
        rightChanges = [
          new DiffChange(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1)
        ];
      }
      return this.ConcatenateChanges(leftChanges, rightChanges);
    }
    return [
      new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
    ];
  }
  WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr) {
    let forwardChanges = null;
    let reverseChanges = null;
    let changeHelper = new DiffChangeHelper();
    let diagonalMin = diagonalForwardStart;
    let diagonalMax = diagonalForwardEnd;
    let diagonalRelative = midOriginalArr[0] - midModifiedArr[0] - diagonalForwardOffset;
    let lastOriginalIndex = -1073741824;
    let historyIndex = this.m_forwardHistory.length - 1;
    do {
      const diagonal = diagonalRelative + diagonalForwardBase;
      if (diagonal === diagonalMin || diagonal < diagonalMax && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1]) {
        originalIndex = forwardPoints[diagonal + 1];
        modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
        if (originalIndex < lastOriginalIndex) {
          changeHelper.MarkNextChange();
        }
        lastOriginalIndex = originalIndex;
        changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex);
        diagonalRelative = diagonal + 1 - diagonalForwardBase;
      } else {
        originalIndex = forwardPoints[diagonal - 1] + 1;
        modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
        if (originalIndex < lastOriginalIndex) {
          changeHelper.MarkNextChange();
        }
        lastOriginalIndex = originalIndex - 1;
        changeHelper.AddOriginalElement(originalIndex, modifiedIndex + 1);
        diagonalRelative = diagonal - 1 - diagonalForwardBase;
      }
      if (historyIndex >= 0) {
        forwardPoints = this.m_forwardHistory[historyIndex];
        diagonalForwardBase = forwardPoints[0];
        diagonalMin = 1;
        diagonalMax = forwardPoints.length - 1;
      }
    } while (--historyIndex >= -1);
    forwardChanges = changeHelper.getReverseChanges();
    if (quitEarlyArr[0]) {
      let originalStartPoint = midOriginalArr[0] + 1;
      let modifiedStartPoint = midModifiedArr[0] + 1;
      if (forwardChanges !== null && forwardChanges.length > 0) {
        const lastForwardChange = forwardChanges[forwardChanges.length - 1];
        originalStartPoint = Math.max(originalStartPoint, lastForwardChange.getOriginalEnd());
        modifiedStartPoint = Math.max(modifiedStartPoint, lastForwardChange.getModifiedEnd());
      }
      reverseChanges = [
        new DiffChange(originalStartPoint, originalEnd - originalStartPoint + 1, modifiedStartPoint, modifiedEnd - modifiedStartPoint + 1)
      ];
    } else {
      changeHelper = new DiffChangeHelper();
      diagonalMin = diagonalReverseStart;
      diagonalMax = diagonalReverseEnd;
      diagonalRelative = midOriginalArr[0] - midModifiedArr[0] - diagonalReverseOffset;
      lastOriginalIndex = 1073741824;
      historyIndex = deltaIsEven ? this.m_reverseHistory.length - 1 : this.m_reverseHistory.length - 2;
      do {
        const diagonal = diagonalRelative + diagonalReverseBase;
        if (diagonal === diagonalMin || diagonal < diagonalMax && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1]) {
          originalIndex = reversePoints[diagonal + 1] - 1;
          modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
          if (originalIndex > lastOriginalIndex) {
            changeHelper.MarkNextChange();
          }
          lastOriginalIndex = originalIndex + 1;
          changeHelper.AddOriginalElement(originalIndex + 1, modifiedIndex + 1);
          diagonalRelative = diagonal + 1 - diagonalReverseBase;
        } else {
          originalIndex = reversePoints[diagonal - 1];
          modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
          if (originalIndex > lastOriginalIndex) {
            changeHelper.MarkNextChange();
          }
          lastOriginalIndex = originalIndex;
          changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex + 1);
          diagonalRelative = diagonal - 1 - diagonalReverseBase;
        }
        if (historyIndex >= 0) {
          reversePoints = this.m_reverseHistory[historyIndex];
          diagonalReverseBase = reversePoints[0];
          diagonalMin = 1;
          diagonalMax = reversePoints.length - 1;
        }
      } while (--historyIndex >= -1);
      reverseChanges = changeHelper.getChanges();
    }
    return this.ConcatenateChanges(forwardChanges, reverseChanges);
  }
  ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr) {
    let originalIndex = 0, modifiedIndex = 0;
    let diagonalForwardStart = 0, diagonalForwardEnd = 0;
    let diagonalReverseStart = 0, diagonalReverseEnd = 0;
    originalStart--;
    modifiedStart--;
    midOriginalArr[0] = 0;
    midModifiedArr[0] = 0;
    this.m_forwardHistory = [];
    this.m_reverseHistory = [];
    const maxDifferences = originalEnd - originalStart + (modifiedEnd - modifiedStart);
    const numDiagonals = maxDifferences + 1;
    const forwardPoints = new Int32Array(numDiagonals);
    const reversePoints = new Int32Array(numDiagonals);
    const diagonalForwardBase = modifiedEnd - modifiedStart;
    const diagonalReverseBase = originalEnd - originalStart;
    const diagonalForwardOffset = originalStart - modifiedStart;
    const diagonalReverseOffset = originalEnd - modifiedEnd;
    const delta = diagonalReverseBase - diagonalForwardBase;
    const deltaIsEven = delta % 2 === 0;
    forwardPoints[diagonalForwardBase] = originalStart;
    reversePoints[diagonalReverseBase] = originalEnd;
    quitEarlyArr[0] = false;
    for (let numDifferences = 1; numDifferences <= maxDifferences / 2 + 1; numDifferences++) {
      let furthestOriginalIndex = 0;
      let furthestModifiedIndex = 0;
      diagonalForwardStart = this.ClipDiagonalBound(diagonalForwardBase - numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
      diagonalForwardEnd = this.ClipDiagonalBound(diagonalForwardBase + numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
      for (let diagonal = diagonalForwardStart; diagonal <= diagonalForwardEnd; diagonal += 2) {
        if (diagonal === diagonalForwardStart || diagonal < diagonalForwardEnd && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1]) {
          originalIndex = forwardPoints[diagonal + 1];
        } else {
          originalIndex = forwardPoints[diagonal - 1] + 1;
        }
        modifiedIndex = originalIndex - (diagonal - diagonalForwardBase) - diagonalForwardOffset;
        const tempOriginalIndex = originalIndex;
        while (originalIndex < originalEnd && modifiedIndex < modifiedEnd && this.ElementsAreEqual(originalIndex + 1, modifiedIndex + 1)) {
          originalIndex++;
          modifiedIndex++;
        }
        forwardPoints[diagonal] = originalIndex;
        if (originalIndex + modifiedIndex > furthestOriginalIndex + furthestModifiedIndex) {
          furthestOriginalIndex = originalIndex;
          furthestModifiedIndex = modifiedIndex;
        }
        if (!deltaIsEven && Math.abs(diagonal - diagonalReverseBase) <= numDifferences - 1) {
          if (originalIndex >= reversePoints[diagonal]) {
            midOriginalArr[0] = originalIndex;
            midModifiedArr[0] = modifiedIndex;
            if (tempOriginalIndex <= reversePoints[diagonal] && 1447 > 0 && numDifferences <= 1447 + 1) {
              return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
            } else {
              return null;
            }
          }
        }
      }
      const matchLengthOfLongest = (furthestOriginalIndex - originalStart + (furthestModifiedIndex - modifiedStart) - numDifferences) / 2;
      if (this.ContinueProcessingPredicate !== null && !this.ContinueProcessingPredicate(furthestOriginalIndex, matchLengthOfLongest)) {
        quitEarlyArr[0] = true;
        midOriginalArr[0] = furthestOriginalIndex;
        midModifiedArr[0] = furthestModifiedIndex;
        if (matchLengthOfLongest > 0 && 1447 > 0 && numDifferences <= 1447 + 1) {
          return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
        } else {
          originalStart++;
          modifiedStart++;
          return [
            new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
          ];
        }
      }
      diagonalReverseStart = this.ClipDiagonalBound(diagonalReverseBase - numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
      diagonalReverseEnd = this.ClipDiagonalBound(diagonalReverseBase + numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
      for (let diagonal = diagonalReverseStart; diagonal <= diagonalReverseEnd; diagonal += 2) {
        if (diagonal === diagonalReverseStart || diagonal < diagonalReverseEnd && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1]) {
          originalIndex = reversePoints[diagonal + 1] - 1;
        } else {
          originalIndex = reversePoints[diagonal - 1];
        }
        modifiedIndex = originalIndex - (diagonal - diagonalReverseBase) - diagonalReverseOffset;
        const tempOriginalIndex = originalIndex;
        while (originalIndex > originalStart && modifiedIndex > modifiedStart && this.ElementsAreEqual(originalIndex, modifiedIndex)) {
          originalIndex--;
          modifiedIndex--;
        }
        reversePoints[diagonal] = originalIndex;
        if (deltaIsEven && Math.abs(diagonal - diagonalForwardBase) <= numDifferences) {
          if (originalIndex <= forwardPoints[diagonal]) {
            midOriginalArr[0] = originalIndex;
            midModifiedArr[0] = modifiedIndex;
            if (tempOriginalIndex >= forwardPoints[diagonal] && 1447 > 0 && numDifferences <= 1447 + 1) {
              return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
            } else {
              return null;
            }
          }
        }
      }
      if (numDifferences <= 1447) {
        let temp = new Int32Array(diagonalForwardEnd - diagonalForwardStart + 2);
        temp[0] = diagonalForwardBase - diagonalForwardStart + 1;
        MyArray.Copy2(forwardPoints, diagonalForwardStart, temp, 1, diagonalForwardEnd - diagonalForwardStart + 1);
        this.m_forwardHistory.push(temp);
        temp = new Int32Array(diagonalReverseEnd - diagonalReverseStart + 2);
        temp[0] = diagonalReverseBase - diagonalReverseStart + 1;
        MyArray.Copy2(reversePoints, diagonalReverseStart, temp, 1, diagonalReverseEnd - diagonalReverseStart + 1);
        this.m_reverseHistory.push(temp);
      }
    }
    return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
  }
  PrettifyChanges(changes) {
    for (let i3 = 0; i3 < changes.length; i3++) {
      const change = changes[i3];
      const originalStop = i3 < changes.length - 1 ? changes[i3 + 1].originalStart : this._originalElementsOrHash.length;
      const modifiedStop = i3 < changes.length - 1 ? changes[i3 + 1].modifiedStart : this._modifiedElementsOrHash.length;
      const checkOriginal = change.originalLength > 0;
      const checkModified = change.modifiedLength > 0;
      while (change.originalStart + change.originalLength < originalStop && change.modifiedStart + change.modifiedLength < modifiedStop && (!checkOriginal || this.OriginalElementsAreEqual(change.originalStart, change.originalStart + change.originalLength)) && (!checkModified || this.ModifiedElementsAreEqual(change.modifiedStart, change.modifiedStart + change.modifiedLength))) {
        change.originalStart++;
        change.modifiedStart++;
      }
      let mergedChangeArr = [null];
      if (i3 < changes.length - 1 && this.ChangesOverlap(changes[i3], changes[i3 + 1], mergedChangeArr)) {
        changes[i3] = mergedChangeArr[0];
        changes.splice(i3 + 1, 1);
        i3--;
        continue;
      }
    }
    for (let i3 = changes.length - 1; i3 >= 0; i3--) {
      const change = changes[i3];
      let originalStop = 0;
      let modifiedStop = 0;
      if (i3 > 0) {
        const prevChange = changes[i3 - 1];
        if (prevChange.originalLength > 0) {
          originalStop = prevChange.originalStart + prevChange.originalLength;
        }
        if (prevChange.modifiedLength > 0) {
          modifiedStop = prevChange.modifiedStart + prevChange.modifiedLength;
        }
      }
      const checkOriginal = change.originalLength > 0;
      const checkModified = change.modifiedLength > 0;
      let bestDelta = 0;
      let bestScore = this._boundaryScore(change.originalStart, change.originalLength, change.modifiedStart, change.modifiedLength);
      for (let delta = 1; ; delta++) {
        const originalStart = change.originalStart - delta;
        const modifiedStart = change.modifiedStart - delta;
        if (originalStart < originalStop || modifiedStart < modifiedStop) {
          break;
        }
        if (checkOriginal && !this.OriginalElementsAreEqual(originalStart, originalStart + change.originalLength)) {
          break;
        }
        if (checkModified && !this.ModifiedElementsAreEqual(modifiedStart, modifiedStart + change.modifiedLength)) {
          break;
        }
        const score2 = this._boundaryScore(originalStart, change.originalLength, modifiedStart, change.modifiedLength);
        if (score2 > bestScore) {
          bestScore = score2;
          bestDelta = delta;
        }
      }
      change.originalStart -= bestDelta;
      change.modifiedStart -= bestDelta;
    }
    return changes;
  }
  _OriginalIsBoundary(index3) {
    if (index3 <= 0 || index3 >= this._originalElementsOrHash.length - 1) {
      return true;
    }
    return this._hasStrings && /^\s*$/.test(this._originalStringElements[index3]);
  }
  _OriginalRegionIsBoundary(originalStart, originalLength) {
    if (this._OriginalIsBoundary(originalStart) || this._OriginalIsBoundary(originalStart - 1)) {
      return true;
    }
    if (originalLength > 0) {
      const originalEnd = originalStart + originalLength;
      if (this._OriginalIsBoundary(originalEnd - 1) || this._OriginalIsBoundary(originalEnd)) {
        return true;
      }
    }
    return false;
  }
  _ModifiedIsBoundary(index3) {
    if (index3 <= 0 || index3 >= this._modifiedElementsOrHash.length - 1) {
      return true;
    }
    return this._hasStrings && /^\s*$/.test(this._modifiedStringElements[index3]);
  }
  _ModifiedRegionIsBoundary(modifiedStart, modifiedLength) {
    if (this._ModifiedIsBoundary(modifiedStart) || this._ModifiedIsBoundary(modifiedStart - 1)) {
      return true;
    }
    if (modifiedLength > 0) {
      const modifiedEnd = modifiedStart + modifiedLength;
      if (this._ModifiedIsBoundary(modifiedEnd - 1) || this._ModifiedIsBoundary(modifiedEnd)) {
        return true;
      }
    }
    return false;
  }
  _boundaryScore(originalStart, originalLength, modifiedStart, modifiedLength) {
    const originalScore = this._OriginalRegionIsBoundary(originalStart, originalLength) ? 1 : 0;
    const modifiedScore = this._ModifiedRegionIsBoundary(modifiedStart, modifiedLength) ? 1 : 0;
    return originalScore + modifiedScore;
  }
  ConcatenateChanges(left2, right2) {
    let mergedChangeArr = [];
    if (left2.length === 0 || right2.length === 0) {
      return right2.length > 0 ? right2 : left2;
    } else if (this.ChangesOverlap(left2[left2.length - 1], right2[0], mergedChangeArr)) {
      const result = new Array(left2.length + right2.length - 1);
      MyArray.Copy(left2, 0, result, 0, left2.length - 1);
      result[left2.length - 1] = mergedChangeArr[0];
      MyArray.Copy(right2, 1, result, left2.length, right2.length - 1);
      return result;
    } else {
      const result = new Array(left2.length + right2.length);
      MyArray.Copy(left2, 0, result, 0, left2.length);
      MyArray.Copy(right2, 0, result, left2.length, right2.length);
      return result;
    }
  }
  ChangesOverlap(left2, right2, mergedChangeArr) {
    Debug.Assert(left2.originalStart <= right2.originalStart, "Left change is not less than or equal to right change");
    Debug.Assert(left2.modifiedStart <= right2.modifiedStart, "Left change is not less than or equal to right change");
    if (left2.originalStart + left2.originalLength >= right2.originalStart || left2.modifiedStart + left2.modifiedLength >= right2.modifiedStart) {
      const originalStart = left2.originalStart;
      let originalLength = left2.originalLength;
      const modifiedStart = left2.modifiedStart;
      let modifiedLength = left2.modifiedLength;
      if (left2.originalStart + left2.originalLength >= right2.originalStart) {
        originalLength = right2.originalStart + right2.originalLength - left2.originalStart;
      }
      if (left2.modifiedStart + left2.modifiedLength >= right2.modifiedStart) {
        modifiedLength = right2.modifiedStart + right2.modifiedLength - left2.modifiedStart;
      }
      mergedChangeArr[0] = new DiffChange(originalStart, originalLength, modifiedStart, modifiedLength);
      return true;
    } else {
      mergedChangeArr[0] = null;
      return false;
    }
  }
  ClipDiagonalBound(diagonal, numDifferences, diagonalBaseIndex, numDiagonals) {
    if (diagonal >= 0 && diagonal < numDiagonals) {
      return diagonal;
    }
    const diagonalsBelow = diagonalBaseIndex;
    const diagonalsAbove = numDiagonals - diagonalBaseIndex - 1;
    const diffEven = numDifferences % 2 === 0;
    if (diagonal < 0) {
      const lowerBoundEven = diagonalsBelow % 2 === 0;
      return diffEven === lowerBoundEven ? 0 : 1;
    } else {
      const upperBoundEven = diagonalsAbove % 2 === 0;
      return diffEven === upperBoundEven ? numDiagonals - 1 : numDiagonals - 2;
    }
  }
};
var MINIMUM_MATCHING_CHARACTER_LENGTH = 3;
function computeDiff(originalSequence, modifiedSequence, continueProcessingPredicate, pretty) {
  const diffAlgo = new LcsDiff(originalSequence, modifiedSequence, continueProcessingPredicate);
  return diffAlgo.ComputeDiff(pretty);
}
var LineSequence = class {
  constructor(lines) {
    const startColumns = [];
    const endColumns = [];
    for (let i3 = 0, length = lines.length; i3 < length; i3++) {
      startColumns[i3] = getFirstNonBlankColumn(lines[i3], 1);
      endColumns[i3] = getLastNonBlankColumn(lines[i3], 1);
    }
    this.lines = lines;
    this._startColumns = startColumns;
    this._endColumns = endColumns;
  }
  getElements() {
    const elements = [];
    for (let i3 = 0, len2 = this.lines.length; i3 < len2; i3++) {
      elements[i3] = this.lines[i3].substring(this._startColumns[i3] - 1, this._endColumns[i3] - 1);
    }
    return elements;
  }
  getStartLineNumber(i3) {
    return i3 + 1;
  }
  getEndLineNumber(i3) {
    return i3 + 1;
  }
  createCharSequence(shouldIgnoreTrimWhitespace, startIndex, endIndex) {
    const charCodes = [];
    const lineNumbers = [];
    const columns = [];
    let len2 = 0;
    for (let index3 = startIndex; index3 <= endIndex; index3++) {
      const lineContent = this.lines[index3];
      const startColumn = shouldIgnoreTrimWhitespace ? this._startColumns[index3] : 1;
      const endColumn = shouldIgnoreTrimWhitespace ? this._endColumns[index3] : lineContent.length + 1;
      for (let col = startColumn; col < endColumn; col++) {
        charCodes[len2] = lineContent.charCodeAt(col - 1);
        lineNumbers[len2] = index3 + 1;
        columns[len2] = col;
        len2++;
      }
    }
    return new CharSequence(charCodes, lineNumbers, columns);
  }
};
var CharSequence = class {
  constructor(charCodes, lineNumbers, columns) {
    this._charCodes = charCodes;
    this._lineNumbers = lineNumbers;
    this._columns = columns;
  }
  getElements() {
    return this._charCodes;
  }
  getStartLineNumber(i3) {
    return this._lineNumbers[i3];
  }
  getStartColumn(i3) {
    return this._columns[i3];
  }
  getEndLineNumber(i3) {
    return this._lineNumbers[i3];
  }
  getEndColumn(i3) {
    return this._columns[i3] + 1;
  }
};
var CharChange = class {
  constructor(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn) {
    this.originalStartLineNumber = originalStartLineNumber;
    this.originalStartColumn = originalStartColumn;
    this.originalEndLineNumber = originalEndLineNumber;
    this.originalEndColumn = originalEndColumn;
    this.modifiedStartLineNumber = modifiedStartLineNumber;
    this.modifiedStartColumn = modifiedStartColumn;
    this.modifiedEndLineNumber = modifiedEndLineNumber;
    this.modifiedEndColumn = modifiedEndColumn;
  }
  static createFromDiffChange(diffChange, originalCharSequence, modifiedCharSequence) {
    let originalStartLineNumber;
    let originalStartColumn;
    let originalEndLineNumber;
    let originalEndColumn;
    let modifiedStartLineNumber;
    let modifiedStartColumn;
    let modifiedEndLineNumber;
    let modifiedEndColumn;
    if (diffChange.originalLength === 0) {
      originalStartLineNumber = 0;
      originalStartColumn = 0;
      originalEndLineNumber = 0;
      originalEndColumn = 0;
    } else {
      originalStartLineNumber = originalCharSequence.getStartLineNumber(diffChange.originalStart);
      originalStartColumn = originalCharSequence.getStartColumn(diffChange.originalStart);
      originalEndLineNumber = originalCharSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
      originalEndColumn = originalCharSequence.getEndColumn(diffChange.originalStart + diffChange.originalLength - 1);
    }
    if (diffChange.modifiedLength === 0) {
      modifiedStartLineNumber = 0;
      modifiedStartColumn = 0;
      modifiedEndLineNumber = 0;
      modifiedEndColumn = 0;
    } else {
      modifiedStartLineNumber = modifiedCharSequence.getStartLineNumber(diffChange.modifiedStart);
      modifiedStartColumn = modifiedCharSequence.getStartColumn(diffChange.modifiedStart);
      modifiedEndLineNumber = modifiedCharSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
      modifiedEndColumn = modifiedCharSequence.getEndColumn(diffChange.modifiedStart + diffChange.modifiedLength - 1);
    }
    return new CharChange(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn);
  }
};
function postProcessCharChanges(rawChanges) {
  if (rawChanges.length <= 1) {
    return rawChanges;
  }
  const result = [rawChanges[0]];
  let prevChange = result[0];
  for (let i3 = 1, len2 = rawChanges.length; i3 < len2; i3++) {
    const currChange = rawChanges[i3];
    const originalMatchingLength = currChange.originalStart - (prevChange.originalStart + prevChange.originalLength);
    const modifiedMatchingLength = currChange.modifiedStart - (prevChange.modifiedStart + prevChange.modifiedLength);
    const matchingLength = Math.min(originalMatchingLength, modifiedMatchingLength);
    if (matchingLength < MINIMUM_MATCHING_CHARACTER_LENGTH) {
      prevChange.originalLength = currChange.originalStart + currChange.originalLength - prevChange.originalStart;
      prevChange.modifiedLength = currChange.modifiedStart + currChange.modifiedLength - prevChange.modifiedStart;
    } else {
      result.push(currChange);
      prevChange = currChange;
    }
  }
  return result;
}
var LineChange = class {
  constructor(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges) {
    this.originalStartLineNumber = originalStartLineNumber;
    this.originalEndLineNumber = originalEndLineNumber;
    this.modifiedStartLineNumber = modifiedStartLineNumber;
    this.modifiedEndLineNumber = modifiedEndLineNumber;
    this.charChanges = charChanges;
  }
  static createFromDiffResult(shouldIgnoreTrimWhitespace, diffChange, originalLineSequence, modifiedLineSequence, continueCharDiff, shouldComputeCharChanges, shouldPostProcessCharChanges) {
    let originalStartLineNumber;
    let originalEndLineNumber;
    let modifiedStartLineNumber;
    let modifiedEndLineNumber;
    let charChanges = void 0;
    if (diffChange.originalLength === 0) {
      originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart) - 1;
      originalEndLineNumber = 0;
    } else {
      originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart);
      originalEndLineNumber = originalLineSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
    }
    if (diffChange.modifiedLength === 0) {
      modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart) - 1;
      modifiedEndLineNumber = 0;
    } else {
      modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart);
      modifiedEndLineNumber = modifiedLineSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
    }
    if (shouldComputeCharChanges && diffChange.originalLength > 0 && diffChange.originalLength < 20 && diffChange.modifiedLength > 0 && diffChange.modifiedLength < 20 && continueCharDiff()) {
      const originalCharSequence = originalLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1);
      const modifiedCharSequence = modifiedLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1);
      let rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueCharDiff, true).changes;
      if (shouldPostProcessCharChanges) {
        rawChanges = postProcessCharChanges(rawChanges);
      }
      charChanges = [];
      for (let i3 = 0, length = rawChanges.length; i3 < length; i3++) {
        charChanges.push(CharChange.createFromDiffChange(rawChanges[i3], originalCharSequence, modifiedCharSequence));
      }
    }
    return new LineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges);
  }
};
var DiffComputer = class {
  constructor(originalLines, modifiedLines, opts) {
    this.shouldComputeCharChanges = opts.shouldComputeCharChanges;
    this.shouldPostProcessCharChanges = opts.shouldPostProcessCharChanges;
    this.shouldIgnoreTrimWhitespace = opts.shouldIgnoreTrimWhitespace;
    this.shouldMakePrettyDiff = opts.shouldMakePrettyDiff;
    this.originalLines = originalLines;
    this.modifiedLines = modifiedLines;
    this.original = new LineSequence(originalLines);
    this.modified = new LineSequence(modifiedLines);
    this.continueLineDiff = createContinueProcessingPredicate(opts.maxComputationTime);
    this.continueCharDiff = createContinueProcessingPredicate(opts.maxComputationTime === 0 ? 0 : Math.min(opts.maxComputationTime, 5e3));
  }
  computeDiff() {
    if (this.original.lines.length === 1 && this.original.lines[0].length === 0) {
      return {
        quitEarly: false,
        changes: [{
          originalStartLineNumber: 1,
          originalEndLineNumber: 1,
          modifiedStartLineNumber: 1,
          modifiedEndLineNumber: this.modified.lines.length,
          charChanges: [{
            modifiedEndColumn: 0,
            modifiedEndLineNumber: 0,
            modifiedStartColumn: 0,
            modifiedStartLineNumber: 0,
            originalEndColumn: 0,
            originalEndLineNumber: 0,
            originalStartColumn: 0,
            originalStartLineNumber: 0
          }]
        }]
      };
    }
    if (this.modified.lines.length === 1 && this.modified.lines[0].length === 0) {
      return {
        quitEarly: false,
        changes: [{
          originalStartLineNumber: 1,
          originalEndLineNumber: this.original.lines.length,
          modifiedStartLineNumber: 1,
          modifiedEndLineNumber: 1,
          charChanges: [{
            modifiedEndColumn: 0,
            modifiedEndLineNumber: 0,
            modifiedStartColumn: 0,
            modifiedStartLineNumber: 0,
            originalEndColumn: 0,
            originalEndLineNumber: 0,
            originalStartColumn: 0,
            originalStartLineNumber: 0
          }]
        }]
      };
    }
    const diffResult = computeDiff(this.original, this.modified, this.continueLineDiff, this.shouldMakePrettyDiff);
    const rawChanges = diffResult.changes;
    const quitEarly = diffResult.quitEarly;
    if (this.shouldIgnoreTrimWhitespace) {
      const lineChanges = [];
      for (let i3 = 0, length = rawChanges.length; i3 < length; i3++) {
        lineChanges.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, rawChanges[i3], this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
      }
      return {
        quitEarly,
        changes: lineChanges
      };
    }
    const result = [];
    let originalLineIndex = 0;
    let modifiedLineIndex = 0;
    for (let i3 = -1, len2 = rawChanges.length; i3 < len2; i3++) {
      const nextChange = i3 + 1 < len2 ? rawChanges[i3 + 1] : null;
      const originalStop = nextChange ? nextChange.originalStart : this.originalLines.length;
      const modifiedStop = nextChange ? nextChange.modifiedStart : this.modifiedLines.length;
      while (originalLineIndex < originalStop && modifiedLineIndex < modifiedStop) {
        const originalLine = this.originalLines[originalLineIndex];
        const modifiedLine = this.modifiedLines[modifiedLineIndex];
        if (originalLine !== modifiedLine) {
          {
            let originalStartColumn = getFirstNonBlankColumn(originalLine, 1);
            let modifiedStartColumn = getFirstNonBlankColumn(modifiedLine, 1);
            while (originalStartColumn > 1 && modifiedStartColumn > 1) {
              const originalChar = originalLine.charCodeAt(originalStartColumn - 2);
              const modifiedChar = modifiedLine.charCodeAt(modifiedStartColumn - 2);
              if (originalChar !== modifiedChar) {
                break;
              }
              originalStartColumn--;
              modifiedStartColumn--;
            }
            if (originalStartColumn > 1 || modifiedStartColumn > 1) {
              this._pushTrimWhitespaceCharChange(result, originalLineIndex + 1, 1, originalStartColumn, modifiedLineIndex + 1, 1, modifiedStartColumn);
            }
          }
          {
            let originalEndColumn = getLastNonBlankColumn(originalLine, 1);
            let modifiedEndColumn = getLastNonBlankColumn(modifiedLine, 1);
            const originalMaxColumn = originalLine.length + 1;
            const modifiedMaxColumn = modifiedLine.length + 1;
            while (originalEndColumn < originalMaxColumn && modifiedEndColumn < modifiedMaxColumn) {
              const originalChar = originalLine.charCodeAt(originalEndColumn - 1);
              const modifiedChar = originalLine.charCodeAt(modifiedEndColumn - 1);
              if (originalChar !== modifiedChar) {
                break;
              }
              originalEndColumn++;
              modifiedEndColumn++;
            }
            if (originalEndColumn < originalMaxColumn || modifiedEndColumn < modifiedMaxColumn) {
              this._pushTrimWhitespaceCharChange(result, originalLineIndex + 1, originalEndColumn, originalMaxColumn, modifiedLineIndex + 1, modifiedEndColumn, modifiedMaxColumn);
            }
          }
        }
        originalLineIndex++;
        modifiedLineIndex++;
      }
      if (nextChange) {
        result.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, nextChange, this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
        originalLineIndex += nextChange.originalLength;
        modifiedLineIndex += nextChange.modifiedLength;
      }
    }
    return {
      quitEarly,
      changes: result
    };
  }
  _pushTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
    if (this._mergeTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn)) {
      return;
    }
    let charChanges = void 0;
    if (this.shouldComputeCharChanges) {
      charChanges = [new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn)];
    }
    result.push(new LineChange(originalLineNumber, originalLineNumber, modifiedLineNumber, modifiedLineNumber, charChanges));
  }
  _mergeTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
    const len2 = result.length;
    if (len2 === 0) {
      return false;
    }
    const prevChange = result[len2 - 1];
    if (prevChange.originalEndLineNumber === 0 || prevChange.modifiedEndLineNumber === 0) {
      return false;
    }
    if (prevChange.originalEndLineNumber + 1 === originalLineNumber && prevChange.modifiedEndLineNumber + 1 === modifiedLineNumber) {
      prevChange.originalEndLineNumber = originalLineNumber;
      prevChange.modifiedEndLineNumber = modifiedLineNumber;
      if (this.shouldComputeCharChanges && prevChange.charChanges) {
        prevChange.charChanges.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn));
      }
      return true;
    }
    return false;
  }
};
function getFirstNonBlankColumn(txt, defaultValue) {
  const r3 = firstNonWhitespaceIndex(txt);
  if (r3 === -1) {
    return defaultValue;
  }
  return r3 + 1;
}
function getLastNonBlankColumn(txt, defaultValue) {
  const r3 = lastNonWhitespaceIndex(txt);
  if (r3 === -1) {
    return defaultValue;
  }
  return r3 + 2;
}
function createContinueProcessingPredicate(maximumRuntime) {
  if (maximumRuntime === 0) {
    return () => true;
  }
  const startTime2 = Date.now();
  return () => {
    return Date.now() - startTime2 < maximumRuntime;
  };
}
function toUint8(v2) {
  if (v2 < 0) {
    return 0;
  }
  if (v2 > 255) {
    return 255;
  }
  return v2 | 0;
}
function toUint32(v2) {
  if (v2 < 0) {
    return 0;
  }
  if (v2 > 4294967295) {
    return 4294967295;
  }
  return v2 | 0;
}
var PrefixSumIndexOfResult = class {
  constructor(index3, remainder) {
    this.index = index3;
    this.remainder = remainder;
  }
};
var PrefixSumComputer = class {
  constructor(values2) {
    this.values = values2;
    this.prefixSum = new Uint32Array(values2.length);
    this.prefixSumValidIndex = new Int32Array(1);
    this.prefixSumValidIndex[0] = -1;
  }
  insertValues(insertIndex, insertValues) {
    insertIndex = toUint32(insertIndex);
    const oldValues = this.values;
    const oldPrefixSum = this.prefixSum;
    const insertValuesLen = insertValues.length;
    if (insertValuesLen === 0) {
      return false;
    }
    this.values = new Uint32Array(oldValues.length + insertValuesLen);
    this.values.set(oldValues.subarray(0, insertIndex), 0);
    this.values.set(oldValues.subarray(insertIndex), insertIndex + insertValuesLen);
    this.values.set(insertValues, insertIndex);
    if (insertIndex - 1 < this.prefixSumValidIndex[0]) {
      this.prefixSumValidIndex[0] = insertIndex - 1;
    }
    this.prefixSum = new Uint32Array(this.values.length);
    if (this.prefixSumValidIndex[0] >= 0) {
      this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
    }
    return true;
  }
  changeValue(index3, value) {
    index3 = toUint32(index3);
    value = toUint32(value);
    if (this.values[index3] === value) {
      return false;
    }
    this.values[index3] = value;
    if (index3 - 1 < this.prefixSumValidIndex[0]) {
      this.prefixSumValidIndex[0] = index3 - 1;
    }
    return true;
  }
  removeValues(startIndex, cnt) {
    startIndex = toUint32(startIndex);
    cnt = toUint32(cnt);
    const oldValues = this.values;
    const oldPrefixSum = this.prefixSum;
    if (startIndex >= oldValues.length) {
      return false;
    }
    let maxCnt = oldValues.length - startIndex;
    if (cnt >= maxCnt) {
      cnt = maxCnt;
    }
    if (cnt === 0) {
      return false;
    }
    this.values = new Uint32Array(oldValues.length - cnt);
    this.values.set(oldValues.subarray(0, startIndex), 0);
    this.values.set(oldValues.subarray(startIndex + cnt), startIndex);
    this.prefixSum = new Uint32Array(this.values.length);
    if (startIndex - 1 < this.prefixSumValidIndex[0]) {
      this.prefixSumValidIndex[0] = startIndex - 1;
    }
    if (this.prefixSumValidIndex[0] >= 0) {
      this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
    }
    return true;
  }
  getTotalValue() {
    if (this.values.length === 0) {
      return 0;
    }
    return this._getAccumulatedValue(this.values.length - 1);
  }
  getAccumulatedValue(index3) {
    if (index3 < 0) {
      return 0;
    }
    index3 = toUint32(index3);
    return this._getAccumulatedValue(index3);
  }
  _getAccumulatedValue(index3) {
    if (index3 <= this.prefixSumValidIndex[0]) {
      return this.prefixSum[index3];
    }
    let startIndex = this.prefixSumValidIndex[0] + 1;
    if (startIndex === 0) {
      this.prefixSum[0] = this.values[0];
      startIndex++;
    }
    if (index3 >= this.values.length) {
      index3 = this.values.length - 1;
    }
    for (let i3 = startIndex; i3 <= index3; i3++) {
      this.prefixSum[i3] = this.prefixSum[i3 - 1] + this.values[i3];
    }
    this.prefixSumValidIndex[0] = Math.max(this.prefixSumValidIndex[0], index3);
    return this.prefixSum[index3];
  }
  getIndexOf(accumulatedValue) {
    accumulatedValue = Math.floor(accumulatedValue);
    this.getTotalValue();
    let low = 0;
    let high = this.values.length - 1;
    let mid = 0;
    let midStop = 0;
    let midStart = 0;
    while (low <= high) {
      mid = low + (high - low) / 2 | 0;
      midStop = this.prefixSum[mid];
      midStart = midStop - this.values[mid];
      if (accumulatedValue < midStart) {
        high = mid - 1;
      } else if (accumulatedValue >= midStop) {
        low = mid + 1;
      } else {
        break;
      }
    }
    return new PrefixSumIndexOfResult(mid, accumulatedValue - midStart);
  }
};
var MirrorTextModel = class {
  constructor(uri, lines, eol, versionId) {
    this._uri = uri;
    this._lines = lines;
    this._eol = eol;
    this._versionId = versionId;
    this._lineStarts = null;
    this._cachedTextValue = null;
  }
  dispose() {
    this._lines.length = 0;
  }
  getText() {
    if (this._cachedTextValue === null) {
      this._cachedTextValue = this._lines.join(this._eol);
    }
    return this._cachedTextValue;
  }
  onEvents(e2) {
    if (e2.eol && e2.eol !== this._eol) {
      this._eol = e2.eol;
      this._lineStarts = null;
    }
    const changes = e2.changes;
    for (const change of changes) {
      this._acceptDeleteRange(change.range);
      this._acceptInsertText(new Position(change.range.startLineNumber, change.range.startColumn), change.text);
    }
    this._versionId = e2.versionId;
    this._cachedTextValue = null;
  }
  _ensureLineStarts() {
    if (!this._lineStarts) {
      const eolLength = this._eol.length;
      const linesLength = this._lines.length;
      const lineStartValues = new Uint32Array(linesLength);
      for (let i3 = 0; i3 < linesLength; i3++) {
        lineStartValues[i3] = this._lines[i3].length + eolLength;
      }
      this._lineStarts = new PrefixSumComputer(lineStartValues);
    }
  }
  _setLineText(lineIndex, newValue) {
    this._lines[lineIndex] = newValue;
    if (this._lineStarts) {
      this._lineStarts.changeValue(lineIndex, this._lines[lineIndex].length + this._eol.length);
    }
  }
  _acceptDeleteRange(range3) {
    if (range3.startLineNumber === range3.endLineNumber) {
      if (range3.startColumn === range3.endColumn) {
        return;
      }
      this._setLineText(range3.startLineNumber - 1, this._lines[range3.startLineNumber - 1].substring(0, range3.startColumn - 1) + this._lines[range3.startLineNumber - 1].substring(range3.endColumn - 1));
      return;
    }
    this._setLineText(range3.startLineNumber - 1, this._lines[range3.startLineNumber - 1].substring(0, range3.startColumn - 1) + this._lines[range3.endLineNumber - 1].substring(range3.endColumn - 1));
    this._lines.splice(range3.startLineNumber, range3.endLineNumber - range3.startLineNumber);
    if (this._lineStarts) {
      this._lineStarts.removeValues(range3.startLineNumber, range3.endLineNumber - range3.startLineNumber);
    }
  }
  _acceptInsertText(position2, insertText) {
    if (insertText.length === 0) {
      return;
    }
    let insertLines = insertText.split(/\r\n|\r|\n/);
    if (insertLines.length === 1) {
      this._setLineText(position2.lineNumber - 1, this._lines[position2.lineNumber - 1].substring(0, position2.column - 1) + insertLines[0] + this._lines[position2.lineNumber - 1].substring(position2.column - 1));
      return;
    }
    insertLines[insertLines.length - 1] += this._lines[position2.lineNumber - 1].substring(position2.column - 1);
    this._setLineText(position2.lineNumber - 1, this._lines[position2.lineNumber - 1].substring(0, position2.column - 1) + insertLines[0]);
    let newLengths = new Uint32Array(insertLines.length - 1);
    for (let i3 = 1; i3 < insertLines.length; i3++) {
      this._lines.splice(position2.lineNumber + i3 - 1, 0, insertLines[i3]);
      newLengths[i3 - 1] = insertLines[i3].length + this._eol.length;
    }
    if (this._lineStarts) {
      this._lineStarts.insertValues(position2.lineNumber, newLengths);
    }
  }
};
var CharacterClassifier = class {
  constructor(_defaultValue) {
    let defaultValue = toUint8(_defaultValue);
    this._defaultValue = defaultValue;
    this._asciiMap = CharacterClassifier._createAsciiMap(defaultValue);
    this._map = new Map();
  }
  static _createAsciiMap(defaultValue) {
    let asciiMap = new Uint8Array(256);
    for (let i3 = 0; i3 < 256; i3++) {
      asciiMap[i3] = defaultValue;
    }
    return asciiMap;
  }
  set(charCode, _value) {
    let value = toUint8(_value);
    if (charCode >= 0 && charCode < 256) {
      this._asciiMap[charCode] = value;
    } else {
      this._map.set(charCode, value);
    }
  }
  get(charCode) {
    if (charCode >= 0 && charCode < 256) {
      return this._asciiMap[charCode];
    } else {
      return this._map.get(charCode) || this._defaultValue;
    }
  }
};
var Uint8Matrix = class {
  constructor(rows, cols, defaultValue) {
    const data2 = new Uint8Array(rows * cols);
    for (let i3 = 0, len2 = rows * cols; i3 < len2; i3++) {
      data2[i3] = defaultValue;
    }
    this._data = data2;
    this.rows = rows;
    this.cols = cols;
  }
  get(row, col) {
    return this._data[row * this.cols + col];
  }
  set(row, col, value) {
    this._data[row * this.cols + col] = value;
  }
};
var StateMachine = class {
  constructor(edges) {
    let maxCharCode = 0;
    let maxState = 0;
    for (let i3 = 0, len2 = edges.length; i3 < len2; i3++) {
      let [from, chCode, to] = edges[i3];
      if (chCode > maxCharCode) {
        maxCharCode = chCode;
      }
      if (from > maxState) {
        maxState = from;
      }
      if (to > maxState) {
        maxState = to;
      }
    }
    maxCharCode++;
    maxState++;
    let states = new Uint8Matrix(maxState, maxCharCode, 0);
    for (let i3 = 0, len2 = edges.length; i3 < len2; i3++) {
      let [from, chCode, to] = edges[i3];
      states.set(from, chCode, to);
    }
    this._states = states;
    this._maxCharCode = maxCharCode;
  }
  nextState(currentState, chCode) {
    if (chCode < 0 || chCode >= this._maxCharCode) {
      return 0;
    }
    return this._states.get(currentState, chCode);
  }
};
var _stateMachine = null;
function getStateMachine() {
  if (_stateMachine === null) {
    _stateMachine = new StateMachine([
      [1, 104, 2],
      [1, 72, 2],
      [1, 102, 6],
      [1, 70, 6],
      [2, 116, 3],
      [2, 84, 3],
      [3, 116, 4],
      [3, 84, 4],
      [4, 112, 5],
      [4, 80, 5],
      [5, 115, 9],
      [5, 83, 9],
      [5, 58, 10],
      [6, 105, 7],
      [6, 73, 7],
      [7, 108, 8],
      [7, 76, 8],
      [8, 101, 9],
      [8, 69, 9],
      [9, 58, 10],
      [10, 47, 11],
      [11, 47, 12]
    ]);
  }
  return _stateMachine;
}
var _classifier = null;
function getClassifier() {
  if (_classifier === null) {
    _classifier = new CharacterClassifier(0);
    const FORCE_TERMINATION_CHARACTERS = ` 	<>'"、。｡､，．：；‘“〈《「『【〔（［｛｢｣｝］）〕】』」》〉”’｀～…`;
    for (let i3 = 0; i3 < FORCE_TERMINATION_CHARACTERS.length; i3++) {
      _classifier.set(FORCE_TERMINATION_CHARACTERS.charCodeAt(i3), 1);
    }
    const CANNOT_END_WITH_CHARACTERS = ".,;";
    for (let i3 = 0; i3 < CANNOT_END_WITH_CHARACTERS.length; i3++) {
      _classifier.set(CANNOT_END_WITH_CHARACTERS.charCodeAt(i3), 2);
    }
  }
  return _classifier;
}
var LinkComputer = class {
  static _createLink(classifier, line, lineNumber, linkBeginIndex, linkEndIndex) {
    let lastIncludedCharIndex = linkEndIndex - 1;
    do {
      const chCode = line.charCodeAt(lastIncludedCharIndex);
      const chClass = classifier.get(chCode);
      if (chClass !== 2) {
        break;
      }
      lastIncludedCharIndex--;
    } while (lastIncludedCharIndex > linkBeginIndex);
    if (linkBeginIndex > 0) {
      const charCodeBeforeLink = line.charCodeAt(linkBeginIndex - 1);
      const lastCharCodeInLink = line.charCodeAt(lastIncludedCharIndex);
      if (charCodeBeforeLink === 40 && lastCharCodeInLink === 41 || charCodeBeforeLink === 91 && lastCharCodeInLink === 93 || charCodeBeforeLink === 123 && lastCharCodeInLink === 125) {
        lastIncludedCharIndex--;
      }
    }
    return {
      range: {
        startLineNumber: lineNumber,
        startColumn: linkBeginIndex + 1,
        endLineNumber: lineNumber,
        endColumn: lastIncludedCharIndex + 2
      },
      url: line.substring(linkBeginIndex, lastIncludedCharIndex + 1)
    };
  }
  static computeLinks(model, stateMachine = getStateMachine()) {
    const classifier = getClassifier();
    let result = [];
    for (let i3 = 1, lineCount = model.getLineCount(); i3 <= lineCount; i3++) {
      const line = model.getLineContent(i3);
      const len2 = line.length;
      let j = 0;
      let linkBeginIndex = 0;
      let linkBeginChCode = 0;
      let state = 1;
      let hasOpenParens = false;
      let hasOpenSquareBracket = false;
      let inSquareBrackets = false;
      let hasOpenCurlyBracket = false;
      while (j < len2) {
        let resetStateMachine = false;
        const chCode = line.charCodeAt(j);
        if (state === 13) {
          let chClass;
          switch (chCode) {
            case 40:
              hasOpenParens = true;
              chClass = 0;
              break;
            case 41:
              chClass = hasOpenParens ? 0 : 1;
              break;
            case 91:
              inSquareBrackets = true;
              hasOpenSquareBracket = true;
              chClass = 0;
              break;
            case 93:
              inSquareBrackets = false;
              chClass = hasOpenSquareBracket ? 0 : 1;
              break;
            case 123:
              hasOpenCurlyBracket = true;
              chClass = 0;
              break;
            case 125:
              chClass = hasOpenCurlyBracket ? 0 : 1;
              break;
            case 39:
              chClass = linkBeginChCode === 34 || linkBeginChCode === 96 ? 0 : 1;
              break;
            case 34:
              chClass = linkBeginChCode === 39 || linkBeginChCode === 96 ? 0 : 1;
              break;
            case 96:
              chClass = linkBeginChCode === 39 || linkBeginChCode === 34 ? 0 : 1;
              break;
            case 42:
              chClass = linkBeginChCode === 42 ? 1 : 0;
              break;
            case 124:
              chClass = linkBeginChCode === 124 ? 1 : 0;
              break;
            case 32:
              chClass = inSquareBrackets ? 0 : 1;
              break;
            default:
              chClass = classifier.get(chCode);
          }
          if (chClass === 1) {
            result.push(LinkComputer._createLink(classifier, line, i3, linkBeginIndex, j));
            resetStateMachine = true;
          }
        } else if (state === 12) {
          let chClass;
          if (chCode === 91) {
            hasOpenSquareBracket = true;
            chClass = 0;
          } else {
            chClass = classifier.get(chCode);
          }
          if (chClass === 1) {
            resetStateMachine = true;
          } else {
            state = 13;
          }
        } else {
          state = stateMachine.nextState(state, chCode);
          if (state === 0) {
            resetStateMachine = true;
          }
        }
        if (resetStateMachine) {
          state = 1;
          hasOpenParens = false;
          hasOpenSquareBracket = false;
          hasOpenCurlyBracket = false;
          linkBeginIndex = j + 1;
          linkBeginChCode = chCode;
        }
        j++;
      }
      if (state === 13) {
        result.push(LinkComputer._createLink(classifier, line, i3, linkBeginIndex, len2));
      }
    }
    return result;
  }
};
function computeLinks(model) {
  if (!model || typeof model.getLineCount !== "function" || typeof model.getLineContent !== "function") {
    return [];
  }
  return LinkComputer.computeLinks(model);
}
var BasicInplaceReplace = class {
  constructor() {
    this._defaultValueSet = [
      ["true", "false"],
      ["True", "False"],
      ["Private", "Public", "Friend", "ReadOnly", "Partial", "Protected", "WriteOnly"],
      ["public", "protected", "private"]
    ];
  }
  navigateValueSet(range1, text1, range22, text2, up) {
    if (range1 && text1) {
      let result = this.doNavigateValueSet(text1, up);
      if (result) {
        return {
          range: range1,
          value: result
        };
      }
    }
    if (range22 && text2) {
      let result = this.doNavigateValueSet(text2, up);
      if (result) {
        return {
          range: range22,
          value: result
        };
      }
    }
    return null;
  }
  doNavigateValueSet(text, up) {
    let numberResult = this.numberReplace(text, up);
    if (numberResult !== null) {
      return numberResult;
    }
    return this.textReplace(text, up);
  }
  numberReplace(value, up) {
    let precision = Math.pow(10, value.length - (value.lastIndexOf(".") + 1));
    let n1 = Number(value);
    let n22 = parseFloat(value);
    if (!isNaN(n1) && !isNaN(n22) && n1 === n22) {
      if (n1 === 0 && !up) {
        return null;
      } else {
        n1 = Math.floor(n1 * precision);
        n1 += up ? precision : -precision;
        return String(n1 / precision);
      }
    }
    return null;
  }
  textReplace(value, up) {
    return this.valueSetsReplace(this._defaultValueSet, value, up);
  }
  valueSetsReplace(valueSets, value, up) {
    let result = null;
    for (let i3 = 0, len2 = valueSets.length; result === null && i3 < len2; i3++) {
      result = this.valueSetReplace(valueSets[i3], value, up);
    }
    return result;
  }
  valueSetReplace(valueSet, value, up) {
    let idx = valueSet.indexOf(value);
    if (idx >= 0) {
      idx += up ? 1 : -1;
      if (idx < 0) {
        idx = valueSet.length - 1;
      } else {
        idx %= valueSet.length;
      }
      return valueSet[idx];
    }
    return null;
  }
};
BasicInplaceReplace.INSTANCE = new BasicInplaceReplace();
var __awaiter$2 = function(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var MirrorModel = class extends MirrorTextModel {
  get uri() {
    return this._uri;
  }
  get version() {
    return this._versionId;
  }
  get eol() {
    return this._eol;
  }
  getValue() {
    return this.getText();
  }
  getLinesContent() {
    return this._lines.slice(0);
  }
  getLineCount() {
    return this._lines.length;
  }
  getLineContent(lineNumber) {
    return this._lines[lineNumber - 1];
  }
  getWordAtPosition(position2, wordDefinition) {
    let wordAtText = getWordAtText(position2.column, ensureValidWordDefinition(wordDefinition), this._lines[position2.lineNumber - 1], 0);
    if (wordAtText) {
      return new Range(position2.lineNumber, wordAtText.startColumn, position2.lineNumber, wordAtText.endColumn);
    }
    return null;
  }
  words(wordDefinition) {
    const lines = this._lines;
    const wordenize = this._wordenize.bind(this);
    let lineNumber = 0;
    let lineText = "";
    let wordRangesIdx = 0;
    let wordRanges = [];
    return {
      *[Symbol.iterator]() {
        while (true) {
          if (wordRangesIdx < wordRanges.length) {
            const value = lineText.substring(wordRanges[wordRangesIdx].start, wordRanges[wordRangesIdx].end);
            wordRangesIdx += 1;
            yield value;
          } else {
            if (lineNumber < lines.length) {
              lineText = lines[lineNumber];
              wordRanges = wordenize(lineText, wordDefinition);
              wordRangesIdx = 0;
              lineNumber += 1;
            } else {
              break;
            }
          }
        }
      }
    };
  }
  getLineWords(lineNumber, wordDefinition) {
    let content2 = this._lines[lineNumber - 1];
    let ranges = this._wordenize(content2, wordDefinition);
    let words2 = [];
    for (const range3 of ranges) {
      words2.push({
        word: content2.substring(range3.start, range3.end),
        startColumn: range3.start + 1,
        endColumn: range3.end + 1
      });
    }
    return words2;
  }
  _wordenize(content2, wordDefinition) {
    const result = [];
    let match2;
    wordDefinition.lastIndex = 0;
    while (match2 = wordDefinition.exec(content2)) {
      if (match2[0].length === 0) {
        break;
      }
      result.push({start: match2.index, end: match2.index + match2[0].length});
    }
    return result;
  }
  getValueInRange(range3) {
    range3 = this._validateRange(range3);
    if (range3.startLineNumber === range3.endLineNumber) {
      return this._lines[range3.startLineNumber - 1].substring(range3.startColumn - 1, range3.endColumn - 1);
    }
    let lineEnding = this._eol;
    let startLineIndex = range3.startLineNumber - 1;
    let endLineIndex = range3.endLineNumber - 1;
    let resultLines = [];
    resultLines.push(this._lines[startLineIndex].substring(range3.startColumn - 1));
    for (let i3 = startLineIndex + 1; i3 < endLineIndex; i3++) {
      resultLines.push(this._lines[i3]);
    }
    resultLines.push(this._lines[endLineIndex].substring(0, range3.endColumn - 1));
    return resultLines.join(lineEnding);
  }
  offsetAt(position2) {
    position2 = this._validatePosition(position2);
    this._ensureLineStarts();
    return this._lineStarts.getAccumulatedValue(position2.lineNumber - 2) + (position2.column - 1);
  }
  positionAt(offset2) {
    offset2 = Math.floor(offset2);
    offset2 = Math.max(0, offset2);
    this._ensureLineStarts();
    let out = this._lineStarts.getIndexOf(offset2);
    let lineLength = this._lines[out.index].length;
    return {
      lineNumber: 1 + out.index,
      column: 1 + Math.min(out.remainder, lineLength)
    };
  }
  _validateRange(range3) {
    const start3 = this._validatePosition({lineNumber: range3.startLineNumber, column: range3.startColumn});
    const end2 = this._validatePosition({lineNumber: range3.endLineNumber, column: range3.endColumn});
    if (start3.lineNumber !== range3.startLineNumber || start3.column !== range3.startColumn || end2.lineNumber !== range3.endLineNumber || end2.column !== range3.endColumn) {
      return {
        startLineNumber: start3.lineNumber,
        startColumn: start3.column,
        endLineNumber: end2.lineNumber,
        endColumn: end2.column
      };
    }
    return range3;
  }
  _validatePosition(position2) {
    if (!Position.isIPosition(position2)) {
      throw new Error("bad position");
    }
    let {lineNumber, column} = position2;
    let hasChanged = false;
    if (lineNumber < 1) {
      lineNumber = 1;
      column = 1;
      hasChanged = true;
    } else if (lineNumber > this._lines.length) {
      lineNumber = this._lines.length;
      column = this._lines[lineNumber - 1].length + 1;
      hasChanged = true;
    } else {
      let maxCharacter = this._lines[lineNumber - 1].length + 1;
      if (column < 1) {
        column = 1;
        hasChanged = true;
      } else if (column > maxCharacter) {
        column = maxCharacter;
        hasChanged = true;
      }
    }
    if (!hasChanged) {
      return position2;
    } else {
      return {lineNumber, column};
    }
  }
};
var EditorSimpleWorker = class {
  constructor(host, foreignModuleFactory) {
    this._host = host;
    this._models = Object.create(null);
    this._foreignModuleFactory = foreignModuleFactory;
    this._foreignModule = null;
  }
  dispose() {
    this._models = Object.create(null);
  }
  _getModel(uri) {
    return this._models[uri];
  }
  _getModels() {
    let all2 = [];
    Object.keys(this._models).forEach((key) => all2.push(this._models[key]));
    return all2;
  }
  acceptNewModel(data2) {
    this._models[data2.url] = new MirrorModel(URI.parse(data2.url), data2.lines, data2.EOL, data2.versionId);
  }
  acceptModelChanged(strURL, e2) {
    if (!this._models[strURL]) {
      return;
    }
    let model = this._models[strURL];
    model.onEvents(e2);
  }
  acceptRemovedModel(strURL) {
    if (!this._models[strURL]) {
      return;
    }
    delete this._models[strURL];
  }
  computeDiff(originalUrl, modifiedUrl, ignoreTrimWhitespace, maxComputationTime) {
    return __awaiter$2(this, void 0, void 0, function* () {
      const original = this._getModel(originalUrl);
      const modified = this._getModel(modifiedUrl);
      if (!original || !modified) {
        return null;
      }
      const originalLines = original.getLinesContent();
      const modifiedLines = modified.getLinesContent();
      const diffComputer = new DiffComputer(originalLines, modifiedLines, {
        shouldComputeCharChanges: true,
        shouldPostProcessCharChanges: true,
        shouldIgnoreTrimWhitespace: ignoreTrimWhitespace,
        shouldMakePrettyDiff: true,
        maxComputationTime
      });
      const diffResult = diffComputer.computeDiff();
      const identical = diffResult.changes.length > 0 ? false : this._modelsAreIdentical(original, modified);
      return {
        quitEarly: diffResult.quitEarly,
        identical,
        changes: diffResult.changes
      };
    });
  }
  _modelsAreIdentical(original, modified) {
    const originalLineCount = original.getLineCount();
    const modifiedLineCount = modified.getLineCount();
    if (originalLineCount !== modifiedLineCount) {
      return false;
    }
    for (let line = 1; line <= originalLineCount; line++) {
      const originalLine = original.getLineContent(line);
      const modifiedLine = modified.getLineContent(line);
      if (originalLine !== modifiedLine) {
        return false;
      }
    }
    return true;
  }
  computeMoreMinimalEdits(modelUrl, edits) {
    return __awaiter$2(this, void 0, void 0, function* () {
      const model = this._getModel(modelUrl);
      if (!model) {
        return edits;
      }
      const result = [];
      let lastEol = void 0;
      edits = mergeSort(edits, (a2, b2) => {
        if (a2.range && b2.range) {
          return Range.compareRangesUsingStarts(a2.range, b2.range);
        }
        let aRng = a2.range ? 0 : 1;
        let bRng = b2.range ? 0 : 1;
        return aRng - bRng;
      });
      for (let {range: range3, text, eol} of edits) {
        if (typeof eol === "number") {
          lastEol = eol;
        }
        if (Range.isEmpty(range3) && !text) {
          continue;
        }
        const original = model.getValueInRange(range3);
        text = text.replace(/\r\n|\n|\r/g, model.eol);
        if (original === text) {
          continue;
        }
        if (Math.max(text.length, original.length) > EditorSimpleWorker._diffLimit) {
          result.push({range: range3, text});
          continue;
        }
        const changes = stringDiff(original, text, false);
        const editOffset = model.offsetAt(Range.lift(range3).getStartPosition());
        for (const change of changes) {
          const start3 = model.positionAt(editOffset + change.originalStart);
          const end2 = model.positionAt(editOffset + change.originalStart + change.originalLength);
          const newEdit = {
            text: text.substr(change.modifiedStart, change.modifiedLength),
            range: {startLineNumber: start3.lineNumber, startColumn: start3.column, endLineNumber: end2.lineNumber, endColumn: end2.column}
          };
          if (model.getValueInRange(newEdit.range) !== newEdit.text) {
            result.push(newEdit);
          }
        }
      }
      if (typeof lastEol === "number") {
        result.push({eol: lastEol, text: "", range: {startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0}});
      }
      return result;
    });
  }
  computeLinks(modelUrl) {
    return __awaiter$2(this, void 0, void 0, function* () {
      let model = this._getModel(modelUrl);
      if (!model) {
        return null;
      }
      return computeLinks(model);
    });
  }
  textualSuggest(modelUrl, position2, wordDef, wordDefFlags) {
    return __awaiter$2(this, void 0, void 0, function* () {
      const model = this._getModel(modelUrl);
      if (!model) {
        return null;
      }
      const words2 = [];
      const seen = new Set();
      const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
      const wordAt = model.getWordAtPosition(position2, wordDefRegExp);
      if (wordAt) {
        seen.add(model.getValueInRange(wordAt));
      }
      for (let word of model.words(wordDefRegExp)) {
        if (seen.has(word)) {
          continue;
        }
        seen.add(word);
        if (!isNaN(Number(word))) {
          continue;
        }
        words2.push(word);
        if (seen.size > EditorSimpleWorker._suggestionsLimit) {
          break;
        }
      }
      return words2;
    });
  }
  computeWordRanges(modelUrl, range3, wordDef, wordDefFlags) {
    return __awaiter$2(this, void 0, void 0, function* () {
      let model = this._getModel(modelUrl);
      if (!model) {
        return Object.create(null);
      }
      const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
      const result = Object.create(null);
      for (let line = range3.startLineNumber; line < range3.endLineNumber; line++) {
        let words2 = model.getLineWords(line, wordDefRegExp);
        for (const word of words2) {
          if (!isNaN(Number(word.word))) {
            continue;
          }
          let array2 = result[word.word];
          if (!array2) {
            array2 = [];
            result[word.word] = array2;
          }
          array2.push({
            startLineNumber: line,
            startColumn: word.startColumn,
            endLineNumber: line,
            endColumn: word.endColumn
          });
        }
      }
      return result;
    });
  }
  navigateValueSet(modelUrl, range3, up, wordDef, wordDefFlags) {
    return __awaiter$2(this, void 0, void 0, function* () {
      let model = this._getModel(modelUrl);
      if (!model) {
        return null;
      }
      let wordDefRegExp = new RegExp(wordDef, wordDefFlags);
      if (range3.startColumn === range3.endColumn) {
        range3 = {
          startLineNumber: range3.startLineNumber,
          startColumn: range3.startColumn,
          endLineNumber: range3.endLineNumber,
          endColumn: range3.endColumn + 1
        };
      }
      let selectionText = model.getValueInRange(range3);
      let wordRange = model.getWordAtPosition({lineNumber: range3.startLineNumber, column: range3.startColumn}, wordDefRegExp);
      if (!wordRange) {
        return null;
      }
      let word = model.getValueInRange(wordRange);
      let result = BasicInplaceReplace.INSTANCE.navigateValueSet(range3, selectionText, wordRange, word, up);
      return result;
    });
  }
  loadForeignModule(moduleId, createData, foreignHostMethods) {
    const proxyMethodRequest = (method, args) => {
      return this._host.fhr(method, args);
    };
    const foreignHost = createProxyObject(foreignHostMethods, proxyMethodRequest);
    let ctx = {
      host: foreignHost,
      getMirrorModels: () => {
        return this._getModels();
      }
    };
    if (this._foreignModuleFactory) {
      this._foreignModule = this._foreignModuleFactory(ctx, createData);
      return Promise.resolve(getAllMethodNames(this._foreignModule));
    }
    return Promise.reject(new Error(`Unexpected usage`));
  }
  fmr(method, args) {
    if (!this._foreignModule || typeof this._foreignModule[method] !== "function") {
      return Promise.reject(new Error("Missing requestHandler or method: " + method));
    }
    try {
      return Promise.resolve(this._foreignModule[method].apply(this._foreignModule, args));
    } catch (e2) {
      return Promise.reject(e2);
    }
  }
};
EditorSimpleWorker._diffLimit = 1e5;
EditorSimpleWorker._suggestionsLimit = 1e4;
if (typeof importScripts === "function") {
  globals.monaco = createMonacoBaseAPI();
}
var ITextResourceConfigurationService = createDecorator("textResourceConfigurationService");
var ITextResourcePropertiesService = createDecorator("textResourcePropertiesService");
var ILogService = createDecorator("logService");
var LogLevel;
(function(LogLevel2) {
  LogLevel2[LogLevel2["Trace"] = 0] = "Trace";
  LogLevel2[LogLevel2["Debug"] = 1] = "Debug";
  LogLevel2[LogLevel2["Info"] = 2] = "Info";
  LogLevel2[LogLevel2["Warning"] = 3] = "Warning";
  LogLevel2[LogLevel2["Error"] = 4] = "Error";
  LogLevel2[LogLevel2["Critical"] = 5] = "Critical";
  LogLevel2[LogLevel2["Off"] = 6] = "Off";
})(LogLevel || (LogLevel = {}));
var DEFAULT_LOG_LEVEL = LogLevel.Info;
var AbstractLogService = class extends Disposable {
  constructor() {
    super(...arguments);
    this.level = DEFAULT_LOG_LEVEL;
    this._onDidChangeLogLevel = this._register(new Emitter());
  }
  setLevel(level2) {
    if (this.level !== level2) {
      this.level = level2;
      this._onDidChangeLogLevel.fire(this.level);
    }
  }
  getLevel() {
    return this.level;
  }
};
var ConsoleLogService = class extends AbstractLogService {
  constructor(logLevel = DEFAULT_LOG_LEVEL) {
    super();
    this.setLevel(logLevel);
  }
  trace(message, ...args) {
    if (this.getLevel() <= LogLevel.Trace) {
      console.log("%cTRACE", "color: #888", message, ...args);
    }
  }
  info(message, ...args) {
    if (this.getLevel() <= LogLevel.Info) {
      console.log("%c INFO", "color: #33f", message, ...args);
    }
  }
  error(message, ...args) {
    if (this.getLevel() <= LogLevel.Error) {
      console.log("%c  ERR", "color: #f33", message, ...args);
    }
  }
  dispose() {
  }
};
var hasPerformanceNow = globals.performance && typeof globals.performance.now === "function";
var StopWatch = class {
  constructor(highResolution) {
    this._highResolution = hasPerformanceNow && highResolution;
    this._startTime = this._now();
    this._stopTime = -1;
  }
  static create(highResolution = true) {
    return new StopWatch(highResolution);
  }
  stop() {
    this._stopTime = this._now();
  }
  elapsed() {
    if (this._stopTime !== -1) {
      return this._stopTime - this._startTime;
    }
    return this._now() - this._startTime;
  }
  _now() {
    return this._highResolution ? globals.performance.now() : new Date().getTime();
  }
};
var __decorate$1 = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$1 = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$3 = function(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var STOP_SYNC_MODEL_DELTA_TIME_MS = 60 * 1e3;
var STOP_WORKER_DELTA_TIME_MS = 5 * 60 * 1e3;
function canSyncModel(modelService, resource2) {
  let model = modelService.getModel(resource2);
  if (!model) {
    return false;
  }
  if (model.isTooLargeForSyncing()) {
    return false;
  }
  return true;
}
var EditorWorkerServiceImpl = class EditorWorkerServiceImpl2 extends Disposable {
  constructor(modelService, configurationService, logService) {
    super();
    this._modelService = modelService;
    this._workerManager = this._register(new WorkerManager(this._modelService));
    this._logService = logService;
    this._register(LinkProviderRegistry.register("*", {
      provideLinks: (model, token2) => {
        if (!canSyncModel(this._modelService, model.uri)) {
          return Promise.resolve({links: []});
        }
        return this._workerManager.withWorker().then((client2) => client2.computeLinks(model.uri)).then((links) => {
          return links && {links};
        });
      }
    }));
    this._register(CompletionProviderRegistry.register("*", new WordBasedCompletionItemProvider(this._workerManager, configurationService, this._modelService)));
  }
  dispose() {
    super.dispose();
  }
  canComputeDiff(original, modified) {
    return canSyncModel(this._modelService, original) && canSyncModel(this._modelService, modified);
  }
  computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime) {
    return this._workerManager.withWorker().then((client2) => client2.computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime));
  }
  computeMoreMinimalEdits(resource2, edits) {
    if (isNonEmptyArray(edits)) {
      if (!canSyncModel(this._modelService, resource2)) {
        return Promise.resolve(edits);
      }
      const sw = StopWatch.create(true);
      const result = this._workerManager.withWorker().then((client2) => client2.computeMoreMinimalEdits(resource2, edits));
      result.finally(() => this._logService.trace("FORMAT#computeMoreMinimalEdits", resource2.toString(true), sw.elapsed()));
      return result;
    } else {
      return Promise.resolve(void 0);
    }
  }
  canNavigateValueSet(resource2) {
    return canSyncModel(this._modelService, resource2);
  }
  navigateValueSet(resource2, range3, up) {
    return this._workerManager.withWorker().then((client2) => client2.navigateValueSet(resource2, range3, up));
  }
  canComputeWordRanges(resource2) {
    return canSyncModel(this._modelService, resource2);
  }
  computeWordRanges(resource2, range3) {
    return this._workerManager.withWorker().then((client2) => client2.computeWordRanges(resource2, range3));
  }
};
EditorWorkerServiceImpl = __decorate$1([
  __param$1(0, IModelService),
  __param$1(1, ITextResourceConfigurationService),
  __param$1(2, ILogService)
], EditorWorkerServiceImpl);
var WordBasedCompletionItemProvider = class {
  constructor(workerManager, configurationService, modelService) {
    this._debugDisplayName = "wordbasedCompletions";
    this._workerManager = workerManager;
    this._configurationService = configurationService;
    this._modelService = modelService;
  }
  provideCompletionItems(model, position2) {
    return __awaiter$3(this, void 0, void 0, function* () {
      const {wordBasedSuggestions} = this._configurationService.getValue(model.uri, position2, "editor");
      if (!wordBasedSuggestions) {
        return void 0;
      }
      if (!canSyncModel(this._modelService, model.uri)) {
        return void 0;
      }
      const word = model.getWordAtPosition(position2);
      const replace2 = !word ? Range.fromPositions(position2) : new Range(position2.lineNumber, word.startColumn, position2.lineNumber, word.endColumn);
      const insert2 = replace2.setEndPosition(position2.lineNumber, position2.column);
      const client2 = yield this._workerManager.withWorker();
      const words2 = yield client2.textualSuggest(model.uri, position2);
      if (!words2) {
        return void 0;
      }
      return {
        suggestions: words2.map((word2) => {
          return {
            kind: 18,
            label: word2,
            insertText: word2,
            range: {insert: insert2, replace: replace2}
          };
        })
      };
    });
  }
};
var WorkerManager = class extends Disposable {
  constructor(modelService) {
    super();
    this._modelService = modelService;
    this._editorWorkerClient = null;
    this._lastWorkerUsedTime = new Date().getTime();
    let stopWorkerInterval = this._register(new IntervalTimer());
    stopWorkerInterval.cancelAndSet(() => this._checkStopIdleWorker(), Math.round(STOP_WORKER_DELTA_TIME_MS / 2));
    this._register(this._modelService.onModelRemoved((_23) => this._checkStopEmptyWorker()));
  }
  dispose() {
    if (this._editorWorkerClient) {
      this._editorWorkerClient.dispose();
      this._editorWorkerClient = null;
    }
    super.dispose();
  }
  _checkStopEmptyWorker() {
    if (!this._editorWorkerClient) {
      return;
    }
    let models = this._modelService.getModels();
    if (models.length === 0) {
      this._editorWorkerClient.dispose();
      this._editorWorkerClient = null;
    }
  }
  _checkStopIdleWorker() {
    if (!this._editorWorkerClient) {
      return;
    }
    let timeSinceLastWorkerUsedTime = new Date().getTime() - this._lastWorkerUsedTime;
    if (timeSinceLastWorkerUsedTime > STOP_WORKER_DELTA_TIME_MS) {
      this._editorWorkerClient.dispose();
      this._editorWorkerClient = null;
    }
  }
  withWorker() {
    this._lastWorkerUsedTime = new Date().getTime();
    if (!this._editorWorkerClient) {
      this._editorWorkerClient = new EditorWorkerClient(this._modelService, false, "editorWorkerService");
    }
    return Promise.resolve(this._editorWorkerClient);
  }
};
var EditorModelManager = class extends Disposable {
  constructor(proxy, modelService, keepIdleModels) {
    super();
    this._syncedModels = Object.create(null);
    this._syncedModelsLastUsedTime = Object.create(null);
    this._proxy = proxy;
    this._modelService = modelService;
    if (!keepIdleModels) {
      let timer2 = new IntervalTimer();
      timer2.cancelAndSet(() => this._checkStopModelSync(), Math.round(STOP_SYNC_MODEL_DELTA_TIME_MS / 2));
      this._register(timer2);
    }
  }
  dispose() {
    for (let modelUrl in this._syncedModels) {
      dispose(this._syncedModels[modelUrl]);
    }
    this._syncedModels = Object.create(null);
    this._syncedModelsLastUsedTime = Object.create(null);
    super.dispose();
  }
  ensureSyncedResources(resources) {
    for (const resource2 of resources) {
      let resourceStr = resource2.toString();
      if (!this._syncedModels[resourceStr]) {
        this._beginModelSync(resource2);
      }
      if (this._syncedModels[resourceStr]) {
        this._syncedModelsLastUsedTime[resourceStr] = new Date().getTime();
      }
    }
  }
  _checkStopModelSync() {
    let currentTime = new Date().getTime();
    let toRemove = [];
    for (let modelUrl in this._syncedModelsLastUsedTime) {
      let elapsedTime = currentTime - this._syncedModelsLastUsedTime[modelUrl];
      if (elapsedTime > STOP_SYNC_MODEL_DELTA_TIME_MS) {
        toRemove.push(modelUrl);
      }
    }
    for (const e2 of toRemove) {
      this._stopModelSync(e2);
    }
  }
  _beginModelSync(resource2) {
    let model = this._modelService.getModel(resource2);
    if (!model) {
      return;
    }
    if (model.isTooLargeForSyncing()) {
      return;
    }
    let modelUrl = resource2.toString();
    this._proxy.acceptNewModel({
      url: model.uri.toString(),
      lines: model.getLinesContent(),
      EOL: model.getEOL(),
      versionId: model.getVersionId()
    });
    const toDispose = new DisposableStore();
    toDispose.add(model.onDidChangeContent((e2) => {
      this._proxy.acceptModelChanged(modelUrl.toString(), e2);
    }));
    toDispose.add(model.onWillDispose(() => {
      this._stopModelSync(modelUrl);
    }));
    toDispose.add(toDisposable(() => {
      this._proxy.acceptRemovedModel(modelUrl);
    }));
    this._syncedModels[modelUrl] = toDispose;
  }
  _stopModelSync(modelUrl) {
    let toDispose = this._syncedModels[modelUrl];
    delete this._syncedModels[modelUrl];
    delete this._syncedModelsLastUsedTime[modelUrl];
    dispose(toDispose);
  }
};
var SynchronousWorkerClient = class {
  constructor(instance2) {
    this._instance = instance2;
    this._proxyObj = Promise.resolve(this._instance);
  }
  dispose() {
    this._instance.dispose();
  }
  getProxyObject() {
    return this._proxyObj;
  }
};
var EditorWorkerHost = class {
  constructor(workerClient) {
    this._workerClient = workerClient;
  }
  fhr(method, args) {
    return this._workerClient.fhr(method, args);
  }
};
var EditorWorkerClient = class extends Disposable {
  constructor(modelService, keepIdleModels, label2) {
    super();
    this._disposed = false;
    this._modelService = modelService;
    this._keepIdleModels = keepIdleModels;
    this._workerFactory = new DefaultWorkerFactory(label2);
    this._worker = null;
    this._modelManager = null;
  }
  fhr(method, args) {
    throw new Error(`Not implemented!`);
  }
  _getOrCreateWorker() {
    if (!this._worker) {
      try {
        this._worker = this._register(new SimpleWorkerClient(this._workerFactory, "vs/editor/common/services/editorSimpleWorker", new EditorWorkerHost(this)));
      } catch (err) {
        logOnceWebWorkerWarning(err);
        this._worker = new SynchronousWorkerClient(new EditorSimpleWorker(new EditorWorkerHost(this), null));
      }
    }
    return this._worker;
  }
  _getProxy() {
    return this._getOrCreateWorker().getProxyObject().then(void 0, (err) => {
      logOnceWebWorkerWarning(err);
      this._worker = new SynchronousWorkerClient(new EditorSimpleWorker(new EditorWorkerHost(this), null));
      return this._getOrCreateWorker().getProxyObject();
    });
  }
  _getOrCreateModelManager(proxy) {
    if (!this._modelManager) {
      this._modelManager = this._register(new EditorModelManager(proxy, this._modelService, this._keepIdleModels));
    }
    return this._modelManager;
  }
  _withSyncedResources(resources) {
    if (this._disposed) {
      return Promise.reject(canceled());
    }
    return this._getProxy().then((proxy) => {
      this._getOrCreateModelManager(proxy).ensureSyncedResources(resources);
      return proxy;
    });
  }
  computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime) {
    return this._withSyncedResources([original, modified]).then((proxy) => {
      return proxy.computeDiff(original.toString(), modified.toString(), ignoreTrimWhitespace, maxComputationTime);
    });
  }
  computeMoreMinimalEdits(resource2, edits) {
    return this._withSyncedResources([resource2]).then((proxy) => {
      return proxy.computeMoreMinimalEdits(resource2.toString(), edits);
    });
  }
  computeLinks(resource2) {
    return this._withSyncedResources([resource2]).then((proxy) => {
      return proxy.computeLinks(resource2.toString());
    });
  }
  textualSuggest(resource2, position2) {
    return this._withSyncedResources([resource2]).then((proxy) => {
      let model = this._modelService.getModel(resource2);
      if (!model) {
        return null;
      }
      let wordDefRegExp = LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id);
      let wordDef = wordDefRegExp.source;
      let wordDefFlags = regExpFlags(wordDefRegExp);
      return proxy.textualSuggest(resource2.toString(), position2, wordDef, wordDefFlags);
    });
  }
  computeWordRanges(resource2, range3) {
    return this._withSyncedResources([resource2]).then((proxy) => {
      let model = this._modelService.getModel(resource2);
      if (!model) {
        return Promise.resolve(null);
      }
      let wordDefRegExp = LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id);
      let wordDef = wordDefRegExp.source;
      let wordDefFlags = regExpFlags(wordDefRegExp);
      return proxy.computeWordRanges(resource2.toString(), range3, wordDef, wordDefFlags);
    });
  }
  navigateValueSet(resource2, range3, up) {
    return this._withSyncedResources([resource2]).then((proxy) => {
      let model = this._modelService.getModel(resource2);
      if (!model) {
        return null;
      }
      let wordDefRegExp = LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id);
      let wordDef = wordDefRegExp.source;
      let wordDefFlags = regExpFlags(wordDefRegExp);
      return proxy.navigateValueSet(resource2.toString(), range3, up, wordDef, wordDefFlags);
    });
  }
  dispose() {
    super.dispose();
    this._disposed = true;
  }
};
function createWebWorker(modelService, opts) {
  return new MonacoWebWorkerImpl(modelService, opts);
}
var MonacoWebWorkerImpl = class extends EditorWorkerClient {
  constructor(modelService, opts) {
    super(modelService, opts.keepIdleModels || false, opts.label);
    this._foreignModuleId = opts.moduleId;
    this._foreignModuleCreateData = opts.createData || null;
    this._foreignModuleHost = opts.host || null;
    this._foreignProxy = null;
  }
  fhr(method, args) {
    if (!this._foreignModuleHost || typeof this._foreignModuleHost[method] !== "function") {
      return Promise.reject(new Error("Missing method " + method + " or missing main thread foreign host."));
    }
    try {
      return Promise.resolve(this._foreignModuleHost[method].apply(this._foreignModuleHost, args));
    } catch (e2) {
      return Promise.reject(e2);
    }
  }
  _getForeignProxy() {
    if (!this._foreignProxy) {
      this._foreignProxy = this._getProxy().then((proxy) => {
        const foreignHostMethods = this._foreignModuleHost ? getAllMethodNames(this._foreignModuleHost) : [];
        return proxy.loadForeignModule(this._foreignModuleId, this._foreignModuleCreateData, foreignHostMethods).then((foreignMethods) => {
          this._foreignModuleCreateData = null;
          const proxyMethodRequest = (method, args) => {
            return proxy.fmr(method, args);
          };
          const createProxyMethod = (method, proxyMethodRequest2) => {
            return function() {
              const args = Array.prototype.slice.call(arguments, 0);
              return proxyMethodRequest2(method, args);
            };
          };
          let foreignProxy = {};
          for (const foreignMethod of foreignMethods) {
            foreignProxy[foreignMethod] = createProxyMethod(foreignMethod, proxyMethodRequest);
          }
          return foreignProxy;
        });
      });
    }
    return this._foreignProxy;
  }
  getProxy() {
    return this._getForeignProxy();
  }
  withSyncedResources(resources) {
    return this._withSyncedResources(resources).then((_23) => this.getProxy());
  }
};
var LineTokens = class {
  constructor(tokens, text) {
    this._tokens = tokens;
    this._tokensCount = this._tokens.length >>> 1;
    this._text = text;
  }
  equals(other) {
    if (other instanceof LineTokens) {
      return this.slicedEquals(other, 0, this._tokensCount);
    }
    return false;
  }
  slicedEquals(other, sliceFromTokenIndex, sliceTokenCount) {
    if (this._text !== other._text) {
      return false;
    }
    if (this._tokensCount !== other._tokensCount) {
      return false;
    }
    const from = sliceFromTokenIndex << 1;
    const to = from + (sliceTokenCount << 1);
    for (let i3 = from; i3 < to; i3++) {
      if (this._tokens[i3] !== other._tokens[i3]) {
        return false;
      }
    }
    return true;
  }
  getLineContent() {
    return this._text;
  }
  getCount() {
    return this._tokensCount;
  }
  getStartOffset(tokenIndex) {
    if (tokenIndex > 0) {
      return this._tokens[tokenIndex - 1 << 1];
    }
    return 0;
  }
  getMetadata(tokenIndex) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return metadata;
  }
  getLanguageId(tokenIndex) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return TokenMetadata.getLanguageId(metadata);
  }
  getStandardTokenType(tokenIndex) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return TokenMetadata.getTokenType(metadata);
  }
  getForeground(tokenIndex) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return TokenMetadata.getForeground(metadata);
  }
  getClassName(tokenIndex) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return TokenMetadata.getClassNameFromMetadata(metadata);
  }
  getInlineStyle(tokenIndex, colorMap) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return TokenMetadata.getInlineStyleFromMetadata(metadata, colorMap);
  }
  getEndOffset(tokenIndex) {
    return this._tokens[tokenIndex << 1];
  }
  findTokenIndexAtOffset(offset2) {
    return LineTokens.findIndexInTokensArray(this._tokens, offset2);
  }
  inflate() {
    return this;
  }
  sliceAndInflate(startOffset, endOffset, deltaOffset) {
    return new SlicedLineTokens(this, startOffset, endOffset, deltaOffset);
  }
  static convertToEndOffset(tokens, lineTextLength) {
    const tokenCount = tokens.length >>> 1;
    const lastTokenIndex = tokenCount - 1;
    for (let tokenIndex = 0; tokenIndex < lastTokenIndex; tokenIndex++) {
      tokens[tokenIndex << 1] = tokens[tokenIndex + 1 << 1];
    }
    tokens[lastTokenIndex << 1] = lineTextLength;
  }
  static findIndexInTokensArray(tokens, desiredIndex) {
    if (tokens.length <= 2) {
      return 0;
    }
    let low = 0;
    let high = (tokens.length >>> 1) - 1;
    while (low < high) {
      const mid = low + Math.floor((high - low) / 2);
      const endOffset = tokens[mid << 1];
      if (endOffset === desiredIndex) {
        return mid + 1;
      } else if (endOffset < desiredIndex) {
        low = mid + 1;
      } else if (endOffset > desiredIndex) {
        high = mid;
      }
    }
    return low;
  }
};
var SlicedLineTokens = class {
  constructor(source2, startOffset, endOffset, deltaOffset) {
    this._source = source2;
    this._startOffset = startOffset;
    this._endOffset = endOffset;
    this._deltaOffset = deltaOffset;
    this._firstTokenIndex = source2.findTokenIndexAtOffset(startOffset);
    this._tokensCount = 0;
    for (let i3 = this._firstTokenIndex, len2 = source2.getCount(); i3 < len2; i3++) {
      const tokenStartOffset = source2.getStartOffset(i3);
      if (tokenStartOffset >= endOffset) {
        break;
      }
      this._tokensCount++;
    }
  }
  equals(other) {
    if (other instanceof SlicedLineTokens) {
      return this._startOffset === other._startOffset && this._endOffset === other._endOffset && this._deltaOffset === other._deltaOffset && this._source.slicedEquals(other._source, this._firstTokenIndex, this._tokensCount);
    }
    return false;
  }
  getCount() {
    return this._tokensCount;
  }
  getForeground(tokenIndex) {
    return this._source.getForeground(this._firstTokenIndex + tokenIndex);
  }
  getEndOffset(tokenIndex) {
    const tokenEndOffset = this._source.getEndOffset(this._firstTokenIndex + tokenIndex);
    return Math.min(this._endOffset, tokenEndOffset) - this._startOffset + this._deltaOffset;
  }
  getClassName(tokenIndex) {
    return this._source.getClassName(this._firstTokenIndex + tokenIndex);
  }
  getInlineStyle(tokenIndex, colorMap) {
    return this._source.getInlineStyle(this._firstTokenIndex + tokenIndex, colorMap);
  }
  findTokenIndexAtOffset(offset2) {
    return this._source.findTokenIndexAtOffset(offset2 + this._startOffset - this._deltaOffset) - this._firstTokenIndex;
  }
};
var LineDecoration = class {
  constructor(startColumn, endColumn, className, type) {
    this.startColumn = startColumn;
    this.endColumn = endColumn;
    this.className = className;
    this.type = type;
  }
  static _equals(a2, b2) {
    return a2.startColumn === b2.startColumn && a2.endColumn === b2.endColumn && a2.className === b2.className && a2.type === b2.type;
  }
  static equalsArr(a2, b2) {
    const aLen = a2.length;
    const bLen = b2.length;
    if (aLen !== bLen) {
      return false;
    }
    for (let i3 = 0; i3 < aLen; i3++) {
      if (!LineDecoration._equals(a2[i3], b2[i3])) {
        return false;
      }
    }
    return true;
  }
  static filter(lineDecorations, lineNumber, minLineColumn, maxLineColumn) {
    if (lineDecorations.length === 0) {
      return [];
    }
    let result = [], resultLen = 0;
    for (let i3 = 0, len2 = lineDecorations.length; i3 < len2; i3++) {
      const d2 = lineDecorations[i3];
      const range3 = d2.range;
      if (range3.endLineNumber < lineNumber || range3.startLineNumber > lineNumber) {
        continue;
      }
      if (range3.isEmpty() && (d2.type === 0 || d2.type === 3)) {
        continue;
      }
      const startColumn = range3.startLineNumber === lineNumber ? range3.startColumn : minLineColumn;
      const endColumn = range3.endLineNumber === lineNumber ? range3.endColumn : maxLineColumn;
      result[resultLen++] = new LineDecoration(startColumn, endColumn, d2.inlineClassName, d2.type);
    }
    return result;
  }
  static _typeCompare(a2, b2) {
    const ORDER = [2, 0, 1, 3];
    return ORDER[a2] - ORDER[b2];
  }
  static compare(a2, b2) {
    if (a2.startColumn === b2.startColumn) {
      if (a2.endColumn === b2.endColumn) {
        const typeCmp = LineDecoration._typeCompare(a2.type, b2.type);
        if (typeCmp === 0) {
          if (a2.className < b2.className) {
            return -1;
          }
          if (a2.className > b2.className) {
            return 1;
          }
          return 0;
        }
        return typeCmp;
      }
      return a2.endColumn - b2.endColumn;
    }
    return a2.startColumn - b2.startColumn;
  }
};
var DecorationSegment = class {
  constructor(startOffset, endOffset, className, metadata) {
    this.startOffset = startOffset;
    this.endOffset = endOffset;
    this.className = className;
    this.metadata = metadata;
  }
};
var Stack2 = class {
  constructor() {
    this.stopOffsets = [];
    this.classNames = [];
    this.metadata = [];
    this.count = 0;
  }
  static _metadata(metadata) {
    let result = 0;
    for (let i3 = 0, len2 = metadata.length; i3 < len2; i3++) {
      result |= metadata[i3];
    }
    return result;
  }
  consumeLowerThan(maxStopOffset, nextStartOffset, result) {
    while (this.count > 0 && this.stopOffsets[0] < maxStopOffset) {
      let i3 = 0;
      while (i3 + 1 < this.count && this.stopOffsets[i3] === this.stopOffsets[i3 + 1]) {
        i3++;
      }
      result.push(new DecorationSegment(nextStartOffset, this.stopOffsets[i3], this.classNames.join(" "), Stack2._metadata(this.metadata)));
      nextStartOffset = this.stopOffsets[i3] + 1;
      this.stopOffsets.splice(0, i3 + 1);
      this.classNames.splice(0, i3 + 1);
      this.metadata.splice(0, i3 + 1);
      this.count -= i3 + 1;
    }
    if (this.count > 0 && nextStartOffset < maxStopOffset) {
      result.push(new DecorationSegment(nextStartOffset, maxStopOffset - 1, this.classNames.join(" "), Stack2._metadata(this.metadata)));
      nextStartOffset = maxStopOffset;
    }
    return nextStartOffset;
  }
  insert(stopOffset, className, metadata) {
    if (this.count === 0 || this.stopOffsets[this.count - 1] <= stopOffset) {
      this.stopOffsets.push(stopOffset);
      this.classNames.push(className);
      this.metadata.push(metadata);
    } else {
      for (let i3 = 0; i3 < this.count; i3++) {
        if (this.stopOffsets[i3] >= stopOffset) {
          this.stopOffsets.splice(i3, 0, stopOffset);
          this.classNames.splice(i3, 0, className);
          this.metadata.splice(i3, 0, metadata);
          break;
        }
      }
    }
    this.count++;
    return;
  }
};
var LineDecorationsNormalizer = class {
  static normalize(lineContent, lineDecorations) {
    if (lineDecorations.length === 0) {
      return [];
    }
    let result = [];
    const stack2 = new Stack2();
    let nextStartOffset = 0;
    for (let i3 = 0, len2 = lineDecorations.length; i3 < len2; i3++) {
      const d2 = lineDecorations[i3];
      let startColumn = d2.startColumn;
      let endColumn = d2.endColumn;
      const className = d2.className;
      const metadata = d2.type === 1 ? 2 : d2.type === 2 ? 4 : 0;
      if (startColumn > 1) {
        const charCodeBefore = lineContent.charCodeAt(startColumn - 2);
        if (isHighSurrogate(charCodeBefore)) {
          startColumn--;
        }
      }
      if (endColumn > 1) {
        const charCodeBefore = lineContent.charCodeAt(endColumn - 2);
        if (isHighSurrogate(charCodeBefore)) {
          endColumn--;
        }
      }
      const currentStartOffset = startColumn - 1;
      const currentEndOffset = endColumn - 2;
      nextStartOffset = stack2.consumeLowerThan(currentStartOffset, nextStartOffset, result);
      if (stack2.count === 0) {
        nextStartOffset = currentStartOffset;
      }
      stack2.insert(currentEndOffset, className, metadata);
    }
    stack2.consumeLowerThan(1073741824, nextStartOffset, result);
    return result;
  }
};
var LinePart = class {
  constructor(endIndex, type, metadata) {
    this.endIndex = endIndex;
    this.type = type;
    this.metadata = metadata;
  }
  isWhitespace() {
    return this.metadata & 1 ? true : false;
  }
};
var LineRange = class {
  constructor(startIndex, endIndex) {
    this.startOffset = startIndex;
    this.endOffset = endIndex;
  }
  equals(otherLineRange) {
    return this.startOffset === otherLineRange.startOffset && this.endOffset === otherLineRange.endOffset;
  }
};
var RenderLineInput = class {
  constructor(useMonospaceOptimizations, canUseHalfwidthRightwardsArrow, lineContent, continuesWithWrappedLine, isBasicASCII2, containsRTL2, fauxIndentLength, lineTokens, lineDecorations, tabSize, startVisibleColumn, spaceWidth, middotWidth, wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, selectionsOnLine) {
    this.useMonospaceOptimizations = useMonospaceOptimizations;
    this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
    this.lineContent = lineContent;
    this.continuesWithWrappedLine = continuesWithWrappedLine;
    this.isBasicASCII = isBasicASCII2;
    this.containsRTL = containsRTL2;
    this.fauxIndentLength = fauxIndentLength;
    this.lineTokens = lineTokens;
    this.lineDecorations = lineDecorations;
    this.tabSize = tabSize;
    this.startVisibleColumn = startVisibleColumn;
    this.spaceWidth = spaceWidth;
    this.stopRenderingLineAfter = stopRenderingLineAfter;
    this.renderWhitespace = renderWhitespace === "all" ? 4 : renderWhitespace === "boundary" ? 1 : renderWhitespace === "selection" ? 2 : renderWhitespace === "trailing" ? 3 : 0;
    this.renderControlCharacters = renderControlCharacters;
    this.fontLigatures = fontLigatures;
    this.selectionsOnLine = selectionsOnLine && selectionsOnLine.sort((a2, b2) => a2.startOffset < b2.startOffset ? -1 : 1);
    const wsmiddotDiff = Math.abs(wsmiddotWidth - spaceWidth);
    const middotDiff = Math.abs(middotWidth - spaceWidth);
    if (wsmiddotDiff < middotDiff) {
      this.renderSpaceWidth = wsmiddotWidth;
      this.renderSpaceCharCode = 11825;
    } else {
      this.renderSpaceWidth = middotWidth;
      this.renderSpaceCharCode = 183;
    }
  }
  sameSelection(otherSelections) {
    if (this.selectionsOnLine === null) {
      return otherSelections === null;
    }
    if (otherSelections === null) {
      return false;
    }
    if (otherSelections.length !== this.selectionsOnLine.length) {
      return false;
    }
    for (let i3 = 0; i3 < this.selectionsOnLine.length; i3++) {
      if (!this.selectionsOnLine[i3].equals(otherSelections[i3])) {
        return false;
      }
    }
    return true;
  }
  equals(other) {
    return this.useMonospaceOptimizations === other.useMonospaceOptimizations && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineContent === other.lineContent && this.continuesWithWrappedLine === other.continuesWithWrappedLine && this.isBasicASCII === other.isBasicASCII && this.containsRTL === other.containsRTL && this.fauxIndentLength === other.fauxIndentLength && this.tabSize === other.tabSize && this.startVisibleColumn === other.startVisibleColumn && this.spaceWidth === other.spaceWidth && this.renderSpaceWidth === other.renderSpaceWidth && this.renderSpaceCharCode === other.renderSpaceCharCode && this.stopRenderingLineAfter === other.stopRenderingLineAfter && this.renderWhitespace === other.renderWhitespace && this.renderControlCharacters === other.renderControlCharacters && this.fontLigatures === other.fontLigatures && LineDecoration.equalsArr(this.lineDecorations, other.lineDecorations) && this.lineTokens.equals(other.lineTokens) && this.sameSelection(other.selectionsOnLine);
  }
};
var CharacterMapping = class {
  constructor(length, partCount) {
    this.length = length;
    this._data = new Uint32Array(this.length);
    this._absoluteOffsets = new Uint32Array(this.length);
  }
  static getPartIndex(partData) {
    return (partData & 4294901760) >>> 16;
  }
  static getCharIndex(partData) {
    return (partData & 65535) >>> 0;
  }
  setPartData(charOffset, partIndex, charIndex, partAbsoluteOffset) {
    let partData = (partIndex << 16 | charIndex << 0) >>> 0;
    this._data[charOffset] = partData;
    this._absoluteOffsets[charOffset] = partAbsoluteOffset + charIndex;
  }
  getAbsoluteOffsets() {
    return this._absoluteOffsets;
  }
  charOffsetToPartData(charOffset) {
    if (this.length === 0) {
      return 0;
    }
    if (charOffset < 0) {
      return this._data[0];
    }
    if (charOffset >= this.length) {
      return this._data[this.length - 1];
    }
    return this._data[charOffset];
  }
  partDataToCharOffset(partIndex, partLength, charIndex) {
    if (this.length === 0) {
      return 0;
    }
    let searchEntry = (partIndex << 16 | charIndex << 0) >>> 0;
    let min2 = 0;
    let max2 = this.length - 1;
    while (min2 + 1 < max2) {
      let mid = min2 + max2 >>> 1;
      let midEntry = this._data[mid];
      if (midEntry === searchEntry) {
        return mid;
      } else if (midEntry > searchEntry) {
        max2 = mid;
      } else {
        min2 = mid;
      }
    }
    if (min2 === max2) {
      return min2;
    }
    let minEntry = this._data[min2];
    let maxEntry = this._data[max2];
    if (minEntry === searchEntry) {
      return min2;
    }
    if (maxEntry === searchEntry) {
      return max2;
    }
    let minPartIndex = CharacterMapping.getPartIndex(minEntry);
    let minCharIndex = CharacterMapping.getCharIndex(minEntry);
    let maxPartIndex = CharacterMapping.getPartIndex(maxEntry);
    let maxCharIndex;
    if (minPartIndex !== maxPartIndex) {
      maxCharIndex = partLength;
    } else {
      maxCharIndex = CharacterMapping.getCharIndex(maxEntry);
    }
    let minEntryDistance = charIndex - minCharIndex;
    let maxEntryDistance = maxCharIndex - charIndex;
    if (minEntryDistance <= maxEntryDistance) {
      return min2;
    }
    return max2;
  }
};
var RenderLineOutput = class {
  constructor(characterMapping, containsRTL2, containsForeignElements) {
    this.characterMapping = characterMapping;
    this.containsRTL = containsRTL2;
    this.containsForeignElements = containsForeignElements;
  }
};
function renderViewLine(input, sb2) {
  if (input.lineContent.length === 0) {
    let containsForeignElements = 0;
    let content2 = "<span><span></span></span>";
    if (input.lineDecorations.length > 0) {
      const beforeClassNames = [];
      const afterClassNames = [];
      for (let i3 = 0, len2 = input.lineDecorations.length; i3 < len2; i3++) {
        const lineDecoration = input.lineDecorations[i3];
        if (lineDecoration.type === 1) {
          beforeClassNames.push(input.lineDecorations[i3].className);
          containsForeignElements |= 1;
        }
        if (lineDecoration.type === 2) {
          afterClassNames.push(input.lineDecorations[i3].className);
          containsForeignElements |= 2;
        }
      }
      if (containsForeignElements !== 0) {
        const beforeSpan = beforeClassNames.length > 0 ? `<span class="${beforeClassNames.join(" ")}"></span>` : ``;
        const afterSpan = afterClassNames.length > 0 ? `<span class="${afterClassNames.join(" ")}"></span>` : ``;
        content2 = `<span>${beforeSpan}${afterSpan}</span>`;
      }
    }
    sb2.appendASCIIString(content2);
    return new RenderLineOutput(new CharacterMapping(0, 0), false, containsForeignElements);
  }
  return _renderLine(resolveRenderLineInput(input), sb2);
}
var RenderLineOutput2 = class {
  constructor(characterMapping, html, containsRTL2, containsForeignElements) {
    this.characterMapping = characterMapping;
    this.html = html;
    this.containsRTL = containsRTL2;
    this.containsForeignElements = containsForeignElements;
  }
};
function renderViewLine2(input) {
  let sb2 = createStringBuilder(1e4);
  let out = renderViewLine(input, sb2);
  return new RenderLineOutput2(out.characterMapping, sb2.build(), out.containsRTL, out.containsForeignElements);
}
var ResolvedRenderLineInput = class {
  constructor(fontIsMonospace, canUseHalfwidthRightwardsArrow, lineContent, len2, isOverflowing, parts, containsForeignElements, fauxIndentLength, tabSize, startVisibleColumn, containsRTL2, spaceWidth, renderSpaceCharCode, renderWhitespace, renderControlCharacters) {
    this.fontIsMonospace = fontIsMonospace;
    this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
    this.lineContent = lineContent;
    this.len = len2;
    this.isOverflowing = isOverflowing;
    this.parts = parts;
    this.containsForeignElements = containsForeignElements;
    this.fauxIndentLength = fauxIndentLength;
    this.tabSize = tabSize;
    this.startVisibleColumn = startVisibleColumn;
    this.containsRTL = containsRTL2;
    this.spaceWidth = spaceWidth;
    this.renderSpaceCharCode = renderSpaceCharCode;
    this.renderWhitespace = renderWhitespace;
    this.renderControlCharacters = renderControlCharacters;
  }
};
function resolveRenderLineInput(input) {
  const lineContent = input.lineContent;
  let isOverflowing;
  let len2;
  if (input.stopRenderingLineAfter !== -1 && input.stopRenderingLineAfter < lineContent.length) {
    isOverflowing = true;
    len2 = input.stopRenderingLineAfter;
  } else {
    isOverflowing = false;
    len2 = lineContent.length;
  }
  let tokens = transformAndRemoveOverflowing(input.lineTokens, input.fauxIndentLength, len2);
  if (input.renderWhitespace === 4 || input.renderWhitespace === 1 || input.renderWhitespace === 2 && !!input.selectionsOnLine || input.renderWhitespace === 3) {
    tokens = _applyRenderWhitespace(input, lineContent, len2, tokens);
  }
  let containsForeignElements = 0;
  if (input.lineDecorations.length > 0) {
    for (let i3 = 0, len3 = input.lineDecorations.length; i3 < len3; i3++) {
      const lineDecoration = input.lineDecorations[i3];
      if (lineDecoration.type === 3) {
        containsForeignElements |= 1;
      } else if (lineDecoration.type === 1) {
        containsForeignElements |= 1;
      } else if (lineDecoration.type === 2) {
        containsForeignElements |= 2;
      }
    }
    tokens = _applyInlineDecorations(lineContent, len2, tokens, input.lineDecorations);
  }
  if (!input.containsRTL) {
    tokens = splitLargeTokens(lineContent, tokens, !input.isBasicASCII || input.fontLigatures);
  }
  return new ResolvedRenderLineInput(input.useMonospaceOptimizations, input.canUseHalfwidthRightwardsArrow, lineContent, len2, isOverflowing, tokens, containsForeignElements, input.fauxIndentLength, input.tabSize, input.startVisibleColumn, input.containsRTL, input.spaceWidth, input.renderSpaceCharCode, input.renderWhitespace, input.renderControlCharacters);
}
function transformAndRemoveOverflowing(tokens, fauxIndentLength, len2) {
  let result = [], resultLen = 0;
  if (fauxIndentLength > 0) {
    result[resultLen++] = new LinePart(fauxIndentLength, "", 0);
  }
  for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
    const endIndex = tokens.getEndOffset(tokenIndex);
    if (endIndex <= fauxIndentLength) {
      continue;
    }
    const type = tokens.getClassName(tokenIndex);
    if (endIndex >= len2) {
      result[resultLen++] = new LinePart(len2, type, 0);
      break;
    }
    result[resultLen++] = new LinePart(endIndex, type, 0);
  }
  return result;
}
function splitLargeTokens(lineContent, tokens, onlyAtSpaces) {
  let lastTokenEndIndex = 0;
  let result = [], resultLen = 0;
  if (onlyAtSpaces) {
    for (let i3 = 0, len2 = tokens.length; i3 < len2; i3++) {
      const token2 = tokens[i3];
      const tokenEndIndex = token2.endIndex;
      if (lastTokenEndIndex + 50 < tokenEndIndex) {
        const tokenType = token2.type;
        const tokenMetadata = token2.metadata;
        let lastSpaceOffset = -1;
        let currTokenStart = lastTokenEndIndex;
        for (let j = lastTokenEndIndex; j < tokenEndIndex; j++) {
          if (lineContent.charCodeAt(j) === 32) {
            lastSpaceOffset = j;
          }
          if (lastSpaceOffset !== -1 && j - currTokenStart >= 50) {
            result[resultLen++] = new LinePart(lastSpaceOffset + 1, tokenType, tokenMetadata);
            currTokenStart = lastSpaceOffset + 1;
            lastSpaceOffset = -1;
          }
        }
        if (currTokenStart !== tokenEndIndex) {
          result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata);
        }
      } else {
        result[resultLen++] = token2;
      }
      lastTokenEndIndex = tokenEndIndex;
    }
  } else {
    for (let i3 = 0, len2 = tokens.length; i3 < len2; i3++) {
      const token2 = tokens[i3];
      const tokenEndIndex = token2.endIndex;
      let diff = tokenEndIndex - lastTokenEndIndex;
      if (diff > 50) {
        const tokenType = token2.type;
        const tokenMetadata = token2.metadata;
        const piecesCount = Math.ceil(diff / 50);
        for (let j = 1; j < piecesCount; j++) {
          let pieceEndIndex = lastTokenEndIndex + j * 50;
          result[resultLen++] = new LinePart(pieceEndIndex, tokenType, tokenMetadata);
        }
        result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata);
      } else {
        result[resultLen++] = token2;
      }
      lastTokenEndIndex = tokenEndIndex;
    }
  }
  return result;
}
function _applyRenderWhitespace(input, lineContent, len2, tokens) {
  const continuesWithWrappedLine = input.continuesWithWrappedLine;
  const fauxIndentLength = input.fauxIndentLength;
  const tabSize = input.tabSize;
  const startVisibleColumn = input.startVisibleColumn;
  const useMonospaceOptimizations = input.useMonospaceOptimizations;
  const selections = input.selectionsOnLine;
  const onlyBoundary = input.renderWhitespace === 1;
  const onlyTrailing = input.renderWhitespace === 3;
  const generateLinePartForEachWhitespace = input.renderSpaceWidth !== input.spaceWidth;
  let result = [], resultLen = 0;
  let tokenIndex = 0;
  let tokenType = tokens[tokenIndex].type;
  let tokenEndIndex = tokens[tokenIndex].endIndex;
  const tokensLength = tokens.length;
  let lineIsEmptyOrWhitespace = false;
  let firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
  let lastNonWhitespaceIndex$1;
  if (firstNonWhitespaceIndex$1 === -1) {
    lineIsEmptyOrWhitespace = true;
    firstNonWhitespaceIndex$1 = len2;
    lastNonWhitespaceIndex$1 = len2;
  } else {
    lastNonWhitespaceIndex$1 = lastNonWhitespaceIndex(lineContent);
  }
  let wasInWhitespace = false;
  let currentSelectionIndex = 0;
  let currentSelection = selections && selections[currentSelectionIndex];
  let tmpIndent = startVisibleColumn % tabSize;
  for (let charIndex = fauxIndentLength; charIndex < len2; charIndex++) {
    const chCode = lineContent.charCodeAt(charIndex);
    if (currentSelection && charIndex >= currentSelection.endOffset) {
      currentSelectionIndex++;
      currentSelection = selections && selections[currentSelectionIndex];
    }
    let isInWhitespace;
    if (charIndex < firstNonWhitespaceIndex$1 || charIndex > lastNonWhitespaceIndex$1) {
      isInWhitespace = true;
    } else if (chCode === 9) {
      isInWhitespace = true;
    } else if (chCode === 32) {
      if (onlyBoundary) {
        if (wasInWhitespace) {
          isInWhitespace = true;
        } else {
          const nextChCode = charIndex + 1 < len2 ? lineContent.charCodeAt(charIndex + 1) : 0;
          isInWhitespace = nextChCode === 32 || nextChCode === 9;
        }
      } else {
        isInWhitespace = true;
      }
    } else {
      isInWhitespace = false;
    }
    if (isInWhitespace && selections) {
      isInWhitespace = !!currentSelection && currentSelection.startOffset <= charIndex && currentSelection.endOffset > charIndex;
    }
    if (isInWhitespace && onlyTrailing) {
      isInWhitespace = lineIsEmptyOrWhitespace || charIndex > lastNonWhitespaceIndex$1;
    }
    if (wasInWhitespace) {
      if (!isInWhitespace || !useMonospaceOptimizations && tmpIndent >= tabSize) {
        if (generateLinePartForEachWhitespace) {
          const lastEndIndex = resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength;
          for (let i3 = lastEndIndex + 1; i3 <= charIndex; i3++) {
            result[resultLen++] = new LinePart(i3, "mtkw", 1);
          }
        } else {
          result[resultLen++] = new LinePart(charIndex, "mtkw", 1);
        }
        tmpIndent = tmpIndent % tabSize;
      }
    } else {
      if (charIndex === tokenEndIndex || isInWhitespace && charIndex > fauxIndentLength) {
        result[resultLen++] = new LinePart(charIndex, tokenType, 0);
        tmpIndent = tmpIndent % tabSize;
      }
    }
    if (chCode === 9) {
      tmpIndent = tabSize;
    } else if (isFullWidthCharacter(chCode)) {
      tmpIndent += 2;
    } else {
      tmpIndent++;
    }
    wasInWhitespace = isInWhitespace;
    while (charIndex === tokenEndIndex) {
      tokenIndex++;
      if (tokenIndex < tokensLength) {
        tokenType = tokens[tokenIndex].type;
        tokenEndIndex = tokens[tokenIndex].endIndex;
      }
    }
  }
  let generateWhitespace = false;
  if (wasInWhitespace) {
    if (continuesWithWrappedLine && onlyBoundary) {
      let lastCharCode = len2 > 0 ? lineContent.charCodeAt(len2 - 1) : 0;
      let prevCharCode = len2 > 1 ? lineContent.charCodeAt(len2 - 2) : 0;
      let isSingleTrailingSpace = lastCharCode === 32 && (prevCharCode !== 32 && prevCharCode !== 9);
      if (!isSingleTrailingSpace) {
        generateWhitespace = true;
      }
    } else {
      generateWhitespace = true;
    }
  }
  if (generateWhitespace) {
    if (generateLinePartForEachWhitespace) {
      const lastEndIndex = resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength;
      for (let i3 = lastEndIndex + 1; i3 <= len2; i3++) {
        result[resultLen++] = new LinePart(i3, "mtkw", 1);
      }
    } else {
      result[resultLen++] = new LinePart(len2, "mtkw", 1);
    }
  } else {
    result[resultLen++] = new LinePart(len2, tokenType, 0);
  }
  return result;
}
function _applyInlineDecorations(lineContent, len2, tokens, _lineDecorations) {
  _lineDecorations.sort(LineDecoration.compare);
  const lineDecorations = LineDecorationsNormalizer.normalize(lineContent, _lineDecorations);
  const lineDecorationsLen = lineDecorations.length;
  let lineDecorationIndex = 0;
  let result = [], resultLen = 0, lastResultEndIndex = 0;
  for (let tokenIndex = 0, len3 = tokens.length; tokenIndex < len3; tokenIndex++) {
    const token2 = tokens[tokenIndex];
    const tokenEndIndex = token2.endIndex;
    const tokenType = token2.type;
    const tokenMetadata = token2.metadata;
    while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset < tokenEndIndex) {
      const lineDecoration = lineDecorations[lineDecorationIndex];
      if (lineDecoration.startOffset > lastResultEndIndex) {
        lastResultEndIndex = lineDecoration.startOffset;
        result[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata);
      }
      if (lineDecoration.endOffset + 1 <= tokenEndIndex) {
        lastResultEndIndex = lineDecoration.endOffset + 1;
        result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + " " + lineDecoration.className, tokenMetadata | lineDecoration.metadata);
        lineDecorationIndex++;
      } else {
        lastResultEndIndex = tokenEndIndex;
        result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + " " + lineDecoration.className, tokenMetadata | lineDecoration.metadata);
        break;
      }
    }
    if (tokenEndIndex > lastResultEndIndex) {
      lastResultEndIndex = tokenEndIndex;
      result[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata);
    }
  }
  const lastTokenEndIndex = tokens[tokens.length - 1].endIndex;
  if (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
    let classNames2 = [];
    let metadata = 0;
    while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
      classNames2.push(lineDecorations[lineDecorationIndex].className);
      metadata |= lineDecorations[lineDecorationIndex].metadata;
      lineDecorationIndex++;
    }
    result[resultLen++] = new LinePart(lastResultEndIndex, classNames2.join(" "), metadata);
  }
  return result;
}
function _renderLine(input, sb2) {
  const fontIsMonospace = input.fontIsMonospace;
  const canUseHalfwidthRightwardsArrow = input.canUseHalfwidthRightwardsArrow;
  const containsForeignElements = input.containsForeignElements;
  const lineContent = input.lineContent;
  const len2 = input.len;
  const isOverflowing = input.isOverflowing;
  const parts = input.parts;
  const fauxIndentLength = input.fauxIndentLength;
  const tabSize = input.tabSize;
  const startVisibleColumn = input.startVisibleColumn;
  const containsRTL2 = input.containsRTL;
  const spaceWidth = input.spaceWidth;
  const renderSpaceCharCode = input.renderSpaceCharCode;
  const renderWhitespace = input.renderWhitespace;
  const renderControlCharacters = input.renderControlCharacters;
  const characterMapping = new CharacterMapping(len2 + 1, parts.length);
  let charIndex = 0;
  let visibleColumn = startVisibleColumn;
  let charOffsetInPart = 0;
  let partDisplacement = 0;
  let prevPartContentCnt = 0;
  let partAbsoluteOffset = 0;
  if (containsRTL2) {
    sb2.appendASCIIString('<span dir="ltr">');
  } else {
    sb2.appendASCIIString("<span>");
  }
  for (let partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) {
    partAbsoluteOffset += prevPartContentCnt;
    const part = parts[partIndex];
    const partEndIndex = part.endIndex;
    const partType = part.type;
    const partRendersWhitespace = renderWhitespace !== 0 && part.isWhitespace();
    const partRendersWhitespaceWithWidth = partRendersWhitespace && !fontIsMonospace && (partType === "mtkw" || !containsForeignElements);
    const partIsEmptyAndHasPseudoAfter = charIndex === partEndIndex && part.metadata === 4;
    charOffsetInPart = 0;
    sb2.appendASCIIString('<span class="');
    sb2.appendASCIIString(partRendersWhitespaceWithWidth ? "mtkz" : partType);
    sb2.appendASCII(34);
    if (partRendersWhitespace) {
      let partContentCnt = 0;
      {
        let _charIndex = charIndex;
        let _visibleColumn = visibleColumn;
        for (; _charIndex < partEndIndex; _charIndex++) {
          const charCode = lineContent.charCodeAt(_charIndex);
          const charWidth = (charCode === 9 ? tabSize - _visibleColumn % tabSize : 1) | 0;
          partContentCnt += charWidth;
          if (_charIndex >= fauxIndentLength) {
            _visibleColumn += charWidth;
          }
        }
      }
      if (partRendersWhitespaceWithWidth) {
        sb2.appendASCIIString(' style="width:');
        sb2.appendASCIIString(String(spaceWidth * partContentCnt));
        sb2.appendASCIIString('px"');
      }
      sb2.appendASCII(62);
      for (; charIndex < partEndIndex; charIndex++) {
        characterMapping.setPartData(charIndex, partIndex - partDisplacement, charOffsetInPart, partAbsoluteOffset);
        partDisplacement = 0;
        const charCode = lineContent.charCodeAt(charIndex);
        let charWidth;
        if (charCode === 9) {
          charWidth = tabSize - visibleColumn % tabSize | 0;
          if (!canUseHalfwidthRightwardsArrow || charWidth > 1) {
            sb2.write1(8594);
          } else {
            sb2.write1(65515);
          }
          for (let space = 2; space <= charWidth; space++) {
            sb2.write1(160);
          }
        } else {
          charWidth = 1;
          sb2.write1(renderSpaceCharCode);
        }
        charOffsetInPart += charWidth;
        if (charIndex >= fauxIndentLength) {
          visibleColumn += charWidth;
        }
      }
      prevPartContentCnt = partContentCnt;
    } else {
      let partContentCnt = 0;
      sb2.appendASCII(62);
      for (; charIndex < partEndIndex; charIndex++) {
        characterMapping.setPartData(charIndex, partIndex - partDisplacement, charOffsetInPart, partAbsoluteOffset);
        partDisplacement = 0;
        const charCode = lineContent.charCodeAt(charIndex);
        let producedCharacters = 1;
        let charWidth = 1;
        switch (charCode) {
          case 9:
            producedCharacters = tabSize - visibleColumn % tabSize;
            charWidth = producedCharacters;
            for (let space = 1; space <= producedCharacters; space++) {
              sb2.write1(160);
            }
            break;
          case 32:
            sb2.write1(160);
            break;
          case 60:
            sb2.appendASCIIString("&lt;");
            break;
          case 62:
            sb2.appendASCIIString("&gt;");
            break;
          case 38:
            sb2.appendASCIIString("&amp;");
            break;
          case 0:
            sb2.appendASCIIString("&#00;");
            break;
          case 65279:
          case 8232:
          case 8233:
          case 133:
            sb2.write1(65533);
            break;
          default:
            if (isFullWidthCharacter(charCode)) {
              charWidth++;
            }
            if (renderControlCharacters && charCode < 32) {
              sb2.write1(9216 + charCode);
            } else {
              sb2.write1(charCode);
            }
        }
        charOffsetInPart += producedCharacters;
        partContentCnt += producedCharacters;
        if (charIndex >= fauxIndentLength) {
          visibleColumn += charWidth;
        }
      }
      prevPartContentCnt = partContentCnt;
    }
    if (partIsEmptyAndHasPseudoAfter) {
      partDisplacement++;
    } else {
      partDisplacement = 0;
    }
    sb2.appendASCIIString("</span>");
  }
  characterMapping.setPartData(len2, parts.length - 1, charOffsetInPart, partAbsoluteOffset);
  if (isOverflowing) {
    sb2.appendASCIIString("<span>&hellip;</span>");
  }
  sb2.appendASCIIString("</span>");
  return new RenderLineOutput(characterMapping, containsRTL2, containsForeignElements);
}
var Viewport = class {
  constructor(top2, left2, width2, height) {
    this.top = top2 | 0;
    this.left = left2 | 0;
    this.width = width2 | 0;
    this.height = height | 0;
  }
};
var MinimapLinesRenderingData = class {
  constructor(tabSize, data2) {
    this.tabSize = tabSize;
    this.data = data2;
  }
};
var ViewLineData = class {
  constructor(content2, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens) {
    this.content = content2;
    this.continuesWithWrappedLine = continuesWithWrappedLine;
    this.minColumn = minColumn;
    this.maxColumn = maxColumn;
    this.startVisibleColumn = startVisibleColumn;
    this.tokens = tokens;
  }
};
var ViewLineRenderingData = class {
  constructor(minColumn, maxColumn, content2, continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, tokens, inlineDecorations, tabSize, startVisibleColumn) {
    this.minColumn = minColumn;
    this.maxColumn = maxColumn;
    this.content = content2;
    this.continuesWithWrappedLine = continuesWithWrappedLine;
    this.isBasicASCII = ViewLineRenderingData.isBasicASCII(content2, mightContainNonBasicASCII);
    this.containsRTL = ViewLineRenderingData.containsRTL(content2, this.isBasicASCII, mightContainRTL);
    this.tokens = tokens;
    this.inlineDecorations = inlineDecorations;
    this.tabSize = tabSize;
    this.startVisibleColumn = startVisibleColumn;
  }
  static isBasicASCII(lineContent, mightContainNonBasicASCII) {
    if (mightContainNonBasicASCII) {
      return isBasicASCII(lineContent);
    }
    return true;
  }
  static containsRTL(lineContent, isBasicASCII2, mightContainRTL) {
    if (!isBasicASCII2 && mightContainRTL) {
      return containsRTL(lineContent);
    }
    return false;
  }
};
var InlineDecoration = class {
  constructor(range3, inlineClassName, type) {
    this.range = range3;
    this.inlineClassName = inlineClassName;
    this.type = type;
  }
};
var ViewModelDecoration = class {
  constructor(range3, options) {
    this.range = range3;
    this.options = options;
  }
};
function isFuzzyActionArr(what) {
  return Array.isArray(what);
}
function isFuzzyAction(what) {
  return !isFuzzyActionArr(what);
}
function isString$1(what) {
  return typeof what === "string";
}
function isIAction(what) {
  return !isString$1(what);
}
function empty(s2) {
  return s2 ? false : true;
}
function fixCase(lexer, str) {
  return lexer.ignoreCase && str ? str.toLowerCase() : str;
}
function sanitize(s2) {
  return s2.replace(/[&<>'"_]/g, "-");
}
function log2(lexer, msg) {
  console.log(`${lexer.languageId}: ${msg}`);
}
function createError3(lexer, msg) {
  return new Error(`${lexer.languageId}: ${msg}`);
}
function substituteMatches(lexer, str, id3, matches2, state) {
  const re2 = /\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g;
  let stateMatches = null;
  return str.replace(re2, function(full, sub, dollar, hash2, n3, s2, attr2, ofs, total) {
    if (!empty(dollar)) {
      return "$";
    }
    if (!empty(hash2)) {
      return fixCase(lexer, id3);
    }
    if (!empty(n3) && n3 < matches2.length) {
      return fixCase(lexer, matches2[n3]);
    }
    if (!empty(attr2) && lexer && typeof lexer[attr2] === "string") {
      return lexer[attr2];
    }
    if (stateMatches === null) {
      stateMatches = state.split(".");
      stateMatches.unshift(state);
    }
    if (!empty(s2) && s2 < stateMatches.length) {
      return fixCase(lexer, stateMatches[s2]);
    }
    return "";
  });
}
function findRules(lexer, inState) {
  let state = inState;
  while (state && state.length > 0) {
    const rules = lexer.tokenizer[state];
    if (rules) {
      return rules;
    }
    const idx = state.lastIndexOf(".");
    if (idx < 0) {
      state = null;
    } else {
      state = state.substr(0, idx);
    }
  }
  return null;
}
function stateExists(lexer, inState) {
  let state = inState;
  while (state && state.length > 0) {
    const exist = lexer.stateNames[state];
    if (exist) {
      return true;
    }
    const idx = state.lastIndexOf(".");
    if (idx < 0) {
      state = null;
    } else {
      state = state.substr(0, idx);
    }
  }
  return false;
}
var CACHE_STACK_DEPTH = 5;
var MonarchStackElementFactory = class {
  constructor(maxCacheDepth) {
    this._maxCacheDepth = maxCacheDepth;
    this._entries = Object.create(null);
  }
  static create(parent, state) {
    return this._INSTANCE.create(parent, state);
  }
  create(parent, state) {
    if (parent !== null && parent.depth >= this._maxCacheDepth) {
      return new MonarchStackElement(parent, state);
    }
    let stackElementId = MonarchStackElement.getStackElementId(parent);
    if (stackElementId.length > 0) {
      stackElementId += "|";
    }
    stackElementId += state;
    let result = this._entries[stackElementId];
    if (result) {
      return result;
    }
    result = new MonarchStackElement(parent, state);
    this._entries[stackElementId] = result;
    return result;
  }
};
MonarchStackElementFactory._INSTANCE = new MonarchStackElementFactory(CACHE_STACK_DEPTH);
var MonarchStackElement = class {
  constructor(parent, state) {
    this.parent = parent;
    this.state = state;
    this.depth = (this.parent ? this.parent.depth : 0) + 1;
  }
  static getStackElementId(element) {
    let result = "";
    while (element !== null) {
      if (result.length > 0) {
        result += "|";
      }
      result += element.state;
      element = element.parent;
    }
    return result;
  }
  static _equals(a2, b2) {
    while (a2 !== null && b2 !== null) {
      if (a2 === b2) {
        return true;
      }
      if (a2.state !== b2.state) {
        return false;
      }
      a2 = a2.parent;
      b2 = b2.parent;
    }
    if (a2 === null && b2 === null) {
      return true;
    }
    return false;
  }
  equals(other) {
    return MonarchStackElement._equals(this, other);
  }
  push(state) {
    return MonarchStackElementFactory.create(this, state);
  }
  pop() {
    return this.parent;
  }
  popall() {
    let result = this;
    while (result.parent) {
      result = result.parent;
    }
    return result;
  }
  switchTo(state) {
    return MonarchStackElementFactory.create(this.parent, state);
  }
};
var EmbeddedModeData = class {
  constructor(modeId, state) {
    this.modeId = modeId;
    this.state = state;
  }
  equals(other) {
    return this.modeId === other.modeId && this.state.equals(other.state);
  }
  clone() {
    let stateClone = this.state.clone();
    if (stateClone === this.state) {
      return this;
    }
    return new EmbeddedModeData(this.modeId, this.state);
  }
};
var MonarchLineStateFactory = class {
  constructor(maxCacheDepth) {
    this._maxCacheDepth = maxCacheDepth;
    this._entries = Object.create(null);
  }
  static create(stack2, embeddedModeData) {
    return this._INSTANCE.create(stack2, embeddedModeData);
  }
  create(stack2, embeddedModeData) {
    if (embeddedModeData !== null) {
      return new MonarchLineState(stack2, embeddedModeData);
    }
    if (stack2 !== null && stack2.depth >= this._maxCacheDepth) {
      return new MonarchLineState(stack2, embeddedModeData);
    }
    let stackElementId = MonarchStackElement.getStackElementId(stack2);
    let result = this._entries[stackElementId];
    if (result) {
      return result;
    }
    result = new MonarchLineState(stack2, null);
    this._entries[stackElementId] = result;
    return result;
  }
};
MonarchLineStateFactory._INSTANCE = new MonarchLineStateFactory(CACHE_STACK_DEPTH);
var MonarchLineState = class {
  constructor(stack2, embeddedModeData) {
    this.stack = stack2;
    this.embeddedModeData = embeddedModeData;
  }
  clone() {
    let embeddedModeDataClone = this.embeddedModeData ? this.embeddedModeData.clone() : null;
    if (embeddedModeDataClone === this.embeddedModeData) {
      return this;
    }
    return MonarchLineStateFactory.create(this.stack, this.embeddedModeData);
  }
  equals(other) {
    if (!(other instanceof MonarchLineState)) {
      return false;
    }
    if (!this.stack.equals(other.stack)) {
      return false;
    }
    if (this.embeddedModeData === null && other.embeddedModeData === null) {
      return true;
    }
    if (this.embeddedModeData === null || other.embeddedModeData === null) {
      return false;
    }
    return this.embeddedModeData.equals(other.embeddedModeData);
  }
};
var MonarchClassicTokensCollector = class {
  constructor() {
    this._tokens = [];
    this._language = null;
    this._lastTokenType = null;
    this._lastTokenLanguage = null;
  }
  enterMode(startOffset, modeId) {
    this._language = modeId;
  }
  emit(startOffset, type) {
    if (this._lastTokenType === type && this._lastTokenLanguage === this._language) {
      return;
    }
    this._lastTokenType = type;
    this._lastTokenLanguage = this._language;
    this._tokens.push(new Token(startOffset, type, this._language));
  }
  nestedModeTokenize(embeddedModeLine, embeddedModeData, offsetDelta) {
    const nestedModeId = embeddedModeData.modeId;
    const embeddedModeState = embeddedModeData.state;
    const nestedModeTokenizationSupport = TokenizationRegistry.get(nestedModeId);
    if (!nestedModeTokenizationSupport) {
      this.enterMode(offsetDelta, nestedModeId);
      this.emit(offsetDelta, "");
      return embeddedModeState;
    }
    let nestedResult = nestedModeTokenizationSupport.tokenize(embeddedModeLine, embeddedModeState, offsetDelta);
    this._tokens = this._tokens.concat(nestedResult.tokens);
    this._lastTokenType = null;
    this._lastTokenLanguage = null;
    this._language = null;
    return nestedResult.endState;
  }
  finalize(endState) {
    return new TokenizationResult(this._tokens, endState);
  }
};
var MonarchModernTokensCollector = class {
  constructor(modeService, theme) {
    this._modeService = modeService;
    this._theme = theme;
    this._prependTokens = null;
    this._tokens = [];
    this._currentLanguageId = 0;
    this._lastTokenMetadata = 0;
  }
  enterMode(startOffset, modeId) {
    this._currentLanguageId = this._modeService.getLanguageIdentifier(modeId).id;
  }
  emit(startOffset, type) {
    let metadata = this._theme.match(this._currentLanguageId, type);
    if (this._lastTokenMetadata === metadata) {
      return;
    }
    this._lastTokenMetadata = metadata;
    this._tokens.push(startOffset);
    this._tokens.push(metadata);
  }
  static _merge(a2, b2, c3) {
    let aLen = a2 !== null ? a2.length : 0;
    let bLen = b2.length;
    let cLen = c3 !== null ? c3.length : 0;
    if (aLen === 0 && bLen === 0 && cLen === 0) {
      return new Uint32Array(0);
    }
    if (aLen === 0 && bLen === 0) {
      return c3;
    }
    if (bLen === 0 && cLen === 0) {
      return a2;
    }
    let result = new Uint32Array(aLen + bLen + cLen);
    if (a2 !== null) {
      result.set(a2);
    }
    for (let i3 = 0; i3 < bLen; i3++) {
      result[aLen + i3] = b2[i3];
    }
    if (c3 !== null) {
      result.set(c3, aLen + bLen);
    }
    return result;
  }
  nestedModeTokenize(embeddedModeLine, embeddedModeData, offsetDelta) {
    const nestedModeId = embeddedModeData.modeId;
    const embeddedModeState = embeddedModeData.state;
    const nestedModeTokenizationSupport = TokenizationRegistry.get(nestedModeId);
    if (!nestedModeTokenizationSupport) {
      this.enterMode(offsetDelta, nestedModeId);
      this.emit(offsetDelta, "");
      return embeddedModeState;
    }
    let nestedResult = nestedModeTokenizationSupport.tokenize2(embeddedModeLine, embeddedModeState, offsetDelta);
    this._prependTokens = MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, nestedResult.tokens);
    this._tokens = [];
    this._currentLanguageId = 0;
    this._lastTokenMetadata = 0;
    return nestedResult.endState;
  }
  finalize(endState) {
    return new TokenizationResult2(MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, null), endState);
  }
};
var MonarchTokenizer = class {
  constructor(modeService, standaloneThemeService, modeId, lexer) {
    this._modeService = modeService;
    this._standaloneThemeService = standaloneThemeService;
    this._modeId = modeId;
    this._lexer = lexer;
    this._embeddedModes = Object.create(null);
    this.embeddedLoaded = Promise.resolve(void 0);
    let emitting = false;
    this._tokenizationRegistryListener = TokenizationRegistry.onDidChange((e2) => {
      if (emitting) {
        return;
      }
      let isOneOfMyEmbeddedModes = false;
      for (let i3 = 0, len2 = e2.changedLanguages.length; i3 < len2; i3++) {
        let language = e2.changedLanguages[i3];
        if (this._embeddedModes[language]) {
          isOneOfMyEmbeddedModes = true;
          break;
        }
      }
      if (isOneOfMyEmbeddedModes) {
        emitting = true;
        TokenizationRegistry.fire([this._modeId]);
        emitting = false;
      }
    });
  }
  dispose() {
    this._tokenizationRegistryListener.dispose();
  }
  getLoadStatus() {
    let promises = [];
    for (let nestedModeId in this._embeddedModes) {
      const tokenizationSupport = TokenizationRegistry.get(nestedModeId);
      if (tokenizationSupport) {
        if (tokenizationSupport instanceof MonarchTokenizer) {
          const nestedModeStatus = tokenizationSupport.getLoadStatus();
          if (nestedModeStatus.loaded === false) {
            promises.push(nestedModeStatus.promise);
          }
        }
        continue;
      }
      const tokenizationSupportPromise = TokenizationRegistry.getPromise(nestedModeId);
      if (tokenizationSupportPromise) {
        promises.push(tokenizationSupportPromise);
      }
    }
    if (promises.length === 0) {
      return {
        loaded: true
      };
    }
    return {
      loaded: false,
      promise: Promise.all(promises).then((_23) => void 0)
    };
  }
  getInitialState() {
    let rootState = MonarchStackElementFactory.create(null, this._lexer.start);
    return MonarchLineStateFactory.create(rootState, null);
  }
  tokenize(line, lineState, offsetDelta) {
    let tokensCollector = new MonarchClassicTokensCollector();
    let endLineState = this._tokenize(line, lineState, offsetDelta, tokensCollector);
    return tokensCollector.finalize(endLineState);
  }
  tokenize2(line, lineState, offsetDelta) {
    let tokensCollector = new MonarchModernTokensCollector(this._modeService, this._standaloneThemeService.getColorTheme().tokenTheme);
    let endLineState = this._tokenize(line, lineState, offsetDelta, tokensCollector);
    return tokensCollector.finalize(endLineState);
  }
  _tokenize(line, lineState, offsetDelta, collector) {
    if (lineState.embeddedModeData) {
      return this._nestedTokenize(line, lineState, offsetDelta, collector);
    } else {
      return this._myTokenize(line, lineState, offsetDelta, collector);
    }
  }
  _findLeavingNestedModeOffset(line, state) {
    let rules = this._lexer.tokenizer[state.stack.state];
    if (!rules) {
      rules = findRules(this._lexer, state.stack.state);
      if (!rules) {
        throw createError3(this._lexer, "tokenizer state is not defined: " + state.stack.state);
      }
    }
    let popOffset = -1;
    let hasEmbeddedPopRule = false;
    for (const rule of rules) {
      if (!isIAction(rule.action) || rule.action.nextEmbedded !== "@pop") {
        continue;
      }
      hasEmbeddedPopRule = true;
      let regex = rule.regex;
      let regexSource = rule.regex.source;
      if (regexSource.substr(0, 4) === "^(?:" && regexSource.substr(regexSource.length - 1, 1) === ")") {
        let flags2 = (regex.ignoreCase ? "i" : "") + (regex.unicode ? "u" : "");
        regex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags2);
      }
      let result = line.search(regex);
      if (result === -1 || result !== 0 && rule.matchOnlyAtLineStart) {
        continue;
      }
      if (popOffset === -1 || result < popOffset) {
        popOffset = result;
      }
    }
    if (!hasEmbeddedPopRule) {
      throw createError3(this._lexer, 'no rule containing nextEmbedded: "@pop" in tokenizer embedded state: ' + state.stack.state);
    }
    return popOffset;
  }
  _nestedTokenize(line, lineState, offsetDelta, tokensCollector) {
    let popOffset = this._findLeavingNestedModeOffset(line, lineState);
    if (popOffset === -1) {
      let nestedEndState = tokensCollector.nestedModeTokenize(line, lineState.embeddedModeData, offsetDelta);
      return MonarchLineStateFactory.create(lineState.stack, new EmbeddedModeData(lineState.embeddedModeData.modeId, nestedEndState));
    }
    let nestedModeLine = line.substring(0, popOffset);
    if (nestedModeLine.length > 0) {
      tokensCollector.nestedModeTokenize(nestedModeLine, lineState.embeddedModeData, offsetDelta);
    }
    let restOfTheLine = line.substring(popOffset);
    return this._myTokenize(restOfTheLine, lineState, offsetDelta + popOffset, tokensCollector);
  }
  _safeRuleName(rule) {
    if (rule) {
      return rule.name;
    }
    return "(unknown)";
  }
  _myTokenize(line, lineState, offsetDelta, tokensCollector) {
    tokensCollector.enterMode(offsetDelta, this._modeId);
    const lineLength = line.length;
    let embeddedModeData = lineState.embeddedModeData;
    let stack2 = lineState.stack;
    let pos = 0;
    let groupMatching = null;
    let forceEvaluation = true;
    while (forceEvaluation || pos < lineLength) {
      const pos0 = pos;
      const stackLen0 = stack2.depth;
      const groupLen0 = groupMatching ? groupMatching.groups.length : 0;
      const state = stack2.state;
      let matches2 = null;
      let matched = null;
      let action = null;
      let rule = null;
      let enteringEmbeddedMode = null;
      if (groupMatching) {
        matches2 = groupMatching.matches;
        const groupEntry = groupMatching.groups.shift();
        matched = groupEntry.matched;
        action = groupEntry.action;
        rule = groupMatching.rule;
        if (groupMatching.groups.length === 0) {
          groupMatching = null;
        }
      } else {
        if (!forceEvaluation && pos >= lineLength) {
          break;
        }
        forceEvaluation = false;
        let rules = this._lexer.tokenizer[state];
        if (!rules) {
          rules = findRules(this._lexer, state);
          if (!rules) {
            throw createError3(this._lexer, "tokenizer state is not defined: " + state);
          }
        }
        let restOfLine = line.substr(pos);
        for (const rule2 of rules) {
          if (pos === 0 || !rule2.matchOnlyAtLineStart) {
            matches2 = restOfLine.match(rule2.regex);
            if (matches2) {
              matched = matches2[0];
              action = rule2.action;
              break;
            }
          }
        }
      }
      if (!matches2) {
        matches2 = [""];
        matched = "";
      }
      if (!action) {
        if (pos < lineLength) {
          matches2 = [line.charAt(pos)];
          matched = matches2[0];
        }
        action = this._lexer.defaultToken;
      }
      if (matched === null) {
        break;
      }
      pos += matched.length;
      while (isFuzzyAction(action) && isIAction(action) && action.test) {
        action = action.test(matched, matches2, state, pos === lineLength);
      }
      let result = null;
      if (typeof action === "string" || Array.isArray(action)) {
        result = action;
      } else if (action.group) {
        result = action.group;
      } else if (action.token !== null && action.token !== void 0) {
        if (action.tokenSubst) {
          result = substituteMatches(this._lexer, action.token, matched, matches2, state);
        } else {
          result = action.token;
        }
        if (action.nextEmbedded) {
          if (action.nextEmbedded === "@pop") {
            if (!embeddedModeData) {
              throw createError3(this._lexer, "cannot pop embedded mode if not inside one");
            }
            embeddedModeData = null;
          } else if (embeddedModeData) {
            throw createError3(this._lexer, "cannot enter embedded mode from within an embedded mode");
          } else {
            enteringEmbeddedMode = substituteMatches(this._lexer, action.nextEmbedded, matched, matches2, state);
          }
        }
        if (action.goBack) {
          pos = Math.max(0, pos - action.goBack);
        }
        if (action.switchTo && typeof action.switchTo === "string") {
          let nextState = substituteMatches(this._lexer, action.switchTo, matched, matches2, state);
          if (nextState[0] === "@") {
            nextState = nextState.substr(1);
          }
          if (!findRules(this._lexer, nextState)) {
            throw createError3(this._lexer, "trying to switch to a state '" + nextState + "' that is undefined in rule: " + this._safeRuleName(rule));
          } else {
            stack2 = stack2.switchTo(nextState);
          }
        } else if (action.transform && typeof action.transform === "function") {
          throw createError3(this._lexer, "action.transform not supported");
        } else if (action.next) {
          if (action.next === "@push") {
            if (stack2.depth >= this._lexer.maxStack) {
              throw createError3(this._lexer, "maximum tokenizer stack size reached: [" + stack2.state + "," + stack2.parent.state + ",...]");
            } else {
              stack2 = stack2.push(state);
            }
          } else if (action.next === "@pop") {
            if (stack2.depth <= 1) {
              throw createError3(this._lexer, "trying to pop an empty stack in rule: " + this._safeRuleName(rule));
            } else {
              stack2 = stack2.pop();
            }
          } else if (action.next === "@popall") {
            stack2 = stack2.popall();
          } else {
            let nextState = substituteMatches(this._lexer, action.next, matched, matches2, state);
            if (nextState[0] === "@") {
              nextState = nextState.substr(1);
            }
            if (!findRules(this._lexer, nextState)) {
              throw createError3(this._lexer, "trying to set a next state '" + nextState + "' that is undefined in rule: " + this._safeRuleName(rule));
            } else {
              stack2 = stack2.push(nextState);
            }
          }
        }
        if (action.log && typeof action.log === "string") {
          log2(this._lexer, this._lexer.languageId + ": " + substituteMatches(this._lexer, action.log, matched, matches2, state));
        }
      }
      if (result === null) {
        throw createError3(this._lexer, "lexer rule has no well-defined action in rule: " + this._safeRuleName(rule));
      }
      const computeNewStateForEmbeddedMode = (enteringEmbeddedMode2) => {
        let enteringEmbeddedModeId = this._modeService.getModeIdForLanguageName(enteringEmbeddedMode2);
        if (enteringEmbeddedModeId) {
          enteringEmbeddedMode2 = enteringEmbeddedModeId;
        }
        const embeddedModeData2 = this._getNestedEmbeddedModeData(enteringEmbeddedMode2);
        if (pos < lineLength) {
          const restOfLine = line.substr(pos);
          return this._nestedTokenize(restOfLine, MonarchLineStateFactory.create(stack2, embeddedModeData2), offsetDelta + pos, tokensCollector);
        } else {
          return MonarchLineStateFactory.create(stack2, embeddedModeData2);
        }
      };
      if (Array.isArray(result)) {
        if (groupMatching && groupMatching.groups.length > 0) {
          throw createError3(this._lexer, "groups cannot be nested: " + this._safeRuleName(rule));
        }
        if (matches2.length !== result.length + 1) {
          throw createError3(this._lexer, "matched number of groups does not match the number of actions in rule: " + this._safeRuleName(rule));
        }
        let totalLen = 0;
        for (let i3 = 1; i3 < matches2.length; i3++) {
          totalLen += matches2[i3].length;
        }
        if (totalLen !== matched.length) {
          throw createError3(this._lexer, "with groups, all characters should be matched in consecutive groups in rule: " + this._safeRuleName(rule));
        }
        groupMatching = {
          rule,
          matches: matches2,
          groups: []
        };
        for (let i3 = 0; i3 < result.length; i3++) {
          groupMatching.groups[i3] = {
            action: result[i3],
            matched: matches2[i3 + 1]
          };
        }
        pos -= matched.length;
        continue;
      } else {
        if (result === "@rematch") {
          pos -= matched.length;
          matched = "";
          matches2 = null;
          result = "";
          if (enteringEmbeddedMode !== null) {
            return computeNewStateForEmbeddedMode(enteringEmbeddedMode);
          }
        }
        if (matched.length === 0) {
          if (lineLength === 0 || stackLen0 !== stack2.depth || state !== stack2.state || (!groupMatching ? 0 : groupMatching.groups.length) !== groupLen0) {
            continue;
          } else {
            throw createError3(this._lexer, "no progress in tokenizer in rule: " + this._safeRuleName(rule));
          }
        }
        let tokenType = null;
        if (isString$1(result) && result.indexOf("@brackets") === 0) {
          let rest = result.substr("@brackets".length);
          let bracket = findBracket(this._lexer, matched);
          if (!bracket) {
            throw createError3(this._lexer, "@brackets token returned but no bracket defined as: " + matched);
          }
          tokenType = sanitize(bracket.token + rest);
        } else {
          let token2 = result === "" ? "" : result + this._lexer.tokenPostfix;
          tokenType = sanitize(token2);
        }
        tokensCollector.emit(pos0 + offsetDelta, tokenType);
      }
      if (enteringEmbeddedMode !== null) {
        return computeNewStateForEmbeddedMode(enteringEmbeddedMode);
      }
    }
    return MonarchLineStateFactory.create(stack2, embeddedModeData);
  }
  _getNestedEmbeddedModeData(mimetypeOrModeId) {
    let nestedModeId = this._locateMode(mimetypeOrModeId);
    if (nestedModeId) {
      let tokenizationSupport = TokenizationRegistry.get(nestedModeId);
      if (tokenizationSupport) {
        return new EmbeddedModeData(nestedModeId, tokenizationSupport.getInitialState());
      }
    }
    return new EmbeddedModeData(nestedModeId || NULL_MODE_ID, NULL_STATE);
  }
  _locateMode(mimetypeOrModeId) {
    if (!mimetypeOrModeId || !this._modeService.isRegisteredMode(mimetypeOrModeId)) {
      return null;
    }
    if (mimetypeOrModeId === this._modeId) {
      return mimetypeOrModeId;
    }
    let modeId = this._modeService.getModeId(mimetypeOrModeId);
    if (modeId) {
      this._modeService.triggerMode(modeId);
      this._embeddedModes[modeId] = true;
    }
    return modeId;
  }
};
function findBracket(lexer, matched) {
  if (!matched) {
    return null;
  }
  matched = fixCase(lexer, matched);
  let brackets = lexer.brackets;
  for (const bracket of brackets) {
    if (bracket.open === matched) {
      return {token: bracket.token, bracketType: 1};
    } else if (bracket.close === matched) {
      return {token: bracket.token, bracketType: -1};
    }
  }
  return null;
}
function createTokenizationSupport(modeService, standaloneThemeService, modeId, lexer) {
  return new MonarchTokenizer(modeService, standaloneThemeService, modeId, lexer);
}
var Colorizer = class {
  static colorizeElement(themeService, modeService, domNode, options) {
    options = options || {};
    let theme = options.theme || "vs";
    let mimeType = options.mimeType || domNode.getAttribute("lang") || domNode.getAttribute("data-lang");
    if (!mimeType) {
      console.error("Mode not detected");
      return Promise.resolve();
    }
    themeService.setTheme(theme);
    let text = domNode.firstChild ? domNode.firstChild.nodeValue : "";
    domNode.className += " " + theme;
    let render4 = (str) => {
      domNode.innerHTML = str;
    };
    return this.colorize(modeService, text || "", mimeType, options).then(render4, (err) => console.error(err));
  }
  static colorize(modeService, text, mimeType, options) {
    let tabSize = 4;
    if (options && typeof options.tabSize === "number") {
      tabSize = options.tabSize;
    }
    if (startsWithUTF8BOM(text)) {
      text = text.substr(1);
    }
    let lines = text.split(/\r\n|\r|\n/);
    let language = modeService.getModeId(mimeType);
    if (!language) {
      return Promise.resolve(_fakeColorize(lines, tabSize));
    }
    modeService.triggerMode(language);
    const tokenizationSupport = TokenizationRegistry.get(language);
    if (tokenizationSupport) {
      return _colorize(lines, tabSize, tokenizationSupport);
    }
    const tokenizationSupportPromise = TokenizationRegistry.getPromise(language);
    if (tokenizationSupportPromise) {
      return new Promise((resolve2, reject) => {
        tokenizationSupportPromise.then((tokenizationSupport2) => {
          _colorize(lines, tabSize, tokenizationSupport2).then(resolve2, reject);
        }, reject);
      });
    }
    return new Promise((resolve2, reject) => {
      let listener = null;
      let timeout3 = null;
      const execute = () => {
        if (listener) {
          listener.dispose();
          listener = null;
        }
        if (timeout3) {
          timeout3.dispose();
          timeout3 = null;
        }
        const tokenizationSupport2 = TokenizationRegistry.get(language);
        if (tokenizationSupport2) {
          _colorize(lines, tabSize, tokenizationSupport2).then(resolve2, reject);
          return;
        }
        resolve2(_fakeColorize(lines, tabSize));
      };
      timeout3 = new TimeoutTimer();
      timeout3.cancelAndSet(execute, 500);
      listener = TokenizationRegistry.onDidChange((e2) => {
        if (e2.changedLanguages.indexOf(language) >= 0) {
          execute();
        }
      });
    });
  }
  static colorizeLine(line, mightContainNonBasicASCII, mightContainRTL, tokens, tabSize = 4) {
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(line, mightContainNonBasicASCII);
    const containsRTL2 = ViewLineRenderingData.containsRTL(line, isBasicASCII2, mightContainRTL);
    let renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII2, containsRTL2, 0, tokens, [], tabSize, 0, 0, 0, 0, -1, "none", false, false, null));
    return renderResult.html;
  }
  static colorizeModelLine(model, lineNumber, tabSize = 4) {
    let content2 = model.getLineContent(lineNumber);
    model.forceTokenization(lineNumber);
    let tokens = model.getLineTokens(lineNumber);
    let inflatedTokens = tokens.inflate();
    return this.colorizeLine(content2, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize);
  }
};
function _colorize(lines, tabSize, tokenizationSupport) {
  return new Promise((c3, e2) => {
    const execute = () => {
      const result = _actualColorize(lines, tabSize, tokenizationSupport);
      if (tokenizationSupport instanceof MonarchTokenizer) {
        const status = tokenizationSupport.getLoadStatus();
        if (status.loaded === false) {
          status.promise.then(execute, e2);
          return;
        }
      }
      c3(result);
    };
    execute();
  });
}
function _fakeColorize(lines, tabSize) {
  let html = [];
  const defaultMetadata = (0 << 11 | 1 << 14 | 2 << 23) >>> 0;
  const tokens = new Uint32Array(2);
  tokens[0] = 0;
  tokens[1] = defaultMetadata;
  for (let i3 = 0, length = lines.length; i3 < length; i3++) {
    let line = lines[i3];
    tokens[0] = line.length;
    const lineTokens = new LineTokens(tokens, line);
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(line, true);
    const containsRTL2 = ViewLineRenderingData.containsRTL(line, isBasicASCII2, true);
    let renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII2, containsRTL2, 0, lineTokens, [], tabSize, 0, 0, 0, 0, -1, "none", false, false, null));
    html = html.concat(renderResult.html);
    html.push("<br/>");
  }
  return html.join("");
}
function _actualColorize(lines, tabSize, tokenizationSupport) {
  let html = [];
  let state = tokenizationSupport.getInitialState();
  for (let i3 = 0, length = lines.length; i3 < length; i3++) {
    let line = lines[i3];
    let tokenizeResult = tokenizationSupport.tokenize2(line, state, 0);
    LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length);
    let lineTokens = new LineTokens(tokenizeResult.tokens, line);
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(line, true);
    const containsRTL2 = ViewLineRenderingData.containsRTL(line, isBasicASCII2, true);
    let renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII2, containsRTL2, 0, lineTokens.inflate(), [], tabSize, 0, 0, 0, 0, -1, "none", false, false, null));
    html = html.concat(renderResult.html);
    html.push("<br/>");
    state = tokenizeResult.endState;
  }
  return html.join("");
}
var Severity;
(function(Severity2) {
  Severity2[Severity2["Ignore"] = 0] = "Ignore";
  Severity2[Severity2["Info"] = 1] = "Info";
  Severity2[Severity2["Warning"] = 2] = "Warning";
  Severity2[Severity2["Error"] = 3] = "Error";
})(Severity || (Severity = {}));
(function(Severity2) {
  const _error = "error";
  const _warning = "warning";
  const _warn = "warn";
  const _info = "info";
  function fromValue(value) {
    if (!value) {
      return Severity2.Ignore;
    }
    if (equalsIgnoreCase(_error, value)) {
      return Severity2.Error;
    }
    if (equalsIgnoreCase(_warning, value) || equalsIgnoreCase(_warn, value)) {
      return Severity2.Warning;
    }
    if (equalsIgnoreCase(_info, value)) {
      return Severity2.Info;
    }
    return Severity2.Ignore;
  }
  Severity2.fromValue = fromValue;
})(Severity || (Severity = {}));
var Severity$1 = Severity;
function isCodeEditor(thing) {
  if (thing && typeof thing.getEditorType === "function") {
    return thing.getEditorType() === EditorType.ICodeEditor;
  } else {
    return false;
  }
}
var IBulkEditService = createDecorator("IWorkspaceEditService");
function isWorkspaceFileEdit(thing) {
  return isObject3(thing) && (Boolean(thing.newUri) || Boolean(thing.oldUri));
}
function isWorkspaceTextEdit(thing) {
  return isObject3(thing) && URI.isUri(thing.resource) && isObject3(thing.edit);
}
var ResourceEdit = class {
  constructor(metadata) {
    this.metadata = metadata;
  }
  static convert(edit) {
    return edit.edits.map((edit2) => {
      if (isWorkspaceTextEdit(edit2)) {
        return new ResourceTextEdit(edit2.resource, edit2.edit, edit2.modelVersionId, edit2.metadata);
      }
      if (isWorkspaceFileEdit(edit2)) {
        return new ResourceFileEdit(edit2.oldUri, edit2.newUri, edit2.options, edit2.metadata);
      }
      throw new Error("Unsupported edit");
    });
  }
};
var ResourceTextEdit = class extends ResourceEdit {
  constructor(resource2, textEdit, versionId, metadata) {
    super(metadata);
    this.resource = resource2;
    this.textEdit = textEdit;
    this.versionId = versionId;
    this.metadata = metadata;
  }
};
var ResourceFileEdit = class extends ResourceEdit {
  constructor(oldResource, newResource, options, metadata) {
    super(metadata);
    this.oldResource = oldResource;
    this.newResource = newResource;
    this.options = options;
    this.metadata = metadata;
  }
};
var RegistryImpl = class {
  constructor() {
    this.data = new Map();
  }
  add(id3, data2) {
    ok2(isString3(id3));
    ok2(isObject3(data2));
    ok2(!this.data.has(id3), "There is already an extension with this id");
    this.data.set(id3, data2);
  }
  as(id3) {
    return this.data.get(id3) || null;
  }
};
var Registry$1 = new RegistryImpl();
var Extensions = {
  JSONContribution: "base.contributions.json"
};
function normalizeId(id3) {
  if (id3.length > 0 && id3.charAt(id3.length - 1) === "#") {
    return id3.substring(0, id3.length - 1);
  }
  return id3;
}
var JSONContributionRegistry = class {
  constructor() {
    this._onDidChangeSchema = new Emitter();
    this.schemasById = {};
  }
  registerSchema(uri, unresolvedSchemaContent) {
    this.schemasById[normalizeId(uri)] = unresolvedSchemaContent;
    this._onDidChangeSchema.fire(uri);
  }
  notifySchemaChanged(uri) {
    this._onDidChangeSchema.fire(uri);
  }
};
var jsonContributionRegistry = new JSONContributionRegistry();
Registry$1.add(Extensions.JSONContribution, jsonContributionRegistry);
var Extensions$1 = {
  Configuration: "base.contributions.configuration"
};
var resourceLanguageSettingsSchemaId = "vscode://schemas/settings/resourceLanguage";
var contributionRegistry = Registry$1.as(Extensions.JSONContribution);
var ConfigurationRegistry = class {
  constructor() {
    this.overrideIdentifiers = new Set();
    this._onDidSchemaChange = new Emitter();
    this._onDidUpdateConfiguration = new Emitter();
    this.defaultValues = {};
    this.defaultLanguageConfigurationOverridesNode = {
      id: "defaultOverrides",
      title: localize("defaultLanguageConfigurationOverrides.title", "Default Language Configuration Overrides"),
      properties: {}
    };
    this.configurationContributors = [this.defaultLanguageConfigurationOverridesNode];
    this.resourceLanguageSettingsSchema = {properties: {}, patternProperties: {}, additionalProperties: false, errorMessage: "Unknown editor configuration setting", allowTrailingCommas: true, allowComments: true};
    this.configurationProperties = {};
    this.excludedConfigurationProperties = {};
    contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
  }
  registerConfiguration(configuration, validate = true) {
    this.registerConfigurations([configuration], validate);
  }
  registerConfigurations(configurations, validate = true) {
    const properties = [];
    configurations.forEach((configuration) => {
      properties.push(...this.validateAndRegisterProperties(configuration, validate));
      this.configurationContributors.push(configuration);
      this.registerJSONConfiguration(configuration);
    });
    contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
    this._onDidSchemaChange.fire();
    this._onDidUpdateConfiguration.fire(properties);
  }
  registerOverrideIdentifiers(overrideIdentifiers) {
    for (const overrideIdentifier of overrideIdentifiers) {
      this.overrideIdentifiers.add(overrideIdentifier);
    }
    this.updateOverridePropertyPatternKey();
  }
  validateAndRegisterProperties(configuration, validate = true, scope = 3) {
    scope = isUndefinedOrNull(configuration.scope) ? scope : configuration.scope;
    let propertyKeys = [];
    let properties = configuration.properties;
    if (properties) {
      for (let key in properties) {
        if (validate && validateProperty(key)) {
          delete properties[key];
          continue;
        }
        const property2 = properties[key];
        this.updatePropertyDefaultValue(key, property2);
        if (OVERRIDE_PROPERTY_PATTERN.test(key)) {
          property2.scope = void 0;
        } else {
          property2.scope = isUndefinedOrNull(property2.scope) ? scope : property2.scope;
        }
        if (properties[key].hasOwnProperty("included") && !properties[key].included) {
          this.excludedConfigurationProperties[key] = properties[key];
          delete properties[key];
          continue;
        } else {
          this.configurationProperties[key] = properties[key];
        }
        if (!properties[key].deprecationMessage && properties[key].markdownDeprecationMessage) {
          properties[key].deprecationMessage = properties[key].markdownDeprecationMessage;
        }
        propertyKeys.push(key);
      }
    }
    let subNodes = configuration.allOf;
    if (subNodes) {
      for (let node of subNodes) {
        propertyKeys.push(...this.validateAndRegisterProperties(node, validate, scope));
      }
    }
    return propertyKeys;
  }
  getConfigurationProperties() {
    return this.configurationProperties;
  }
  registerJSONConfiguration(configuration) {
    const register2 = (configuration2) => {
      let properties = configuration2.properties;
      if (properties) {
        for (const key in properties) {
          this.updateSchema(key, properties[key]);
        }
      }
      let subNodes = configuration2.allOf;
      if (subNodes) {
        subNodes.forEach(register2);
      }
    };
    register2(configuration);
  }
  updateSchema(key, property2) {
    switch (property2.scope) {
      case 1:
        break;
      case 2:
        break;
      case 6:
        break;
      case 3:
        break;
      case 4:
        break;
      case 5:
        this.resourceLanguageSettingsSchema.properties[key] = property2;
        break;
    }
  }
  updateOverridePropertyPatternKey() {
    for (const overrideIdentifier of this.overrideIdentifiers.values()) {
      const overrideIdentifierProperty = `[${overrideIdentifier}]`;
      const resourceLanguagePropertiesSchema = {
        type: "object",
        description: localize("overrideSettings.defaultDescription", "Configure editor settings to be overridden for a language."),
        errorMessage: localize("overrideSettings.errorMessage", "This setting does not support per-language configuration."),
        $ref: resourceLanguageSettingsSchemaId
      };
      this.updatePropertyDefaultValue(overrideIdentifierProperty, resourceLanguagePropertiesSchema);
    }
    this._onDidSchemaChange.fire();
  }
  updatePropertyDefaultValue(key, property2) {
    let defaultValue = this.defaultValues[key];
    if (isUndefined3(defaultValue)) {
      defaultValue = property2.default;
    }
    if (isUndefined3(defaultValue)) {
      defaultValue = getDefaultValue(property2.type);
    }
    property2.default = defaultValue;
  }
};
var OVERRIDE_PROPERTY = "\\[.*\\]$";
var OVERRIDE_PROPERTY_PATTERN = new RegExp(OVERRIDE_PROPERTY);
function overrideIdentifierFromKey(key) {
  return key.substring(1, key.length - 1);
}
function getDefaultValue(type) {
  const t5 = Array.isArray(type) ? type[0] : type;
  switch (t5) {
    case "boolean":
      return false;
    case "integer":
    case "number":
      return 0;
    case "string":
      return "";
    case "array":
      return [];
    case "object":
      return {};
    default:
      return null;
  }
}
var configurationRegistry = new ConfigurationRegistry();
Registry$1.add(Extensions$1.Configuration, configurationRegistry);
function validateProperty(property2) {
  if (OVERRIDE_PROPERTY_PATTERN.test(property2)) {
    return localize("config.property.languageDefault", "Cannot register '{0}'. This matches property pattern '\\\\[.*\\\\]$' for describing language specific editor settings. Use 'configurationDefaults' contribution.", property2);
  }
  if (configurationRegistry.getConfigurationProperties()[property2] !== void 0) {
    return localize("config.property.duplicate", "Cannot register '{0}'. This property is already registered.", property2);
  }
  return null;
}
var hasOwnProperty2 = Object.prototype.hasOwnProperty;
function forEach3(from, callback) {
  for (let key in from) {
    if (hasOwnProperty2.call(from, key)) {
      const result = callback({key, value: from[key]}, function() {
        delete from[key];
      });
      if (result === false) {
        return;
      }
    }
  }
}
var SetMap = class {
  constructor() {
    this.map = new Map();
  }
  add(key, value) {
    let values2 = this.map.get(key);
    if (!values2) {
      values2 = new Set();
      this.map.set(key, values2);
    }
    values2.add(value);
  }
  delete(key, value) {
    const values2 = this.map.get(key);
    if (!values2) {
      return;
    }
    values2.delete(value);
    if (values2.size === 0) {
      this.map.delete(key);
    }
  }
  forEach(key, fn) {
    const values2 = this.map.get(key);
    if (!values2) {
      return;
    }
    values2.forEach(fn);
  }
};
var TabFocus = new class {
  constructor() {
    this._tabFocus = false;
    this._onDidChangeTabFocus = new Emitter();
    this.onDidChangeTabFocus = this._onDidChangeTabFocus.event;
  }
  getTabFocusMode() {
    return this._tabFocus;
  }
  setTabFocusMode(tabFocusMode) {
    if (this._tabFocus === tabFocusMode) {
      return;
    }
    this._tabFocus = tabFocusMode;
    this._onDidChangeTabFocus.fire(this._tabFocus);
  }
}();
var hasOwnProperty$1 = Object.hasOwnProperty;
var ComputedEditorOptions = class {
  constructor() {
    this._values = [];
  }
  _read(id3) {
    return this._values[id3];
  }
  get(id3) {
    return this._values[id3];
  }
  _write(id3, value) {
    this._values[id3] = value;
  }
};
var RawEditorOptions = class {
  constructor() {
    this._values = [];
  }
  _read(id3) {
    return this._values[id3];
  }
  _write(id3, value) {
    this._values[id3] = value;
  }
};
var EditorConfiguration2 = class {
  static readOptions(_options) {
    const options = _options;
    const result = new RawEditorOptions();
    for (const editorOption of editorOptionsRegistry) {
      const value = editorOption.name === "_never_" ? void 0 : options[editorOption.name];
      result._write(editorOption.id, value);
    }
    return result;
  }
  static validateOptions(options) {
    const result = new ValidatedEditorOptions();
    for (const editorOption of editorOptionsRegistry) {
      result._write(editorOption.id, editorOption.validate(options._read(editorOption.id)));
    }
    return result;
  }
  static computeOptions(options, env2) {
    const result = new ComputedEditorOptions();
    for (const editorOption of editorOptionsRegistry) {
      result._write(editorOption.id, editorOption.compute(env2, result, options._read(editorOption.id)));
    }
    return result;
  }
  static _deepEquals(a2, b2) {
    if (typeof a2 !== "object" || typeof b2 !== "object") {
      return a2 === b2;
    }
    if (Array.isArray(a2) || Array.isArray(b2)) {
      return Array.isArray(a2) && Array.isArray(b2) ? equals(a2, b2) : false;
    }
    for (let key in a2) {
      if (!EditorConfiguration2._deepEquals(a2[key], b2[key])) {
        return false;
      }
    }
    return true;
  }
  static checkEquals(a2, b2) {
    const result = [];
    let somethingChanged = false;
    for (const editorOption of editorOptionsRegistry) {
      const changed = !EditorConfiguration2._deepEquals(a2._read(editorOption.id), b2._read(editorOption.id));
      result[editorOption.id] = changed;
      if (changed) {
        somethingChanged = true;
      }
    }
    return somethingChanged ? new ConfigurationChangedEvent(result) : null;
  }
};
function migrateOptions(options) {
  const wordWrap = options.wordWrap;
  if (wordWrap === true) {
    options.wordWrap = "on";
  } else if (wordWrap === false) {
    options.wordWrap = "off";
  }
  const lineNumbers = options.lineNumbers;
  if (lineNumbers === true) {
    options.lineNumbers = "on";
  } else if (lineNumbers === false) {
    options.lineNumbers = "off";
  }
  const autoClosingBrackets = options.autoClosingBrackets;
  if (autoClosingBrackets === false) {
    options.autoClosingBrackets = "never";
    options.autoClosingQuotes = "never";
    options.autoSurround = "never";
  }
  const cursorBlinking = options.cursorBlinking;
  if (cursorBlinking === "visible") {
    options.cursorBlinking = "solid";
  }
  const renderWhitespace = options.renderWhitespace;
  if (renderWhitespace === true) {
    options.renderWhitespace = "boundary";
  } else if (renderWhitespace === false) {
    options.renderWhitespace = "none";
  }
  const renderLineHighlight = options.renderLineHighlight;
  if (renderLineHighlight === true) {
    options.renderLineHighlight = "line";
  } else if (renderLineHighlight === false) {
    options.renderLineHighlight = "none";
  }
  const acceptSuggestionOnEnter = options.acceptSuggestionOnEnter;
  if (acceptSuggestionOnEnter === true) {
    options.acceptSuggestionOnEnter = "on";
  } else if (acceptSuggestionOnEnter === false) {
    options.acceptSuggestionOnEnter = "off";
  }
  const tabCompletion = options.tabCompletion;
  if (tabCompletion === false) {
    options.tabCompletion = "off";
  } else if (tabCompletion === true) {
    options.tabCompletion = "onlySnippets";
  }
  const suggest = options.suggest;
  if (suggest && typeof suggest.filteredTypes === "object" && suggest.filteredTypes) {
    const mapping = {};
    mapping["method"] = "showMethods";
    mapping["function"] = "showFunctions";
    mapping["constructor"] = "showConstructors";
    mapping["field"] = "showFields";
    mapping["variable"] = "showVariables";
    mapping["class"] = "showClasses";
    mapping["struct"] = "showStructs";
    mapping["interface"] = "showInterfaces";
    mapping["module"] = "showModules";
    mapping["property"] = "showProperties";
    mapping["event"] = "showEvents";
    mapping["operator"] = "showOperators";
    mapping["unit"] = "showUnits";
    mapping["value"] = "showValues";
    mapping["constant"] = "showConstants";
    mapping["enum"] = "showEnums";
    mapping["enumMember"] = "showEnumMembers";
    mapping["keyword"] = "showKeywords";
    mapping["text"] = "showWords";
    mapping["color"] = "showColors";
    mapping["file"] = "showFiles";
    mapping["reference"] = "showReferences";
    mapping["folder"] = "showFolders";
    mapping["typeParameter"] = "showTypeParameters";
    mapping["snippet"] = "showSnippets";
    forEach3(mapping, (entry) => {
      const value = suggest.filteredTypes[entry.key];
      if (value === false) {
        suggest[entry.value] = value;
      }
    });
  }
  const hover = options.hover;
  if (hover === true) {
    options.hover = {
      enabled: true
    };
  } else if (hover === false) {
    options.hover = {
      enabled: false
    };
  }
  const parameterHints = options.parameterHints;
  if (parameterHints === true) {
    options.parameterHints = {
      enabled: true
    };
  } else if (parameterHints === false) {
    options.parameterHints = {
      enabled: false
    };
  }
  const autoIndent = options.autoIndent;
  if (autoIndent === true) {
    options.autoIndent = "full";
  } else if (autoIndent === false) {
    options.autoIndent = "advanced";
  }
  const matchBrackets = options.matchBrackets;
  if (matchBrackets === true) {
    options.matchBrackets = "always";
  } else if (matchBrackets === false) {
    options.matchBrackets = "never";
  }
}
function deepCloneAndMigrateOptions(_options) {
  const options = deepClone(_options);
  migrateOptions(options);
  return options;
}
var CommonEditorConfiguration = class extends Disposable {
  constructor(isSimpleWidget, _options) {
    super();
    this._onDidChange = this._register(new Emitter());
    this.onDidChange = this._onDidChange.event;
    this._onDidChangeFast = this._register(new Emitter());
    this.onDidChangeFast = this._onDidChangeFast.event;
    this.isSimpleWidget = isSimpleWidget;
    this._isDominatedByLongLines = false;
    this._computeOptionsMemory = new ComputeOptionsMemory();
    this._viewLineCount = 1;
    this._lineNumbersDigitCount = 1;
    this._rawOptions = deepCloneAndMigrateOptions(_options);
    this._readOptions = EditorConfiguration2.readOptions(this._rawOptions);
    this._validatedOptions = EditorConfiguration2.validateOptions(this._readOptions);
    this._register(EditorZoom.onDidChangeZoomLevel((_23) => this._recomputeOptions()));
    this._register(TabFocus.onDidChangeTabFocus((_23) => this._recomputeOptions()));
  }
  observeReferenceElement(dimension) {
  }
  dispose() {
    super.dispose();
  }
  _recomputeOptions() {
    const oldOptions = this.options;
    const newOptions = this._computeInternalOptions();
    if (!oldOptions) {
      this.options = newOptions;
    } else {
      const changeEvent = EditorConfiguration2.checkEquals(oldOptions, newOptions);
      if (changeEvent === null) {
        return;
      }
      this.options = newOptions;
      this._onDidChangeFast.fire(changeEvent);
      this._onDidChange.fire(changeEvent);
    }
  }
  getRawOptions() {
    return this._rawOptions;
  }
  _computeInternalOptions() {
    const partialEnv = this._getEnvConfiguration();
    const bareFontInfo = BareFontInfo.createFromValidatedSettings(this._validatedOptions, partialEnv.zoomLevel, this.isSimpleWidget);
    const env2 = {
      memory: this._computeOptionsMemory,
      outerWidth: partialEnv.outerWidth,
      outerHeight: partialEnv.outerHeight,
      fontInfo: this.readConfiguration(bareFontInfo),
      extraEditorClassName: partialEnv.extraEditorClassName,
      isDominatedByLongLines: this._isDominatedByLongLines,
      viewLineCount: this._viewLineCount,
      lineNumbersDigitCount: this._lineNumbersDigitCount,
      emptySelectionClipboard: partialEnv.emptySelectionClipboard,
      pixelRatio: partialEnv.pixelRatio,
      tabFocusMode: TabFocus.getTabFocusMode(),
      accessibilitySupport: partialEnv.accessibilitySupport
    };
    return EditorConfiguration2.computeOptions(this._validatedOptions, env2);
  }
  static _subsetEquals(base, subset) {
    for (const key in subset) {
      if (hasOwnProperty$1.call(subset, key)) {
        const subsetValue = subset[key];
        const baseValue = base[key];
        if (baseValue === subsetValue) {
          continue;
        }
        if (Array.isArray(baseValue) && Array.isArray(subsetValue)) {
          if (!equals(baseValue, subsetValue)) {
            return false;
          }
          continue;
        }
        if (baseValue && typeof baseValue === "object" && subsetValue && typeof subsetValue === "object") {
          if (!this._subsetEquals(baseValue, subsetValue)) {
            return false;
          }
          continue;
        }
        return false;
      }
    }
    return true;
  }
  updateOptions(_newOptions) {
    if (typeof _newOptions === "undefined") {
      return;
    }
    const newOptions = deepCloneAndMigrateOptions(_newOptions);
    if (CommonEditorConfiguration._subsetEquals(this._rawOptions, newOptions)) {
      return;
    }
    this._rawOptions = mixin(this._rawOptions, newOptions || {});
    this._readOptions = EditorConfiguration2.readOptions(this._rawOptions);
    this._validatedOptions = EditorConfiguration2.validateOptions(this._readOptions);
    this._recomputeOptions();
  }
  setIsDominatedByLongLines(isDominatedByLongLines) {
    this._isDominatedByLongLines = isDominatedByLongLines;
    this._recomputeOptions();
  }
  setMaxLineNumber(maxLineNumber) {
    const lineNumbersDigitCount = CommonEditorConfiguration._digitCount(maxLineNumber);
    if (this._lineNumbersDigitCount === lineNumbersDigitCount) {
      return;
    }
    this._lineNumbersDigitCount = lineNumbersDigitCount;
    this._recomputeOptions();
  }
  setViewLineCount(viewLineCount) {
    if (this._viewLineCount === viewLineCount) {
      return;
    }
    this._viewLineCount = viewLineCount;
    this._recomputeOptions();
  }
  static _digitCount(n3) {
    let r3 = 0;
    while (n3) {
      n3 = Math.floor(n3 / 10);
      r3++;
    }
    return r3 ? r3 : 1;
  }
};
var editorConfigurationBaseNode = Object.freeze({
  id: "editor",
  order: 5,
  type: "object",
  title: localize("editorConfigurationTitle", "Editor"),
  scope: 5
});
var configurationRegistry$1 = Registry$1.as(Extensions$1.Configuration);
var editorConfiguration = Object.assign(Object.assign({}, editorConfigurationBaseNode), {properties: {
  "editor.tabSize": {
    type: "number",
    default: EDITOR_MODEL_DEFAULTS.tabSize,
    minimum: 1,
    markdownDescription: localize("tabSize", "The number of spaces a tab is equal to. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.")
  },
  "editor.insertSpaces": {
    type: "boolean",
    default: EDITOR_MODEL_DEFAULTS.insertSpaces,
    markdownDescription: localize("insertSpaces", "Insert spaces when pressing `Tab`. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.")
  },
  "editor.detectIndentation": {
    type: "boolean",
    default: EDITOR_MODEL_DEFAULTS.detectIndentation,
    markdownDescription: localize("detectIndentation", "Controls whether `#editor.tabSize#` and `#editor.insertSpaces#` will be automatically detected when a file is opened based on the file contents.")
  },
  "editor.trimAutoWhitespace": {
    type: "boolean",
    default: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
    description: localize("trimAutoWhitespace", "Remove trailing auto inserted whitespace.")
  },
  "editor.largeFileOptimizations": {
    type: "boolean",
    default: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
    description: localize("largeFileOptimizations", "Special handling for large files to disable certain memory intensive features.")
  },
  "editor.wordBasedSuggestions": {
    type: "boolean",
    default: true,
    description: localize("wordBasedSuggestions", "Controls whether completions should be computed based on words in the document.")
  },
  "editor.semanticHighlighting.enabled": {
    enum: [true, false, "configuredByTheme"],
    enumDescriptions: [
      localize("semanticHighlighting.true", "Semantic highlighting enabled for all color themes."),
      localize("semanticHighlighting.false", "Semantic highlighting disabled for all color themes."),
      localize("semanticHighlighting.configuredByTheme", "Semantic highlighting is configured by the current color theme's `semanticHighlighting` setting.")
    ],
    default: "configuredByTheme",
    description: localize("semanticHighlighting.enabled", "Controls whether the semanticHighlighting is shown for the languages that support it.")
  },
  "editor.stablePeek": {
    type: "boolean",
    default: false,
    markdownDescription: localize("stablePeek", "Keep peek editors open even when double clicking their content or when hitting `Escape`.")
  },
  "editor.maxTokenizationLineLength": {
    type: "integer",
    default: 2e4,
    description: localize("maxTokenizationLineLength", "Lines above this length will not be tokenized for performance reasons")
  },
  "diffEditor.maxComputationTime": {
    type: "number",
    default: 5e3,
    description: localize("maxComputationTime", "Timeout in milliseconds after which diff computation is cancelled. Use 0 for no timeout.")
  },
  "diffEditor.renderSideBySide": {
    type: "boolean",
    default: true,
    description: localize("sideBySide", "Controls whether the diff editor shows the diff side by side or inline.")
  },
  "diffEditor.ignoreTrimWhitespace": {
    type: "boolean",
    default: true,
    description: localize("ignoreTrimWhitespace", "When enabled, the diff editor ignores changes in leading or trailing whitespace.")
  },
  "diffEditor.renderIndicators": {
    type: "boolean",
    default: true,
    description: localize("renderIndicators", "Controls whether the diff editor shows +/- indicators for added/removed changes.")
  },
  "diffEditor.codeLens": {
    type: "boolean",
    default: false,
    description: localize("codeLens", "Controls whether the editor shows CodeLens.")
  }
}});
function isConfigurationPropertySchema(x2) {
  return typeof x2.type !== "undefined" || typeof x2.anyOf !== "undefined";
}
for (const editorOption of editorOptionsRegistry) {
  const schema = editorOption.schema;
  if (typeof schema !== "undefined") {
    if (isConfigurationPropertySchema(schema)) {
      editorConfiguration.properties[`editor.${editorOption.name}`] = schema;
    } else {
      for (let key in schema) {
        if (hasOwnProperty$1.call(schema, key)) {
          editorConfiguration.properties[key] = schema[key];
        }
      }
    }
  }
}
var cachedEditorConfigurationKeys = null;
function getEditorConfigurationKeys() {
  if (cachedEditorConfigurationKeys === null) {
    cachedEditorConfigurationKeys = Object.create(null);
    Object.keys(editorConfiguration.properties).forEach((prop) => {
      cachedEditorConfigurationKeys[prop] = true;
    });
  }
  return cachedEditorConfigurationKeys;
}
function isEditorConfigurationKey(key) {
  const editorConfigurationKeys = getEditorConfigurationKeys();
  return editorConfigurationKeys[`editor.${key}`] || false;
}
function isDiffEditorConfigurationKey(key) {
  const editorConfigurationKeys = getEditorConfigurationKeys();
  return editorConfigurationKeys[`diffEditor.${key}`] || false;
}
configurationRegistry$1.registerConfiguration(editorConfiguration);
var EditOperation = class {
  static insert(position2, text) {
    return {
      range: new Range(position2.lineNumber, position2.column, position2.lineNumber, position2.column),
      text,
      forceMoveMarkers: true
    };
  }
  static delete(range3) {
    return {
      range: range3,
      text: null
    };
  }
  static replace(range3, text) {
    return {
      range: range3,
      text
    };
  }
  static replaceMove(range3, text) {
    return {
      range: range3,
      text,
      forceMoveMarkers: true
    };
  }
};
var IConfigurationService = createDecorator("configurationService");
function toValuesTree(properties, conflictReporter) {
  const root4 = Object.create(null);
  for (let key in properties) {
    addToValueTree(root4, key, properties[key], conflictReporter);
  }
  return root4;
}
function addToValueTree(settingsTreeRoot, key, value, conflictReporter) {
  const segments = key.split(".");
  const last2 = segments.pop();
  let curr = settingsTreeRoot;
  for (let i3 = 0; i3 < segments.length; i3++) {
    let s2 = segments[i3];
    let obj = curr[s2];
    switch (typeof obj) {
      case "undefined":
        obj = curr[s2] = Object.create(null);
        break;
      case "object":
        break;
      default:
        conflictReporter(`Ignoring ${key} as ${segments.slice(0, i3 + 1).join(".")} is ${JSON.stringify(obj)}`);
        return;
    }
    curr = obj;
  }
  if (typeof curr === "object" && curr !== null) {
    try {
      curr[last2] = value;
    } catch (e2) {
      conflictReporter(`Ignoring ${key} as ${segments.join(".")} is ${JSON.stringify(curr)}`);
    }
  } else {
    conflictReporter(`Ignoring ${key} as ${segments.join(".")} is ${JSON.stringify(curr)}`);
  }
}
function removeFromValueTree(valueTree, key) {
  const segments = key.split(".");
  doRemoveFromValueTree(valueTree, segments);
}
function doRemoveFromValueTree(valueTree, segments) {
  const first2 = segments.shift();
  if (segments.length === 0) {
    delete valueTree[first2];
    return;
  }
  if (Object.keys(valueTree).indexOf(first2) !== -1) {
    const value = valueTree[first2];
    if (typeof value === "object" && !Array.isArray(value)) {
      doRemoveFromValueTree(value, segments);
      if (Object.keys(value).length === 0) {
        delete valueTree[first2];
      }
    }
  }
}
function getConfigurationValue(config2, settingPath, defaultValue) {
  function accessSetting(config3, path2) {
    let current = config3;
    for (const component of path2) {
      if (typeof current !== "object" || current === null) {
        return void 0;
      }
      current = current[component];
    }
    return current;
  }
  const path = settingPath.split(".");
  const result = accessSetting(config2, path);
  return typeof result === "undefined" ? defaultValue : result;
}
function getConfigurationKeys() {
  const properties = Registry$1.as(Extensions$1.Configuration).getConfigurationProperties();
  return Object.keys(properties);
}
function getDefaultValues() {
  const valueTreeRoot = Object.create(null);
  const properties = Registry$1.as(Extensions$1.Configuration).getConfigurationProperties();
  for (let key in properties) {
    let value = properties[key].default;
    addToValueTree(valueTreeRoot, key, value, (message) => console.error(`Conflict in default settings: ${message}`));
  }
  return valueTreeRoot;
}
var ConfigurationModel = class {
  constructor(_contents = {}, _keys = [], _overrides = []) {
    this._contents = _contents;
    this._keys = _keys;
    this._overrides = _overrides;
    this.isFrozen = false;
  }
  get contents() {
    return this.checkAndFreeze(this._contents);
  }
  get overrides() {
    return this.checkAndFreeze(this._overrides);
  }
  get keys() {
    return this.checkAndFreeze(this._keys);
  }
  isEmpty() {
    return this._keys.length === 0 && Object.keys(this._contents).length === 0 && this._overrides.length === 0;
  }
  getValue(section) {
    return section ? getConfigurationValue(this.contents, section) : this.contents;
  }
  override(identifier) {
    const overrideContents = this.getContentsForOverrideIdentifer(identifier);
    if (!overrideContents || typeof overrideContents !== "object" || !Object.keys(overrideContents).length) {
      return this;
    }
    let contents = {};
    for (const key of distinct([...Object.keys(this.contents), ...Object.keys(overrideContents)])) {
      let contentsForKey = this.contents[key];
      let overrideContentsForKey = overrideContents[key];
      if (overrideContentsForKey) {
        if (typeof contentsForKey === "object" && typeof overrideContentsForKey === "object") {
          contentsForKey = deepClone(contentsForKey);
          this.mergeContents(contentsForKey, overrideContentsForKey);
        } else {
          contentsForKey = overrideContentsForKey;
        }
      }
      contents[key] = contentsForKey;
    }
    return new ConfigurationModel(contents, this.keys, this.overrides);
  }
  merge(...others) {
    const contents = deepClone(this.contents);
    const overrides = deepClone(this.overrides);
    const keys2 = [...this.keys];
    for (const other of others) {
      this.mergeContents(contents, other.contents);
      for (const otherOverride of other.overrides) {
        const [override] = overrides.filter((o) => equals(o.identifiers, otherOverride.identifiers));
        if (override) {
          this.mergeContents(override.contents, otherOverride.contents);
        } else {
          overrides.push(deepClone(otherOverride));
        }
      }
      for (const key of other.keys) {
        if (keys2.indexOf(key) === -1) {
          keys2.push(key);
        }
      }
    }
    return new ConfigurationModel(contents, keys2, overrides);
  }
  freeze() {
    this.isFrozen = true;
    return this;
  }
  mergeContents(source2, target) {
    for (const key of Object.keys(target)) {
      if (key in source2) {
        if (isObject3(source2[key]) && isObject3(target[key])) {
          this.mergeContents(source2[key], target[key]);
          continue;
        }
      }
      source2[key] = deepClone(target[key]);
    }
  }
  checkAndFreeze(data2) {
    if (this.isFrozen && !Object.isFrozen(data2)) {
      return deepFreeze(data2);
    }
    return data2;
  }
  getContentsForOverrideIdentifer(identifier) {
    for (const override of this.overrides) {
      if (override.identifiers.indexOf(identifier) !== -1) {
        return override.contents;
      }
    }
    return null;
  }
  toJSON() {
    return {
      contents: this.contents,
      overrides: this.overrides,
      keys: this.keys
    };
  }
  setValue(key, value) {
    this.addKey(key);
    addToValueTree(this.contents, key, value, (e2) => {
      throw new Error(e2);
    });
  }
  removeValue(key) {
    if (this.removeKey(key)) {
      removeFromValueTree(this.contents, key);
    }
  }
  addKey(key) {
    let index3 = this.keys.length;
    for (let i3 = 0; i3 < index3; i3++) {
      if (key.indexOf(this.keys[i3]) === 0) {
        index3 = i3;
      }
    }
    this.keys.splice(index3, 1, key);
  }
  removeKey(key) {
    let index3 = this.keys.indexOf(key);
    if (index3 !== -1) {
      this.keys.splice(index3, 1);
      return true;
    }
    return false;
  }
};
var DefaultConfigurationModel = class extends ConfigurationModel {
  constructor() {
    const contents = getDefaultValues();
    const keys2 = getConfigurationKeys();
    const overrides = [];
    for (const key of Object.keys(contents)) {
      if (OVERRIDE_PROPERTY_PATTERN.test(key)) {
        overrides.push({
          identifiers: [overrideIdentifierFromKey(key).trim()],
          keys: Object.keys(contents[key]),
          contents: toValuesTree(contents[key], (message) => console.error(`Conflict in default settings file: ${message}`))
        });
      }
    }
    super(contents, keys2, overrides);
  }
};
var Configuration = class {
  constructor(_defaultConfiguration, _localUserConfiguration, _remoteUserConfiguration = new ConfigurationModel(), _workspaceConfiguration = new ConfigurationModel(), _folderConfigurations = new ResourceMap(), _memoryConfiguration = new ConfigurationModel(), _memoryConfigurationByResource = new ResourceMap(), _freeze = true) {
    this._defaultConfiguration = _defaultConfiguration;
    this._localUserConfiguration = _localUserConfiguration;
    this._remoteUserConfiguration = _remoteUserConfiguration;
    this._workspaceConfiguration = _workspaceConfiguration;
    this._folderConfigurations = _folderConfigurations;
    this._memoryConfiguration = _memoryConfiguration;
    this._memoryConfigurationByResource = _memoryConfigurationByResource;
    this._freeze = _freeze;
    this._workspaceConsolidatedConfiguration = null;
    this._foldersConsolidatedConfigurations = new ResourceMap();
    this._userConfiguration = null;
  }
  getValue(section, overrides, workspace) {
    const consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace);
    return consolidateConfigurationModel.getValue(section);
  }
  updateValue(key, value, overrides = {}) {
    let memoryConfiguration;
    if (overrides.resource) {
      memoryConfiguration = this._memoryConfigurationByResource.get(overrides.resource);
      if (!memoryConfiguration) {
        memoryConfiguration = new ConfigurationModel();
        this._memoryConfigurationByResource.set(overrides.resource, memoryConfiguration);
      }
    } else {
      memoryConfiguration = this._memoryConfiguration;
    }
    if (value === void 0) {
      memoryConfiguration.removeValue(key);
    } else {
      memoryConfiguration.setValue(key, value);
    }
    if (!overrides.resource) {
      this._workspaceConsolidatedConfiguration = null;
    }
  }
  get userConfiguration() {
    if (!this._userConfiguration) {
      this._userConfiguration = this._remoteUserConfiguration.isEmpty() ? this._localUserConfiguration : this._localUserConfiguration.merge(this._remoteUserConfiguration);
      if (this._freeze) {
        this._userConfiguration.freeze();
      }
    }
    return this._userConfiguration;
  }
  getConsolidateConfigurationModel(overrides, workspace) {
    let configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace);
    return overrides.overrideIdentifier ? configurationModel.override(overrides.overrideIdentifier) : configurationModel;
  }
  getConsolidatedConfigurationModelForResource({resource: resource2}, workspace) {
    let consolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
    if (workspace && resource2) {
      const root4 = workspace.getFolder(resource2);
      if (root4) {
        consolidateConfiguration = this.getFolderConsolidatedConfiguration(root4.uri) || consolidateConfiguration;
      }
      const memoryConfigurationForResource = this._memoryConfigurationByResource.get(resource2);
      if (memoryConfigurationForResource) {
        consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource);
      }
    }
    return consolidateConfiguration;
  }
  getWorkspaceConsolidatedConfiguration() {
    if (!this._workspaceConsolidatedConfiguration) {
      this._workspaceConsolidatedConfiguration = this._defaultConfiguration.merge(this.userConfiguration, this._workspaceConfiguration, this._memoryConfiguration);
      if (this._freeze) {
        this._workspaceConfiguration = this._workspaceConfiguration.freeze();
      }
    }
    return this._workspaceConsolidatedConfiguration;
  }
  getFolderConsolidatedConfiguration(folder) {
    let folderConsolidatedConfiguration = this._foldersConsolidatedConfigurations.get(folder);
    if (!folderConsolidatedConfiguration) {
      const workspaceConsolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
      const folderConfiguration = this._folderConfigurations.get(folder);
      if (folderConfiguration) {
        folderConsolidatedConfiguration = workspaceConsolidateConfiguration.merge(folderConfiguration);
        if (this._freeze) {
          folderConsolidatedConfiguration = folderConsolidatedConfiguration.freeze();
        }
        this._foldersConsolidatedConfigurations.set(folder, folderConsolidatedConfiguration);
      } else {
        folderConsolidatedConfiguration = workspaceConsolidateConfiguration;
      }
    }
    return folderConsolidatedConfiguration;
  }
  toData() {
    return {
      defaults: {
        contents: this._defaultConfiguration.contents,
        overrides: this._defaultConfiguration.overrides,
        keys: this._defaultConfiguration.keys
      },
      user: {
        contents: this.userConfiguration.contents,
        overrides: this.userConfiguration.overrides,
        keys: this.userConfiguration.keys
      },
      workspace: {
        contents: this._workspaceConfiguration.contents,
        overrides: this._workspaceConfiguration.overrides,
        keys: this._workspaceConfiguration.keys
      },
      folders: [...this._folderConfigurations.keys()].reduce((result, folder) => {
        const {contents, overrides, keys: keys2} = this._folderConfigurations.get(folder);
        result.push([folder, {contents, overrides, keys: keys2}]);
        return result;
      }, [])
    };
  }
  static parse(data2) {
    const defaultConfiguration = this.parseConfigurationModel(data2.defaults);
    const userConfiguration = this.parseConfigurationModel(data2.user);
    const workspaceConfiguration = this.parseConfigurationModel(data2.workspace);
    const folders = data2.folders.reduce((result, value) => {
      result.set(URI.revive(value[0]), this.parseConfigurationModel(value[1]));
      return result;
    }, new ResourceMap());
    return new Configuration(defaultConfiguration, userConfiguration, new ConfigurationModel(), workspaceConfiguration, folders, new ConfigurationModel(), new ResourceMap(), false);
  }
  static parseConfigurationModel(model) {
    return new ConfigurationModel(model.contents, model.keys, model.overrides).freeze();
  }
};
var ConfigurationChangeEvent = class {
  constructor(change, previous, currentConfiguraiton, currentWorkspace) {
    this.change = change;
    this.previous = previous;
    this.currentConfiguraiton = currentConfiguraiton;
    this.currentWorkspace = currentWorkspace;
    this._previousConfiguration = void 0;
    const keysSet = new Set();
    change.keys.forEach((key) => keysSet.add(key));
    change.overrides.forEach(([, keys2]) => keys2.forEach((key) => keysSet.add(key)));
    this.affectedKeys = [...keysSet.values()];
    const configurationModel = new ConfigurationModel();
    this.affectedKeys.forEach((key) => configurationModel.setValue(key, {}));
    this.affectedKeysTree = configurationModel.contents;
  }
  get previousConfiguration() {
    if (!this._previousConfiguration && this.previous) {
      this._previousConfiguration = Configuration.parse(this.previous.data);
    }
    return this._previousConfiguration;
  }
  affectsConfiguration(section, overrides) {
    var _a;
    if (this.doesAffectedKeysTreeContains(this.affectedKeysTree, section)) {
      if (overrides) {
        const value1 = this.previousConfiguration ? this.previousConfiguration.getValue(section, overrides, (_a = this.previous) === null || _a === void 0 ? void 0 : _a.workspace) : void 0;
        const value2 = this.currentConfiguraiton.getValue(section, overrides, this.currentWorkspace);
        return !equals$1(value1, value2);
      }
      return true;
    }
    return false;
  }
  doesAffectedKeysTreeContains(affectedKeysTree, section) {
    let requestedTree = toValuesTree({[section]: true}, () => {
    });
    let key;
    while (typeof requestedTree === "object" && (key = Object.keys(requestedTree)[0])) {
      affectedKeysTree = affectedKeysTree[key];
      if (!affectedKeysTree) {
        return false;
      }
      requestedTree = requestedTree[key];
    }
    return true;
  }
};
var AbstractKeybindingService = class extends Disposable {
  constructor(_contextKeyService, _commandService, _telemetryService, _notificationService, _logService) {
    super();
    this._contextKeyService = _contextKeyService;
    this._commandService = _commandService;
    this._telemetryService = _telemetryService;
    this._notificationService = _notificationService;
    this._logService = _logService;
    this._onDidUpdateKeybindings = this._register(new Emitter());
    this._currentChord = null;
    this._currentChordChecker = new IntervalTimer();
    this._currentChordStatusMessage = null;
    this._logging = false;
  }
  get onDidUpdateKeybindings() {
    return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : Event.None;
  }
  dispose() {
    super.dispose();
  }
  _log(str) {
    if (this._logging) {
      this._logService.info(`[KeybindingService]: ${str}`);
    }
  }
  getKeybindings() {
    return this._getResolver().getKeybindings();
  }
  lookupKeybindings(commandId) {
    return coalesce(this._getResolver().lookupKeybindings(commandId).map((item) => item.resolvedKeybinding));
  }
  lookupKeybinding(commandId) {
    const result = this._getResolver().lookupPrimaryKeybinding(commandId);
    if (!result) {
      return void 0;
    }
    return result.resolvedKeybinding;
  }
  dispatchEvent(e2, target) {
    return this._dispatch(e2, target);
  }
  softDispatch(e2, target) {
    const keybinding = this.resolveKeyboardEvent(e2);
    if (keybinding.isChord()) {
      console.warn("Unexpected keyboard event mapped to a chord");
      return null;
    }
    const [firstPart] = keybinding.getDispatchParts();
    if (firstPart === null) {
      return null;
    }
    const contextValue = this._contextKeyService.getContext(target);
    const currentChord = this._currentChord ? this._currentChord.keypress : null;
    return this._getResolver().resolve(contextValue, currentChord, firstPart);
  }
  _enterChordMode(firstPart, keypressLabel) {
    this._currentChord = {
      keypress: firstPart,
      label: keypressLabel
    };
    this._currentChordStatusMessage = this._notificationService.status(localize("first.chord", "({0}) was pressed. Waiting for second key of chord...", keypressLabel));
    const chordEnterTime = Date.now();
    this._currentChordChecker.cancelAndSet(() => {
      if (!this._documentHasFocus()) {
        this._leaveChordMode();
        return;
      }
      if (Date.now() - chordEnterTime > 5e3) {
        this._leaveChordMode();
      }
    }, 500);
  }
  _leaveChordMode() {
    if (this._currentChordStatusMessage) {
      this._currentChordStatusMessage.dispose();
      this._currentChordStatusMessage = null;
    }
    this._currentChordChecker.cancel();
    this._currentChord = null;
  }
  _dispatch(e2, target) {
    return this._doDispatch(this.resolveKeyboardEvent(e2), target);
  }
  _doDispatch(keybinding, target) {
    let shouldPreventDefault = false;
    if (keybinding.isChord()) {
      console.warn("Unexpected keyboard event mapped to a chord");
      return false;
    }
    const [firstPart] = keybinding.getDispatchParts();
    if (firstPart === null) {
      this._log(`\\ Keyboard event cannot be dispatched.`);
      return shouldPreventDefault;
    }
    const contextValue = this._contextKeyService.getContext(target);
    const currentChord = this._currentChord ? this._currentChord.keypress : null;
    const keypressLabel = keybinding.getLabel();
    const resolveResult = this._getResolver().resolve(contextValue, currentChord, firstPart);
    this._logService.trace("KeybindingService#dispatch", keypressLabel, resolveResult === null || resolveResult === void 0 ? void 0 : resolveResult.commandId);
    if (resolveResult && resolveResult.enterChord) {
      shouldPreventDefault = true;
      this._enterChordMode(firstPart, keypressLabel);
      return shouldPreventDefault;
    }
    if (this._currentChord) {
      if (!resolveResult || !resolveResult.commandId) {
        this._notificationService.status(localize("missing.chord", "The key combination ({0}, {1}) is not a command.", this._currentChord.label, keypressLabel), {hideAfter: 10 * 1e3});
        shouldPreventDefault = true;
      }
    }
    this._leaveChordMode();
    if (resolveResult && resolveResult.commandId) {
      if (!resolveResult.bubble) {
        shouldPreventDefault = true;
      }
      if (typeof resolveResult.commandArgs === "undefined") {
        this._commandService.executeCommand(resolveResult.commandId).then(void 0, (err) => this._notificationService.warn(err));
      } else {
        this._commandService.executeCommand(resolveResult.commandId, resolveResult.commandArgs).then(void 0, (err) => this._notificationService.warn(err));
      }
      this._telemetryService.publicLog2("workbenchActionExecuted", {id: resolveResult.commandId, from: "keybinding"});
    }
    return shouldPreventDefault;
  }
  mightProducePrintableCharacter(event) {
    if (event.ctrlKey || event.metaKey) {
      return false;
    }
    if (event.keyCode >= 31 && event.keyCode <= 56 || event.keyCode >= 21 && event.keyCode <= 30) {
      return true;
    }
    return false;
  }
};
var KeybindingResolver = class {
  constructor(defaultKeybindings, overrides, log4) {
    this._log = log4;
    this._defaultKeybindings = defaultKeybindings;
    this._defaultBoundCommands = new Map();
    for (let i3 = 0, len2 = defaultKeybindings.length; i3 < len2; i3++) {
      const command = defaultKeybindings[i3].command;
      if (command) {
        this._defaultBoundCommands.set(command, true);
      }
    }
    this._map = new Map();
    this._lookupMap = new Map();
    this._keybindings = KeybindingResolver.combine(defaultKeybindings, overrides);
    for (let i3 = 0, len2 = this._keybindings.length; i3 < len2; i3++) {
      let k2 = this._keybindings[i3];
      if (k2.keypressParts.length === 0) {
        continue;
      }
      if (k2.when && k2.when.type === 0) {
        continue;
      }
      this._addKeyPress(k2.keypressParts[0], k2);
    }
  }
  static _isTargetedForRemoval(defaultKb, keypressFirstPart, keypressChordPart, command, when) {
    if (defaultKb.command !== command) {
      return false;
    }
    if (keypressFirstPart && defaultKb.keypressParts[0] !== keypressFirstPart) {
      return false;
    }
    if (keypressChordPart && defaultKb.keypressParts[1] !== keypressChordPart) {
      return false;
    }
    if (when) {
      if (!defaultKb.when) {
        return false;
      }
      if (!when.equals(defaultKb.when)) {
        return false;
      }
    }
    return true;
  }
  static combine(defaults3, rawOverrides) {
    defaults3 = defaults3.slice(0);
    let overrides = [];
    for (const override of rawOverrides) {
      if (!override.command || override.command.length === 0 || override.command.charAt(0) !== "-") {
        overrides.push(override);
        continue;
      }
      const command = override.command.substr(1);
      const keypressFirstPart = override.keypressParts[0];
      const keypressChordPart = override.keypressParts[1];
      const when = override.when;
      for (let j = defaults3.length - 1; j >= 0; j--) {
        if (this._isTargetedForRemoval(defaults3[j], keypressFirstPart, keypressChordPart, command, when)) {
          defaults3.splice(j, 1);
        }
      }
    }
    return defaults3.concat(overrides);
  }
  _addKeyPress(keypress, item) {
    const conflicts = this._map.get(keypress);
    if (typeof conflicts === "undefined") {
      this._map.set(keypress, [item]);
      this._addToLookupMap(item);
      return;
    }
    for (let i3 = conflicts.length - 1; i3 >= 0; i3--) {
      let conflict = conflicts[i3];
      if (conflict.command === item.command) {
        continue;
      }
      const conflictIsChord = conflict.keypressParts.length > 1;
      const itemIsChord = item.keypressParts.length > 1;
      if (conflictIsChord && itemIsChord && conflict.keypressParts[1] !== item.keypressParts[1]) {
        continue;
      }
      if (KeybindingResolver.whenIsEntirelyIncluded(conflict.when, item.when)) {
        this._removeFromLookupMap(conflict);
      }
    }
    conflicts.push(item);
    this._addToLookupMap(item);
  }
  _addToLookupMap(item) {
    if (!item.command) {
      return;
    }
    let arr = this._lookupMap.get(item.command);
    if (typeof arr === "undefined") {
      arr = [item];
      this._lookupMap.set(item.command, arr);
    } else {
      arr.push(item);
    }
  }
  _removeFromLookupMap(item) {
    if (!item.command) {
      return;
    }
    let arr = this._lookupMap.get(item.command);
    if (typeof arr === "undefined") {
      return;
    }
    for (let i3 = 0, len2 = arr.length; i3 < len2; i3++) {
      if (arr[i3] === item) {
        arr.splice(i3, 1);
        return;
      }
    }
  }
  static whenIsEntirelyIncluded(a2, b2) {
    if (!b2) {
      return true;
    }
    if (!a2) {
      return false;
    }
    return this._implies(a2, b2);
  }
  static _implies(p2, q2) {
    const notP = p2.negate();
    const terminals = (node) => {
      if (node.type === 9) {
        return node.expr;
      }
      return [node];
    };
    let expr = terminals(notP).concat(terminals(q2));
    for (let i3 = 0; i3 < expr.length; i3++) {
      const a2 = expr[i3];
      const notA = a2.negate();
      for (let j = i3 + 1; j < expr.length; j++) {
        const b2 = expr[j];
        if (notA.equals(b2)) {
          return true;
        }
      }
    }
    return false;
  }
  getKeybindings() {
    return this._keybindings;
  }
  lookupKeybindings(commandId) {
    let items = this._lookupMap.get(commandId);
    if (typeof items === "undefined" || items.length === 0) {
      return [];
    }
    let result = [], resultLen = 0;
    for (let i3 = items.length - 1; i3 >= 0; i3--) {
      result[resultLen++] = items[i3];
    }
    return result;
  }
  lookupPrimaryKeybinding(commandId) {
    let items = this._lookupMap.get(commandId);
    if (typeof items === "undefined" || items.length === 0) {
      return null;
    }
    return items[items.length - 1];
  }
  resolve(context2, currentChord, keypress) {
    this._log(`| Resolving ${keypress}${currentChord ? ` chorded from ${currentChord}` : ``}`);
    let lookupMap = null;
    if (currentChord !== null) {
      const candidates = this._map.get(currentChord);
      if (typeof candidates === "undefined") {
        this._log(`\\ No keybinding entries.`);
        return null;
      }
      lookupMap = [];
      for (let i3 = 0, len2 = candidates.length; i3 < len2; i3++) {
        let candidate = candidates[i3];
        if (candidate.keypressParts[1] === keypress) {
          lookupMap.push(candidate);
        }
      }
    } else {
      const candidates = this._map.get(keypress);
      if (typeof candidates === "undefined") {
        this._log(`\\ No keybinding entries.`);
        return null;
      }
      lookupMap = candidates;
    }
    let result = this._findCommand(context2, lookupMap);
    if (!result) {
      this._log(`\\ From ${lookupMap.length} keybinding entries, no when clauses matched the context.`);
      return null;
    }
    if (currentChord === null && result.keypressParts.length > 1 && result.keypressParts[1] !== null) {
      this._log(`\\ From ${lookupMap.length} keybinding entries, matched chord, when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
      return {
        enterChord: true,
        leaveChord: false,
        commandId: null,
        commandArgs: null,
        bubble: false
      };
    }
    this._log(`\\ From ${lookupMap.length} keybinding entries, matched ${result.command}, when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
    return {
      enterChord: false,
      leaveChord: result.keypressParts.length > 1,
      commandId: result.command,
      commandArgs: result.commandArgs,
      bubble: result.bubble
    };
  }
  _findCommand(context2, matches2) {
    for (let i3 = matches2.length - 1; i3 >= 0; i3--) {
      let k2 = matches2[i3];
      if (!KeybindingResolver.contextMatchesRules(context2, k2.when)) {
        continue;
      }
      return k2;
    }
    return null;
  }
  static contextMatchesRules(context2, rules) {
    if (!rules) {
      return true;
    }
    return rules.evaluate(context2);
  }
};
function printWhenExplanation(when) {
  if (!when) {
    return `no when condition`;
  }
  return `${when.serialize()}`;
}
function printSourceExplanation(kb2) {
  if (kb2.isDefault) {
    if (kb2.extensionId) {
      return `built-in extension ${kb2.extensionId}`;
    }
    return `built-in`;
  }
  if (kb2.extensionId) {
    return `user extension ${kb2.extensionId}`;
  }
  return `user`;
}
var KeybindingsRegistryImpl = class {
  constructor() {
    this._coreKeybindings = [];
    this._extensionKeybindings = [];
    this._cachedMergedKeybindings = null;
  }
  static bindToCurrentPlatform(kb2) {
    if (OS === 1) {
      if (kb2 && kb2.win) {
        return kb2.win;
      }
    } else if (OS === 2) {
      if (kb2 && kb2.mac) {
        return kb2.mac;
      }
    } else {
      if (kb2 && kb2.linux) {
        return kb2.linux;
      }
    }
    return kb2;
  }
  registerKeybindingRule(rule) {
    const actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule);
    if (actualKb && actualKb.primary) {
      const kk2 = createKeybinding(actualKb.primary, OS);
      if (kk2) {
        this._registerDefaultKeybinding(kk2, rule.id, rule.args, rule.weight, 0, rule.when);
      }
    }
    if (actualKb && Array.isArray(actualKb.secondary)) {
      for (let i3 = 0, len2 = actualKb.secondary.length; i3 < len2; i3++) {
        const k2 = actualKb.secondary[i3];
        const kk2 = createKeybinding(k2, OS);
        if (kk2) {
          this._registerDefaultKeybinding(kk2, rule.id, rule.args, rule.weight, -i3 - 1, rule.when);
        }
      }
    }
  }
  registerCommandAndKeybindingRule(desc) {
    this.registerKeybindingRule(desc);
    CommandsRegistry.registerCommand(desc);
  }
  static _mightProduceChar(keyCode) {
    if (keyCode >= 21 && keyCode <= 30) {
      return true;
    }
    if (keyCode >= 31 && keyCode <= 56) {
      return true;
    }
    return keyCode === 80 || keyCode === 81 || keyCode === 82 || keyCode === 83 || keyCode === 84 || keyCode === 85 || keyCode === 86 || keyCode === 110 || keyCode === 111 || keyCode === 87 || keyCode === 88 || keyCode === 89 || keyCode === 90 || keyCode === 91 || keyCode === 92;
  }
  _assertNoCtrlAlt(keybinding, commandId) {
    if (keybinding.ctrlKey && keybinding.altKey && !keybinding.metaKey) {
      if (KeybindingsRegistryImpl._mightProduceChar(keybinding.keyCode)) {
        console.warn("Ctrl+Alt+ keybindings should not be used by default under Windows. Offender: ", keybinding, " for ", commandId);
      }
    }
  }
  _registerDefaultKeybinding(keybinding, commandId, commandArgs, weight1, weight2, when) {
    if (OS === 1) {
      this._assertNoCtrlAlt(keybinding.parts[0], commandId);
    }
    this._coreKeybindings.push({
      keybinding,
      command: commandId,
      commandArgs,
      when,
      weight1,
      weight2,
      extensionId: null
    });
    this._cachedMergedKeybindings = null;
  }
  getDefaultKeybindings() {
    if (!this._cachedMergedKeybindings) {
      this._cachedMergedKeybindings = [].concat(this._coreKeybindings).concat(this._extensionKeybindings);
      this._cachedMergedKeybindings.sort(sorter);
    }
    return this._cachedMergedKeybindings.slice(0);
  }
};
var KeybindingsRegistry = new KeybindingsRegistryImpl();
var Extensions$2 = {
  EditorModes: "platform.keybindingsRegistry"
};
Registry$1.add(Extensions$2.EditorModes, KeybindingsRegistry);
function sorter(a2, b2) {
  if (a2.weight1 !== b2.weight1) {
    return a2.weight1 - b2.weight1;
  }
  if (a2.command < b2.command) {
    return -1;
  }
  if (a2.command > b2.command) {
    return 1;
  }
  return a2.weight2 - b2.weight2;
}
var ResolvedKeybindingItem = class {
  constructor(resolvedKeybinding, command, commandArgs, when, isDefault, extensionId) {
    this.resolvedKeybinding = resolvedKeybinding;
    this.keypressParts = resolvedKeybinding ? removeElementsAfterNulls(resolvedKeybinding.getDispatchParts()) : [];
    this.bubble = command ? command.charCodeAt(0) === 94 : false;
    this.command = this.bubble ? command.substr(1) : command;
    this.commandArgs = commandArgs;
    this.when = when;
    this.isDefault = isDefault;
    this.extensionId = extensionId;
  }
};
function removeElementsAfterNulls(arr) {
  let result = [];
  for (let i3 = 0, len2 = arr.length; i3 < len2; i3++) {
    const element = arr[i3];
    if (!element) {
      return result;
    }
    result.push(element);
  }
  return result;
}
var ModifierLabelProvider = class {
  constructor(mac, windows, linux = windows) {
    this.modifierLabels = [null];
    this.modifierLabels[2] = mac;
    this.modifierLabels[1] = windows;
    this.modifierLabels[3] = linux;
  }
  toLabel(OS2, parts, keyLabelProvider) {
    if (parts.length === 0) {
      return null;
    }
    const result = [];
    for (let i3 = 0, len2 = parts.length; i3 < len2; i3++) {
      const part = parts[i3];
      const keyLabel = keyLabelProvider(part);
      if (keyLabel === null) {
        return null;
      }
      result[i3] = _simpleAsString(part, keyLabel, this.modifierLabels[OS2]);
    }
    return result.join(" ");
  }
};
var UILabelProvider = new ModifierLabelProvider({
  ctrlKey: "⌃",
  shiftKey: "⇧",
  altKey: "⌥",
  metaKey: "⌘",
  separator: ""
}, {
  ctrlKey: localize({key: "ctrlKey", comment: ["This is the short form for the Control key on the keyboard"]}, "Ctrl"),
  shiftKey: localize({key: "shiftKey", comment: ["This is the short form for the Shift key on the keyboard"]}, "Shift"),
  altKey: localize({key: "altKey", comment: ["This is the short form for the Alt key on the keyboard"]}, "Alt"),
  metaKey: localize({key: "windowsKey", comment: ["This is the short form for the Windows key on the keyboard"]}, "Windows"),
  separator: "+"
}, {
  ctrlKey: localize({key: "ctrlKey", comment: ["This is the short form for the Control key on the keyboard"]}, "Ctrl"),
  shiftKey: localize({key: "shiftKey", comment: ["This is the short form for the Shift key on the keyboard"]}, "Shift"),
  altKey: localize({key: "altKey", comment: ["This is the short form for the Alt key on the keyboard"]}, "Alt"),
  metaKey: localize({key: "superKey", comment: ["This is the short form for the Super key on the keyboard"]}, "Super"),
  separator: "+"
});
var AriaLabelProvider = new ModifierLabelProvider({
  ctrlKey: localize({key: "ctrlKey.long", comment: ["This is the long form for the Control key on the keyboard"]}, "Control"),
  shiftKey: localize({key: "shiftKey.long", comment: ["This is the long form for the Shift key on the keyboard"]}, "Shift"),
  altKey: localize({key: "altKey.long", comment: ["This is the long form for the Alt key on the keyboard"]}, "Alt"),
  metaKey: localize({key: "cmdKey.long", comment: ["This is the long form for the Command key on the keyboard"]}, "Command"),
  separator: "+"
}, {
  ctrlKey: localize({key: "ctrlKey.long", comment: ["This is the long form for the Control key on the keyboard"]}, "Control"),
  shiftKey: localize({key: "shiftKey.long", comment: ["This is the long form for the Shift key on the keyboard"]}, "Shift"),
  altKey: localize({key: "altKey.long", comment: ["This is the long form for the Alt key on the keyboard"]}, "Alt"),
  metaKey: localize({key: "windowsKey.long", comment: ["This is the long form for the Windows key on the keyboard"]}, "Windows"),
  separator: "+"
}, {
  ctrlKey: localize({key: "ctrlKey.long", comment: ["This is the long form for the Control key on the keyboard"]}, "Control"),
  shiftKey: localize({key: "shiftKey.long", comment: ["This is the long form for the Shift key on the keyboard"]}, "Shift"),
  altKey: localize({key: "altKey.long", comment: ["This is the long form for the Alt key on the keyboard"]}, "Alt"),
  metaKey: localize({key: "superKey.long", comment: ["This is the long form for the Super key on the keyboard"]}, "Super"),
  separator: "+"
});
function _simpleAsString(modifiers, key, labels) {
  if (key === null) {
    return "";
  }
  const result = [];
  if (modifiers.ctrlKey) {
    result.push(labels.ctrlKey);
  }
  if (modifiers.shiftKey) {
    result.push(labels.shiftKey);
  }
  if (modifiers.altKey) {
    result.push(labels.altKey);
  }
  if (modifiers.metaKey) {
    result.push(labels.metaKey);
  }
  if (key !== "") {
    result.push(key);
  }
  return result.join(labels.separator);
}
var BaseResolvedKeybinding = class extends ResolvedKeybinding {
  constructor(os, parts) {
    super();
    if (parts.length === 0) {
      throw illegalArgument(`parts`);
    }
    this._os = os;
    this._parts = parts;
  }
  getLabel() {
    return UILabelProvider.toLabel(this._os, this._parts, (keybinding) => this._getLabel(keybinding));
  }
  getAriaLabel() {
    return AriaLabelProvider.toLabel(this._os, this._parts, (keybinding) => this._getAriaLabel(keybinding));
  }
  isChord() {
    return this._parts.length > 1;
  }
  getParts() {
    return this._parts.map((keybinding) => this._getPart(keybinding));
  }
  _getPart(keybinding) {
    return new ResolvedKeybindingPart(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, this._getLabel(keybinding), this._getAriaLabel(keybinding));
  }
  getDispatchParts() {
    return this._parts.map((keybinding) => this._getDispatchPart(keybinding));
  }
};
var USLayoutResolvedKeybinding = class extends BaseResolvedKeybinding {
  constructor(actual, os) {
    super(os, actual.parts);
  }
  _keyCodeToUILabel(keyCode) {
    if (this._os === 2) {
      switch (keyCode) {
        case 15:
          return "←";
        case 16:
          return "↑";
        case 17:
          return "→";
        case 18:
          return "↓";
      }
    }
    return KeyCodeUtils.toString(keyCode);
  }
  _getLabel(keybinding) {
    if (keybinding.isDuplicateModifierCase()) {
      return "";
    }
    return this._keyCodeToUILabel(keybinding.keyCode);
  }
  _getAriaLabel(keybinding) {
    if (keybinding.isDuplicateModifierCase()) {
      return "";
    }
    return KeyCodeUtils.toString(keybinding.keyCode);
  }
  _getDispatchPart(keybinding) {
    return USLayoutResolvedKeybinding.getDispatchStr(keybinding);
  }
  static getDispatchStr(keybinding) {
    if (keybinding.isModifierKey()) {
      return null;
    }
    let result = "";
    if (keybinding.ctrlKey) {
      result += "ctrl+";
    }
    if (keybinding.shiftKey) {
      result += "shift+";
    }
    if (keybinding.altKey) {
      result += "alt+";
    }
    if (keybinding.metaKey) {
      result += "meta+";
    }
    result += KeyCodeUtils.toString(keybinding.keyCode);
    return result;
  }
};
var INotificationService = createDecorator("notificationService");
var NoOpNotification = class {
};
var IWorkspaceContextService = createDecorator("contextService");
var IWorkspace;
(function(IWorkspace2) {
  function isIWorkspace(thing) {
    return !!(thing && typeof thing === "object" && typeof thing.id === "string" && Array.isArray(thing.folders));
  }
  IWorkspace2.isIWorkspace = isIWorkspace;
})(IWorkspace || (IWorkspace = {}));
var IWorkspaceFolder;
(function(IWorkspaceFolder2) {
  function isIWorkspaceFolder(thing) {
    return !!(thing && typeof thing === "object" && URI.isUri(thing.uri) && typeof thing.name === "string" && typeof thing.toResource === "function");
  }
  IWorkspaceFolder2.isIWorkspaceFolder = isIWorkspaceFolder;
})(IWorkspaceFolder || (IWorkspaceFolder = {}));
var WorkspaceFolder = class {
  constructor(data2, raw) {
    this.raw = raw;
    this.uri = data2.uri;
    this.index = data2.index;
    this.name = data2.name;
  }
  toResource(relativePath2) {
    return joinPath(this.uri, relativePath2);
  }
  toJSON() {
    return {uri: this.uri, name: this.name, index: this.index};
  }
};
var AccessibilityHelpNLS;
(function(AccessibilityHelpNLS2) {
  AccessibilityHelpNLS2.noSelection = localize("noSelection", "No selection");
  AccessibilityHelpNLS2.singleSelectionRange = localize("singleSelectionRange", "Line {0}, Column {1} ({2} selected)");
  AccessibilityHelpNLS2.singleSelection = localize("singleSelection", "Line {0}, Column {1}");
  AccessibilityHelpNLS2.multiSelectionRange = localize("multiSelectionRange", "{0} selections ({1} characters selected)");
  AccessibilityHelpNLS2.multiSelection = localize("multiSelection", "{0} selections");
  AccessibilityHelpNLS2.emergencyConfOn = localize("emergencyConfOn", "Now changing the setting `accessibilitySupport` to 'on'.");
  AccessibilityHelpNLS2.openingDocs = localize("openingDocs", "Now opening the Editor Accessibility documentation page.");
  AccessibilityHelpNLS2.readonlyDiffEditor = localize("readonlyDiffEditor", " in a read-only pane of a diff editor.");
  AccessibilityHelpNLS2.editableDiffEditor = localize("editableDiffEditor", " in a pane of a diff editor.");
  AccessibilityHelpNLS2.readonlyEditor = localize("readonlyEditor", " in a read-only code editor");
  AccessibilityHelpNLS2.editableEditor = localize("editableEditor", " in a code editor");
  AccessibilityHelpNLS2.changeConfigToOnMac = localize("changeConfigToOnMac", "To configure the editor to be optimized for usage with a Screen Reader press Command+E now.");
  AccessibilityHelpNLS2.changeConfigToOnWinLinux = localize("changeConfigToOnWinLinux", "To configure the editor to be optimized for usage with a Screen Reader press Control+E now.");
  AccessibilityHelpNLS2.auto_on = localize("auto_on", "The editor is configured to be optimized for usage with a Screen Reader.");
  AccessibilityHelpNLS2.auto_off = localize("auto_off", "The editor is configured to never be optimized for usage with a Screen Reader, which is not the case at this time.");
  AccessibilityHelpNLS2.tabFocusModeOnMsg = localize("tabFocusModeOnMsg", "Pressing Tab in the current editor will move focus to the next focusable element. Toggle this behavior by pressing {0}.");
  AccessibilityHelpNLS2.tabFocusModeOnMsgNoKb = localize("tabFocusModeOnMsgNoKb", "Pressing Tab in the current editor will move focus to the next focusable element. The command {0} is currently not triggerable by a keybinding.");
  AccessibilityHelpNLS2.tabFocusModeOffMsg = localize("tabFocusModeOffMsg", "Pressing Tab in the current editor will insert the tab character. Toggle this behavior by pressing {0}.");
  AccessibilityHelpNLS2.tabFocusModeOffMsgNoKb = localize("tabFocusModeOffMsgNoKb", "Pressing Tab in the current editor will insert the tab character. The command {0} is currently not triggerable by a keybinding.");
  AccessibilityHelpNLS2.openDocMac = localize("openDocMac", "Press Command+H now to open a browser window with more information related to editor accessibility.");
  AccessibilityHelpNLS2.openDocWinLinux = localize("openDocWinLinux", "Press Control+H now to open a browser window with more information related to editor accessibility.");
  AccessibilityHelpNLS2.outroMsg = localize("outroMsg", "You can dismiss this tooltip and return to the editor by pressing Escape or Shift+Escape.");
  AccessibilityHelpNLS2.showAccessibilityHelpAction = localize("showAccessibilityHelpAction", "Show Accessibility Help");
})(AccessibilityHelpNLS || (AccessibilityHelpNLS = {}));
var InspectTokensNLS;
(function(InspectTokensNLS2) {
  InspectTokensNLS2.inspectTokensAction = localize("inspectTokens", "Developer: Inspect Tokens");
})(InspectTokensNLS || (InspectTokensNLS = {}));
var GoToLineNLS;
(function(GoToLineNLS2) {
  GoToLineNLS2.gotoLineActionLabel = localize("gotoLineActionLabel", "Go to Line/Column...");
})(GoToLineNLS || (GoToLineNLS = {}));
var QuickHelpNLS;
(function(QuickHelpNLS2) {
  QuickHelpNLS2.helpQuickAccessActionLabel = localize("helpQuickAccess", "Show all Quick Access Providers");
})(QuickHelpNLS || (QuickHelpNLS = {}));
var QuickCommandNLS;
(function(QuickCommandNLS2) {
  QuickCommandNLS2.quickCommandActionLabel = localize("quickCommandActionLabel", "Command Palette");
  QuickCommandNLS2.quickCommandHelp = localize("quickCommandActionHelp", "Show And Run Commands");
})(QuickCommandNLS || (QuickCommandNLS = {}));
var QuickOutlineNLS;
(function(QuickOutlineNLS2) {
  QuickOutlineNLS2.quickOutlineActionLabel = localize("quickOutlineActionLabel", "Go to Symbol...");
  QuickOutlineNLS2.quickOutlineByCategoryActionLabel = localize("quickOutlineByCategoryActionLabel", "Go to Symbol by Category...");
})(QuickOutlineNLS || (QuickOutlineNLS = {}));
var StandaloneCodeEditorNLS;
(function(StandaloneCodeEditorNLS2) {
  StandaloneCodeEditorNLS2.editorViewAccessibleLabel = localize("editorViewAccessibleLabel", "Editor content");
  StandaloneCodeEditorNLS2.accessibilityHelpMessage = localize("accessibilityHelpMessage", "Press Alt+F1 for Accessibility Options.");
})(StandaloneCodeEditorNLS || (StandaloneCodeEditorNLS = {}));
var ToggleHighContrastNLS;
(function(ToggleHighContrastNLS2) {
  ToggleHighContrastNLS2.toggleHighContrast = localize("toggleHighContrast", "Toggle High Contrast Theme");
})(ToggleHighContrastNLS || (ToggleHighContrastNLS = {}));
var SimpleServicesNLS;
(function(SimpleServicesNLS2) {
  SimpleServicesNLS2.bulkEditServiceSummary = localize("bulkEditServiceSummary", "Made {0} edits in {1} files");
})(SimpleServicesNLS || (SimpleServicesNLS = {}));
var __decorate$2 = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$2 = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$4 = function(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var SimpleModel = class {
  constructor(model) {
    this.disposed = false;
    this.model = model;
    this._onDispose = new Emitter();
  }
  get textEditorModel() {
    return this.model;
  }
  dispose() {
    this.disposed = true;
    this._onDispose.fire();
  }
};
function withTypedEditor(widget, codeEditorCallback, diffEditorCallback) {
  if (isCodeEditor(widget)) {
    return codeEditorCallback(widget);
  } else {
    return diffEditorCallback(widget);
  }
}
var SimpleEditorModelResolverService = class SimpleEditorModelResolverService2 {
  constructor(modelService) {
    this.modelService = modelService;
  }
  setEditor(editor2) {
    this.editor = editor2;
  }
  createModelReference(resource2) {
    let model = null;
    if (this.editor) {
      model = withTypedEditor(this.editor, (editor2) => this.findModel(editor2, resource2), (diffEditor) => this.findModel(diffEditor.getOriginalEditor(), resource2) || this.findModel(diffEditor.getModifiedEditor(), resource2));
    }
    if (!model) {
      return Promise.reject(new Error(`Model not found`));
    }
    return Promise.resolve(new ImmortalReference(new SimpleModel(model)));
  }
  findModel(editor2, resource2) {
    let model = this.modelService.getModel(resource2);
    if (model && model.uri.toString() !== resource2.toString()) {
      return null;
    }
    return model;
  }
};
SimpleEditorModelResolverService = __decorate$2([
  __param$2(0, IModelService)
], SimpleEditorModelResolverService);
var SimpleEditorProgressService = class {
  show() {
    return SimpleEditorProgressService.NULL_PROGRESS_RUNNER;
  }
  showWhile(promise, delay3) {
    return Promise.resolve(void 0);
  }
};
SimpleEditorProgressService.NULL_PROGRESS_RUNNER = {
  done: () => {
  },
  total: () => {
  },
  worked: () => {
  }
};
var SimpleDialogService = class {
  confirm(confirmation) {
    return this.doConfirm(confirmation).then((confirmed) => {
      return {
        confirmed,
        checkboxChecked: false
      };
    });
  }
  doConfirm(confirmation) {
    let messageText = confirmation.message;
    if (confirmation.detail) {
      messageText = messageText + "\n\n" + confirmation.detail;
    }
    return Promise.resolve(window.confirm(messageText));
  }
  show(severity, message, buttons, options) {
    return Promise.resolve({choice: 0});
  }
};
var SimpleNotificationService = class {
  info(message) {
    return this.notify({severity: Severity$1.Info, message});
  }
  warn(message) {
    return this.notify({severity: Severity$1.Warning, message});
  }
  error(error2) {
    return this.notify({severity: Severity$1.Error, message: error2});
  }
  notify(notification) {
    switch (notification.severity) {
      case Severity$1.Error:
        console.error(notification.message);
        break;
      case Severity$1.Warning:
        console.warn(notification.message);
        break;
      default:
        console.log(notification.message);
        break;
    }
    return SimpleNotificationService.NO_OP;
  }
  status(message, options) {
    return Disposable.None;
  }
};
SimpleNotificationService.NO_OP = new NoOpNotification();
var StandaloneCommandService = class {
  constructor(instantiationService) {
    this._onWillExecuteCommand = new Emitter();
    this._onDidExecuteCommand = new Emitter();
    this._instantiationService = instantiationService;
  }
  executeCommand(id3, ...args) {
    const command = CommandsRegistry.getCommand(id3);
    if (!command) {
      return Promise.reject(new Error(`command '${id3}' not found`));
    }
    try {
      this._onWillExecuteCommand.fire({commandId: id3, args});
      const result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler, ...args]);
      this._onDidExecuteCommand.fire({commandId: id3, args});
      return Promise.resolve(result);
    } catch (err) {
      return Promise.reject(err);
    }
  }
};
var StandaloneKeybindingService = class extends AbstractKeybindingService {
  constructor(contextKeyService, commandService, telemetryService, notificationService, logService, domNode) {
    super(contextKeyService, commandService, telemetryService, notificationService, logService);
    this._cachedResolver = null;
    this._dynamicKeybindings = [];
    this._register(addDisposableListener(domNode, EventType.KEY_DOWN, (e2) => {
      let keyEvent = new StandardKeyboardEvent(e2);
      let shouldPreventDefault = this._dispatch(keyEvent, keyEvent.target);
      if (shouldPreventDefault) {
        keyEvent.preventDefault();
        keyEvent.stopPropagation();
      }
    }));
  }
  addDynamicKeybinding(commandId, _keybinding, handler, when) {
    const keybinding = createKeybinding(_keybinding, OS);
    const toDispose = new DisposableStore();
    if (keybinding) {
      this._dynamicKeybindings.push({
        keybinding,
        command: commandId,
        when,
        weight1: 1e3,
        weight2: 0,
        extensionId: null
      });
      toDispose.add(toDisposable(() => {
        for (let i3 = 0; i3 < this._dynamicKeybindings.length; i3++) {
          let kb2 = this._dynamicKeybindings[i3];
          if (kb2.command === commandId) {
            this._dynamicKeybindings.splice(i3, 1);
            this.updateResolver({source: 1});
            return;
          }
        }
      }));
    }
    toDispose.add(CommandsRegistry.registerCommand(commandId, handler));
    this.updateResolver({source: 1});
    return toDispose;
  }
  updateResolver(event) {
    this._cachedResolver = null;
    this._onDidUpdateKeybindings.fire(event);
  }
  _getResolver() {
    if (!this._cachedResolver) {
      const defaults3 = this._toNormalizedKeybindingItems(KeybindingsRegistry.getDefaultKeybindings(), true);
      const overrides = this._toNormalizedKeybindingItems(this._dynamicKeybindings, false);
      this._cachedResolver = new KeybindingResolver(defaults3, overrides, (str) => this._log(str));
    }
    return this._cachedResolver;
  }
  _documentHasFocus() {
    return document.hasFocus();
  }
  _toNormalizedKeybindingItems(items, isDefault) {
    let result = [], resultLen = 0;
    for (const item of items) {
      const when = item.when || void 0;
      const keybinding = item.keybinding;
      if (!keybinding) {
        result[resultLen++] = new ResolvedKeybindingItem(void 0, item.command, item.commandArgs, when, isDefault, null);
      } else {
        const resolvedKeybindings = this.resolveKeybinding(keybinding);
        for (const resolvedKeybinding of resolvedKeybindings) {
          result[resultLen++] = new ResolvedKeybindingItem(resolvedKeybinding, item.command, item.commandArgs, when, isDefault, null);
        }
      }
    }
    return result;
  }
  resolveKeybinding(keybinding) {
    return [new USLayoutResolvedKeybinding(keybinding, OS)];
  }
  resolveKeyboardEvent(keyboardEvent) {
    let keybinding = new SimpleKeybinding(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, keyboardEvent.keyCode).toChord();
    return new USLayoutResolvedKeybinding(keybinding, OS);
  }
};
function isConfigurationOverrides(thing) {
  return thing && typeof thing === "object" && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === "string") && (!thing.resource || thing.resource instanceof URI);
}
var SimpleConfigurationService = class {
  constructor() {
    this._onDidChangeConfiguration = new Emitter();
    this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
    this._configuration = new Configuration(new DefaultConfigurationModel(), new ConfigurationModel());
  }
  getValue(arg1, arg2) {
    const section = typeof arg1 === "string" ? arg1 : void 0;
    const overrides = isConfigurationOverrides(arg1) ? arg1 : isConfigurationOverrides(arg2) ? arg2 : {};
    return this._configuration.getValue(section, overrides, void 0);
  }
  updateValues(values2) {
    const previous = {data: this._configuration.toData()};
    let changedKeys = [];
    for (const entry of values2) {
      const [key, value] = entry;
      if (this.getValue(key) === value) {
        continue;
      }
      this._configuration.updateValue(key, value);
      changedKeys.push(key);
    }
    if (changedKeys.length > 0) {
      const configurationChangeEvent = new ConfigurationChangeEvent({keys: changedKeys, overrides: []}, previous, this._configuration);
      configurationChangeEvent.source = 7;
      configurationChangeEvent.sourceConfig = null;
      this._onDidChangeConfiguration.fire(configurationChangeEvent);
    }
    return Promise.resolve();
  }
};
var SimpleResourceConfigurationService = class {
  constructor(configurationService) {
    this.configurationService = configurationService;
    this._onDidChangeConfiguration = new Emitter();
    this.configurationService.onDidChangeConfiguration((e2) => {
      this._onDidChangeConfiguration.fire({affectedKeys: e2.affectedKeys, affectsConfiguration: (resource2, configuration) => e2.affectsConfiguration(configuration)});
    });
  }
  getValue(resource2, arg2, arg3) {
    const position2 = Position.isIPosition(arg2) ? arg2 : null;
    const section = position2 ? typeof arg3 === "string" ? arg3 : void 0 : typeof arg2 === "string" ? arg2 : void 0;
    if (typeof section === "undefined") {
      return this.configurationService.getValue();
    }
    return this.configurationService.getValue(section);
  }
};
var SimpleResourcePropertiesService = class SimpleResourcePropertiesService2 {
  constructor(configurationService) {
    this.configurationService = configurationService;
  }
  getEOL(resource2, language) {
    const eol = this.configurationService.getValue("files.eol", {overrideIdentifier: language, resource: resource2});
    if (eol && eol !== "auto") {
      return eol;
    }
    return isLinux || isMacintosh ? "\n" : "\r\n";
  }
};
SimpleResourcePropertiesService = __decorate$2([
  __param$2(0, IConfigurationService)
], SimpleResourcePropertiesService);
var StandaloneTelemetryService = class {
  publicLog(eventName, data2) {
    return Promise.resolve(void 0);
  }
  publicLog2(eventName, data2) {
    return this.publicLog(eventName, data2);
  }
};
var SimpleWorkspaceContextService = class {
  constructor() {
    const resource2 = URI.from({scheme: SimpleWorkspaceContextService.SCHEME, authority: "model", path: "/"});
    this.workspace = {id: "4064f6ec-cb38-4ad0-af64-ee6467e63c82", folders: [new WorkspaceFolder({uri: resource2, name: "", index: 0})]};
  }
  getWorkspace() {
    return this.workspace;
  }
  getWorkspaceFolder(resource2) {
    return resource2 && resource2.scheme === SimpleWorkspaceContextService.SCHEME ? this.workspace.folders[0] : null;
  }
};
SimpleWorkspaceContextService.SCHEME = "inmemory";
function applyConfigurationValues(configurationService, source2, isDiffEditor) {
  if (!source2) {
    return;
  }
  if (!(configurationService instanceof SimpleConfigurationService)) {
    return;
  }
  let toUpdate = [];
  Object.keys(source2).forEach((key) => {
    if (isEditorConfigurationKey(key)) {
      toUpdate.push([`editor.${key}`, source2[key]]);
    }
    if (isDiffEditor && isDiffEditorConfigurationKey(key)) {
      toUpdate.push([`diffEditor.${key}`, source2[key]]);
    }
  });
  if (toUpdate.length > 0) {
    configurationService.updateValues(toUpdate);
  }
}
var SimpleBulkEditService = class {
  constructor(_modelService) {
    this._modelService = _modelService;
  }
  hasPreviewHandler() {
    return false;
  }
  apply(edits, _options) {
    return __awaiter$4(this, void 0, void 0, function* () {
      const textEdits = new Map();
      for (let edit of edits) {
        if (!(edit instanceof ResourceTextEdit)) {
          throw new Error("bad edit - only text edits are supported");
        }
        const model = this._modelService.getModel(edit.resource);
        if (!model) {
          throw new Error("bad edit - model not found");
        }
        if (typeof edit.versionId === "number" && model.getVersionId() !== edit.versionId) {
          throw new Error("bad state - model changed in the meantime");
        }
        let array2 = textEdits.get(model);
        if (!array2) {
          array2 = [];
          textEdits.set(model, array2);
        }
        array2.push(EditOperation.replaceMove(Range.lift(edit.textEdit.range), edit.textEdit.text));
      }
      let totalEdits = 0;
      let totalFiles = 0;
      for (const [model, edits2] of textEdits) {
        model.pushStackElement();
        model.pushEditOperations([], edits2, () => []);
        model.pushStackElement();
        totalFiles += 1;
        totalEdits += edits2.length;
      }
      return {
        ariaSummary: format(SimpleServicesNLS.bulkEditServiceSummary, totalEdits, totalFiles)
      };
    });
  }
};
var SimpleUriLabelService = class {
  getUriLabel(resource2, options) {
    if (resource2.scheme === "file") {
      return resource2.fsPath;
    }
    return resource2.path;
  }
};
var SimpleLayoutService = class {
  constructor(_codeEditorService, _container) {
    this._codeEditorService = _codeEditorService;
    this._container = _container;
    this.onLayout = Event.None;
  }
  get dimension() {
    if (!this._dimension) {
      this._dimension = getClientArea(window.document.body);
    }
    return this._dimension;
  }
  get container() {
    return this._container;
  }
  focus() {
    var _a;
    (_a = this._codeEditorService.getFocusedCodeEditor()) === null || _a === void 0 ? void 0 : _a.focus();
  }
};
function __snowpack__injectStyle$1(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$1("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-aria-container {\r\n	position: absolute; /* try to hide from window but not from screen readers */\r\n	left:-999em;\r\n}");
var MAX_MESSAGE_LENGTH = 2e4;
var ariaContainer;
var alertContainer;
var alertContainer2;
function setARIAContainer(parent) {
  ariaContainer = document.createElement("div");
  ariaContainer.className = "monaco-aria-container";
  const createAlertContainer = () => {
    const element = document.createElement("div");
    element.className = "monaco-alert";
    element.setAttribute("role", "alert");
    element.setAttribute("aria-atomic", "true");
    ariaContainer.appendChild(element);
    return element;
  };
  alertContainer = createAlertContainer();
  alertContainer2 = createAlertContainer();
  const createStatusContainer = () => {
    const element = document.createElement("div");
    element.className = "monaco-status";
    element.setAttribute("role", "complementary");
    element.setAttribute("aria-live", "polite");
    element.setAttribute("aria-atomic", "true");
    ariaContainer.appendChild(element);
    return element;
  };
  createStatusContainer();
  createStatusContainer();
  parent.appendChild(ariaContainer);
}
function alert3(msg) {
  if (!ariaContainer) {
    return;
  }
  if (alertContainer.textContent !== msg) {
    clearNode(alertContainer2);
    insertMessage(alertContainer, msg);
  } else {
    clearNode(alertContainer);
    insertMessage(alertContainer2, msg);
  }
}
function insertMessage(target, msg) {
  clearNode(target);
  if (msg.length > MAX_MESSAGE_LENGTH) {
    msg = msg.substr(0, MAX_MESSAGE_LENGTH);
  }
  target.textContent = msg;
  target.style.visibility = "hidden";
  target.style.visibility = "visible";
}
function __snowpack__injectStyle$2(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$2("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n/* -------------------- IE10 remove auto clear button -------------------- */\r\n\r\n::-ms-clear {\r\n	display: none;\r\n}\r\n\r\n/* All widgets */\r\n/* I am not a big fan of this rule */\r\n.monaco-editor .editor-widget input {\r\n	color: inherit;\r\n}\r\n\r\n/* -------------------- Editor -------------------- */\r\n\r\n.monaco-editor {\r\n	position: relative;\r\n	overflow: visible;\r\n	-webkit-text-size-adjust: 100%;\r\n}\r\n\r\n/* -------------------- Misc -------------------- */\r\n\r\n.monaco-editor .overflow-guard {\r\n	position: relative;\r\n	overflow: hidden;\r\n}\r\n\r\n.monaco-editor .view-overlays {\r\n	position: absolute;\r\n	top: 0;\r\n}\r\n\r\n/*\r\n.monaco-editor .auto-closed-character {\r\n	opacity: 0.3;\r\n}\r\n*/\r\n");
var CharWidthRequest = class {
  constructor(chr, type) {
    this.chr = chr;
    this.type = type;
    this.width = 0;
  }
  fulfill(width2) {
    this.width = width2;
  }
};
var DomCharWidthReader = class {
  constructor(bareFontInfo, requests) {
    this._bareFontInfo = bareFontInfo;
    this._requests = requests;
    this._container = null;
    this._testElements = null;
  }
  read() {
    this._createDomElements();
    document.body.appendChild(this._container);
    this._readFromDomElements();
    document.body.removeChild(this._container);
    this._container = null;
    this._testElements = null;
  }
  _createDomElements() {
    const container = document.createElement("div");
    container.style.position = "absolute";
    container.style.top = "-50000px";
    container.style.width = "50000px";
    const regularDomNode = document.createElement("div");
    regularDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
    regularDomNode.style.fontWeight = this._bareFontInfo.fontWeight;
    regularDomNode.style.fontSize = this._bareFontInfo.fontSize + "px";
    regularDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
    regularDomNode.style.lineHeight = this._bareFontInfo.lineHeight + "px";
    regularDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + "px";
    container.appendChild(regularDomNode);
    const boldDomNode = document.createElement("div");
    boldDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
    boldDomNode.style.fontWeight = "bold";
    boldDomNode.style.fontSize = this._bareFontInfo.fontSize + "px";
    boldDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
    boldDomNode.style.lineHeight = this._bareFontInfo.lineHeight + "px";
    boldDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + "px";
    container.appendChild(boldDomNode);
    const italicDomNode = document.createElement("div");
    italicDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
    italicDomNode.style.fontWeight = this._bareFontInfo.fontWeight;
    italicDomNode.style.fontSize = this._bareFontInfo.fontSize + "px";
    italicDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
    italicDomNode.style.lineHeight = this._bareFontInfo.lineHeight + "px";
    italicDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + "px";
    italicDomNode.style.fontStyle = "italic";
    container.appendChild(italicDomNode);
    const testElements = [];
    for (const request2 of this._requests) {
      let parent;
      if (request2.type === 0) {
        parent = regularDomNode;
      }
      if (request2.type === 2) {
        parent = boldDomNode;
      }
      if (request2.type === 1) {
        parent = italicDomNode;
      }
      parent.appendChild(document.createElement("br"));
      const testElement = document.createElement("span");
      DomCharWidthReader._render(testElement, request2);
      parent.appendChild(testElement);
      testElements.push(testElement);
    }
    this._container = container;
    this._testElements = testElements;
  }
  static _render(testElement, request2) {
    if (request2.chr === " ") {
      let htmlString = " ";
      for (let i3 = 0; i3 < 8; i3++) {
        htmlString += htmlString;
      }
      testElement.innerText = htmlString;
    } else {
      let testString = request2.chr;
      for (let i3 = 0; i3 < 8; i3++) {
        testString += testString;
      }
      testElement.textContent = testString;
    }
  }
  _readFromDomElements() {
    for (let i3 = 0, len2 = this._requests.length; i3 < len2; i3++) {
      const request2 = this._requests[i3];
      const testElement = this._testElements[i3];
      request2.fulfill(testElement.offsetWidth / 256);
    }
  }
};
function readCharWidths(bareFontInfo, requests) {
  const reader = new DomCharWidthReader(bareFontInfo, requests);
  reader.read();
}
var ElementSizeObserver = class extends Disposable {
  constructor(referenceDomElement, dimension, changeCallback) {
    super();
    this.referenceDomElement = referenceDomElement;
    this.changeCallback = changeCallback;
    this.width = -1;
    this.height = -1;
    this.resizeObserver = null;
    this.measureReferenceDomElementToken = -1;
    this.measureReferenceDomElement(false, dimension);
  }
  dispose() {
    this.stopObserving();
    super.dispose();
  }
  getWidth() {
    return this.width;
  }
  getHeight() {
    return this.height;
  }
  startObserving() {
    if (typeof ResizeObserver !== "undefined") {
      if (!this.resizeObserver && this.referenceDomElement) {
        this.resizeObserver = new ResizeObserver((entries) => {
          if (entries && entries[0] && entries[0].contentRect) {
            this.observe({width: entries[0].contentRect.width, height: entries[0].contentRect.height});
          } else {
            this.observe();
          }
        });
        this.resizeObserver.observe(this.referenceDomElement);
      }
    } else {
      if (this.measureReferenceDomElementToken === -1) {
        this.measureReferenceDomElementToken = setInterval(() => this.observe(), 100);
      }
    }
  }
  stopObserving() {
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
      this.resizeObserver = null;
    }
    if (this.measureReferenceDomElementToken !== -1) {
      clearInterval(this.measureReferenceDomElementToken);
      this.measureReferenceDomElementToken = -1;
    }
  }
  observe(dimension) {
    this.measureReferenceDomElement(true, dimension);
  }
  measureReferenceDomElement(callChangeCallback, dimension) {
    let observedWidth = 0;
    let observedHeight = 0;
    if (dimension) {
      observedWidth = dimension.width;
      observedHeight = dimension.height;
    } else if (this.referenceDomElement) {
      observedWidth = this.referenceDomElement.clientWidth;
      observedHeight = this.referenceDomElement.clientHeight;
    }
    observedWidth = Math.max(5, observedWidth);
    observedHeight = Math.max(5, observedHeight);
    if (this.width !== observedWidth || this.height !== observedHeight) {
      this.width = observedWidth;
      this.height = observedHeight;
      if (callChangeCallback) {
        this.changeCallback();
      }
    }
  }
};
var CSSBasedConfigurationCache = class {
  constructor() {
    this._keys = Object.create(null);
    this._values = Object.create(null);
  }
  has(item) {
    const itemId = item.getId();
    return !!this._values[itemId];
  }
  get(item) {
    const itemId = item.getId();
    return this._values[itemId];
  }
  put(item, value) {
    const itemId = item.getId();
    this._keys[itemId] = item;
    this._values[itemId] = value;
  }
  remove(item) {
    const itemId = item.getId();
    delete this._keys[itemId];
    delete this._values[itemId];
  }
  getValues() {
    return Object.keys(this._keys).map((id3) => this._values[id3]);
  }
};
function clearAllFontInfos() {
  CSSBasedConfiguration.INSTANCE.clearCache();
}
var CSSBasedConfiguration = class extends Disposable {
  constructor() {
    super();
    this._onDidChange = this._register(new Emitter());
    this.onDidChange = this._onDidChange.event;
    this._cache = new CSSBasedConfigurationCache();
    this._evictUntrustedReadingsTimeout = -1;
  }
  dispose() {
    if (this._evictUntrustedReadingsTimeout !== -1) {
      clearTimeout(this._evictUntrustedReadingsTimeout);
      this._evictUntrustedReadingsTimeout = -1;
    }
    super.dispose();
  }
  clearCache() {
    this._cache = new CSSBasedConfigurationCache();
    this._onDidChange.fire();
  }
  _writeToCache(item, value) {
    this._cache.put(item, value);
    if (!value.isTrusted && this._evictUntrustedReadingsTimeout === -1) {
      this._evictUntrustedReadingsTimeout = setTimeout(() => {
        this._evictUntrustedReadingsTimeout = -1;
        this._evictUntrustedReadings();
      }, 5e3);
    }
  }
  _evictUntrustedReadings() {
    const values2 = this._cache.getValues();
    let somethingRemoved = false;
    for (let i3 = 0, len2 = values2.length; i3 < len2; i3++) {
      const item = values2[i3];
      if (!item.isTrusted) {
        somethingRemoved = true;
        this._cache.remove(item);
      }
    }
    if (somethingRemoved) {
      this._onDidChange.fire();
    }
  }
  readConfiguration(bareFontInfo) {
    if (!this._cache.has(bareFontInfo)) {
      let readConfig = CSSBasedConfiguration._actualReadConfiguration(bareFontInfo);
      if (readConfig.typicalHalfwidthCharacterWidth <= 2 || readConfig.typicalFullwidthCharacterWidth <= 2 || readConfig.spaceWidth <= 2 || readConfig.maxDigitWidth <= 2) {
        readConfig = new FontInfo({
          zoomLevel: getZoomLevel(),
          fontFamily: readConfig.fontFamily,
          fontWeight: readConfig.fontWeight,
          fontSize: readConfig.fontSize,
          fontFeatureSettings: readConfig.fontFeatureSettings,
          lineHeight: readConfig.lineHeight,
          letterSpacing: readConfig.letterSpacing,
          isMonospace: readConfig.isMonospace,
          typicalHalfwidthCharacterWidth: Math.max(readConfig.typicalHalfwidthCharacterWidth, 5),
          typicalFullwidthCharacterWidth: Math.max(readConfig.typicalFullwidthCharacterWidth, 5),
          canUseHalfwidthRightwardsArrow: readConfig.canUseHalfwidthRightwardsArrow,
          spaceWidth: Math.max(readConfig.spaceWidth, 5),
          middotWidth: Math.max(readConfig.middotWidth, 5),
          wsmiddotWidth: Math.max(readConfig.wsmiddotWidth, 5),
          maxDigitWidth: Math.max(readConfig.maxDigitWidth, 5)
        }, false);
      }
      this._writeToCache(bareFontInfo, readConfig);
    }
    return this._cache.get(bareFontInfo);
  }
  static createRequest(chr, type, all2, monospace) {
    const result = new CharWidthRequest(chr, type);
    all2.push(result);
    if (monospace) {
      monospace.push(result);
    }
    return result;
  }
  static _actualReadConfiguration(bareFontInfo) {
    const all2 = [];
    const monospace = [];
    const typicalHalfwidthCharacter = this.createRequest("n", 0, all2, monospace);
    const typicalFullwidthCharacter = this.createRequest("ｍ", 0, all2, null);
    const space = this.createRequest(" ", 0, all2, monospace);
    const digit0 = this.createRequest("0", 0, all2, monospace);
    const digit1 = this.createRequest("1", 0, all2, monospace);
    const digit2 = this.createRequest("2", 0, all2, monospace);
    const digit3 = this.createRequest("3", 0, all2, monospace);
    const digit4 = this.createRequest("4", 0, all2, monospace);
    const digit5 = this.createRequest("5", 0, all2, monospace);
    const digit6 = this.createRequest("6", 0, all2, monospace);
    const digit7 = this.createRequest("7", 0, all2, monospace);
    const digit8 = this.createRequest("8", 0, all2, monospace);
    const digit9 = this.createRequest("9", 0, all2, monospace);
    const rightwardsArrow = this.createRequest("→", 0, all2, monospace);
    const halfwidthRightwardsArrow = this.createRequest("￫", 0, all2, null);
    const middot = this.createRequest("·", 0, all2, monospace);
    const wsmiddotWidth = this.createRequest(String.fromCharCode(11825), 0, all2, null);
    this.createRequest("|", 0, all2, monospace);
    this.createRequest("/", 0, all2, monospace);
    this.createRequest("-", 0, all2, monospace);
    this.createRequest("_", 0, all2, monospace);
    this.createRequest("i", 0, all2, monospace);
    this.createRequest("l", 0, all2, monospace);
    this.createRequest("m", 0, all2, monospace);
    this.createRequest("|", 1, all2, monospace);
    this.createRequest("_", 1, all2, monospace);
    this.createRequest("i", 1, all2, monospace);
    this.createRequest("l", 1, all2, monospace);
    this.createRequest("m", 1, all2, monospace);
    this.createRequest("n", 1, all2, monospace);
    this.createRequest("|", 2, all2, monospace);
    this.createRequest("_", 2, all2, monospace);
    this.createRequest("i", 2, all2, monospace);
    this.createRequest("l", 2, all2, monospace);
    this.createRequest("m", 2, all2, monospace);
    this.createRequest("n", 2, all2, monospace);
    readCharWidths(bareFontInfo, all2);
    const maxDigitWidth = Math.max(digit0.width, digit1.width, digit2.width, digit3.width, digit4.width, digit5.width, digit6.width, digit7.width, digit8.width, digit9.width);
    let isMonospace = bareFontInfo.fontFeatureSettings === EditorFontLigatures.OFF;
    const referenceWidth = monospace[0].width;
    for (let i3 = 1, len2 = monospace.length; isMonospace && i3 < len2; i3++) {
      const diff = referenceWidth - monospace[i3].width;
      if (diff < -1e-3 || diff > 1e-3) {
        isMonospace = false;
        break;
      }
    }
    let canUseHalfwidthRightwardsArrow = true;
    if (isMonospace && halfwidthRightwardsArrow.width !== referenceWidth) {
      canUseHalfwidthRightwardsArrow = false;
    }
    if (halfwidthRightwardsArrow.width > rightwardsArrow.width) {
      canUseHalfwidthRightwardsArrow = false;
    }
    const canTrustBrowserZoomLevel = getTimeSinceLastZoomLevelChanged() > 2e3;
    return new FontInfo({
      zoomLevel: getZoomLevel(),
      fontFamily: bareFontInfo.fontFamily,
      fontWeight: bareFontInfo.fontWeight,
      fontSize: bareFontInfo.fontSize,
      fontFeatureSettings: bareFontInfo.fontFeatureSettings,
      lineHeight: bareFontInfo.lineHeight,
      letterSpacing: bareFontInfo.letterSpacing,
      isMonospace,
      typicalHalfwidthCharacterWidth: typicalHalfwidthCharacter.width,
      typicalFullwidthCharacterWidth: typicalFullwidthCharacter.width,
      canUseHalfwidthRightwardsArrow,
      spaceWidth: space.width,
      middotWidth: middot.width,
      wsmiddotWidth: wsmiddotWidth.width,
      maxDigitWidth
    }, canTrustBrowserZoomLevel);
  }
};
CSSBasedConfiguration.INSTANCE = new CSSBasedConfiguration();
var Configuration$1 = class extends CommonEditorConfiguration {
  constructor(isSimpleWidget, options, referenceDomElement = null, accessibilityService) {
    super(isSimpleWidget, options);
    this.accessibilityService = accessibilityService;
    this._elementSizeObserver = this._register(new ElementSizeObserver(referenceDomElement, options.dimension, () => this._onReferenceDomElementSizeChanged()));
    this._register(CSSBasedConfiguration.INSTANCE.onDidChange(() => this._onCSSBasedConfigurationChanged()));
    if (this._validatedOptions.get(9)) {
      this._elementSizeObserver.startObserving();
    }
    this._register(onDidChangeZoomLevel((_23) => this._recomputeOptions()));
    this._register(this.accessibilityService.onDidChangeScreenReaderOptimized(() => this._recomputeOptions()));
    this._recomputeOptions();
  }
  static applyFontInfoSlow(domNode, fontInfo) {
    domNode.style.fontFamily = fontInfo.getMassagedFontFamily();
    domNode.style.fontWeight = fontInfo.fontWeight;
    domNode.style.fontSize = fontInfo.fontSize + "px";
    domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings;
    domNode.style.lineHeight = fontInfo.lineHeight + "px";
    domNode.style.letterSpacing = fontInfo.letterSpacing + "px";
  }
  static applyFontInfo(domNode, fontInfo) {
    domNode.setFontFamily(fontInfo.getMassagedFontFamily());
    domNode.setFontWeight(fontInfo.fontWeight);
    domNode.setFontSize(fontInfo.fontSize);
    domNode.setFontFeatureSettings(fontInfo.fontFeatureSettings);
    domNode.setLineHeight(fontInfo.lineHeight);
    domNode.setLetterSpacing(fontInfo.letterSpacing);
  }
  _onReferenceDomElementSizeChanged() {
    this._recomputeOptions();
  }
  _onCSSBasedConfigurationChanged() {
    this._recomputeOptions();
  }
  observeReferenceElement(dimension) {
    this._elementSizeObserver.observe(dimension);
  }
  dispose() {
    super.dispose();
  }
  _getExtraEditorClassName() {
    let extra = "";
    if (!isSafari && !isWebkitWebView) {
      extra += "no-user-select ";
    }
    if (isMacintosh) {
      extra += "mac ";
    }
    return extra;
  }
  _getEnvConfiguration() {
    return {
      extraEditorClassName: this._getExtraEditorClassName(),
      outerWidth: this._elementSizeObserver.getWidth(),
      outerHeight: this._elementSizeObserver.getHeight(),
      emptySelectionClipboard: isWebKit || isFirefox,
      pixelRatio: getPixelRatio(),
      zoomLevel: getZoomLevel(),
      accessibilitySupport: this.accessibilityService.isScreenReaderOptimized() ? 2 : this.accessibilityService.getAccessibilitySupport()
    };
  }
  readConfiguration(bareFontInfo) {
    return CSSBasedConfiguration.INSTANCE.readConfiguration(bareFontInfo);
  }
};
var __awaiter$5 = function(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var Action = class extends Disposable {
  constructor(id3, label2 = "", cssClass = "", enabled = true, actionCallback) {
    super();
    this._onDidChange = this._register(new Emitter());
    this.onDidChange = this._onDidChange.event;
    this._enabled = true;
    this._checked = false;
    this._id = id3;
    this._label = label2;
    this._cssClass = cssClass;
    this._enabled = enabled;
    this._actionCallback = actionCallback;
  }
  get id() {
    return this._id;
  }
  get label() {
    return this._label;
  }
  set label(value) {
    this._setLabel(value);
  }
  _setLabel(value) {
    if (this._label !== value) {
      this._label = value;
      this._onDidChange.fire({label: value});
    }
  }
  get tooltip() {
    return this._tooltip || "";
  }
  set tooltip(value) {
    this._setTooltip(value);
  }
  _setTooltip(value) {
    if (this._tooltip !== value) {
      this._tooltip = value;
      this._onDidChange.fire({tooltip: value});
    }
  }
  get class() {
    return this._cssClass;
  }
  set class(value) {
    this._setClass(value);
  }
  _setClass(value) {
    if (this._cssClass !== value) {
      this._cssClass = value;
      this._onDidChange.fire({class: value});
    }
  }
  get enabled() {
    return this._enabled;
  }
  set enabled(value) {
    this._setEnabled(value);
  }
  _setEnabled(value) {
    if (this._enabled !== value) {
      this._enabled = value;
      this._onDidChange.fire({enabled: value});
    }
  }
  get checked() {
    return this._checked;
  }
  set checked(value) {
    this._setChecked(value);
  }
  _setChecked(value) {
    if (this._checked !== value) {
      this._checked = value;
      this._onDidChange.fire({checked: value});
    }
  }
  run(event, _data) {
    if (this._actionCallback) {
      return this._actionCallback(event);
    }
    return Promise.resolve(true);
  }
};
var ActionRunner = class extends Disposable {
  constructor() {
    super(...arguments);
    this._onDidBeforeRun = this._register(new Emitter());
    this.onDidBeforeRun = this._onDidBeforeRun.event;
    this._onDidRun = this._register(new Emitter());
    this.onDidRun = this._onDidRun.event;
  }
  run(action, context2) {
    return __awaiter$5(this, void 0, void 0, function* () {
      if (!action.enabled) {
        return Promise.resolve(null);
      }
      this._onDidBeforeRun.fire({action});
      try {
        const result = yield this.runAction(action, context2);
        this._onDidRun.fire({action, result});
      } catch (error2) {
        this._onDidRun.fire({action, error: error2});
      }
    });
  }
  runAction(action, context2) {
    const res = context2 ? action.run(context2) : action.run();
    return Promise.resolve(res);
  }
};
var Separator = class extends Action {
  constructor(label2) {
    super(Separator.ID, label2, label2 ? "separator text" : "separator");
    this.checked = false;
    this.enabled = false;
  }
};
Separator.ID = "vs.actions.separator";
var SubmenuAction = class extends Action {
  constructor(id3, label2, _actions, cssClass) {
    super(id3, label2, cssClass, true);
    this._actions = _actions;
  }
  get actions() {
    return Array.isArray(this._actions) ? this._actions : this._actions();
  }
};
var STATIC_VALUES = new Map();
STATIC_VALUES.set("false", false);
STATIC_VALUES.set("true", true);
STATIC_VALUES.set("isMac", isMacintosh);
STATIC_VALUES.set("isLinux", isLinux);
STATIC_VALUES.set("isWindows", isWindows);
STATIC_VALUES.set("isWeb", isWeb2);
STATIC_VALUES.set("isMacNative", isMacintosh && !isWeb2);
var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
var ContextKeyExpr = class {
  static has(key) {
    return ContextKeyDefinedExpr.create(key);
  }
  static equals(key, value) {
    return ContextKeyEqualsExpr.create(key, value);
  }
  static regex(key, value) {
    return ContextKeyRegexExpr.create(key, value);
  }
  static not(key) {
    return ContextKeyNotExpr.create(key);
  }
  static and(...expr) {
    return ContextKeyAndExpr.create(expr);
  }
  static or(...expr) {
    return ContextKeyOrExpr.create(expr);
  }
  static deserialize(serialized, strict = false) {
    if (!serialized) {
      return void 0;
    }
    return this._deserializeOrExpression(serialized, strict);
  }
  static _deserializeOrExpression(serialized, strict) {
    let pieces = serialized.split("||");
    return ContextKeyOrExpr.create(pieces.map((p2) => this._deserializeAndExpression(p2, strict)));
  }
  static _deserializeAndExpression(serialized, strict) {
    let pieces = serialized.split("&&");
    return ContextKeyAndExpr.create(pieces.map((p2) => this._deserializeOne(p2, strict)));
  }
  static _deserializeOne(serializedOne, strict) {
    serializedOne = serializedOne.trim();
    if (serializedOne.indexOf("!=") >= 0) {
      let pieces = serializedOne.split("!=");
      return ContextKeyNotEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict));
    }
    if (serializedOne.indexOf("==") >= 0) {
      let pieces = serializedOne.split("==");
      return ContextKeyEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict));
    }
    if (serializedOne.indexOf("=~") >= 0) {
      let pieces = serializedOne.split("=~");
      return ContextKeyRegexExpr.create(pieces[0].trim(), this._deserializeRegexValue(pieces[1], strict));
    }
    if (serializedOne.indexOf(" in ") >= 0) {
      let pieces = serializedOne.split(" in ");
      return ContextKeyInExpr.create(pieces[0].trim(), pieces[1].trim());
    }
    if (/^\!\s*/.test(serializedOne)) {
      return ContextKeyNotExpr.create(serializedOne.substr(1).trim());
    }
    return ContextKeyDefinedExpr.create(serializedOne);
  }
  static _deserializeValue(serializedValue, strict) {
    serializedValue = serializedValue.trim();
    if (serializedValue === "true") {
      return true;
    }
    if (serializedValue === "false") {
      return false;
    }
    let m2 = /^'([^']*)'$/.exec(serializedValue);
    if (m2) {
      return m2[1].trim();
    }
    return serializedValue;
  }
  static _deserializeRegexValue(serializedValue, strict) {
    if (isFalsyOrWhitespace(serializedValue)) {
      if (strict) {
        throw new Error("missing regexp-value for =~-expression");
      } else {
        console.warn("missing regexp-value for =~-expression");
      }
      return null;
    }
    let start3 = serializedValue.indexOf("/");
    let end2 = serializedValue.lastIndexOf("/");
    if (start3 === end2 || start3 < 0) {
      if (strict) {
        throw new Error(`bad regexp-value '${serializedValue}', missing /-enclosure`);
      } else {
        console.warn(`bad regexp-value '${serializedValue}', missing /-enclosure`);
      }
      return null;
    }
    let value = serializedValue.slice(start3 + 1, end2);
    let caseIgnoreFlag = serializedValue[end2 + 1] === "i" ? "i" : "";
    try {
      return new RegExp(value, caseIgnoreFlag);
    } catch (e2) {
      if (strict) {
        throw new Error(`bad regexp-value '${serializedValue}', parse error: ${e2}`);
      } else {
        console.warn(`bad regexp-value '${serializedValue}', parse error: ${e2}`);
      }
      return null;
    }
  }
};
function cmp(a2, b2) {
  return a2.cmp(b2);
}
var ContextKeyFalseExpr = class {
  constructor() {
    this.type = 0;
  }
  cmp(other) {
    return this.type - other.type;
  }
  equals(other) {
    return other.type === this.type;
  }
  evaluate(context2) {
    return false;
  }
  serialize() {
    return "false";
  }
  keys() {
    return [];
  }
  negate() {
    return ContextKeyTrueExpr.INSTANCE;
  }
};
ContextKeyFalseExpr.INSTANCE = new ContextKeyFalseExpr();
var ContextKeyTrueExpr = class {
  constructor() {
    this.type = 1;
  }
  cmp(other) {
    return this.type - other.type;
  }
  equals(other) {
    return other.type === this.type;
  }
  evaluate(context2) {
    return true;
  }
  serialize() {
    return "true";
  }
  keys() {
    return [];
  }
  negate() {
    return ContextKeyFalseExpr.INSTANCE;
  }
};
ContextKeyTrueExpr.INSTANCE = new ContextKeyTrueExpr();
var ContextKeyDefinedExpr = class {
  constructor(key) {
    this.key = key;
    this.type = 2;
  }
  static create(key) {
    const staticValue = STATIC_VALUES.get(key);
    if (typeof staticValue === "boolean") {
      return staticValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
    }
    return new ContextKeyDefinedExpr(key);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.key < other.key) {
      return -1;
    }
    if (this.key > other.key) {
      return 1;
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key;
    }
    return false;
  }
  evaluate(context2) {
    return !!context2.getValue(this.key);
  }
  serialize() {
    return this.key;
  }
  keys() {
    return [this.key];
  }
  negate() {
    return ContextKeyNotExpr.create(this.key);
  }
};
var ContextKeyEqualsExpr = class {
  constructor(key, value) {
    this.key = key;
    this.value = value;
    this.type = 4;
  }
  static create(key, value) {
    if (typeof value === "boolean") {
      return value ? ContextKeyDefinedExpr.create(key) : ContextKeyNotExpr.create(key);
    }
    const staticValue = STATIC_VALUES.get(key);
    if (typeof staticValue === "boolean") {
      const trueValue = staticValue ? "true" : "false";
      return value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
    }
    return new ContextKeyEqualsExpr(key, value);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.key < other.key) {
      return -1;
    }
    if (this.key > other.key) {
      return 1;
    }
    if (this.value < other.value) {
      return -1;
    }
    if (this.value > other.value) {
      return 1;
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key && this.value === other.value;
    }
    return false;
  }
  evaluate(context2) {
    return context2.getValue(this.key) == this.value;
  }
  serialize() {
    return this.key + " == '" + this.value + "'";
  }
  keys() {
    return [this.key];
  }
  negate() {
    return ContextKeyNotEqualsExpr.create(this.key, this.value);
  }
};
var ContextKeyInExpr = class {
  constructor(key, valueKey) {
    this.key = key;
    this.valueKey = valueKey;
    this.type = 10;
  }
  static create(key, valueKey) {
    return new ContextKeyInExpr(key, valueKey);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.key < other.key) {
      return -1;
    }
    if (this.key > other.key) {
      return 1;
    }
    if (this.valueKey < other.valueKey) {
      return -1;
    }
    if (this.valueKey > other.valueKey) {
      return 1;
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key && this.valueKey === other.valueKey;
    }
    return false;
  }
  evaluate(context2) {
    const source2 = context2.getValue(this.valueKey);
    const item = context2.getValue(this.key);
    if (Array.isArray(source2)) {
      return source2.indexOf(item) >= 0;
    }
    if (typeof item === "string" && typeof source2 === "object" && source2 !== null) {
      return hasOwnProperty$2.call(source2, item);
    }
    return false;
  }
  serialize() {
    return this.key + " in '" + this.valueKey + "'";
  }
  keys() {
    return [this.key, this.valueKey];
  }
  negate() {
    return ContextKeyNotInExpr.create(this);
  }
};
var ContextKeyNotInExpr = class {
  constructor(_actual) {
    this._actual = _actual;
    this.type = 11;
  }
  static create(actual) {
    return new ContextKeyNotInExpr(actual);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return this._actual.cmp(other._actual);
  }
  equals(other) {
    if (other.type === this.type) {
      return this._actual.equals(other._actual);
    }
    return false;
  }
  evaluate(context2) {
    return !this._actual.evaluate(context2);
  }
  serialize() {
    throw new Error("Method not implemented.");
  }
  keys() {
    return this._actual.keys();
  }
  negate() {
    return this._actual;
  }
};
var ContextKeyNotEqualsExpr = class {
  constructor(key, value) {
    this.key = key;
    this.value = value;
    this.type = 5;
  }
  static create(key, value) {
    if (typeof value === "boolean") {
      if (value) {
        return ContextKeyNotExpr.create(key);
      }
      return ContextKeyDefinedExpr.create(key);
    }
    const staticValue = STATIC_VALUES.get(key);
    if (typeof staticValue === "boolean") {
      const falseValue = staticValue ? "true" : "false";
      return value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE;
    }
    return new ContextKeyNotEqualsExpr(key, value);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.key < other.key) {
      return -1;
    }
    if (this.key > other.key) {
      return 1;
    }
    if (this.value < other.value) {
      return -1;
    }
    if (this.value > other.value) {
      return 1;
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key && this.value === other.value;
    }
    return false;
  }
  evaluate(context2) {
    return context2.getValue(this.key) != this.value;
  }
  serialize() {
    return this.key + " != '" + this.value + "'";
  }
  keys() {
    return [this.key];
  }
  negate() {
    return ContextKeyEqualsExpr.create(this.key, this.value);
  }
};
var ContextKeyNotExpr = class {
  constructor(key) {
    this.key = key;
    this.type = 3;
  }
  static create(key) {
    const staticValue = STATIC_VALUES.get(key);
    if (typeof staticValue === "boolean") {
      return staticValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE;
    }
    return new ContextKeyNotExpr(key);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.key < other.key) {
      return -1;
    }
    if (this.key > other.key) {
      return 1;
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key;
    }
    return false;
  }
  evaluate(context2) {
    return !context2.getValue(this.key);
  }
  serialize() {
    return "!" + this.key;
  }
  keys() {
    return [this.key];
  }
  negate() {
    return ContextKeyDefinedExpr.create(this.key);
  }
};
var ContextKeyRegexExpr = class {
  constructor(key, regexp) {
    this.key = key;
    this.regexp = regexp;
    this.type = 7;
  }
  static create(key, regexp) {
    return new ContextKeyRegexExpr(key, regexp);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.key < other.key) {
      return -1;
    }
    if (this.key > other.key) {
      return 1;
    }
    const thisSource = this.regexp ? this.regexp.source : "";
    const otherSource = other.regexp ? other.regexp.source : "";
    if (thisSource < otherSource) {
      return -1;
    }
    if (thisSource > otherSource) {
      return 1;
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      const thisSource = this.regexp ? this.regexp.source : "";
      const otherSource = other.regexp ? other.regexp.source : "";
      return this.key === other.key && thisSource === otherSource;
    }
    return false;
  }
  evaluate(context2) {
    let value = context2.getValue(this.key);
    return this.regexp ? this.regexp.test(value) : false;
  }
  serialize() {
    const value = this.regexp ? `/${this.regexp.source}/${this.regexp.ignoreCase ? "i" : ""}` : "/invalid/";
    return `${this.key} =~ ${value}`;
  }
  keys() {
    return [this.key];
  }
  negate() {
    return ContextKeyNotRegexExpr.create(this);
  }
};
var ContextKeyNotRegexExpr = class {
  constructor(_actual) {
    this._actual = _actual;
    this.type = 8;
  }
  static create(actual) {
    return new ContextKeyNotRegexExpr(actual);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return this._actual.cmp(other._actual);
  }
  equals(other) {
    if (other.type === this.type) {
      return this._actual.equals(other._actual);
    }
    return false;
  }
  evaluate(context2) {
    return !this._actual.evaluate(context2);
  }
  serialize() {
    throw new Error("Method not implemented.");
  }
  keys() {
    return this._actual.keys();
  }
  negate() {
    return this._actual;
  }
};
var ContextKeyAndExpr = class {
  constructor(expr) {
    this.expr = expr;
    this.type = 6;
  }
  static create(_expr) {
    return ContextKeyAndExpr._normalizeArr(_expr);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.expr.length < other.expr.length) {
      return -1;
    }
    if (this.expr.length > other.expr.length) {
      return 1;
    }
    for (let i3 = 0, len2 = this.expr.length; i3 < len2; i3++) {
      const r3 = cmp(this.expr[i3], other.expr[i3]);
      if (r3 !== 0) {
        return r3;
      }
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      if (this.expr.length !== other.expr.length) {
        return false;
      }
      for (let i3 = 0, len2 = this.expr.length; i3 < len2; i3++) {
        if (!this.expr[i3].equals(other.expr[i3])) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  evaluate(context2) {
    for (let i3 = 0, len2 = this.expr.length; i3 < len2; i3++) {
      if (!this.expr[i3].evaluate(context2)) {
        return false;
      }
    }
    return true;
  }
  static _normalizeArr(arr) {
    const expr = [];
    let hasTrue = false;
    for (const e2 of arr) {
      if (!e2) {
        continue;
      }
      if (e2.type === 1) {
        hasTrue = true;
        continue;
      }
      if (e2.type === 0) {
        return ContextKeyFalseExpr.INSTANCE;
      }
      if (e2.type === 6) {
        expr.push(...e2.expr);
        continue;
      }
      expr.push(e2);
    }
    if (expr.length === 0 && hasTrue) {
      return ContextKeyTrueExpr.INSTANCE;
    }
    if (expr.length === 0) {
      return void 0;
    }
    if (expr.length === 1) {
      return expr[0];
    }
    expr.sort(cmp);
    while (expr.length > 1) {
      const lastElement = expr[expr.length - 1];
      if (lastElement.type !== 9) {
        break;
      }
      expr.pop();
      const secondToLastElement = expr.pop();
      const resultElement = ContextKeyOrExpr.create(lastElement.expr.map((el) => ContextKeyAndExpr.create([el, secondToLastElement])));
      if (resultElement) {
        expr.push(resultElement);
        expr.sort(cmp);
      }
    }
    return new ContextKeyAndExpr(expr);
  }
  serialize() {
    return this.expr.map((e2) => e2.serialize()).join(" && ");
  }
  keys() {
    const result = [];
    for (let expr of this.expr) {
      result.push(...expr.keys());
    }
    return result;
  }
  negate() {
    let result = [];
    for (let expr of this.expr) {
      result.push(expr.negate());
    }
    return ContextKeyOrExpr.create(result);
  }
};
var ContextKeyOrExpr = class {
  constructor(expr) {
    this.expr = expr;
    this.type = 9;
  }
  static create(_expr) {
    const expr = ContextKeyOrExpr._normalizeArr(_expr);
    if (expr.length === 0) {
      return void 0;
    }
    if (expr.length === 1) {
      return expr[0];
    }
    return new ContextKeyOrExpr(expr);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.expr.length < other.expr.length) {
      return -1;
    }
    if (this.expr.length > other.expr.length) {
      return 1;
    }
    for (let i3 = 0, len2 = this.expr.length; i3 < len2; i3++) {
      const r3 = cmp(this.expr[i3], other.expr[i3]);
      if (r3 !== 0) {
        return r3;
      }
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      if (this.expr.length !== other.expr.length) {
        return false;
      }
      for (let i3 = 0, len2 = this.expr.length; i3 < len2; i3++) {
        if (!this.expr[i3].equals(other.expr[i3])) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  evaluate(context2) {
    for (let i3 = 0, len2 = this.expr.length; i3 < len2; i3++) {
      if (this.expr[i3].evaluate(context2)) {
        return true;
      }
    }
    return false;
  }
  static _normalizeArr(arr) {
    let expr = [];
    let hasFalse = false;
    if (arr) {
      for (let i3 = 0, len2 = arr.length; i3 < len2; i3++) {
        const e2 = arr[i3];
        if (!e2) {
          continue;
        }
        if (e2.type === 0) {
          hasFalse = true;
          continue;
        }
        if (e2.type === 1) {
          return [ContextKeyTrueExpr.INSTANCE];
        }
        if (e2.type === 9) {
          expr = expr.concat(e2.expr);
          continue;
        }
        expr.push(e2);
      }
      if (expr.length === 0 && hasFalse) {
        return [ContextKeyFalseExpr.INSTANCE];
      }
      expr.sort(cmp);
    }
    return expr;
  }
  serialize() {
    return this.expr.map((e2) => e2.serialize()).join(" || ");
  }
  keys() {
    const result = [];
    for (let expr of this.expr) {
      result.push(...expr.keys());
    }
    return result;
  }
  negate() {
    let result = [];
    for (let expr of this.expr) {
      result.push(expr.negate());
    }
    const terminals = (node) => {
      if (node.type === 9) {
        return node.expr;
      }
      return [node];
    };
    while (result.length > 1) {
      const LEFT = result.shift();
      const RIGHT = result.shift();
      const all2 = [];
      for (const left2 of terminals(LEFT)) {
        for (const right2 of terminals(RIGHT)) {
          all2.push(ContextKeyExpr.and(left2, right2));
        }
      }
      result.unshift(ContextKeyExpr.or(...all2));
    }
    return result[0];
  }
};
var RawContextKey = class extends ContextKeyDefinedExpr {
  constructor(key, defaultValue) {
    super(key);
    this._defaultValue = defaultValue;
  }
  bindTo(target) {
    return target.createKey(this.key, this._defaultValue);
  }
  getValue(target) {
    return target.getContextKeyValue(this.key);
  }
  toNegated() {
    return ContextKeyExpr.not(this.key);
  }
};
var IContextKeyService = createDecorator("contextKeyService");
var SET_CONTEXT_COMMAND_ID = "setContext";
var __decorate$3 = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$3 = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
function isIMenuItem(item) {
  return item.command !== void 0;
}
var MenuId = class {
  constructor(debugName) {
    this.id = MenuId._idPool++;
    this._debugName = debugName;
  }
};
MenuId._idPool = 0;
MenuId.CommandPalette = new MenuId("CommandPalette");
MenuId.EditorContext = new MenuId("EditorContext");
MenuId.EditorContextPeek = new MenuId("EditorContextPeek");
MenuId.MenubarEditMenu = new MenuId("MenubarEditMenu");
MenuId.MenubarGoMenu = new MenuId("MenubarGoMenu");
MenuId.MenubarSelectionMenu = new MenuId("MenubarSelectionMenu");
var IMenuService = createDecorator("menuService");
var MenuRegistry = new class {
  constructor() {
    this._commands = new Map();
    this._menuItems = new Map();
    this._onDidChangeMenu = new Emitter();
    this.onDidChangeMenu = this._onDidChangeMenu.event;
    this._commandPaletteChangeEvent = {
      has: (id3) => id3 === MenuId.CommandPalette
    };
  }
  addCommand(command) {
    return this.addCommands(Iterable.single(command));
  }
  addCommands(commands) {
    for (const command of commands) {
      this._commands.set(command.id, command);
    }
    this._onDidChangeMenu.fire(this._commandPaletteChangeEvent);
    return toDisposable(() => {
      let didChange = false;
      for (const command of commands) {
        didChange = this._commands.delete(command.id) || didChange;
      }
      if (didChange) {
        this._onDidChangeMenu.fire(this._commandPaletteChangeEvent);
      }
    });
  }
  getCommand(id3) {
    return this._commands.get(id3);
  }
  getCommands() {
    const map2 = new Map();
    this._commands.forEach((value, key) => map2.set(key, value));
    return map2;
  }
  appendMenuItem(id3, item) {
    return this.appendMenuItems(Iterable.single({id: id3, item}));
  }
  appendMenuItems(items) {
    const changedIds = new Set();
    const toRemove = new LinkedList();
    for (const {id: id3, item} of items) {
      let list3 = this._menuItems.get(id3);
      if (!list3) {
        list3 = new LinkedList();
        this._menuItems.set(id3, list3);
      }
      toRemove.push(list3.push(item));
      changedIds.add(id3);
    }
    this._onDidChangeMenu.fire(changedIds);
    return toDisposable(() => {
      if (toRemove.size > 0) {
        for (let fn of toRemove) {
          fn();
        }
        this._onDidChangeMenu.fire(changedIds);
        toRemove.clear();
      }
    });
  }
  getMenuItems(id3) {
    let result;
    if (this._menuItems.has(id3)) {
      result = [...this._menuItems.get(id3)];
    } else {
      result = [];
    }
    if (id3 === MenuId.CommandPalette) {
      this._appendImplicitItems(result);
    }
    return result;
  }
  _appendImplicitItems(result) {
    const set3 = new Set();
    for (const item of result) {
      if (isIMenuItem(item)) {
        set3.add(item.command.id);
        if (item.alt) {
          set3.add(item.alt.id);
        }
      }
    }
    this._commands.forEach((command, id3) => {
      if (!set3.has(id3)) {
        result.push({command});
      }
    });
  }
}();
var ExecuteCommandAction = class ExecuteCommandAction2 extends Action {
  constructor(id3, label2, _commandService) {
    super(id3, label2);
    this._commandService = _commandService;
  }
  run(...args) {
    return this._commandService.executeCommand(this.id, ...args);
  }
};
ExecuteCommandAction = __decorate$3([
  __param$3(2, ICommandService)
], ExecuteCommandAction);
var SubmenuItemAction = class extends SubmenuAction {
  constructor(item, menuService, contextKeyService, options) {
    super(`submenuitem.${item.submenu.id}`, typeof item.title === "string" ? item.title : item.title.value, () => {
      const result = [];
      const menu = menuService.createMenu(item.submenu, contextKeyService);
      const groups2 = menu.getActions(options);
      menu.dispose();
      for (let group of groups2) {
        const [, actions2] = group;
        if (actions2.length > 0) {
          result.push(...actions2);
          result.push(new Separator());
        }
      }
      if (result.length) {
        result.pop();
      }
      return result;
    }, "submenu");
    this.item = item;
  }
};
var MenuItemAction = class MenuItemAction2 extends ExecuteCommandAction {
  constructor(item, alt, options, contextKeyService, commandService) {
    typeof item.title === "string" ? super(item.id, item.title, commandService) : super(item.id, item.title.value, commandService);
    this._cssClass = void 0;
    this._enabled = !item.precondition || contextKeyService.contextMatchesRules(item.precondition);
    this._tooltip = item.tooltip ? typeof item.tooltip === "string" ? item.tooltip : item.tooltip.value : void 0;
    if (item.toggled) {
      const toggled = item.toggled.condition ? item.toggled : {condition: item.toggled};
      this._checked = contextKeyService.contextMatchesRules(toggled.condition);
      if (this._checked && toggled.tooltip) {
        this._tooltip = typeof toggled.tooltip === "string" ? toggled.tooltip : toggled.tooltip.value;
      }
    }
    this._options = options || {};
    this.item = item;
    this.alt = alt ? new MenuItemAction2(alt, void 0, this._options, contextKeyService, commandService) : void 0;
  }
  dispose() {
    if (this.alt) {
      this.alt.dispose();
    }
    super.dispose();
  }
  run(...args) {
    let runArgs = [];
    if (this._options.arg) {
      runArgs = [...runArgs, this._options.arg];
    }
    if (this._options.shouldForwardArgs) {
      runArgs = [...runArgs, ...args];
    }
    return super.run(...runArgs);
  }
};
MenuItemAction = __decorate$3([
  __param$3(3, IContextKeyService),
  __param$3(4, ICommandService)
], MenuItemAction);
var ITelemetryService = createDecorator("telemetryService");
var Command = class {
  constructor(opts) {
    this.id = opts.id;
    this.precondition = opts.precondition;
    this._kbOpts = opts.kbOpts;
    this._menuOpts = opts.menuOpts;
    this._description = opts.description;
  }
  register() {
    if (Array.isArray(this._menuOpts)) {
      this._menuOpts.forEach(this._registerMenuItem, this);
    } else if (this._menuOpts) {
      this._registerMenuItem(this._menuOpts);
    }
    if (this._kbOpts) {
      let kbWhen = this._kbOpts.kbExpr;
      if (this.precondition) {
        if (kbWhen) {
          kbWhen = ContextKeyExpr.and(kbWhen, this.precondition);
        } else {
          kbWhen = this.precondition;
        }
      }
      KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: this.id,
        handler: (accessor, args) => this.runCommand(accessor, args),
        weight: this._kbOpts.weight,
        args: this._kbOpts.args,
        when: kbWhen,
        primary: this._kbOpts.primary,
        secondary: this._kbOpts.secondary,
        win: this._kbOpts.win,
        linux: this._kbOpts.linux,
        mac: this._kbOpts.mac,
        description: this._description
      });
    } else {
      CommandsRegistry.registerCommand({
        id: this.id,
        handler: (accessor, args) => this.runCommand(accessor, args),
        description: this._description
      });
    }
  }
  _registerMenuItem(item) {
    MenuRegistry.appendMenuItem(item.menuId, {
      group: item.group,
      command: {
        id: this.id,
        title: item.title,
        icon: item.icon
      },
      when: item.when,
      order: item.order
    });
  }
};
var MultiCommand = class extends Command {
  constructor() {
    super(...arguments);
    this._implementations = [];
  }
  addImplementation(priority, implementation) {
    this._implementations.push([priority, implementation]);
    this._implementations.sort((a2, b2) => b2[0] - a2[0]);
    return {
      dispose: () => {
        for (let i3 = 0; i3 < this._implementations.length; i3++) {
          if (this._implementations[i3][1] === implementation) {
            this._implementations.splice(i3, 1);
            return;
          }
        }
      }
    };
  }
  runCommand(accessor, args) {
    for (const impl of this._implementations) {
      if (impl[1](accessor, args)) {
        return;
      }
    }
  }
};
var ProxyCommand = class extends Command {
  constructor(command, opts) {
    super(opts);
    this.command = command;
  }
  runCommand(accessor, args) {
    return this.command.runCommand(accessor, args);
  }
};
var EditorCommand = class extends Command {
  static bindToContribution(controllerGetter) {
    return class EditorControllerCommandImpl extends EditorCommand {
      constructor(opts) {
        super(opts);
        this._callback = opts.handler;
      }
      runEditorCommand(accessor, editor2, args) {
        const controller = controllerGetter(editor2);
        if (controller) {
          this._callback(controllerGetter(editor2), args);
        }
      }
    };
  }
  runCommand(accessor, args) {
    const codeEditorService = accessor.get(ICodeEditorService);
    const editor2 = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
    if (!editor2) {
      return;
    }
    return editor2.invokeWithinContext((editorAccessor) => {
      const kbService = editorAccessor.get(IContextKeyService);
      if (!kbService.contextMatchesRules(withNullAsUndefined(this.precondition))) {
        return;
      }
      return this.runEditorCommand(editorAccessor, editor2, args);
    });
  }
};
var EditorAction = class extends EditorCommand {
  constructor(opts) {
    super(EditorAction.convertOptions(opts));
    this.label = opts.label;
    this.alias = opts.alias;
  }
  static convertOptions(opts) {
    let menuOpts;
    if (Array.isArray(opts.menuOpts)) {
      menuOpts = opts.menuOpts;
    } else if (opts.menuOpts) {
      menuOpts = [opts.menuOpts];
    } else {
      menuOpts = [];
    }
    function withDefaults(item) {
      if (!item.menuId) {
        item.menuId = MenuId.EditorContext;
      }
      if (!item.title) {
        item.title = opts.label;
      }
      item.when = ContextKeyExpr.and(opts.precondition, item.when);
      return item;
    }
    if (Array.isArray(opts.contextMenuOpts)) {
      menuOpts.push(...opts.contextMenuOpts.map(withDefaults));
    } else if (opts.contextMenuOpts) {
      menuOpts.push(withDefaults(opts.contextMenuOpts));
    }
    opts.menuOpts = menuOpts;
    return opts;
  }
  runEditorCommand(accessor, editor2, args) {
    this.reportTelemetry(accessor, editor2);
    return this.run(accessor, editor2, args || {});
  }
  reportTelemetry(accessor, editor2) {
    accessor.get(ITelemetryService).publicLog2("editorActionInvoked", {name: this.label, id: this.id});
  }
};
function registerEditorCommand(editorCommand) {
  EditorContributionRegistry.INSTANCE.registerEditorCommand(editorCommand);
  return editorCommand;
}
function registerEditorAction(ctor) {
  const action = new ctor();
  EditorContributionRegistry.INSTANCE.registerEditorAction(action);
  return action;
}
function registerEditorContribution(id3, ctor) {
  EditorContributionRegistry.INSTANCE.registerEditorContribution(id3, ctor);
}
var EditorExtensionsRegistry;
(function(EditorExtensionsRegistry2) {
  function getEditorCommand(commandId) {
    return EditorContributionRegistry.INSTANCE.getEditorCommand(commandId);
  }
  EditorExtensionsRegistry2.getEditorCommand = getEditorCommand;
  function getEditorActions() {
    return EditorContributionRegistry.INSTANCE.getEditorActions();
  }
  EditorExtensionsRegistry2.getEditorActions = getEditorActions;
  function getEditorContributions() {
    return EditorContributionRegistry.INSTANCE.getEditorContributions();
  }
  EditorExtensionsRegistry2.getEditorContributions = getEditorContributions;
  function getSomeEditorContributions(ids) {
    return EditorContributionRegistry.INSTANCE.getEditorContributions().filter((c3) => ids.indexOf(c3.id) >= 0);
  }
  EditorExtensionsRegistry2.getSomeEditorContributions = getSomeEditorContributions;
  function getDiffEditorContributions() {
    return EditorContributionRegistry.INSTANCE.getDiffEditorContributions();
  }
  EditorExtensionsRegistry2.getDiffEditorContributions = getDiffEditorContributions;
})(EditorExtensionsRegistry || (EditorExtensionsRegistry = {}));
var Extensions$3 = {
  EditorCommonContributions: "editor.contributions"
};
var EditorContributionRegistry = class {
  constructor() {
    this.editorContributions = [];
    this.diffEditorContributions = [];
    this.editorActions = [];
    this.editorCommands = Object.create(null);
  }
  registerEditorContribution(id3, ctor) {
    this.editorContributions.push({id: id3, ctor});
  }
  getEditorContributions() {
    return this.editorContributions.slice(0);
  }
  getDiffEditorContributions() {
    return this.diffEditorContributions.slice(0);
  }
  registerEditorAction(action) {
    action.register();
    this.editorActions.push(action);
  }
  getEditorActions() {
    return this.editorActions.slice(0);
  }
  registerEditorCommand(editorCommand) {
    editorCommand.register();
    this.editorCommands[editorCommand.id] = editorCommand;
  }
  getEditorCommand(commandId) {
    return this.editorCommands[commandId] || null;
  }
};
EditorContributionRegistry.INSTANCE = new EditorContributionRegistry();
Registry$1.add(Extensions$3.EditorCommonContributions, EditorContributionRegistry.INSTANCE);
function registerCommand(command) {
  command.register();
  return command;
}
var UndoCommand = registerCommand(new MultiCommand({
  id: "undo",
  precondition: void 0,
  kbOpts: {
    weight: 0,
    primary: 2048 | 56
  },
  menuOpts: [{
    menuId: MenuId.MenubarEditMenu,
    group: "1_do",
    title: localize({key: "miUndo", comment: ["&& denotes a mnemonic"]}, "&&Undo"),
    order: 1
  }, {
    menuId: MenuId.CommandPalette,
    group: "",
    title: localize("undo", "Undo"),
    order: 1
  }]
}));
registerCommand(new ProxyCommand(UndoCommand, {id: "default:undo", precondition: void 0}));
var RedoCommand = registerCommand(new MultiCommand({
  id: "redo",
  precondition: void 0,
  kbOpts: {
    weight: 0,
    primary: 2048 | 55,
    secondary: [2048 | 1024 | 56],
    mac: {primary: 2048 | 1024 | 56}
  },
  menuOpts: [{
    menuId: MenuId.MenubarEditMenu,
    group: "1_do",
    title: localize({key: "miRedo", comment: ["&& denotes a mnemonic"]}, "&&Redo"),
    order: 2
  }, {
    menuId: MenuId.CommandPalette,
    group: "",
    title: localize("redo", "Redo"),
    order: 1
  }]
}));
registerCommand(new ProxyCommand(RedoCommand, {id: "default:redo", precondition: void 0}));
var SelectAllCommand = registerCommand(new MultiCommand({
  id: "editor.action.selectAll",
  precondition: void 0,
  kbOpts: {
    weight: 0,
    kbExpr: null,
    primary: 2048 | 31
  },
  menuOpts: [{
    menuId: MenuId.MenubarSelectionMenu,
    group: "1_basic",
    title: localize({key: "miSelectAll", comment: ["&& denotes a mnemonic"]}, "&&Select All"),
    order: 1
  }, {
    menuId: MenuId.CommandPalette,
    group: "",
    title: localize("selectAll", "Select All"),
    order: 1
  }]
}));
var FastDomNode = class {
  constructor(domNode) {
    this.domNode = domNode;
    this._maxWidth = -1;
    this._width = -1;
    this._height = -1;
    this._top = -1;
    this._left = -1;
    this._bottom = -1;
    this._right = -1;
    this._fontFamily = "";
    this._fontWeight = "";
    this._fontSize = -1;
    this._fontFeatureSettings = "";
    this._lineHeight = -1;
    this._letterSpacing = -100;
    this._className = "";
    this._display = "";
    this._position = "";
    this._visibility = "";
    this._backgroundColor = "";
    this._layerHint = false;
    this._contain = "none";
    this._boxShadow = "";
  }
  setMaxWidth(maxWidth) {
    if (this._maxWidth === maxWidth) {
      return;
    }
    this._maxWidth = maxWidth;
    this.domNode.style.maxWidth = this._maxWidth + "px";
  }
  setWidth(width2) {
    if (this._width === width2) {
      return;
    }
    this._width = width2;
    this.domNode.style.width = this._width + "px";
  }
  setHeight(height) {
    if (this._height === height) {
      return;
    }
    this._height = height;
    this.domNode.style.height = this._height + "px";
  }
  setTop(top2) {
    if (this._top === top2) {
      return;
    }
    this._top = top2;
    this.domNode.style.top = this._top + "px";
  }
  unsetTop() {
    if (this._top === -1) {
      return;
    }
    this._top = -1;
    this.domNode.style.top = "";
  }
  setLeft(left2) {
    if (this._left === left2) {
      return;
    }
    this._left = left2;
    this.domNode.style.left = this._left + "px";
  }
  setBottom(bottom2) {
    if (this._bottom === bottom2) {
      return;
    }
    this._bottom = bottom2;
    this.domNode.style.bottom = this._bottom + "px";
  }
  setRight(right2) {
    if (this._right === right2) {
      return;
    }
    this._right = right2;
    this.domNode.style.right = this._right + "px";
  }
  setFontFamily(fontFamily) {
    if (this._fontFamily === fontFamily) {
      return;
    }
    this._fontFamily = fontFamily;
    this.domNode.style.fontFamily = this._fontFamily;
  }
  setFontWeight(fontWeight) {
    if (this._fontWeight === fontWeight) {
      return;
    }
    this._fontWeight = fontWeight;
    this.domNode.style.fontWeight = this._fontWeight;
  }
  setFontSize(fontSize) {
    if (this._fontSize === fontSize) {
      return;
    }
    this._fontSize = fontSize;
    this.domNode.style.fontSize = this._fontSize + "px";
  }
  setFontFeatureSettings(fontFeatureSettings) {
    if (this._fontFeatureSettings === fontFeatureSettings) {
      return;
    }
    this._fontFeatureSettings = fontFeatureSettings;
    this.domNode.style.fontFeatureSettings = this._fontFeatureSettings;
  }
  setLineHeight(lineHeight) {
    if (this._lineHeight === lineHeight) {
      return;
    }
    this._lineHeight = lineHeight;
    this.domNode.style.lineHeight = this._lineHeight + "px";
  }
  setLetterSpacing(letterSpacing) {
    if (this._letterSpacing === letterSpacing) {
      return;
    }
    this._letterSpacing = letterSpacing;
    this.domNode.style.letterSpacing = this._letterSpacing + "px";
  }
  setClassName(className) {
    if (this._className === className) {
      return;
    }
    this._className = className;
    this.domNode.className = this._className;
  }
  toggleClassName(className, shouldHaveIt) {
    toggleClass(this.domNode, className, shouldHaveIt);
    this._className = this.domNode.className;
  }
  setDisplay(display) {
    if (this._display === display) {
      return;
    }
    this._display = display;
    this.domNode.style.display = this._display;
  }
  setPosition(position2) {
    if (this._position === position2) {
      return;
    }
    this._position = position2;
    this.domNode.style.position = this._position;
  }
  setVisibility(visibility) {
    if (this._visibility === visibility) {
      return;
    }
    this._visibility = visibility;
    this.domNode.style.visibility = this._visibility;
  }
  setBackgroundColor(backgroundColor) {
    if (this._backgroundColor === backgroundColor) {
      return;
    }
    this._backgroundColor = backgroundColor;
    this.domNode.style.backgroundColor = this._backgroundColor;
  }
  setLayerHinting(layerHint) {
    if (this._layerHint === layerHint) {
      return;
    }
    this._layerHint = layerHint;
    this.domNode.style.transform = this._layerHint ? "translate3d(0px, 0px, 0px)" : "";
  }
  setBoxShadow(boxShadow) {
    if (this._boxShadow === boxShadow) {
      return;
    }
    this._boxShadow = boxShadow;
    this.domNode.style.boxShadow = boxShadow;
  }
  setContain(contain) {
    if (this._contain === contain) {
      return;
    }
    this._contain = contain;
    this.domNode.style.contain = this._contain;
  }
  setAttribute(name, value) {
    this.domNode.setAttribute(name, value);
  }
  removeAttribute(name) {
    this.domNode.removeAttribute(name);
  }
  appendChild(child) {
    this.domNode.appendChild(child.domNode);
  }
  removeChild(child) {
    this.domNode.removeChild(child.domNode);
  }
};
function createFastDomNode(domNode) {
  return new FastDomNode(domNode);
}
var memoizeId = 0;
function createMemoizer() {
  const memoizeKeyPrefix = `$memoize${memoizeId++}`;
  let self2 = void 0;
  const result = function memoize3(target, key, descriptor) {
    let fnKey = null;
    let fn = null;
    if (typeof descriptor.value === "function") {
      fnKey = "value";
      fn = descriptor.value;
      if (fn.length !== 0) {
        console.warn("Memoize should only be used in functions with zero parameters");
      }
    } else if (typeof descriptor.get === "function") {
      fnKey = "get";
      fn = descriptor.get;
    }
    if (!fn) {
      throw new Error("not supported");
    }
    const memoizeKey = `${memoizeKeyPrefix}:${key}`;
    descriptor[fnKey] = function(...args) {
      self2 = this;
      if (!this.hasOwnProperty(memoizeKey)) {
        Object.defineProperty(this, memoizeKey, {
          configurable: true,
          enumerable: false,
          writable: true,
          value: fn.apply(this, args)
        });
      }
      return this[memoizeKey];
    };
  };
  result.clear = () => {
    if (typeof self2 === "undefined") {
      return;
    }
    Object.getOwnPropertyNames(self2).forEach((property2) => {
      if (property2.indexOf(memoizeKeyPrefix) === 0) {
        delete self2[property2];
      }
    });
  };
  return result;
}
function memoize(target, key, descriptor) {
  return createMemoizer()(target, key, descriptor);
}
var __decorate$4 = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var EventType$1;
(function(EventType2) {
  EventType2.Tap = "-monaco-gesturetap";
  EventType2.Change = "-monaco-gesturechange";
  EventType2.Start = "-monaco-gesturestart";
  EventType2.End = "-monaco-gesturesend";
  EventType2.Contextmenu = "-monaco-gesturecontextmenu";
})(EventType$1 || (EventType$1 = {}));
var Gesture = class extends Disposable {
  constructor() {
    super();
    this.dispatched = false;
    this.activeTouches = {};
    this.handle = null;
    this.targets = [];
    this.ignoreTargets = [];
    this._lastSetTapCountTime = 0;
    this._register(addDisposableListener(document, "touchstart", (e2) => this.onTouchStart(e2), {passive: false}));
    this._register(addDisposableListener(document, "touchend", (e2) => this.onTouchEnd(e2)));
    this._register(addDisposableListener(document, "touchmove", (e2) => this.onTouchMove(e2), {passive: false}));
  }
  static addTarget(element) {
    if (!Gesture.isTouchDevice()) {
      return Disposable.None;
    }
    if (!Gesture.INSTANCE) {
      Gesture.INSTANCE = new Gesture();
    }
    Gesture.INSTANCE.targets.push(element);
    return {
      dispose: () => {
        Gesture.INSTANCE.targets = Gesture.INSTANCE.targets.filter((t5) => t5 !== element);
      }
    };
  }
  static ignoreTarget(element) {
    if (!Gesture.isTouchDevice()) {
      return Disposable.None;
    }
    if (!Gesture.INSTANCE) {
      Gesture.INSTANCE = new Gesture();
    }
    Gesture.INSTANCE.ignoreTargets.push(element);
    return {
      dispose: () => {
        Gesture.INSTANCE.ignoreTargets = Gesture.INSTANCE.ignoreTargets.filter((t5) => t5 !== element);
      }
    };
  }
  static isTouchDevice() {
    return "ontouchstart" in window || navigator.maxTouchPoints > 0 || window.navigator.msMaxTouchPoints > 0;
  }
  dispose() {
    if (this.handle) {
      this.handle.dispose();
      this.handle = null;
    }
    super.dispose();
  }
  onTouchStart(e2) {
    let timestamp = Date.now();
    if (this.handle) {
      this.handle.dispose();
      this.handle = null;
    }
    for (let i3 = 0, len2 = e2.targetTouches.length; i3 < len2; i3++) {
      let touch = e2.targetTouches.item(i3);
      this.activeTouches[touch.identifier] = {
        id: touch.identifier,
        initialTarget: touch.target,
        initialTimeStamp: timestamp,
        initialPageX: touch.pageX,
        initialPageY: touch.pageY,
        rollingTimestamps: [timestamp],
        rollingPageX: [touch.pageX],
        rollingPageY: [touch.pageY]
      };
      let evt = this.newGestureEvent(EventType$1.Start, touch.target);
      evt.pageX = touch.pageX;
      evt.pageY = touch.pageY;
      this.dispatchEvent(evt);
    }
    if (this.dispatched) {
      e2.preventDefault();
      e2.stopPropagation();
      this.dispatched = false;
    }
  }
  onTouchEnd(e2) {
    let timestamp = Date.now();
    let activeTouchCount = Object.keys(this.activeTouches).length;
    for (let i3 = 0, len2 = e2.changedTouches.length; i3 < len2; i3++) {
      let touch = e2.changedTouches.item(i3);
      if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
        console.warn("move of an UNKNOWN touch", touch);
        continue;
      }
      let data2 = this.activeTouches[touch.identifier], holdTime = Date.now() - data2.initialTimeStamp;
      if (holdTime < Gesture.HOLD_DELAY && Math.abs(data2.initialPageX - tail(data2.rollingPageX)) < 30 && Math.abs(data2.initialPageY - tail(data2.rollingPageY)) < 30) {
        let evt = this.newGestureEvent(EventType$1.Tap, data2.initialTarget);
        evt.pageX = tail(data2.rollingPageX);
        evt.pageY = tail(data2.rollingPageY);
        this.dispatchEvent(evt);
      } else if (holdTime >= Gesture.HOLD_DELAY && Math.abs(data2.initialPageX - tail(data2.rollingPageX)) < 30 && Math.abs(data2.initialPageY - tail(data2.rollingPageY)) < 30) {
        let evt = this.newGestureEvent(EventType$1.Contextmenu, data2.initialTarget);
        evt.pageX = tail(data2.rollingPageX);
        evt.pageY = tail(data2.rollingPageY);
        this.dispatchEvent(evt);
      } else if (activeTouchCount === 1) {
        let finalX = tail(data2.rollingPageX);
        let finalY = tail(data2.rollingPageY);
        let deltaT = tail(data2.rollingTimestamps) - data2.rollingTimestamps[0];
        let deltaX = finalX - data2.rollingPageX[0];
        let deltaY = finalY - data2.rollingPageY[0];
        const dispatchTo = this.targets.filter((t5) => data2.initialTarget instanceof Node && t5.contains(data2.initialTarget));
        this.inertia(dispatchTo, timestamp, Math.abs(deltaX) / deltaT, deltaX > 0 ? 1 : -1, finalX, Math.abs(deltaY) / deltaT, deltaY > 0 ? 1 : -1, finalY);
      }
      this.dispatchEvent(this.newGestureEvent(EventType$1.End, data2.initialTarget));
      delete this.activeTouches[touch.identifier];
    }
    if (this.dispatched) {
      e2.preventDefault();
      e2.stopPropagation();
      this.dispatched = false;
    }
  }
  newGestureEvent(type, initialTarget) {
    let event = document.createEvent("CustomEvent");
    event.initEvent(type, false, true);
    event.initialTarget = initialTarget;
    event.tapCount = 0;
    return event;
  }
  dispatchEvent(event) {
    if (event.type === EventType$1.Tap) {
      const currentTime = new Date().getTime();
      let setTapCount = 0;
      if (currentTime - this._lastSetTapCountTime > Gesture.CLEAR_TAP_COUNT_TIME) {
        setTapCount = 1;
      } else {
        setTapCount = 2;
      }
      this._lastSetTapCountTime = currentTime;
      event.tapCount = setTapCount;
    } else if (event.type === EventType$1.Change || event.type === EventType$1.Contextmenu) {
      this._lastSetTapCountTime = 0;
    }
    for (let i3 = 0; i3 < this.ignoreTargets.length; i3++) {
      if (event.initialTarget instanceof Node && this.ignoreTargets[i3].contains(event.initialTarget)) {
        return;
      }
    }
    this.targets.forEach((target) => {
      if (event.initialTarget instanceof Node && target.contains(event.initialTarget)) {
        target.dispatchEvent(event);
        this.dispatched = true;
      }
    });
  }
  inertia(dispatchTo, t1, vX, dirX, x2, vY, dirY, y3) {
    this.handle = scheduleAtNextAnimationFrame(() => {
      let now3 = Date.now();
      let deltaT = now3 - t1, delta_pos_x = 0, delta_pos_y = 0, stopped = true;
      vX += Gesture.SCROLL_FRICTION * deltaT;
      vY += Gesture.SCROLL_FRICTION * deltaT;
      if (vX > 0) {
        stopped = false;
        delta_pos_x = dirX * vX * deltaT;
      }
      if (vY > 0) {
        stopped = false;
        delta_pos_y = dirY * vY * deltaT;
      }
      let evt = this.newGestureEvent(EventType$1.Change);
      evt.translationX = delta_pos_x;
      evt.translationY = delta_pos_y;
      dispatchTo.forEach((d2) => d2.dispatchEvent(evt));
      if (!stopped) {
        this.inertia(dispatchTo, now3, vX, dirX, x2 + delta_pos_x, vY, dirY, y3 + delta_pos_y);
      }
    });
  }
  onTouchMove(e2) {
    let timestamp = Date.now();
    for (let i3 = 0, len2 = e2.changedTouches.length; i3 < len2; i3++) {
      let touch = e2.changedTouches.item(i3);
      if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
        console.warn("end of an UNKNOWN touch", touch);
        continue;
      }
      let data2 = this.activeTouches[touch.identifier];
      let evt = this.newGestureEvent(EventType$1.Change, data2.initialTarget);
      evt.translationX = touch.pageX - tail(data2.rollingPageX);
      evt.translationY = touch.pageY - tail(data2.rollingPageY);
      evt.pageX = touch.pageX;
      evt.pageY = touch.pageY;
      this.dispatchEvent(evt);
      if (data2.rollingPageX.length > 3) {
        data2.rollingPageX.shift();
        data2.rollingPageY.shift();
        data2.rollingTimestamps.shift();
      }
      data2.rollingPageX.push(touch.pageX);
      data2.rollingPageY.push(touch.pageY);
      data2.rollingTimestamps.push(timestamp);
    }
    if (this.dispatched) {
      e2.preventDefault();
      e2.stopPropagation();
      this.dispatched = false;
    }
  }
};
Gesture.SCROLL_FRICTION = -5e-3;
Gesture.HOLD_DELAY = 700;
Gesture.CLEAR_TAP_COUNT_TIME = 400;
__decorate$4([
  memoize
], Gesture, "isTouchDevice", null);
function standardMouseMoveMerger(lastEvent, currentEvent) {
  let ev = new StandardMouseEvent(currentEvent);
  ev.preventDefault();
  return {
    leftButton: ev.leftButton,
    buttons: ev.buttons,
    posx: ev.posx,
    posy: ev.posy
  };
}
var GlobalMouseMoveMonitor = class {
  constructor() {
    this._hooks = new DisposableStore();
    this._mouseMoveEventMerger = null;
    this._mouseMoveCallback = null;
    this._onStopCallback = null;
  }
  dispose() {
    this.stopMonitoring(false);
    this._hooks.dispose();
  }
  stopMonitoring(invokeStopCallback) {
    if (!this.isMonitoring()) {
      return;
    }
    this._hooks.clear();
    this._mouseMoveEventMerger = null;
    this._mouseMoveCallback = null;
    const onStopCallback = this._onStopCallback;
    this._onStopCallback = null;
    if (invokeStopCallback && onStopCallback) {
      onStopCallback();
    }
  }
  isMonitoring() {
    return !!this._mouseMoveEventMerger;
  }
  startMonitoring(initialElement, initialButtons, mouseMoveEventMerger, mouseMoveCallback, onStopCallback) {
    if (this.isMonitoring()) {
      return;
    }
    this._mouseMoveEventMerger = mouseMoveEventMerger;
    this._mouseMoveCallback = mouseMoveCallback;
    this._onStopCallback = onStopCallback;
    const windowChain = IframeUtils.getSameOriginWindowChain();
    const mouseMove = isIOS && BrowserFeatures.pointerEvents ? "pointermove" : "mousemove";
    const mouseUp = isIOS && BrowserFeatures.pointerEvents ? "pointerup" : "mouseup";
    const listenTo = windowChain.map((element) => element.window.document);
    const shadowRoot = getShadowRoot(initialElement);
    if (shadowRoot) {
      listenTo.unshift(shadowRoot);
    }
    for (const element of listenTo) {
      this._hooks.add(addDisposableThrottledListener(element, mouseMove, (data2) => {
        if (data2.buttons !== initialButtons) {
          this.stopMonitoring(true);
          return;
        }
        this._mouseMoveCallback(data2);
      }, (lastEvent, currentEvent) => this._mouseMoveEventMerger(lastEvent, currentEvent)));
      this._hooks.add(addDisposableListener(element, mouseUp, (e2) => this.stopMonitoring(true)));
    }
    if (IframeUtils.hasDifferentOriginAncestor()) {
      let lastSameOriginAncestor = windowChain[windowChain.length - 1];
      this._hooks.add(addDisposableListener(lastSameOriginAncestor.window.document, "mouseout", (browserEvent) => {
        let e2 = new StandardMouseEvent(browserEvent);
        if (e2.target.tagName.toLowerCase() === "html") {
          this.stopMonitoring(true);
        }
      }));
      this._hooks.add(addDisposableListener(lastSameOriginAncestor.window.document, "mouseover", (browserEvent) => {
        let e2 = new StandardMouseEvent(browserEvent);
        if (e2.target.tagName.toLowerCase() === "html") {
          this.stopMonitoring(true);
        }
      }));
      this._hooks.add(addDisposableListener(lastSameOriginAncestor.window.document.body, "mouseleave", (browserEvent) => {
        this.stopMonitoring(true);
      }));
    }
  }
};
var PageCoordinates = class {
  constructor(x2, y3) {
    this.x = x2;
    this.y = y3;
  }
  toClientCoordinates() {
    return new ClientCoordinates(this.x - StandardWindow.scrollX, this.y - StandardWindow.scrollY);
  }
};
var ClientCoordinates = class {
  constructor(clientX, clientY) {
    this.clientX = clientX;
    this.clientY = clientY;
  }
  toPageCoordinates() {
    return new PageCoordinates(this.clientX + StandardWindow.scrollX, this.clientY + StandardWindow.scrollY);
  }
};
var EditorPagePosition = class {
  constructor(x2, y3, width2, height) {
    this.x = x2;
    this.y = y3;
    this.width = width2;
    this.height = height;
  }
};
function createEditorPagePosition(editorViewDomNode) {
  const editorPos = getDomNodePagePosition(editorViewDomNode);
  return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height);
}
var EditorMouseEvent = class extends StandardMouseEvent {
  constructor(e2, editorViewDomNode) {
    super(e2);
    this.pos = new PageCoordinates(this.posx, this.posy);
    this.editorPos = createEditorPagePosition(editorViewDomNode);
  }
};
var EditorMouseEventFactory = class {
  constructor(editorViewDomNode) {
    this._editorViewDomNode = editorViewDomNode;
  }
  _create(e2) {
    return new EditorMouseEvent(e2, this._editorViewDomNode);
  }
  onContextMenu(target, callback) {
    return addDisposableListener(target, "contextmenu", (e2) => {
      callback(this._create(e2));
    });
  }
  onMouseUp(target, callback) {
    return addDisposableListener(target, "mouseup", (e2) => {
      callback(this._create(e2));
    });
  }
  onMouseDown(target, callback) {
    return addDisposableListener(target, "mousedown", (e2) => {
      callback(this._create(e2));
    });
  }
  onMouseLeave(target, callback) {
    return addDisposableNonBubblingMouseOutListener(target, (e2) => {
      callback(this._create(e2));
    });
  }
  onMouseMoveThrottled(target, callback, merger, minimumTimeMs) {
    const myMerger = (lastEvent, currentEvent) => {
      return merger(lastEvent, this._create(currentEvent));
    };
    return addDisposableThrottledListener(target, "mousemove", callback, myMerger, minimumTimeMs);
  }
};
var EditorPointerEventFactory = class {
  constructor(editorViewDomNode) {
    this._editorViewDomNode = editorViewDomNode;
  }
  _create(e2) {
    return new EditorMouseEvent(e2, this._editorViewDomNode);
  }
  onPointerUp(target, callback) {
    return addDisposableListener(target, "pointerup", (e2) => {
      callback(this._create(e2));
    });
  }
  onPointerDown(target, callback) {
    return addDisposableListener(target, "pointerdown", (e2) => {
      callback(this._create(e2));
    });
  }
  onPointerLeave(target, callback) {
    return addDisposableNonBubblingPointerOutListener(target, (e2) => {
      callback(this._create(e2));
    });
  }
  onPointerMoveThrottled(target, callback, merger, minimumTimeMs) {
    const myMerger = (lastEvent, currentEvent) => {
      return merger(lastEvent, this._create(currentEvent));
    };
    return addDisposableThrottledListener(target, "pointermove", callback, myMerger, minimumTimeMs);
  }
};
var GlobalEditorMouseMoveMonitor = class extends Disposable {
  constructor(editorViewDomNode) {
    super();
    this._editorViewDomNode = editorViewDomNode;
    this._globalMouseMoveMonitor = this._register(new GlobalMouseMoveMonitor());
    this._keydownListener = null;
  }
  startMonitoring(initialElement, initialButtons, merger, mouseMoveCallback, onStopCallback) {
    this._keydownListener = addStandardDisposableListener(document, "keydown", (e2) => {
      const kb2 = e2.toKeybinding();
      if (kb2.isModifierKey()) {
        return;
      }
      this._globalMouseMoveMonitor.stopMonitoring(true);
    }, true);
    const myMerger = (lastEvent, currentEvent) => {
      return merger(lastEvent, new EditorMouseEvent(currentEvent, this._editorViewDomNode));
    };
    this._globalMouseMoveMonitor.startMonitoring(initialElement, initialButtons, myMerger, mouseMoveCallback, () => {
      this._keydownListener.dispose();
      onStopCallback();
    });
  }
};
var ViewEventHandler = class extends Disposable {
  constructor() {
    super();
    this._shouldRender = true;
  }
  shouldRender() {
    return this._shouldRender;
  }
  forceShouldRender() {
    this._shouldRender = true;
  }
  setShouldRender() {
    this._shouldRender = true;
  }
  onDidRender() {
    this._shouldRender = false;
  }
  onConfigurationChanged(e2) {
    return false;
  }
  onCursorStateChanged(e2) {
    return false;
  }
  onDecorationsChanged(e2) {
    return false;
  }
  onFlushed(e2) {
    return false;
  }
  onFocusChanged(e2) {
    return false;
  }
  onLanguageConfigurationChanged(e2) {
    return false;
  }
  onLineMappingChanged(e2) {
    return false;
  }
  onLinesChanged(e2) {
    return false;
  }
  onLinesDeleted(e2) {
    return false;
  }
  onLinesInserted(e2) {
    return false;
  }
  onRevealRangeRequest(e2) {
    return false;
  }
  onScrollChanged(e2) {
    return false;
  }
  onThemeChanged(e2) {
    return false;
  }
  onTokensChanged(e2) {
    return false;
  }
  onTokensColorsChanged(e2) {
    return false;
  }
  onZonesChanged(e2) {
    return false;
  }
  handleEvents(events) {
    let shouldRender = false;
    for (let i3 = 0, len2 = events.length; i3 < len2; i3++) {
      let e2 = events[i3];
      switch (e2.type) {
        case 0:
          if (this.onConfigurationChanged(e2)) {
            shouldRender = true;
          }
          break;
        case 1:
          if (this.onCursorStateChanged(e2)) {
            shouldRender = true;
          }
          break;
        case 2:
          if (this.onDecorationsChanged(e2)) {
            shouldRender = true;
          }
          break;
        case 3:
          if (this.onFlushed(e2)) {
            shouldRender = true;
          }
          break;
        case 4:
          if (this.onFocusChanged(e2)) {
            shouldRender = true;
          }
          break;
        case 5:
          if (this.onLanguageConfigurationChanged(e2)) {
            shouldRender = true;
          }
          break;
        case 6:
          if (this.onLineMappingChanged(e2)) {
            shouldRender = true;
          }
          break;
        case 7:
          if (this.onLinesChanged(e2)) {
            shouldRender = true;
          }
          break;
        case 8:
          if (this.onLinesDeleted(e2)) {
            shouldRender = true;
          }
          break;
        case 9:
          if (this.onLinesInserted(e2)) {
            shouldRender = true;
          }
          break;
        case 10:
          if (this.onRevealRangeRequest(e2)) {
            shouldRender = true;
          }
          break;
        case 11:
          if (this.onScrollChanged(e2)) {
            shouldRender = true;
          }
          break;
        case 13:
          if (this.onTokensChanged(e2)) {
            shouldRender = true;
          }
          break;
        case 12:
          if (this.onThemeChanged(e2)) {
            shouldRender = true;
          }
          break;
        case 14:
          if (this.onTokensColorsChanged(e2)) {
            shouldRender = true;
          }
          break;
        case 15:
          if (this.onZonesChanged(e2)) {
            shouldRender = true;
          }
          break;
        default:
          console.info("View received unknown event: ");
          console.info(e2);
      }
    }
    if (shouldRender) {
      this._shouldRender = true;
    }
  }
};
var ViewPart = class extends ViewEventHandler {
  constructor(context2) {
    super();
    this._context = context2;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    super.dispose();
  }
};
var PartFingerprints = class {
  static write(target, partId) {
    if (target instanceof FastDomNode) {
      target.setAttribute("data-mprt", String(partId));
    } else {
      target.setAttribute("data-mprt", String(partId));
    }
  }
  static read(target) {
    const r3 = target.getAttribute("data-mprt");
    if (r3 === null) {
      return 0;
    }
    return parseInt(r3, 10);
  }
  static collect(child, stopAt) {
    let result = [], resultLen = 0;
    while (child && child !== document.body) {
      if (child === stopAt) {
        break;
      }
      if (child.nodeType === child.ELEMENT_NODE) {
        result[resultLen++] = this.read(child);
      }
      child = child.parentElement;
    }
    const r3 = new Uint8Array(resultLen);
    for (let i3 = 0; i3 < resultLen; i3++) {
      r3[i3] = result[resultLen - i3 - 1];
    }
    return r3;
  }
};
var RestrictedRenderingContext = class {
  constructor(viewLayout, viewportData) {
    this._viewLayout = viewLayout;
    this.viewportData = viewportData;
    this.scrollWidth = this._viewLayout.getScrollWidth();
    this.scrollHeight = this._viewLayout.getScrollHeight();
    this.visibleRange = this.viewportData.visibleRange;
    this.bigNumbersDelta = this.viewportData.bigNumbersDelta;
    const vInfo = this._viewLayout.getCurrentViewport();
    this.scrollTop = vInfo.top;
    this.scrollLeft = vInfo.left;
    this.viewportWidth = vInfo.width;
    this.viewportHeight = vInfo.height;
  }
  getScrolledTopFromAbsoluteTop(absoluteTop) {
    return absoluteTop - this.scrollTop;
  }
  getVerticalOffsetForLineNumber(lineNumber) {
    return this._viewLayout.getVerticalOffsetForLineNumber(lineNumber);
  }
  getDecorationsInViewport() {
    return this.viewportData.getDecorationsInViewport();
  }
};
var RenderingContext = class extends RestrictedRenderingContext {
  constructor(viewLayout, viewportData, viewLines) {
    super(viewLayout, viewportData);
    this._viewLines = viewLines;
  }
  linesVisibleRangesForRange(range3, includeNewLines) {
    return this._viewLines.linesVisibleRangesForRange(range3, includeNewLines);
  }
  visibleRangeForPosition(position2) {
    return this._viewLines.visibleRangeForPosition(position2);
  }
};
var LineVisibleRanges = class {
  constructor(outsideRenderedLine, lineNumber, ranges) {
    this.outsideRenderedLine = outsideRenderedLine;
    this.lineNumber = lineNumber;
    this.ranges = ranges;
  }
};
var HorizontalRange = class {
  constructor(left2, width2) {
    this.left = Math.round(left2);
    this.width = Math.round(width2);
  }
  toString() {
    return `[${this.left},${this.width}]`;
  }
};
var HorizontalPosition = class {
  constructor(outsideRenderedLine, left2) {
    this.outsideRenderedLine = outsideRenderedLine;
    this.left = Math.round(left2);
  }
};
var VisibleRanges = class {
  constructor(outsideRenderedLine, ranges) {
    this.outsideRenderedLine = outsideRenderedLine;
    this.ranges = ranges;
  }
};
var FloatHorizontalRange = class {
  constructor(left2, width2) {
    this.left = left2;
    this.width = width2;
  }
  toString() {
    return `[${this.left},${this.width}]`;
  }
  static compare(a2, b2) {
    return a2.left - b2.left;
  }
};
var RangeUtil = class {
  static _createRange() {
    if (!this._handyReadyRange) {
      this._handyReadyRange = document.createRange();
    }
    return this._handyReadyRange;
  }
  static _detachRange(range3, endNode) {
    range3.selectNodeContents(endNode);
  }
  static _readClientRects(startElement, startOffset, endElement, endOffset, endNode) {
    const range3 = this._createRange();
    try {
      range3.setStart(startElement, startOffset);
      range3.setEnd(endElement, endOffset);
      return range3.getClientRects();
    } catch (e2) {
      return null;
    } finally {
      this._detachRange(range3, endNode);
    }
  }
  static _mergeAdjacentRanges(ranges) {
    if (ranges.length === 1) {
      return [new HorizontalRange(ranges[0].left, ranges[0].width)];
    }
    ranges.sort(FloatHorizontalRange.compare);
    let result = [], resultLen = 0;
    let prevLeft = ranges[0].left;
    let prevWidth = ranges[0].width;
    for (let i3 = 1, len2 = ranges.length; i3 < len2; i3++) {
      const range3 = ranges[i3];
      const myLeft = range3.left;
      const myWidth = range3.width;
      if (prevLeft + prevWidth + 0.9 >= myLeft) {
        prevWidth = Math.max(prevWidth, myLeft + myWidth - prevLeft);
      } else {
        result[resultLen++] = new HorizontalRange(prevLeft, prevWidth);
        prevLeft = myLeft;
        prevWidth = myWidth;
      }
    }
    result[resultLen++] = new HorizontalRange(prevLeft, prevWidth);
    return result;
  }
  static _createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft) {
    if (!clientRects || clientRects.length === 0) {
      return null;
    }
    const result = [];
    for (let i3 = 0, len2 = clientRects.length; i3 < len2; i3++) {
      const clientRect = clientRects[i3];
      result[i3] = new FloatHorizontalRange(Math.max(0, clientRect.left - clientRectDeltaLeft), clientRect.width);
    }
    return this._mergeAdjacentRanges(result);
  }
  static readHorizontalRanges(domNode, startChildIndex, startOffset, endChildIndex, endOffset, clientRectDeltaLeft, endNode) {
    const min2 = 0;
    const max2 = domNode.children.length - 1;
    if (min2 > max2) {
      return null;
    }
    startChildIndex = Math.min(max2, Math.max(min2, startChildIndex));
    endChildIndex = Math.min(max2, Math.max(min2, endChildIndex));
    if (startChildIndex === endChildIndex && startOffset === endOffset && startOffset === 0) {
      const clientRects2 = domNode.children[startChildIndex].getClientRects();
      return this._createHorizontalRangesFromClientRects(clientRects2, clientRectDeltaLeft);
    }
    if (startChildIndex !== endChildIndex) {
      if (endChildIndex > 0 && endOffset === 0) {
        endChildIndex--;
        endOffset = 1073741824;
      }
    }
    let startElement = domNode.children[startChildIndex].firstChild;
    let endElement = domNode.children[endChildIndex].firstChild;
    if (!startElement || !endElement) {
      if (!startElement && startOffset === 0 && startChildIndex > 0) {
        startElement = domNode.children[startChildIndex - 1].firstChild;
        startOffset = 1073741824;
      }
      if (!endElement && endOffset === 0 && endChildIndex > 0) {
        endElement = domNode.children[endChildIndex - 1].firstChild;
        endOffset = 1073741824;
      }
    }
    if (!startElement || !endElement) {
      return null;
    }
    startOffset = Math.min(startElement.textContent.length, Math.max(0, startOffset));
    endOffset = Math.min(endElement.textContent.length, Math.max(0, endOffset));
    const clientRects = this._readClientRects(startElement, startOffset, endElement, endOffset, endNode);
    return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft);
  }
};
var IThemeService = createDecorator("themeService");
function themeColorFromId(id3) {
  return {id: id3};
}
var ThemeIcon;
(function(ThemeIcon2) {
  function isThemeIcon(obj) {
    return obj && typeof obj === "object" && typeof obj.id === "string";
  }
  ThemeIcon2.isThemeIcon = isThemeIcon;
  const _regexFromString = /^\$\(([a-z.]+\/)?([a-z-~]+)\)$/i;
  function fromString(str) {
    const match2 = _regexFromString.exec(str);
    if (!match2) {
      return void 0;
    }
    let [, owner, name] = match2;
    if (!owner) {
      owner = `codicon/`;
    }
    return {id: owner + name};
  }
  ThemeIcon2.fromString = fromString;
  const _regexAsClassName = /^(codicon\/)?([a-z-]+)(~[a-z]+)?$/i;
  function asClassName(icon) {
    const match2 = _regexAsClassName.exec(icon.id);
    if (!match2) {
      return void 0;
    }
    let [, , name, modifier] = match2;
    let className = `codicon codicon-${name}`;
    if (modifier) {
      className += ` ${modifier.substr(1)}`;
    }
    return className;
  }
  ThemeIcon2.asClassName = asClassName;
})(ThemeIcon || (ThemeIcon = {}));
var DARK = "dark";
var HIGH_CONTRAST = "hc";
function getThemeTypeSelector(type) {
  switch (type) {
    case DARK:
      return "vs-dark";
    case HIGH_CONTRAST:
      return "hc-black";
    default:
      return "vs";
  }
}
var Extensions$4 = {
  ThemingContribution: "base.contributions.theming"
};
var ThemingRegistry = class {
  constructor() {
    this.themingParticipants = [];
    this.themingParticipants = [];
    this.onThemingParticipantAddedEmitter = new Emitter();
  }
  onColorThemeChange(participant) {
    this.themingParticipants.push(participant);
    this.onThemingParticipantAddedEmitter.fire(participant);
    return toDisposable(() => {
      const idx = this.themingParticipants.indexOf(participant);
      this.themingParticipants.splice(idx, 1);
    });
  }
  getThemingParticipants() {
    return this.themingParticipants;
  }
};
var themingRegistry = new ThemingRegistry();
Registry$1.add(Extensions$4.ThemingContribution, themingRegistry);
function registerThemingParticipant(participant) {
  return themingRegistry.onColorThemeChange(participant);
}
var Themable = class extends Disposable {
  constructor(themeService) {
    super();
    this.themeService = themeService;
    this.theme = themeService.getColorTheme();
    this._register(this.themeService.onDidColorThemeChange((theme) => this.onThemeChange(theme)));
  }
  onThemeChange(theme) {
    this.theme = theme;
    this.updateStyles();
  }
  updateStyles() {
  }
};
var canUseFastRenderedViewLine = function() {
  if (isNative) {
    return true;
  }
  if (isLinux || isFirefox || isSafari) {
    return false;
  }
  return true;
}();
var monospaceAssumptionsAreValid = true;
var alwaysRenderInlineSelection = isEdge2;
var DomReadingContext = class {
  constructor(domNode, endNode) {
    this._domNode = domNode;
    this._clientRectDeltaLeft = 0;
    this._clientRectDeltaLeftRead = false;
    this.endNode = endNode;
  }
  get clientRectDeltaLeft() {
    if (!this._clientRectDeltaLeftRead) {
      this._clientRectDeltaLeftRead = true;
      this._clientRectDeltaLeft = this._domNode.getBoundingClientRect().left;
    }
    return this._clientRectDeltaLeft;
  }
};
var ViewLineOptions = class {
  constructor(config2, themeType) {
    this.themeType = themeType;
    const options = config2.options;
    const fontInfo = options.get(36);
    this.renderWhitespace = options.get(80);
    this.renderControlCharacters = options.get(74);
    this.spaceWidth = fontInfo.spaceWidth;
    this.middotWidth = fontInfo.middotWidth;
    this.wsmiddotWidth = fontInfo.wsmiddotWidth;
    this.useMonospaceOptimizations = fontInfo.isMonospace && !options.get(24);
    this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow;
    this.lineHeight = options.get(51);
    this.stopRenderingLineAfter = options.get(95);
    this.fontLigatures = options.get(37);
  }
  equals(other) {
    return this.themeType === other.themeType && this.renderWhitespace === other.renderWhitespace && this.renderControlCharacters === other.renderControlCharacters && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.useMonospaceOptimizations === other.useMonospaceOptimizations && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineHeight === other.lineHeight && this.stopRenderingLineAfter === other.stopRenderingLineAfter && this.fontLigatures === other.fontLigatures;
  }
};
var ViewLine = class {
  constructor(options) {
    this._options = options;
    this._isMaybeInvalid = true;
    this._renderedViewLine = null;
  }
  getDomNode() {
    if (this._renderedViewLine && this._renderedViewLine.domNode) {
      return this._renderedViewLine.domNode.domNode;
    }
    return null;
  }
  setDomNode(domNode) {
    if (this._renderedViewLine) {
      this._renderedViewLine.domNode = createFastDomNode(domNode);
    } else {
      throw new Error("I have no rendered view line to set the dom node to...");
    }
  }
  onContentChanged() {
    this._isMaybeInvalid = true;
  }
  onTokensChanged() {
    this._isMaybeInvalid = true;
  }
  onDecorationsChanged() {
    this._isMaybeInvalid = true;
  }
  onOptionsChanged(newOptions) {
    this._isMaybeInvalid = true;
    this._options = newOptions;
  }
  onSelectionChanged() {
    if (alwaysRenderInlineSelection || this._options.themeType === HIGH_CONTRAST || this._options.renderWhitespace === "selection") {
      this._isMaybeInvalid = true;
      return true;
    }
    return false;
  }
  renderLine(lineNumber, deltaTop, viewportData, sb2) {
    if (this._isMaybeInvalid === false) {
      return false;
    }
    this._isMaybeInvalid = false;
    const lineData = viewportData.getViewLineRenderingData(lineNumber);
    const options = this._options;
    const actualInlineDecorations = LineDecoration.filter(lineData.inlineDecorations, lineNumber, lineData.minColumn, lineData.maxColumn);
    let selectionsOnLine = null;
    if (alwaysRenderInlineSelection || options.themeType === HIGH_CONTRAST || this._options.renderWhitespace === "selection") {
      const selections = viewportData.selections;
      for (const selection2 of selections) {
        if (selection2.endLineNumber < lineNumber || selection2.startLineNumber > lineNumber) {
          continue;
        }
        const startColumn = selection2.startLineNumber === lineNumber ? selection2.startColumn : lineData.minColumn;
        const endColumn = selection2.endLineNumber === lineNumber ? selection2.endColumn : lineData.maxColumn;
        if (startColumn < endColumn) {
          if (options.themeType === HIGH_CONTRAST || this._options.renderWhitespace !== "selection") {
            actualInlineDecorations.push(new LineDecoration(startColumn, endColumn, "inline-selected-text", 0));
          } else {
            if (!selectionsOnLine) {
              selectionsOnLine = [];
            }
            selectionsOnLine.push(new LineRange(startColumn - 1, endColumn - 1));
          }
        }
      }
    }
    const renderLineInput = new RenderLineInput(options.useMonospaceOptimizations, options.canUseHalfwidthRightwardsArrow, lineData.content, lineData.continuesWithWrappedLine, lineData.isBasicASCII, lineData.containsRTL, lineData.minColumn - 1, lineData.tokens, actualInlineDecorations, lineData.tabSize, lineData.startVisibleColumn, options.spaceWidth, options.middotWidth, options.wsmiddotWidth, options.stopRenderingLineAfter, options.renderWhitespace, options.renderControlCharacters, options.fontLigatures !== EditorFontLigatures.OFF, selectionsOnLine);
    if (this._renderedViewLine && this._renderedViewLine.input.equals(renderLineInput)) {
      return false;
    }
    sb2.appendASCIIString('<div style="top:');
    sb2.appendASCIIString(String(deltaTop));
    sb2.appendASCIIString("px;height:");
    sb2.appendASCIIString(String(this._options.lineHeight));
    sb2.appendASCIIString('px;" class="');
    sb2.appendASCIIString(ViewLine.CLASS_NAME);
    sb2.appendASCIIString('">');
    const output2 = renderViewLine(renderLineInput, sb2);
    sb2.appendASCIIString("</div>");
    let renderedViewLine = null;
    if (monospaceAssumptionsAreValid && canUseFastRenderedViewLine && lineData.isBasicASCII && options.useMonospaceOptimizations && output2.containsForeignElements === 0) {
      if (lineData.content.length < 300 && renderLineInput.lineTokens.getCount() < 100) {
        renderedViewLine = new FastRenderedViewLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output2.characterMapping);
      }
    }
    if (!renderedViewLine) {
      renderedViewLine = createRenderedLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output2.characterMapping, output2.containsRTL, output2.containsForeignElements);
    }
    this._renderedViewLine = renderedViewLine;
    return true;
  }
  layoutLine(lineNumber, deltaTop) {
    if (this._renderedViewLine && this._renderedViewLine.domNode) {
      this._renderedViewLine.domNode.setTop(deltaTop);
      this._renderedViewLine.domNode.setHeight(this._options.lineHeight);
    }
  }
  getWidth() {
    if (!this._renderedViewLine) {
      return 0;
    }
    return this._renderedViewLine.getWidth();
  }
  getWidthIsFast() {
    if (!this._renderedViewLine) {
      return true;
    }
    return this._renderedViewLine.getWidthIsFast();
  }
  needsMonospaceFontCheck() {
    if (!this._renderedViewLine) {
      return false;
    }
    return this._renderedViewLine instanceof FastRenderedViewLine;
  }
  monospaceAssumptionsAreValid() {
    if (!this._renderedViewLine) {
      return monospaceAssumptionsAreValid;
    }
    if (this._renderedViewLine instanceof FastRenderedViewLine) {
      return this._renderedViewLine.monospaceAssumptionsAreValid();
    }
    return monospaceAssumptionsAreValid;
  }
  onMonospaceAssumptionsInvalidated() {
    if (this._renderedViewLine && this._renderedViewLine instanceof FastRenderedViewLine) {
      this._renderedViewLine = this._renderedViewLine.toSlowRenderedLine();
    }
  }
  getVisibleRangesForRange(startColumn, endColumn, context2) {
    if (!this._renderedViewLine) {
      return null;
    }
    startColumn = startColumn | 0;
    endColumn = endColumn | 0;
    startColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, startColumn));
    endColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, endColumn));
    const stopRenderingLineAfter = this._renderedViewLine.input.stopRenderingLineAfter | 0;
    let outsideRenderedLine = false;
    if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1 && endColumn > stopRenderingLineAfter + 1) {
      outsideRenderedLine = true;
    }
    if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1) {
      startColumn = stopRenderingLineAfter + 1;
    }
    if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter + 1) {
      endColumn = stopRenderingLineAfter + 1;
    }
    const horizontalRanges = this._renderedViewLine.getVisibleRangesForRange(startColumn, endColumn, context2);
    if (horizontalRanges && horizontalRanges.length > 0) {
      return new VisibleRanges(outsideRenderedLine, horizontalRanges);
    }
    return null;
  }
  getColumnOfNodeOffset(lineNumber, spanNode, offset2) {
    if (!this._renderedViewLine) {
      return 1;
    }
    return this._renderedViewLine.getColumnOfNodeOffset(lineNumber, spanNode, offset2);
  }
};
ViewLine.CLASS_NAME = "view-line";
var FastRenderedViewLine = class {
  constructor(domNode, renderLineInput, characterMapping) {
    this.domNode = domNode;
    this.input = renderLineInput;
    this._characterMapping = characterMapping;
    this._charWidth = renderLineInput.spaceWidth;
  }
  getWidth() {
    return this._getCharPosition(this._characterMapping.length);
  }
  getWidthIsFast() {
    return true;
  }
  monospaceAssumptionsAreValid() {
    if (!this.domNode) {
      return monospaceAssumptionsAreValid;
    }
    const expectedWidth = this.getWidth();
    const actualWidth = this.domNode.domNode.firstChild.offsetWidth;
    if (Math.abs(expectedWidth - actualWidth) >= 2) {
      console.warn(`monospace assumptions have been violated, therefore disabling monospace optimizations!`);
      monospaceAssumptionsAreValid = false;
    }
    return monospaceAssumptionsAreValid;
  }
  toSlowRenderedLine() {
    return createRenderedLine(this.domNode, this.input, this._characterMapping, false, 0);
  }
  getVisibleRangesForRange(startColumn, endColumn, context2) {
    const startPosition = this._getCharPosition(startColumn);
    const endPosition = this._getCharPosition(endColumn);
    return [new HorizontalRange(startPosition, endPosition - startPosition)];
  }
  _getCharPosition(column) {
    const charOffset = this._characterMapping.getAbsoluteOffsets();
    if (charOffset.length === 0) {
      return 0;
    }
    return Math.round(this._charWidth * charOffset[column - 1]);
  }
  getColumnOfNodeOffset(lineNumber, spanNode, offset2) {
    const spanNodeTextContentLength = spanNode.textContent.length;
    let spanIndex = -1;
    while (spanNode) {
      spanNode = spanNode.previousSibling;
      spanIndex++;
    }
    const charOffset = this._characterMapping.partDataToCharOffset(spanIndex, spanNodeTextContentLength, offset2);
    return charOffset + 1;
  }
};
var RenderedViewLine = class {
  constructor(domNode, renderLineInput, characterMapping, containsRTL2, containsForeignElements) {
    this.domNode = domNode;
    this.input = renderLineInput;
    this._characterMapping = characterMapping;
    this._isWhitespaceOnly = /^\s*$/.test(renderLineInput.lineContent);
    this._containsForeignElements = containsForeignElements;
    this._cachedWidth = -1;
    this._pixelOffsetCache = null;
    if (!containsRTL2 || this._characterMapping.length === 0) {
      this._pixelOffsetCache = new Int32Array(Math.max(2, this._characterMapping.length + 1));
      for (let column = 0, len2 = this._characterMapping.length; column <= len2; column++) {
        this._pixelOffsetCache[column] = -1;
      }
    }
  }
  _getReadingTarget(myDomNode) {
    return myDomNode.domNode.firstChild;
  }
  getWidth() {
    if (!this.domNode) {
      return 0;
    }
    if (this._cachedWidth === -1) {
      this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth;
    }
    return this._cachedWidth;
  }
  getWidthIsFast() {
    if (this._cachedWidth === -1) {
      return false;
    }
    return true;
  }
  getVisibleRangesForRange(startColumn, endColumn, context2) {
    if (!this.domNode) {
      return null;
    }
    if (this._pixelOffsetCache !== null) {
      const startOffset = this._readPixelOffset(this.domNode, startColumn, context2);
      if (startOffset === -1) {
        return null;
      }
      const endOffset = this._readPixelOffset(this.domNode, endColumn, context2);
      if (endOffset === -1) {
        return null;
      }
      return [new HorizontalRange(startOffset, endOffset - startOffset)];
    }
    return this._readVisibleRangesForRange(this.domNode, startColumn, endColumn, context2);
  }
  _readVisibleRangesForRange(domNode, startColumn, endColumn, context2) {
    if (startColumn === endColumn) {
      const pixelOffset = this._readPixelOffset(domNode, startColumn, context2);
      if (pixelOffset === -1) {
        return null;
      } else {
        return [new HorizontalRange(pixelOffset, 0)];
      }
    } else {
      return this._readRawVisibleRangesForRange(domNode, startColumn, endColumn, context2);
    }
  }
  _readPixelOffset(domNode, column, context2) {
    if (this._characterMapping.length === 0) {
      if (this._containsForeignElements === 0) {
        return 0;
      }
      if (this._containsForeignElements === 2) {
        return 0;
      }
      if (this._containsForeignElements === 1) {
        return this.getWidth();
      }
      const readingTarget = this._getReadingTarget(domNode);
      if (readingTarget.firstChild) {
        return readingTarget.firstChild.offsetWidth;
      } else {
        return 0;
      }
    }
    if (this._pixelOffsetCache !== null) {
      const cachedPixelOffset = this._pixelOffsetCache[column];
      if (cachedPixelOffset !== -1) {
        return cachedPixelOffset;
      }
      const result = this._actualReadPixelOffset(domNode, column, context2);
      this._pixelOffsetCache[column] = result;
      return result;
    }
    return this._actualReadPixelOffset(domNode, column, context2);
  }
  _actualReadPixelOffset(domNode, column, context2) {
    if (this._characterMapping.length === 0) {
      const r4 = RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), 0, 0, 0, 0, context2.clientRectDeltaLeft, context2.endNode);
      if (!r4 || r4.length === 0) {
        return -1;
      }
      return r4[0].left;
    }
    if (column === this._characterMapping.length && this._isWhitespaceOnly && this._containsForeignElements === 0) {
      return this.getWidth();
    }
    const partData = this._characterMapping.charOffsetToPartData(column - 1);
    const partIndex = CharacterMapping.getPartIndex(partData);
    const charOffsetInPart = CharacterMapping.getCharIndex(partData);
    const r3 = RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), partIndex, charOffsetInPart, partIndex, charOffsetInPart, context2.clientRectDeltaLeft, context2.endNode);
    if (!r3 || r3.length === 0) {
      return -1;
    }
    const result = r3[0].left;
    if (this.input.isBasicASCII) {
      const charOffset = this._characterMapping.getAbsoluteOffsets();
      const expectedResult = Math.round(this.input.spaceWidth * charOffset[column - 1]);
      if (Math.abs(expectedResult - result) <= 1) {
        return expectedResult;
      }
    }
    return result;
  }
  _readRawVisibleRangesForRange(domNode, startColumn, endColumn, context2) {
    if (startColumn === 1 && endColumn === this._characterMapping.length) {
      return [new HorizontalRange(0, this.getWidth())];
    }
    const startPartData = this._characterMapping.charOffsetToPartData(startColumn - 1);
    const startPartIndex = CharacterMapping.getPartIndex(startPartData);
    const startCharOffsetInPart = CharacterMapping.getCharIndex(startPartData);
    const endPartData = this._characterMapping.charOffsetToPartData(endColumn - 1);
    const endPartIndex = CharacterMapping.getPartIndex(endPartData);
    const endCharOffsetInPart = CharacterMapping.getCharIndex(endPartData);
    return RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), startPartIndex, startCharOffsetInPart, endPartIndex, endCharOffsetInPart, context2.clientRectDeltaLeft, context2.endNode);
  }
  getColumnOfNodeOffset(lineNumber, spanNode, offset2) {
    const spanNodeTextContentLength = spanNode.textContent.length;
    let spanIndex = -1;
    while (spanNode) {
      spanNode = spanNode.previousSibling;
      spanIndex++;
    }
    const charOffset = this._characterMapping.partDataToCharOffset(spanIndex, spanNodeTextContentLength, offset2);
    return charOffset + 1;
  }
};
var WebKitRenderedViewLine = class extends RenderedViewLine {
  _readVisibleRangesForRange(domNode, startColumn, endColumn, context2) {
    const output2 = super._readVisibleRangesForRange(domNode, startColumn, endColumn, context2);
    if (!output2 || output2.length === 0 || startColumn === endColumn || startColumn === 1 && endColumn === this._characterMapping.length) {
      return output2;
    }
    if (!this.input.containsRTL) {
      const endPixelOffset = this._readPixelOffset(domNode, endColumn, context2);
      if (endPixelOffset !== -1) {
        const lastRange = output2[output2.length - 1];
        if (lastRange.left < endPixelOffset) {
          lastRange.width = endPixelOffset - lastRange.left;
        }
      }
    }
    return output2;
  }
};
var createRenderedLine = function() {
  if (isWebKit) {
    return createWebKitRenderedLine;
  }
  return createNormalRenderedLine;
}();
function createWebKitRenderedLine(domNode, renderLineInput, characterMapping, containsRTL2, containsForeignElements) {
  return new WebKitRenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL2, containsForeignElements);
}
function createNormalRenderedLine(domNode, renderLineInput, characterMapping, containsRTL2, containsForeignElements) {
  return new RenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL2, containsForeignElements);
}
var TextChange = class {
  constructor(oldPosition, oldText, newPosition, newText) {
    this.oldPosition = oldPosition;
    this.oldText = oldText;
    this.newPosition = newPosition;
    this.newText = newText;
  }
  get oldLength() {
    return this.oldText.length;
  }
  get oldEnd() {
    return this.oldPosition + this.oldText.length;
  }
  get newLength() {
    return this.newText.length;
  }
  get newEnd() {
    return this.newPosition + this.newText.length;
  }
  toString() {
    if (this.oldText.length === 0) {
      return `(insert@${this.oldPosition} "${this.newText}")`;
    }
    if (this.newText.length === 0) {
      return `(delete@${this.oldPosition} "${this.oldText}")`;
    }
    return `(replace@${this.oldPosition} "${this.oldText}" with "${this.newText}")`;
  }
  static _writeStringSize(str) {
    return 4 + 2 * str.length;
  }
  static _writeString(b2, str, offset2) {
    const len2 = str.length;
    writeUInt32BE(b2, len2, offset2);
    offset2 += 4;
    for (let i3 = 0; i3 < len2; i3++) {
      writeUInt16LE(b2, str.charCodeAt(i3), offset2);
      offset2 += 2;
    }
    return offset2;
  }
  static _readString(b2, offset2) {
    const len2 = readUInt32BE(b2, offset2);
    offset2 += 4;
    return decodeUTF16LE(b2, offset2, len2);
  }
  writeSize() {
    return 4 + 4 + TextChange._writeStringSize(this.oldText) + TextChange._writeStringSize(this.newText);
  }
  write(b2, offset2) {
    writeUInt32BE(b2, this.oldPosition, offset2);
    offset2 += 4;
    writeUInt32BE(b2, this.newPosition, offset2);
    offset2 += 4;
    offset2 = TextChange._writeString(b2, this.oldText, offset2);
    offset2 = TextChange._writeString(b2, this.newText, offset2);
    return offset2;
  }
  static read(b2, offset2, dest) {
    const oldPosition = readUInt32BE(b2, offset2);
    offset2 += 4;
    const newPosition = readUInt32BE(b2, offset2);
    offset2 += 4;
    const oldText = TextChange._readString(b2, offset2);
    offset2 += TextChange._writeStringSize(oldText);
    const newText = TextChange._readString(b2, offset2);
    offset2 += TextChange._writeStringSize(newText);
    dest.push(new TextChange(oldPosition, oldText, newPosition, newText));
    return offset2;
  }
};
function compressConsecutiveTextChanges(prevEdits, currEdits) {
  if (prevEdits === null || prevEdits.length === 0) {
    return currEdits;
  }
  const compressor = new TextChangeCompressor(prevEdits, currEdits);
  return compressor.compress();
}
var TextChangeCompressor = class {
  constructor(prevEdits, currEdits) {
    this._prevEdits = prevEdits;
    this._currEdits = currEdits;
    this._result = [];
    this._resultLen = 0;
    this._prevLen = this._prevEdits.length;
    this._prevDeltaOffset = 0;
    this._currLen = this._currEdits.length;
    this._currDeltaOffset = 0;
  }
  compress() {
    let prevIndex = 0;
    let currIndex = 0;
    let prevEdit = this._getPrev(prevIndex);
    let currEdit = this._getCurr(currIndex);
    while (prevIndex < this._prevLen || currIndex < this._currLen) {
      if (prevEdit === null) {
        this._acceptCurr(currEdit);
        currEdit = this._getCurr(++currIndex);
        continue;
      }
      if (currEdit === null) {
        this._acceptPrev(prevEdit);
        prevEdit = this._getPrev(++prevIndex);
        continue;
      }
      if (currEdit.oldEnd <= prevEdit.newPosition) {
        this._acceptCurr(currEdit);
        currEdit = this._getCurr(++currIndex);
        continue;
      }
      if (prevEdit.newEnd <= currEdit.oldPosition) {
        this._acceptPrev(prevEdit);
        prevEdit = this._getPrev(++prevIndex);
        continue;
      }
      if (currEdit.oldPosition < prevEdit.newPosition) {
        const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newPosition - currEdit.oldPosition);
        this._acceptCurr(e1);
        currEdit = e2;
        continue;
      }
      if (prevEdit.newPosition < currEdit.oldPosition) {
        const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldPosition - prevEdit.newPosition);
        this._acceptPrev(e1);
        prevEdit = e2;
        continue;
      }
      let mergePrev;
      let mergeCurr;
      if (currEdit.oldEnd === prevEdit.newEnd) {
        mergePrev = prevEdit;
        mergeCurr = currEdit;
        prevEdit = this._getPrev(++prevIndex);
        currEdit = this._getCurr(++currIndex);
      } else if (currEdit.oldEnd < prevEdit.newEnd) {
        const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldLength);
        mergePrev = e1;
        mergeCurr = currEdit;
        prevEdit = e2;
        currEdit = this._getCurr(++currIndex);
      } else {
        const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newLength);
        mergePrev = prevEdit;
        mergeCurr = e1;
        prevEdit = this._getPrev(++prevIndex);
        currEdit = e2;
      }
      this._result[this._resultLen++] = new TextChange(mergePrev.oldPosition, mergePrev.oldText, mergeCurr.newPosition, mergeCurr.newText);
      this._prevDeltaOffset += mergePrev.newLength - mergePrev.oldLength;
      this._currDeltaOffset += mergeCurr.newLength - mergeCurr.oldLength;
    }
    const merged = TextChangeCompressor._merge(this._result);
    const cleaned = TextChangeCompressor._removeNoOps(merged);
    return cleaned;
  }
  _acceptCurr(currEdit) {
    this._result[this._resultLen++] = TextChangeCompressor._rebaseCurr(this._prevDeltaOffset, currEdit);
    this._currDeltaOffset += currEdit.newLength - currEdit.oldLength;
  }
  _getCurr(currIndex) {
    return currIndex < this._currLen ? this._currEdits[currIndex] : null;
  }
  _acceptPrev(prevEdit) {
    this._result[this._resultLen++] = TextChangeCompressor._rebasePrev(this._currDeltaOffset, prevEdit);
    this._prevDeltaOffset += prevEdit.newLength - prevEdit.oldLength;
  }
  _getPrev(prevIndex) {
    return prevIndex < this._prevLen ? this._prevEdits[prevIndex] : null;
  }
  static _rebaseCurr(prevDeltaOffset, currEdit) {
    return new TextChange(currEdit.oldPosition - prevDeltaOffset, currEdit.oldText, currEdit.newPosition, currEdit.newText);
  }
  static _rebasePrev(currDeltaOffset, prevEdit) {
    return new TextChange(prevEdit.oldPosition, prevEdit.oldText, prevEdit.newPosition + currDeltaOffset, prevEdit.newText);
  }
  static _splitPrev(edit, offset2) {
    const preText = edit.newText.substr(0, offset2);
    const postText = edit.newText.substr(offset2);
    return [
      new TextChange(edit.oldPosition, edit.oldText, edit.newPosition, preText),
      new TextChange(edit.oldEnd, "", edit.newPosition + offset2, postText)
    ];
  }
  static _splitCurr(edit, offset2) {
    const preText = edit.oldText.substr(0, offset2);
    const postText = edit.oldText.substr(offset2);
    return [
      new TextChange(edit.oldPosition, preText, edit.newPosition, edit.newText),
      new TextChange(edit.oldPosition + offset2, postText, edit.newEnd, "")
    ];
  }
  static _merge(edits) {
    if (edits.length === 0) {
      return edits;
    }
    let result = [], resultLen = 0;
    let prev = edits[0];
    for (let i3 = 1; i3 < edits.length; i3++) {
      const curr = edits[i3];
      if (prev.oldEnd === curr.oldPosition) {
        prev = new TextChange(prev.oldPosition, prev.oldText + curr.oldText, prev.newPosition, prev.newText + curr.newText);
      } else {
        result[resultLen++] = prev;
        prev = curr;
      }
    }
    result[resultLen++] = prev;
    return result;
  }
  static _removeNoOps(edits) {
    if (edits.length === 0) {
      return edits;
    }
    let result = [], resultLen = 0;
    for (let i3 = 0; i3 < edits.length; i3++) {
      const edit = edits[i3];
      if (edit.oldText === edit.newText) {
        continue;
      }
      result[resultLen++] = edit;
    }
    return result;
  }
};
function uriGetComparisonKey(resource2) {
  return resource2.toString();
}
var SingleModelEditStackData = class {
  constructor(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes) {
    this.beforeVersionId = beforeVersionId;
    this.afterVersionId = afterVersionId;
    this.beforeEOL = beforeEOL;
    this.afterEOL = afterEOL;
    this.beforeCursorState = beforeCursorState;
    this.afterCursorState = afterCursorState;
    this.changes = changes;
  }
  static create(model, beforeCursorState) {
    const alternativeVersionId = model.getAlternativeVersionId();
    const eol = getModelEOL(model);
    return new SingleModelEditStackData(alternativeVersionId, alternativeVersionId, eol, eol, beforeCursorState, beforeCursorState, []);
  }
  append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
    if (textChanges.length > 0) {
      this.changes = compressConsecutiveTextChanges(this.changes, textChanges);
    }
    this.afterEOL = afterEOL;
    this.afterVersionId = afterVersionId;
    this.afterCursorState = afterCursorState;
  }
  static _writeSelectionsSize(selections) {
    return 4 + 4 * 4 * (selections ? selections.length : 0);
  }
  static _writeSelections(b2, selections, offset2) {
    writeUInt32BE(b2, selections ? selections.length : 0, offset2);
    offset2 += 4;
    if (selections) {
      for (const selection2 of selections) {
        writeUInt32BE(b2, selection2.selectionStartLineNumber, offset2);
        offset2 += 4;
        writeUInt32BE(b2, selection2.selectionStartColumn, offset2);
        offset2 += 4;
        writeUInt32BE(b2, selection2.positionLineNumber, offset2);
        offset2 += 4;
        writeUInt32BE(b2, selection2.positionColumn, offset2);
        offset2 += 4;
      }
    }
    return offset2;
  }
  static _readSelections(b2, offset2, dest) {
    const count = readUInt32BE(b2, offset2);
    offset2 += 4;
    for (let i3 = 0; i3 < count; i3++) {
      const selectionStartLineNumber = readUInt32BE(b2, offset2);
      offset2 += 4;
      const selectionStartColumn = readUInt32BE(b2, offset2);
      offset2 += 4;
      const positionLineNumber = readUInt32BE(b2, offset2);
      offset2 += 4;
      const positionColumn = readUInt32BE(b2, offset2);
      offset2 += 4;
      dest.push(new Selection(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn));
    }
    return offset2;
  }
  serialize() {
    let necessarySize = 4 + 4 + 1 + 1 + SingleModelEditStackData._writeSelectionsSize(this.beforeCursorState) + SingleModelEditStackData._writeSelectionsSize(this.afterCursorState) + 4;
    for (const change of this.changes) {
      necessarySize += change.writeSize();
    }
    const b2 = new Uint8Array(necessarySize);
    let offset2 = 0;
    writeUInt32BE(b2, this.beforeVersionId, offset2);
    offset2 += 4;
    writeUInt32BE(b2, this.afterVersionId, offset2);
    offset2 += 4;
    writeUInt8(b2, this.beforeEOL, offset2);
    offset2 += 1;
    writeUInt8(b2, this.afterEOL, offset2);
    offset2 += 1;
    offset2 = SingleModelEditStackData._writeSelections(b2, this.beforeCursorState, offset2);
    offset2 = SingleModelEditStackData._writeSelections(b2, this.afterCursorState, offset2);
    writeUInt32BE(b2, this.changes.length, offset2);
    offset2 += 4;
    for (const change of this.changes) {
      offset2 = change.write(b2, offset2);
    }
    return b2.buffer;
  }
  static deserialize(source2) {
    const b2 = new Uint8Array(source2);
    let offset2 = 0;
    const beforeVersionId = readUInt32BE(b2, offset2);
    offset2 += 4;
    const afterVersionId = readUInt32BE(b2, offset2);
    offset2 += 4;
    const beforeEOL = readUInt8(b2, offset2);
    offset2 += 1;
    const afterEOL = readUInt8(b2, offset2);
    offset2 += 1;
    const beforeCursorState = [];
    offset2 = SingleModelEditStackData._readSelections(b2, offset2, beforeCursorState);
    const afterCursorState = [];
    offset2 = SingleModelEditStackData._readSelections(b2, offset2, afterCursorState);
    const changeCount = readUInt32BE(b2, offset2);
    offset2 += 4;
    const changes = [];
    for (let i3 = 0; i3 < changeCount; i3++) {
      offset2 = TextChange.read(b2, offset2, changes);
    }
    return new SingleModelEditStackData(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes);
  }
};
var SingleModelEditStackElement = class {
  constructor(model, beforeCursorState) {
    this.model = model;
    this._data = SingleModelEditStackData.create(model, beforeCursorState);
  }
  get type() {
    return 0;
  }
  get resource() {
    if (URI.isUri(this.model)) {
      return this.model;
    }
    return this.model.uri;
  }
  get label() {
    return localize("edit", "Typing");
  }
  toString() {
    const data2 = this._data instanceof SingleModelEditStackData ? this._data : SingleModelEditStackData.deserialize(this._data);
    return data2.changes.map((change) => change.toString()).join(", ");
  }
  matchesResource(resource2) {
    const uri = URI.isUri(this.model) ? this.model : this.model.uri;
    return uri.toString() === resource2.toString();
  }
  setModel(model) {
    this.model = model;
  }
  canAppend(model) {
    return this.model === model && this._data instanceof SingleModelEditStackData;
  }
  append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
    if (this._data instanceof SingleModelEditStackData) {
      this._data.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
    }
  }
  close() {
    if (this._data instanceof SingleModelEditStackData) {
      this._data = this._data.serialize();
    }
  }
  undo() {
    if (URI.isUri(this.model)) {
      throw new Error(`Invalid SingleModelEditStackElement`);
    }
    if (this._data instanceof SingleModelEditStackData) {
      this._data = this._data.serialize();
    }
    const data2 = SingleModelEditStackData.deserialize(this._data);
    this.model._applyUndo(data2.changes, data2.beforeEOL, data2.beforeVersionId, data2.beforeCursorState);
  }
  redo() {
    if (URI.isUri(this.model)) {
      throw new Error(`Invalid SingleModelEditStackElement`);
    }
    if (this._data instanceof SingleModelEditStackData) {
      this._data = this._data.serialize();
    }
    const data2 = SingleModelEditStackData.deserialize(this._data);
    this.model._applyRedo(data2.changes, data2.afterEOL, data2.afterVersionId, data2.afterCursorState);
  }
};
var MultiModelEditStackElement = class {
  constructor(label2, editStackElements) {
    this.type = 1;
    this.label = label2;
    this._isOpen = true;
    this._editStackElementsArr = editStackElements.slice(0);
    this._editStackElementsMap = new Map();
    for (const editStackElement of this._editStackElementsArr) {
      const key = uriGetComparisonKey(editStackElement.resource);
      this._editStackElementsMap.set(key, editStackElement);
    }
    this._delegate = null;
  }
  get resources() {
    return this._editStackElementsArr.map((editStackElement) => editStackElement.resource);
  }
  prepareUndoRedo() {
    if (this._delegate) {
      return this._delegate.prepareUndoRedo(this);
    }
  }
  matchesResource(resource2) {
    const key = uriGetComparisonKey(resource2);
    return this._editStackElementsMap.has(key);
  }
  setModel(model) {
    const key = uriGetComparisonKey(URI.isUri(model) ? model : model.uri);
    if (this._editStackElementsMap.has(key)) {
      this._editStackElementsMap.get(key).setModel(model);
    }
  }
  canAppend(model) {
    if (!this._isOpen) {
      return false;
    }
    const key = uriGetComparisonKey(model.uri);
    if (this._editStackElementsMap.has(key)) {
      const editStackElement = this._editStackElementsMap.get(key);
      return editStackElement.canAppend(model);
    }
    return false;
  }
  append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
    const key = uriGetComparisonKey(model.uri);
    const editStackElement = this._editStackElementsMap.get(key);
    editStackElement.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
  }
  close() {
    this._isOpen = false;
  }
  undo() {
    this._isOpen = false;
    for (const editStackElement of this._editStackElementsArr) {
      editStackElement.undo();
    }
  }
  redo() {
    for (const editStackElement of this._editStackElementsArr) {
      editStackElement.redo();
    }
  }
  split() {
    return this._editStackElementsArr;
  }
};
function getModelEOL(model) {
  const eol = model.getEOL();
  if (eol === "\n") {
    return 0;
  } else {
    return 1;
  }
}
function isEditStackElement(element) {
  if (!element) {
    return false;
  }
  return element instanceof SingleModelEditStackElement || element instanceof MultiModelEditStackElement;
}
var EditStack = class {
  constructor(model, undoRedoService) {
    this._model = model;
    this._undoRedoService = undoRedoService;
  }
  pushStackElement() {
    const lastElement = this._undoRedoService.getLastElement(this._model.uri);
    if (isEditStackElement(lastElement)) {
      lastElement.close();
    }
  }
  clear() {
    this._undoRedoService.removeElements(this._model.uri);
  }
  _getOrCreateEditStackElement(beforeCursorState) {
    const lastElement = this._undoRedoService.getLastElement(this._model.uri);
    if (isEditStackElement(lastElement) && lastElement.canAppend(this._model)) {
      return lastElement;
    }
    const newElement = new SingleModelEditStackElement(this._model, beforeCursorState);
    this._undoRedoService.pushElement(newElement);
    return newElement;
  }
  pushEOL(eol) {
    const editStackElement = this._getOrCreateEditStackElement(null);
    this._model.setEOL(eol);
    editStackElement.append(this._model, [], getModelEOL(this._model), this._model.getAlternativeVersionId(), null);
  }
  pushEditOperation(beforeCursorState, editOperations, cursorStateComputer) {
    const editStackElement = this._getOrCreateEditStackElement(beforeCursorState);
    const inverseEditOperations = this._model.applyEdits(editOperations, true);
    const afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperations);
    const textChanges = inverseEditOperations.map((op, index3) => ({index: index3, textChange: op.textChange}));
    textChanges.sort((a2, b2) => {
      if (a2.textChange.oldPosition === b2.textChange.oldPosition) {
        return a2.index - b2.index;
      }
      return a2.textChange.oldPosition - b2.textChange.oldPosition;
    });
    editStackElement.append(this._model, textChanges.map((op) => op.textChange), getModelEOL(this._model), this._model.getAlternativeVersionId(), afterCursorState);
    return afterCursorState;
  }
  static _computeCursorState(cursorStateComputer, inverseEditOperations) {
    try {
      return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null;
    } catch (e2) {
      onUnexpectedError(e2);
      return null;
    }
  }
};
var SpacesDiffResult = class {
  constructor() {
    this.spacesDiff = 0;
    this.looksLikeAlignment = false;
  }
};
function spacesDiff(a2, aLength, b2, bLength, result) {
  result.spacesDiff = 0;
  result.looksLikeAlignment = false;
  let i3;
  for (i3 = 0; i3 < aLength && i3 < bLength; i3++) {
    let aCharCode = a2.charCodeAt(i3);
    let bCharCode = b2.charCodeAt(i3);
    if (aCharCode !== bCharCode) {
      break;
    }
  }
  let aSpacesCnt = 0, aTabsCount = 0;
  for (let j = i3; j < aLength; j++) {
    let aCharCode = a2.charCodeAt(j);
    if (aCharCode === 32) {
      aSpacesCnt++;
    } else {
      aTabsCount++;
    }
  }
  let bSpacesCnt = 0, bTabsCount = 0;
  for (let j = i3; j < bLength; j++) {
    let bCharCode = b2.charCodeAt(j);
    if (bCharCode === 32) {
      bSpacesCnt++;
    } else {
      bTabsCount++;
    }
  }
  if (aSpacesCnt > 0 && aTabsCount > 0) {
    return;
  }
  if (bSpacesCnt > 0 && bTabsCount > 0) {
    return;
  }
  let tabsDiff = Math.abs(aTabsCount - bTabsCount);
  let spacesDiff2 = Math.abs(aSpacesCnt - bSpacesCnt);
  if (tabsDiff === 0) {
    result.spacesDiff = spacesDiff2;
    if (spacesDiff2 > 0 && 0 <= bSpacesCnt - 1 && bSpacesCnt - 1 < a2.length && bSpacesCnt < b2.length) {
      if (b2.charCodeAt(bSpacesCnt) !== 32 && a2.charCodeAt(bSpacesCnt - 1) === 32) {
        if (a2.charCodeAt(a2.length - 1) === 44) {
          result.looksLikeAlignment = true;
        }
      }
    }
    return;
  }
  if (spacesDiff2 % tabsDiff === 0) {
    result.spacesDiff = spacesDiff2 / tabsDiff;
    return;
  }
}
function guessIndentation(source2, defaultTabSize, defaultInsertSpaces) {
  const linesCount = Math.min(source2.getLineCount(), 1e4);
  let linesIndentedWithTabsCount = 0;
  let linesIndentedWithSpacesCount = 0;
  let previousLineText = "";
  let previousLineIndentation = 0;
  const ALLOWED_TAB_SIZE_GUESSES = [2, 4, 6, 8, 3, 5, 7];
  const MAX_ALLOWED_TAB_SIZE_GUESS = 8;
  let spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0];
  let tmp = new SpacesDiffResult();
  for (let lineNumber = 1; lineNumber <= linesCount; lineNumber++) {
    let currentLineLength = source2.getLineLength(lineNumber);
    let currentLineText = source2.getLineContent(lineNumber);
    const useCurrentLineText = currentLineLength <= 65536;
    let currentLineHasContent = false;
    let currentLineIndentation = 0;
    let currentLineSpacesCount = 0;
    let currentLineTabsCount = 0;
    for (let j = 0, lenJ = currentLineLength; j < lenJ; j++) {
      let charCode = useCurrentLineText ? currentLineText.charCodeAt(j) : source2.getLineCharCode(lineNumber, j);
      if (charCode === 9) {
        currentLineTabsCount++;
      } else if (charCode === 32) {
        currentLineSpacesCount++;
      } else {
        currentLineHasContent = true;
        currentLineIndentation = j;
        break;
      }
    }
    if (!currentLineHasContent) {
      continue;
    }
    if (currentLineTabsCount > 0) {
      linesIndentedWithTabsCount++;
    } else if (currentLineSpacesCount > 1) {
      linesIndentedWithSpacesCount++;
    }
    spacesDiff(previousLineText, previousLineIndentation, currentLineText, currentLineIndentation, tmp);
    if (tmp.looksLikeAlignment) {
      if (!(defaultInsertSpaces && defaultTabSize === tmp.spacesDiff)) {
        continue;
      }
    }
    let currentSpacesDiff = tmp.spacesDiff;
    if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) {
      spacesDiffCount[currentSpacesDiff]++;
    }
    previousLineText = currentLineText;
    previousLineIndentation = currentLineIndentation;
  }
  let insertSpaces = defaultInsertSpaces;
  if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) {
    insertSpaces = linesIndentedWithTabsCount < linesIndentedWithSpacesCount;
  }
  let tabSize = defaultTabSize;
  if (insertSpaces) {
    let tabSizeScore = insertSpaces ? 0 : 0.1 * linesCount;
    ALLOWED_TAB_SIZE_GUESSES.forEach((possibleTabSize) => {
      let possibleTabSizeScore = spacesDiffCount[possibleTabSize];
      if (possibleTabSizeScore > tabSizeScore) {
        tabSizeScore = possibleTabSizeScore;
        tabSize = possibleTabSize;
      }
    });
    if (tabSize === 4 && spacesDiffCount[4] > 0 && spacesDiffCount[2] > 0 && spacesDiffCount[2] >= spacesDiffCount[4] / 2) {
      tabSize = 2;
    }
  }
  return {
    insertSpaces,
    tabSize
  };
}
function getNodeColor(node) {
  return (node.metadata & 1) >>> 0;
}
function setNodeColor(node, color2) {
  node.metadata = node.metadata & 254 | color2 << 0;
}
function getNodeIsVisited(node) {
  return (node.metadata & 2) >>> 1 === 1;
}
function setNodeIsVisited(node, value) {
  node.metadata = node.metadata & 253 | (value ? 1 : 0) << 1;
}
function getNodeIsForValidation(node) {
  return (node.metadata & 4) >>> 2 === 1;
}
function setNodeIsForValidation(node, value) {
  node.metadata = node.metadata & 251 | (value ? 1 : 0) << 2;
}
function getNodeIsInOverviewRuler(node) {
  return (node.metadata & 8) >>> 3 === 1;
}
function setNodeIsInOverviewRuler(node, value) {
  node.metadata = node.metadata & 247 | (value ? 1 : 0) << 3;
}
function getNodeStickiness(node) {
  return (node.metadata & 48) >>> 4;
}
function _setNodeStickiness(node, stickiness) {
  node.metadata = node.metadata & 207 | stickiness << 4;
}
function getCollapseOnReplaceEdit(node) {
  return (node.metadata & 64) >>> 6 === 1;
}
function setCollapseOnReplaceEdit(node, value) {
  node.metadata = node.metadata & 191 | (value ? 1 : 0) << 6;
}
var IntervalNode = class {
  constructor(id3, start3, end2) {
    this.metadata = 0;
    this.parent = this;
    this.left = this;
    this.right = this;
    setNodeColor(this, 1);
    this.start = start3;
    this.end = end2;
    this.delta = 0;
    this.maxEnd = end2;
    this.id = id3;
    this.ownerId = 0;
    this.options = null;
    setNodeIsForValidation(this, false);
    _setNodeStickiness(this, 1);
    setNodeIsInOverviewRuler(this, false);
    setCollapseOnReplaceEdit(this, false);
    this.cachedVersionId = 0;
    this.cachedAbsoluteStart = start3;
    this.cachedAbsoluteEnd = end2;
    this.range = null;
    setNodeIsVisited(this, false);
  }
  reset(versionId, start3, end2, range3) {
    this.start = start3;
    this.end = end2;
    this.maxEnd = end2;
    this.cachedVersionId = versionId;
    this.cachedAbsoluteStart = start3;
    this.cachedAbsoluteEnd = end2;
    this.range = range3;
  }
  setOptions(options) {
    this.options = options;
    let className = this.options.className;
    setNodeIsForValidation(this, className === "squiggly-error" || className === "squiggly-warning" || className === "squiggly-info");
    _setNodeStickiness(this, this.options.stickiness);
    setNodeIsInOverviewRuler(this, this.options.overviewRuler && this.options.overviewRuler.color ? true : false);
    setCollapseOnReplaceEdit(this, this.options.collapseOnReplaceEdit);
  }
  setCachedOffsets(absoluteStart, absoluteEnd, cachedVersionId) {
    if (this.cachedVersionId !== cachedVersionId) {
      this.range = null;
    }
    this.cachedVersionId = cachedVersionId;
    this.cachedAbsoluteStart = absoluteStart;
    this.cachedAbsoluteEnd = absoluteEnd;
  }
  detach() {
    this.parent = null;
    this.left = null;
    this.right = null;
  }
};
var SENTINEL = new IntervalNode(null, 0, 0);
SENTINEL.parent = SENTINEL;
SENTINEL.left = SENTINEL;
SENTINEL.right = SENTINEL;
setNodeColor(SENTINEL, 0);
var IntervalTree = class {
  constructor() {
    this.root = SENTINEL;
    this.requestNormalizeDelta = false;
  }
  intervalSearch(start3, end2, filterOwnerId, filterOutValidation, cachedVersionId) {
    if (this.root === SENTINEL) {
      return [];
    }
    return intervalSearch(this, start3, end2, filterOwnerId, filterOutValidation, cachedVersionId);
  }
  search(filterOwnerId, filterOutValidation, cachedVersionId) {
    if (this.root === SENTINEL) {
      return [];
    }
    return search(this, filterOwnerId, filterOutValidation, cachedVersionId);
  }
  collectNodesFromOwner(ownerId) {
    return collectNodesFromOwner(this, ownerId);
  }
  collectNodesPostOrder() {
    return collectNodesPostOrder(this);
  }
  insert(node) {
    rbTreeInsert(this, node);
    this._normalizeDeltaIfNecessary();
  }
  delete(node) {
    rbTreeDelete(this, node);
    this._normalizeDeltaIfNecessary();
  }
  resolveNode(node, cachedVersionId) {
    const initialNode = node;
    let delta = 0;
    while (node !== this.root) {
      if (node === node.parent.right) {
        delta += node.parent.delta;
      }
      node = node.parent;
    }
    const nodeStart = initialNode.start + delta;
    const nodeEnd = initialNode.end + delta;
    initialNode.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
  }
  acceptReplace(offset2, length, textLength, forceMoveMarkers) {
    const nodesOfInterest = searchForEditing(this, offset2, offset2 + length);
    for (let i3 = 0, len2 = nodesOfInterest.length; i3 < len2; i3++) {
      const node = nodesOfInterest[i3];
      rbTreeDelete(this, node);
    }
    this._normalizeDeltaIfNecessary();
    noOverlapReplace(this, offset2, offset2 + length, textLength);
    this._normalizeDeltaIfNecessary();
    for (let i3 = 0, len2 = nodesOfInterest.length; i3 < len2; i3++) {
      const node = nodesOfInterest[i3];
      node.start = node.cachedAbsoluteStart;
      node.end = node.cachedAbsoluteEnd;
      nodeAcceptEdit(node, offset2, offset2 + length, textLength, forceMoveMarkers);
      node.maxEnd = node.end;
      rbTreeInsert(this, node);
    }
    this._normalizeDeltaIfNecessary();
  }
  _normalizeDeltaIfNecessary() {
    if (!this.requestNormalizeDelta) {
      return;
    }
    this.requestNormalizeDelta = false;
    normalizeDelta(this);
  }
};
function normalizeDelta(T6) {
  let node = T6.root;
  let delta = 0;
  while (node !== SENTINEL) {
    if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {
      node = node.left;
      continue;
    }
    if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
      delta += node.delta;
      node = node.right;
      continue;
    }
    node.start = delta + node.start;
    node.end = delta + node.end;
    node.delta = 0;
    recomputeMaxEnd(node);
    setNodeIsVisited(node, true);
    setNodeIsVisited(node.left, false);
    setNodeIsVisited(node.right, false);
    if (node === node.parent.right) {
      delta -= node.parent.delta;
    }
    node = node.parent;
  }
  setNodeIsVisited(T6.root, false);
}
function adjustMarkerBeforeColumn(markerOffset, markerStickToPreviousCharacter, checkOffset, moveSemantics) {
  if (markerOffset < checkOffset) {
    return true;
  }
  if (markerOffset > checkOffset) {
    return false;
  }
  if (moveSemantics === 1) {
    return false;
  }
  if (moveSemantics === 2) {
    return true;
  }
  return markerStickToPreviousCharacter;
}
function nodeAcceptEdit(node, start3, end2, textLength, forceMoveMarkers) {
  const nodeStickiness = getNodeStickiness(node);
  const startStickToPreviousCharacter = nodeStickiness === 0 || nodeStickiness === 2;
  const endStickToPreviousCharacter = nodeStickiness === 1 || nodeStickiness === 2;
  const deletingCnt = end2 - start3;
  const insertingCnt = textLength;
  const commonLength = Math.min(deletingCnt, insertingCnt);
  const nodeStart = node.start;
  let startDone = false;
  const nodeEnd = node.end;
  let endDone = false;
  if (start3 <= nodeStart && nodeEnd <= end2 && getCollapseOnReplaceEdit(node)) {
    node.start = start3;
    startDone = true;
    node.end = start3;
    endDone = true;
  }
  {
    const moveSemantics = forceMoveMarkers ? 1 : deletingCnt > 0 ? 2 : 0;
    if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start3, moveSemantics)) {
      startDone = true;
    }
    if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start3, moveSemantics)) {
      endDone = true;
    }
  }
  if (commonLength > 0 && !forceMoveMarkers) {
    const moveSemantics = deletingCnt > insertingCnt ? 2 : 0;
    if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start3 + commonLength, moveSemantics)) {
      startDone = true;
    }
    if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start3 + commonLength, moveSemantics)) {
      endDone = true;
    }
  }
  {
    const moveSemantics = forceMoveMarkers ? 1 : 0;
    if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, end2, moveSemantics)) {
      node.start = start3 + insertingCnt;
      startDone = true;
    }
    if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, end2, moveSemantics)) {
      node.end = start3 + insertingCnt;
      endDone = true;
    }
  }
  const deltaColumn = insertingCnt - deletingCnt;
  if (!startDone) {
    node.start = Math.max(0, nodeStart + deltaColumn);
  }
  if (!endDone) {
    node.end = Math.max(0, nodeEnd + deltaColumn);
  }
  if (node.start > node.end) {
    node.end = node.start;
  }
}
function searchForEditing(T6, start3, end2) {
  let node = T6.root;
  let delta = 0;
  let nodeMaxEnd = 0;
  let nodeStart = 0;
  let nodeEnd = 0;
  let result = [];
  let resultLen = 0;
  while (node !== SENTINEL) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      if (node === node.parent.right) {
        delta -= node.parent.delta;
      }
      node = node.parent;
      continue;
    }
    if (!getNodeIsVisited(node.left)) {
      nodeMaxEnd = delta + node.maxEnd;
      if (nodeMaxEnd < start3) {
        setNodeIsVisited(node, true);
        continue;
      }
      if (node.left !== SENTINEL) {
        node = node.left;
        continue;
      }
    }
    nodeStart = delta + node.start;
    if (nodeStart > end2) {
      setNodeIsVisited(node, true);
      continue;
    }
    nodeEnd = delta + node.end;
    if (nodeEnd >= start3) {
      node.setCachedOffsets(nodeStart, nodeEnd, 0);
      result[resultLen++] = node;
    }
    setNodeIsVisited(node, true);
    if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
      delta += node.delta;
      node = node.right;
      continue;
    }
  }
  setNodeIsVisited(T6.root, false);
  return result;
}
function noOverlapReplace(T6, start3, end2, textLength) {
  let node = T6.root;
  let delta = 0;
  let nodeMaxEnd = 0;
  let nodeStart = 0;
  const editDelta = textLength - (end2 - start3);
  while (node !== SENTINEL) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      if (node === node.parent.right) {
        delta -= node.parent.delta;
      }
      recomputeMaxEnd(node);
      node = node.parent;
      continue;
    }
    if (!getNodeIsVisited(node.left)) {
      nodeMaxEnd = delta + node.maxEnd;
      if (nodeMaxEnd < start3) {
        setNodeIsVisited(node, true);
        continue;
      }
      if (node.left !== SENTINEL) {
        node = node.left;
        continue;
      }
    }
    nodeStart = delta + node.start;
    if (nodeStart > end2) {
      node.start += editDelta;
      node.end += editDelta;
      node.delta += editDelta;
      if (node.delta < -1073741824 || node.delta > 1073741824) {
        T6.requestNormalizeDelta = true;
      }
      setNodeIsVisited(node, true);
      continue;
    }
    setNodeIsVisited(node, true);
    if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
      delta += node.delta;
      node = node.right;
      continue;
    }
  }
  setNodeIsVisited(T6.root, false);
}
function collectNodesFromOwner(T6, ownerId) {
  let node = T6.root;
  let result = [];
  let resultLen = 0;
  while (node !== SENTINEL) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      node = node.parent;
      continue;
    }
    if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {
      node = node.left;
      continue;
    }
    if (node.ownerId === ownerId) {
      result[resultLen++] = node;
    }
    setNodeIsVisited(node, true);
    if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
      node = node.right;
      continue;
    }
  }
  setNodeIsVisited(T6.root, false);
  return result;
}
function collectNodesPostOrder(T6) {
  let node = T6.root;
  let result = [];
  let resultLen = 0;
  while (node !== SENTINEL) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      node = node.parent;
      continue;
    }
    if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {
      node = node.left;
      continue;
    }
    if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
      node = node.right;
      continue;
    }
    result[resultLen++] = node;
    setNodeIsVisited(node, true);
  }
  setNodeIsVisited(T6.root, false);
  return result;
}
function search(T6, filterOwnerId, filterOutValidation, cachedVersionId) {
  let node = T6.root;
  let delta = 0;
  let nodeStart = 0;
  let nodeEnd = 0;
  let result = [];
  let resultLen = 0;
  while (node !== SENTINEL) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      if (node === node.parent.right) {
        delta -= node.parent.delta;
      }
      node = node.parent;
      continue;
    }
    if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {
      node = node.left;
      continue;
    }
    nodeStart = delta + node.start;
    nodeEnd = delta + node.end;
    node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
    let include = true;
    if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
      include = false;
    }
    if (filterOutValidation && getNodeIsForValidation(node)) {
      include = false;
    }
    if (include) {
      result[resultLen++] = node;
    }
    setNodeIsVisited(node, true);
    if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
      delta += node.delta;
      node = node.right;
      continue;
    }
  }
  setNodeIsVisited(T6.root, false);
  return result;
}
function intervalSearch(T6, intervalStart, intervalEnd, filterOwnerId, filterOutValidation, cachedVersionId) {
  let node = T6.root;
  let delta = 0;
  let nodeMaxEnd = 0;
  let nodeStart = 0;
  let nodeEnd = 0;
  let result = [];
  let resultLen = 0;
  while (node !== SENTINEL) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      if (node === node.parent.right) {
        delta -= node.parent.delta;
      }
      node = node.parent;
      continue;
    }
    if (!getNodeIsVisited(node.left)) {
      nodeMaxEnd = delta + node.maxEnd;
      if (nodeMaxEnd < intervalStart) {
        setNodeIsVisited(node, true);
        continue;
      }
      if (node.left !== SENTINEL) {
        node = node.left;
        continue;
      }
    }
    nodeStart = delta + node.start;
    if (nodeStart > intervalEnd) {
      setNodeIsVisited(node, true);
      continue;
    }
    nodeEnd = delta + node.end;
    if (nodeEnd >= intervalStart) {
      node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
      let include = true;
      if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
        include = false;
      }
      if (filterOutValidation && getNodeIsForValidation(node)) {
        include = false;
      }
      if (include) {
        result[resultLen++] = node;
      }
    }
    setNodeIsVisited(node, true);
    if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
      delta += node.delta;
      node = node.right;
      continue;
    }
  }
  setNodeIsVisited(T6.root, false);
  return result;
}
function rbTreeInsert(T6, newNode) {
  if (T6.root === SENTINEL) {
    newNode.parent = SENTINEL;
    newNode.left = SENTINEL;
    newNode.right = SENTINEL;
    setNodeColor(newNode, 0);
    T6.root = newNode;
    return T6.root;
  }
  treeInsert(T6, newNode);
  recomputeMaxEndWalkToRoot(newNode.parent);
  let x2 = newNode;
  while (x2 !== T6.root && getNodeColor(x2.parent) === 1) {
    if (x2.parent === x2.parent.parent.left) {
      const y3 = x2.parent.parent.right;
      if (getNodeColor(y3) === 1) {
        setNodeColor(x2.parent, 0);
        setNodeColor(y3, 0);
        setNodeColor(x2.parent.parent, 1);
        x2 = x2.parent.parent;
      } else {
        if (x2 === x2.parent.right) {
          x2 = x2.parent;
          leftRotate$1(T6, x2);
        }
        setNodeColor(x2.parent, 0);
        setNodeColor(x2.parent.parent, 1);
        rightRotate(T6, x2.parent.parent);
      }
    } else {
      const y3 = x2.parent.parent.left;
      if (getNodeColor(y3) === 1) {
        setNodeColor(x2.parent, 0);
        setNodeColor(y3, 0);
        setNodeColor(x2.parent.parent, 1);
        x2 = x2.parent.parent;
      } else {
        if (x2 === x2.parent.left) {
          x2 = x2.parent;
          rightRotate(T6, x2);
        }
        setNodeColor(x2.parent, 0);
        setNodeColor(x2.parent.parent, 1);
        leftRotate$1(T6, x2.parent.parent);
      }
    }
  }
  setNodeColor(T6.root, 0);
  return newNode;
}
function treeInsert(T6, z2) {
  let delta = 0;
  let x2 = T6.root;
  const zAbsoluteStart = z2.start;
  const zAbsoluteEnd = z2.end;
  while (true) {
    const cmp2 = intervalCompare(zAbsoluteStart, zAbsoluteEnd, x2.start + delta, x2.end + delta);
    if (cmp2 < 0) {
      if (x2.left === SENTINEL) {
        z2.start -= delta;
        z2.end -= delta;
        z2.maxEnd -= delta;
        x2.left = z2;
        break;
      } else {
        x2 = x2.left;
      }
    } else {
      if (x2.right === SENTINEL) {
        z2.start -= delta + x2.delta;
        z2.end -= delta + x2.delta;
        z2.maxEnd -= delta + x2.delta;
        x2.right = z2;
        break;
      } else {
        delta += x2.delta;
        x2 = x2.right;
      }
    }
  }
  z2.parent = x2;
  z2.left = SENTINEL;
  z2.right = SENTINEL;
  setNodeColor(z2, 1);
}
function rbTreeDelete(T6, z2) {
  let x2;
  let y3;
  if (z2.left === SENTINEL) {
    x2 = z2.right;
    y3 = z2;
    x2.delta += z2.delta;
    if (x2.delta < -1073741824 || x2.delta > 1073741824) {
      T6.requestNormalizeDelta = true;
    }
    x2.start += z2.delta;
    x2.end += z2.delta;
  } else if (z2.right === SENTINEL) {
    x2 = z2.left;
    y3 = z2;
  } else {
    y3 = leftest(z2.right);
    x2 = y3.right;
    x2.start += y3.delta;
    x2.end += y3.delta;
    x2.delta += y3.delta;
    if (x2.delta < -1073741824 || x2.delta > 1073741824) {
      T6.requestNormalizeDelta = true;
    }
    y3.start += z2.delta;
    y3.end += z2.delta;
    y3.delta = z2.delta;
    if (y3.delta < -1073741824 || y3.delta > 1073741824) {
      T6.requestNormalizeDelta = true;
    }
  }
  if (y3 === T6.root) {
    T6.root = x2;
    setNodeColor(x2, 0);
    z2.detach();
    resetSentinel();
    recomputeMaxEnd(x2);
    T6.root.parent = SENTINEL;
    return;
  }
  let yWasRed = getNodeColor(y3) === 1;
  if (y3 === y3.parent.left) {
    y3.parent.left = x2;
  } else {
    y3.parent.right = x2;
  }
  if (y3 === z2) {
    x2.parent = y3.parent;
  } else {
    if (y3.parent === z2) {
      x2.parent = y3;
    } else {
      x2.parent = y3.parent;
    }
    y3.left = z2.left;
    y3.right = z2.right;
    y3.parent = z2.parent;
    setNodeColor(y3, getNodeColor(z2));
    if (z2 === T6.root) {
      T6.root = y3;
    } else {
      if (z2 === z2.parent.left) {
        z2.parent.left = y3;
      } else {
        z2.parent.right = y3;
      }
    }
    if (y3.left !== SENTINEL) {
      y3.left.parent = y3;
    }
    if (y3.right !== SENTINEL) {
      y3.right.parent = y3;
    }
  }
  z2.detach();
  if (yWasRed) {
    recomputeMaxEndWalkToRoot(x2.parent);
    if (y3 !== z2) {
      recomputeMaxEndWalkToRoot(y3);
      recomputeMaxEndWalkToRoot(y3.parent);
    }
    resetSentinel();
    return;
  }
  recomputeMaxEndWalkToRoot(x2);
  recomputeMaxEndWalkToRoot(x2.parent);
  if (y3 !== z2) {
    recomputeMaxEndWalkToRoot(y3);
    recomputeMaxEndWalkToRoot(y3.parent);
  }
  let w2;
  while (x2 !== T6.root && getNodeColor(x2) === 0) {
    if (x2 === x2.parent.left) {
      w2 = x2.parent.right;
      if (getNodeColor(w2) === 1) {
        setNodeColor(w2, 0);
        setNodeColor(x2.parent, 1);
        leftRotate$1(T6, x2.parent);
        w2 = x2.parent.right;
      }
      if (getNodeColor(w2.left) === 0 && getNodeColor(w2.right) === 0) {
        setNodeColor(w2, 1);
        x2 = x2.parent;
      } else {
        if (getNodeColor(w2.right) === 0) {
          setNodeColor(w2.left, 0);
          setNodeColor(w2, 1);
          rightRotate(T6, w2);
          w2 = x2.parent.right;
        }
        setNodeColor(w2, getNodeColor(x2.parent));
        setNodeColor(x2.parent, 0);
        setNodeColor(w2.right, 0);
        leftRotate$1(T6, x2.parent);
        x2 = T6.root;
      }
    } else {
      w2 = x2.parent.left;
      if (getNodeColor(w2) === 1) {
        setNodeColor(w2, 0);
        setNodeColor(x2.parent, 1);
        rightRotate(T6, x2.parent);
        w2 = x2.parent.left;
      }
      if (getNodeColor(w2.left) === 0 && getNodeColor(w2.right) === 0) {
        setNodeColor(w2, 1);
        x2 = x2.parent;
      } else {
        if (getNodeColor(w2.left) === 0) {
          setNodeColor(w2.right, 0);
          setNodeColor(w2, 1);
          leftRotate$1(T6, w2);
          w2 = x2.parent.left;
        }
        setNodeColor(w2, getNodeColor(x2.parent));
        setNodeColor(x2.parent, 0);
        setNodeColor(w2.left, 0);
        rightRotate(T6, x2.parent);
        x2 = T6.root;
      }
    }
  }
  setNodeColor(x2, 0);
  resetSentinel();
}
function leftest(node) {
  while (node.left !== SENTINEL) {
    node = node.left;
  }
  return node;
}
function resetSentinel() {
  SENTINEL.parent = SENTINEL;
  SENTINEL.delta = 0;
  SENTINEL.start = 0;
  SENTINEL.end = 0;
}
function leftRotate$1(T6, x2) {
  const y3 = x2.right;
  y3.delta += x2.delta;
  if (y3.delta < -1073741824 || y3.delta > 1073741824) {
    T6.requestNormalizeDelta = true;
  }
  y3.start += x2.delta;
  y3.end += x2.delta;
  x2.right = y3.left;
  if (y3.left !== SENTINEL) {
    y3.left.parent = x2;
  }
  y3.parent = x2.parent;
  if (x2.parent === SENTINEL) {
    T6.root = y3;
  } else if (x2 === x2.parent.left) {
    x2.parent.left = y3;
  } else {
    x2.parent.right = y3;
  }
  y3.left = x2;
  x2.parent = y3;
  recomputeMaxEnd(x2);
  recomputeMaxEnd(y3);
}
function rightRotate(T6, y3) {
  const x2 = y3.left;
  y3.delta -= x2.delta;
  if (y3.delta < -1073741824 || y3.delta > 1073741824) {
    T6.requestNormalizeDelta = true;
  }
  y3.start -= x2.delta;
  y3.end -= x2.delta;
  y3.left = x2.right;
  if (x2.right !== SENTINEL) {
    x2.right.parent = y3;
  }
  x2.parent = y3.parent;
  if (y3.parent === SENTINEL) {
    T6.root = x2;
  } else if (y3 === y3.parent.right) {
    y3.parent.right = x2;
  } else {
    y3.parent.left = x2;
  }
  x2.right = y3;
  y3.parent = x2;
  recomputeMaxEnd(y3);
  recomputeMaxEnd(x2);
}
function computeMaxEnd(node) {
  let maxEnd = node.end;
  if (node.left !== SENTINEL) {
    const leftMaxEnd = node.left.maxEnd;
    if (leftMaxEnd > maxEnd) {
      maxEnd = leftMaxEnd;
    }
  }
  if (node.right !== SENTINEL) {
    const rightMaxEnd = node.right.maxEnd + node.delta;
    if (rightMaxEnd > maxEnd) {
      maxEnd = rightMaxEnd;
    }
  }
  return maxEnd;
}
function recomputeMaxEnd(node) {
  node.maxEnd = computeMaxEnd(node);
}
function recomputeMaxEndWalkToRoot(node) {
  while (node !== SENTINEL) {
    const maxEnd = computeMaxEnd(node);
    if (node.maxEnd === maxEnd) {
      return;
    }
    node.maxEnd = maxEnd;
    node = node.parent;
  }
}
function intervalCompare(aStart, aEnd, bStart, bEnd) {
  if (aStart === bStart) {
    return aEnd - bEnd;
  }
  return aStart - bStart;
}
var TreeNode = class {
  constructor(piece, color2) {
    this.piece = piece;
    this.color = color2;
    this.size_left = 0;
    this.lf_left = 0;
    this.parent = this;
    this.left = this;
    this.right = this;
  }
  next() {
    if (this.right !== SENTINEL$1) {
      return leftest$1(this.right);
    }
    let node = this;
    while (node.parent !== SENTINEL$1) {
      if (node.parent.left === node) {
        break;
      }
      node = node.parent;
    }
    if (node.parent === SENTINEL$1) {
      return SENTINEL$1;
    } else {
      return node.parent;
    }
  }
  prev() {
    if (this.left !== SENTINEL$1) {
      return righttest(this.left);
    }
    let node = this;
    while (node.parent !== SENTINEL$1) {
      if (node.parent.right === node) {
        break;
      }
      node = node.parent;
    }
    if (node.parent === SENTINEL$1) {
      return SENTINEL$1;
    } else {
      return node.parent;
    }
  }
  detach() {
    this.parent = null;
    this.left = null;
    this.right = null;
  }
};
var SENTINEL$1 = new TreeNode(null, 0);
SENTINEL$1.parent = SENTINEL$1;
SENTINEL$1.left = SENTINEL$1;
SENTINEL$1.right = SENTINEL$1;
SENTINEL$1.color = 0;
function leftest$1(node) {
  while (node.left !== SENTINEL$1) {
    node = node.left;
  }
  return node;
}
function righttest(node) {
  while (node.right !== SENTINEL$1) {
    node = node.right;
  }
  return node;
}
function calculateSize(node) {
  if (node === SENTINEL$1) {
    return 0;
  }
  return node.size_left + node.piece.length + calculateSize(node.right);
}
function calculateLF(node) {
  if (node === SENTINEL$1) {
    return 0;
  }
  return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right);
}
function resetSentinel$1() {
  SENTINEL$1.parent = SENTINEL$1;
}
function leftRotate$2(tree, x2) {
  let y3 = x2.right;
  y3.size_left += x2.size_left + (x2.piece ? x2.piece.length : 0);
  y3.lf_left += x2.lf_left + (x2.piece ? x2.piece.lineFeedCnt : 0);
  x2.right = y3.left;
  if (y3.left !== SENTINEL$1) {
    y3.left.parent = x2;
  }
  y3.parent = x2.parent;
  if (x2.parent === SENTINEL$1) {
    tree.root = y3;
  } else if (x2.parent.left === x2) {
    x2.parent.left = y3;
  } else {
    x2.parent.right = y3;
  }
  y3.left = x2;
  x2.parent = y3;
}
function rightRotate$1(tree, y3) {
  let x2 = y3.left;
  y3.left = x2.right;
  if (x2.right !== SENTINEL$1) {
    x2.right.parent = y3;
  }
  x2.parent = y3.parent;
  y3.size_left -= x2.size_left + (x2.piece ? x2.piece.length : 0);
  y3.lf_left -= x2.lf_left + (x2.piece ? x2.piece.lineFeedCnt : 0);
  if (y3.parent === SENTINEL$1) {
    tree.root = x2;
  } else if (y3 === y3.parent.right) {
    y3.parent.right = x2;
  } else {
    y3.parent.left = x2;
  }
  x2.right = y3;
  y3.parent = x2;
}
function rbDelete(tree, z2) {
  let x2;
  let y3;
  if (z2.left === SENTINEL$1) {
    y3 = z2;
    x2 = y3.right;
  } else if (z2.right === SENTINEL$1) {
    y3 = z2;
    x2 = y3.left;
  } else {
    y3 = leftest$1(z2.right);
    x2 = y3.right;
  }
  if (y3 === tree.root) {
    tree.root = x2;
    x2.color = 0;
    z2.detach();
    resetSentinel$1();
    tree.root.parent = SENTINEL$1;
    return;
  }
  let yWasRed = y3.color === 1;
  if (y3 === y3.parent.left) {
    y3.parent.left = x2;
  } else {
    y3.parent.right = x2;
  }
  if (y3 === z2) {
    x2.parent = y3.parent;
    recomputeTreeMetadata(tree, x2);
  } else {
    if (y3.parent === z2) {
      x2.parent = y3;
    } else {
      x2.parent = y3.parent;
    }
    recomputeTreeMetadata(tree, x2);
    y3.left = z2.left;
    y3.right = z2.right;
    y3.parent = z2.parent;
    y3.color = z2.color;
    if (z2 === tree.root) {
      tree.root = y3;
    } else {
      if (z2 === z2.parent.left) {
        z2.parent.left = y3;
      } else {
        z2.parent.right = y3;
      }
    }
    if (y3.left !== SENTINEL$1) {
      y3.left.parent = y3;
    }
    if (y3.right !== SENTINEL$1) {
      y3.right.parent = y3;
    }
    y3.size_left = z2.size_left;
    y3.lf_left = z2.lf_left;
    recomputeTreeMetadata(tree, y3);
  }
  z2.detach();
  if (x2.parent.left === x2) {
    let newSizeLeft = calculateSize(x2);
    let newLFLeft = calculateLF(x2);
    if (newSizeLeft !== x2.parent.size_left || newLFLeft !== x2.parent.lf_left) {
      let delta = newSizeLeft - x2.parent.size_left;
      let lf_delta = newLFLeft - x2.parent.lf_left;
      x2.parent.size_left = newSizeLeft;
      x2.parent.lf_left = newLFLeft;
      updateTreeMetadata(tree, x2.parent, delta, lf_delta);
    }
  }
  recomputeTreeMetadata(tree, x2.parent);
  if (yWasRed) {
    resetSentinel$1();
    return;
  }
  let w2;
  while (x2 !== tree.root && x2.color === 0) {
    if (x2 === x2.parent.left) {
      w2 = x2.parent.right;
      if (w2.color === 1) {
        w2.color = 0;
        x2.parent.color = 1;
        leftRotate$2(tree, x2.parent);
        w2 = x2.parent.right;
      }
      if (w2.left.color === 0 && w2.right.color === 0) {
        w2.color = 1;
        x2 = x2.parent;
      } else {
        if (w2.right.color === 0) {
          w2.left.color = 0;
          w2.color = 1;
          rightRotate$1(tree, w2);
          w2 = x2.parent.right;
        }
        w2.color = x2.parent.color;
        x2.parent.color = 0;
        w2.right.color = 0;
        leftRotate$2(tree, x2.parent);
        x2 = tree.root;
      }
    } else {
      w2 = x2.parent.left;
      if (w2.color === 1) {
        w2.color = 0;
        x2.parent.color = 1;
        rightRotate$1(tree, x2.parent);
        w2 = x2.parent.left;
      }
      if (w2.left.color === 0 && w2.right.color === 0) {
        w2.color = 1;
        x2 = x2.parent;
      } else {
        if (w2.left.color === 0) {
          w2.right.color = 0;
          w2.color = 1;
          leftRotate$2(tree, w2);
          w2 = x2.parent.left;
        }
        w2.color = x2.parent.color;
        x2.parent.color = 0;
        w2.left.color = 0;
        rightRotate$1(tree, x2.parent);
        x2 = tree.root;
      }
    }
  }
  x2.color = 0;
  resetSentinel$1();
}
function fixInsert(tree, x2) {
  recomputeTreeMetadata(tree, x2);
  while (x2 !== tree.root && x2.parent.color === 1) {
    if (x2.parent === x2.parent.parent.left) {
      const y3 = x2.parent.parent.right;
      if (y3.color === 1) {
        x2.parent.color = 0;
        y3.color = 0;
        x2.parent.parent.color = 1;
        x2 = x2.parent.parent;
      } else {
        if (x2 === x2.parent.right) {
          x2 = x2.parent;
          leftRotate$2(tree, x2);
        }
        x2.parent.color = 0;
        x2.parent.parent.color = 1;
        rightRotate$1(tree, x2.parent.parent);
      }
    } else {
      const y3 = x2.parent.parent.left;
      if (y3.color === 1) {
        x2.parent.color = 0;
        y3.color = 0;
        x2.parent.parent.color = 1;
        x2 = x2.parent.parent;
      } else {
        if (x2 === x2.parent.left) {
          x2 = x2.parent;
          rightRotate$1(tree, x2);
        }
        x2.parent.color = 0;
        x2.parent.parent.color = 1;
        leftRotate$2(tree, x2.parent.parent);
      }
    }
  }
  tree.root.color = 0;
}
function updateTreeMetadata(tree, x2, delta, lineFeedCntDelta) {
  while (x2 !== tree.root && x2 !== SENTINEL$1) {
    if (x2.parent.left === x2) {
      x2.parent.size_left += delta;
      x2.parent.lf_left += lineFeedCntDelta;
    }
    x2 = x2.parent;
  }
}
function recomputeTreeMetadata(tree, x2) {
  let delta = 0;
  let lf_delta = 0;
  if (x2 === tree.root) {
    return;
  }
  if (delta === 0) {
    while (x2 !== tree.root && x2 === x2.parent.right) {
      x2 = x2.parent;
    }
    if (x2 === tree.root) {
      return;
    }
    x2 = x2.parent;
    delta = calculateSize(x2.left) - x2.size_left;
    lf_delta = calculateLF(x2.left) - x2.lf_left;
    x2.size_left += delta;
    x2.lf_left += lf_delta;
  }
  while (x2 !== tree.root && (delta !== 0 || lf_delta !== 0)) {
    if (x2.parent.left === x2) {
      x2.parent.size_left += delta;
      x2.parent.lf_left += lf_delta;
    }
    x2 = x2.parent;
  }
}
var WordCharacterClassifier = class extends CharacterClassifier {
  constructor(wordSeparators2) {
    super(0);
    for (let i3 = 0, len2 = wordSeparators2.length; i3 < len2; i3++) {
      this.set(wordSeparators2.charCodeAt(i3), 2);
    }
    this.set(32, 1);
    this.set(9, 1);
  }
};
function once2(computeFn) {
  let cache3 = {};
  return (input) => {
    if (!cache3.hasOwnProperty(input)) {
      cache3[input] = computeFn(input);
    }
    return cache3[input];
  };
}
var getMapForWordSeparators = once2((input) => new WordCharacterClassifier(input));
var LIMIT_FIND_COUNT = 999;
var SearchParams = class {
  constructor(searchString, isRegex2, matchCase, wordSeparators2) {
    this.searchString = searchString;
    this.isRegex = isRegex2;
    this.matchCase = matchCase;
    this.wordSeparators = wordSeparators2;
  }
  parseSearchRequest() {
    if (this.searchString === "") {
      return null;
    }
    let multiline;
    if (this.isRegex) {
      multiline = isMultilineRegexSource(this.searchString);
    } else {
      multiline = this.searchString.indexOf("\n") >= 0;
    }
    let regex = null;
    try {
      regex = createRegExp(this.searchString, this.isRegex, {
        matchCase: this.matchCase,
        wholeWord: false,
        multiline,
        global: true,
        unicode: true
      });
    } catch (err) {
      return null;
    }
    if (!regex) {
      return null;
    }
    let canUseSimpleSearch = !this.isRegex && !multiline;
    if (canUseSimpleSearch && this.searchString.toLowerCase() !== this.searchString.toUpperCase()) {
      canUseSimpleSearch = this.matchCase;
    }
    return new SearchData(regex, this.wordSeparators ? getMapForWordSeparators(this.wordSeparators) : null, canUseSimpleSearch ? this.searchString : null);
  }
};
function isMultilineRegexSource(searchString) {
  if (!searchString || searchString.length === 0) {
    return false;
  }
  for (let i3 = 0, len2 = searchString.length; i3 < len2; i3++) {
    const chCode = searchString.charCodeAt(i3);
    if (chCode === 92) {
      i3++;
      if (i3 >= len2) {
        break;
      }
      const nextChCode = searchString.charCodeAt(i3);
      if (nextChCode === 110 || nextChCode === 114 || nextChCode === 87 || nextChCode === 119) {
        return true;
      }
    }
  }
  return false;
}
var SearchData = class {
  constructor(regex, wordSeparators2, simpleSearch) {
    this.regex = regex;
    this.wordSeparators = wordSeparators2;
    this.simpleSearch = simpleSearch;
  }
};
function createFindMatch(range3, rawMatches, captureMatches) {
  if (!captureMatches) {
    return new FindMatch(range3, null);
  }
  let matches2 = [];
  for (let i3 = 0, len2 = rawMatches.length; i3 < len2; i3++) {
    matches2[i3] = rawMatches[i3];
  }
  return new FindMatch(range3, matches2);
}
var LineFeedCounter = class {
  constructor(text) {
    let lineFeedsOffsets = [];
    let lineFeedsOffsetsLen = 0;
    for (let i3 = 0, textLen = text.length; i3 < textLen; i3++) {
      if (text.charCodeAt(i3) === 10) {
        lineFeedsOffsets[lineFeedsOffsetsLen++] = i3;
      }
    }
    this._lineFeedsOffsets = lineFeedsOffsets;
  }
  findLineFeedCountBeforeOffset(offset2) {
    const lineFeedsOffsets = this._lineFeedsOffsets;
    let min2 = 0;
    let max2 = lineFeedsOffsets.length - 1;
    if (max2 === -1) {
      return 0;
    }
    if (offset2 <= lineFeedsOffsets[0]) {
      return 0;
    }
    while (min2 < max2) {
      const mid = min2 + ((max2 - min2) / 2 >> 0);
      if (lineFeedsOffsets[mid] >= offset2) {
        max2 = mid - 1;
      } else {
        if (lineFeedsOffsets[mid + 1] >= offset2) {
          min2 = mid;
          max2 = mid;
        } else {
          min2 = mid + 1;
        }
      }
    }
    return min2 + 1;
  }
};
var TextModelSearch = class {
  static findMatches(model, searchParams, searchRange, captureMatches, limitResultCount) {
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return [];
    }
    if (searchData.regex.multiline) {
      return this._doFindMatchesMultiline(model, searchRange, new Searcher(searchData.wordSeparators, searchData.regex), captureMatches, limitResultCount);
    }
    return this._doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount);
  }
  static _getMultilineMatchRange(model, deltaOffset, text, lfCounter, matchIndex, match0) {
    let startOffset;
    let lineFeedCountBeforeMatch = 0;
    if (lfCounter) {
      lineFeedCountBeforeMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex);
      startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch;
    } else {
      startOffset = deltaOffset + matchIndex;
    }
    let endOffset;
    if (lfCounter) {
      let lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length);
      let lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch;
      endOffset = startOffset + match0.length + lineFeedCountInMatch;
    } else {
      endOffset = startOffset + match0.length;
    }
    const startPosition = model.getPositionAt(startOffset);
    const endPosition = model.getPositionAt(endOffset);
    return new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
  }
  static _doFindMatchesMultiline(model, searchRange, searcher, captureMatches, limitResultCount) {
    const deltaOffset = model.getOffsetAt(searchRange.getStartPosition());
    const text = model.getValueInRange(searchRange, 1);
    const lfCounter = model.getEOL() === "\r\n" ? new LineFeedCounter(text) : null;
    const result = [];
    let counter = 0;
    let m2;
    searcher.reset(0);
    while (m2 = searcher.next(text)) {
      result[counter++] = createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m2.index, m2[0]), m2, captureMatches);
      if (counter >= limitResultCount) {
        return result;
      }
    }
    return result;
  }
  static _doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount) {
    const result = [];
    let resultLen = 0;
    if (searchRange.startLineNumber === searchRange.endLineNumber) {
      const text2 = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1);
      resultLen = this._findMatchesInLine(searchData, text2, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
      return result;
    }
    const text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1);
    resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
    for (let lineNumber = searchRange.startLineNumber + 1; lineNumber < searchRange.endLineNumber && resultLen < limitResultCount; lineNumber++) {
      resultLen = this._findMatchesInLine(searchData, model.getLineContent(lineNumber), lineNumber, 0, resultLen, result, captureMatches, limitResultCount);
    }
    if (resultLen < limitResultCount) {
      const text2 = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1);
      resultLen = this._findMatchesInLine(searchData, text2, searchRange.endLineNumber, 0, resultLen, result, captureMatches, limitResultCount);
    }
    return result;
  }
  static _findMatchesInLine(searchData, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
    const wordSeparators2 = searchData.wordSeparators;
    if (!captureMatches && searchData.simpleSearch) {
      const searchString = searchData.simpleSearch;
      const searchStringLen = searchString.length;
      const textLength = text.length;
      let lastMatchIndex = -searchStringLen;
      while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
        if (!wordSeparators2 || isValidMatch(wordSeparators2, text, textLength, lastMatchIndex, searchStringLen)) {
          result[resultLen++] = new FindMatch(new Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
          if (resultLen >= limitResultCount) {
            return resultLen;
          }
        }
      }
      return resultLen;
    }
    const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
    let m2;
    searcher.reset(0);
    do {
      m2 = searcher.next(text);
      if (m2) {
        result[resultLen++] = createFindMatch(new Range(lineNumber, m2.index + 1 + deltaOffset, lineNumber, m2.index + 1 + m2[0].length + deltaOffset), m2, captureMatches);
        if (resultLen >= limitResultCount) {
          return resultLen;
        }
      }
    } while (m2);
    return resultLen;
  }
  static findNextMatch(model, searchParams, searchStart, captureMatches) {
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return null;
    }
    const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
    if (searchData.regex.multiline) {
      return this._doFindNextMatchMultiline(model, searchStart, searcher, captureMatches);
    }
    return this._doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches);
  }
  static _doFindNextMatchMultiline(model, searchStart, searcher, captureMatches) {
    const searchTextStart = new Position(searchStart.lineNumber, 1);
    const deltaOffset = model.getOffsetAt(searchTextStart);
    const lineCount = model.getLineCount();
    const text = model.getValueInRange(new Range(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)), 1);
    const lfCounter = model.getEOL() === "\r\n" ? new LineFeedCounter(text) : null;
    searcher.reset(searchStart.column - 1);
    let m2 = searcher.next(text);
    if (m2) {
      return createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m2.index, m2[0]), m2, captureMatches);
    }
    if (searchStart.lineNumber !== 1 || searchStart.column !== 1) {
      return this._doFindNextMatchMultiline(model, new Position(1, 1), searcher, captureMatches);
    }
    return null;
  }
  static _doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches) {
    const lineCount = model.getLineCount();
    const startLineNumber = searchStart.lineNumber;
    const text = model.getLineContent(startLineNumber);
    const r3 = this._findFirstMatchInLine(searcher, text, startLineNumber, searchStart.column, captureMatches);
    if (r3) {
      return r3;
    }
    for (let i3 = 1; i3 <= lineCount; i3++) {
      const lineIndex = (startLineNumber + i3 - 1) % lineCount;
      const text2 = model.getLineContent(lineIndex + 1);
      const r4 = this._findFirstMatchInLine(searcher, text2, lineIndex + 1, 1, captureMatches);
      if (r4) {
        return r4;
      }
    }
    return null;
  }
  static _findFirstMatchInLine(searcher, text, lineNumber, fromColumn, captureMatches) {
    searcher.reset(fromColumn - 1);
    const m2 = searcher.next(text);
    if (m2) {
      return createFindMatch(new Range(lineNumber, m2.index + 1, lineNumber, m2.index + 1 + m2[0].length), m2, captureMatches);
    }
    return null;
  }
  static findPreviousMatch(model, searchParams, searchStart, captureMatches) {
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return null;
    }
    const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
    if (searchData.regex.multiline) {
      return this._doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches);
    }
    return this._doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches);
  }
  static _doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches) {
    const matches2 = this._doFindMatchesMultiline(model, new Range(1, 1, searchStart.lineNumber, searchStart.column), searcher, captureMatches, 10 * LIMIT_FIND_COUNT);
    if (matches2.length > 0) {
      return matches2[matches2.length - 1];
    }
    const lineCount = model.getLineCount();
    if (searchStart.lineNumber !== lineCount || searchStart.column !== model.getLineMaxColumn(lineCount)) {
      return this._doFindPreviousMatchMultiline(model, new Position(lineCount, model.getLineMaxColumn(lineCount)), searcher, captureMatches);
    }
    return null;
  }
  static _doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches) {
    const lineCount = model.getLineCount();
    const startLineNumber = searchStart.lineNumber;
    const text = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1);
    const r3 = this._findLastMatchInLine(searcher, text, startLineNumber, captureMatches);
    if (r3) {
      return r3;
    }
    for (let i3 = 1; i3 <= lineCount; i3++) {
      const lineIndex = (lineCount + startLineNumber - i3 - 1) % lineCount;
      const text2 = model.getLineContent(lineIndex + 1);
      const r4 = this._findLastMatchInLine(searcher, text2, lineIndex + 1, captureMatches);
      if (r4) {
        return r4;
      }
    }
    return null;
  }
  static _findLastMatchInLine(searcher, text, lineNumber, captureMatches) {
    let bestResult = null;
    let m2;
    searcher.reset(0);
    while (m2 = searcher.next(text)) {
      bestResult = createFindMatch(new Range(lineNumber, m2.index + 1, lineNumber, m2.index + 1 + m2[0].length), m2, captureMatches);
    }
    return bestResult;
  }
};
function leftIsWordBounday(wordSeparators2, text, textLength, matchStartIndex, matchLength) {
  if (matchStartIndex === 0) {
    return true;
  }
  const charBefore = text.charCodeAt(matchStartIndex - 1);
  if (wordSeparators2.get(charBefore) !== 0) {
    return true;
  }
  if (charBefore === 13 || charBefore === 10) {
    return true;
  }
  if (matchLength > 0) {
    const firstCharInMatch = text.charCodeAt(matchStartIndex);
    if (wordSeparators2.get(firstCharInMatch) !== 0) {
      return true;
    }
  }
  return false;
}
function rightIsWordBounday(wordSeparators2, text, textLength, matchStartIndex, matchLength) {
  if (matchStartIndex + matchLength === textLength) {
    return true;
  }
  const charAfter = text.charCodeAt(matchStartIndex + matchLength);
  if (wordSeparators2.get(charAfter) !== 0) {
    return true;
  }
  if (charAfter === 13 || charAfter === 10) {
    return true;
  }
  if (matchLength > 0) {
    const lastCharInMatch = text.charCodeAt(matchStartIndex + matchLength - 1);
    if (wordSeparators2.get(lastCharInMatch) !== 0) {
      return true;
    }
  }
  return false;
}
function isValidMatch(wordSeparators2, text, textLength, matchStartIndex, matchLength) {
  return leftIsWordBounday(wordSeparators2, text, textLength, matchStartIndex, matchLength) && rightIsWordBounday(wordSeparators2, text, textLength, matchStartIndex, matchLength);
}
var Searcher = class {
  constructor(wordSeparators2, searchRegex) {
    this._wordSeparators = wordSeparators2;
    this._searchRegex = searchRegex;
    this._prevMatchStartIndex = -1;
    this._prevMatchLength = 0;
  }
  reset(lastIndex) {
    this._searchRegex.lastIndex = lastIndex;
    this._prevMatchStartIndex = -1;
    this._prevMatchLength = 0;
  }
  next(text) {
    const textLength = text.length;
    let m2;
    do {
      if (this._prevMatchStartIndex + this._prevMatchLength === textLength) {
        return null;
      }
      m2 = this._searchRegex.exec(text);
      if (!m2) {
        return null;
      }
      const matchStartIndex = m2.index;
      const matchLength = m2[0].length;
      if (matchStartIndex === this._prevMatchStartIndex && matchLength === this._prevMatchLength) {
        if (matchLength === 0) {
          if (getNextCodePoint(text, textLength, this._searchRegex.lastIndex) > 65535) {
            this._searchRegex.lastIndex += 2;
          } else {
            this._searchRegex.lastIndex += 1;
          }
          continue;
        }
        return null;
      }
      this._prevMatchStartIndex = matchStartIndex;
      this._prevMatchLength = matchLength;
      if (!this._wordSeparators || isValidMatch(this._wordSeparators, text, textLength, matchStartIndex, matchLength)) {
        return m2;
      }
    } while (m2);
    return null;
  }
};
var AverageBufferSize = 65535;
function createUintArray(arr) {
  let r3;
  if (arr[arr.length - 1] < 65536) {
    r3 = new Uint16Array(arr.length);
  } else {
    r3 = new Uint32Array(arr.length);
  }
  r3.set(arr, 0);
  return r3;
}
var LineStarts = class {
  constructor(lineStarts, cr, lf2, crlf, isBasicASCII2) {
    this.lineStarts = lineStarts;
    this.cr = cr;
    this.lf = lf2;
    this.crlf = crlf;
    this.isBasicASCII = isBasicASCII2;
  }
};
function createLineStartsFast(str, readonly = true) {
  let r3 = [0], rLength = 1;
  for (let i3 = 0, len2 = str.length; i3 < len2; i3++) {
    const chr = str.charCodeAt(i3);
    if (chr === 13) {
      if (i3 + 1 < len2 && str.charCodeAt(i3 + 1) === 10) {
        r3[rLength++] = i3 + 2;
        i3++;
      } else {
        r3[rLength++] = i3 + 1;
      }
    } else if (chr === 10) {
      r3[rLength++] = i3 + 1;
    }
  }
  if (readonly) {
    return createUintArray(r3);
  } else {
    return r3;
  }
}
function createLineStarts(r3, str) {
  r3.length = 0;
  r3[0] = 0;
  let rLength = 1;
  let cr = 0, lf2 = 0, crlf = 0;
  let isBasicASCII2 = true;
  for (let i3 = 0, len2 = str.length; i3 < len2; i3++) {
    const chr = str.charCodeAt(i3);
    if (chr === 13) {
      if (i3 + 1 < len2 && str.charCodeAt(i3 + 1) === 10) {
        crlf++;
        r3[rLength++] = i3 + 2;
        i3++;
      } else {
        cr++;
        r3[rLength++] = i3 + 1;
      }
    } else if (chr === 10) {
      lf2++;
      r3[rLength++] = i3 + 1;
    } else {
      if (isBasicASCII2) {
        if (chr !== 9 && (chr < 32 || chr > 126)) {
          isBasicASCII2 = false;
        }
      }
    }
  }
  const result = new LineStarts(createUintArray(r3), cr, lf2, crlf, isBasicASCII2);
  r3.length = 0;
  return result;
}
var Piece = class {
  constructor(bufferIndex, start3, end2, lineFeedCnt, length) {
    this.bufferIndex = bufferIndex;
    this.start = start3;
    this.end = end2;
    this.lineFeedCnt = lineFeedCnt;
    this.length = length;
  }
};
var StringBuffer = class {
  constructor(buffer, lineStarts) {
    this.buffer = buffer;
    this.lineStarts = lineStarts;
  }
};
var PieceTreeSnapshot = class {
  constructor(tree, BOM) {
    this._pieces = [];
    this._tree = tree;
    this._BOM = BOM;
    this._index = 0;
    if (tree.root !== SENTINEL$1) {
      tree.iterate(tree.root, (node) => {
        if (node !== SENTINEL$1) {
          this._pieces.push(node.piece);
        }
        return true;
      });
    }
  }
  read() {
    if (this._pieces.length === 0) {
      if (this._index === 0) {
        this._index++;
        return this._BOM;
      } else {
        return null;
      }
    }
    if (this._index > this._pieces.length - 1) {
      return null;
    }
    if (this._index === 0) {
      return this._BOM + this._tree.getPieceContent(this._pieces[this._index++]);
    }
    return this._tree.getPieceContent(this._pieces[this._index++]);
  }
};
var PieceTreeSearchCache = class {
  constructor(limit) {
    this._limit = limit;
    this._cache = [];
  }
  get(offset2) {
    for (let i3 = this._cache.length - 1; i3 >= 0; i3--) {
      let nodePos = this._cache[i3];
      if (nodePos.nodeStartOffset <= offset2 && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset2) {
        return nodePos;
      }
    }
    return null;
  }
  get2(lineNumber) {
    for (let i3 = this._cache.length - 1; i3 >= 0; i3--) {
      let nodePos = this._cache[i3];
      if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) {
        return nodePos;
      }
    }
    return null;
  }
  set(nodePosition) {
    if (this._cache.length >= this._limit) {
      this._cache.shift();
    }
    this._cache.push(nodePosition);
  }
  validate(offset2) {
    let hasInvalidVal = false;
    let tmp = this._cache;
    for (let i3 = 0; i3 < tmp.length; i3++) {
      let nodePos = tmp[i3];
      if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset2) {
        tmp[i3] = null;
        hasInvalidVal = true;
        continue;
      }
    }
    if (hasInvalidVal) {
      let newArr = [];
      for (const entry of tmp) {
        if (entry !== null) {
          newArr.push(entry);
        }
      }
      this._cache = newArr;
    }
  }
};
var PieceTreeBase = class {
  constructor(chunks, eol, eolNormalized) {
    this.create(chunks, eol, eolNormalized);
  }
  create(chunks, eol, eolNormalized) {
    this._buffers = [
      new StringBuffer("", [0])
    ];
    this._lastChangeBufferPos = {line: 0, column: 0};
    this.root = SENTINEL$1;
    this._lineCnt = 1;
    this._length = 0;
    this._EOL = eol;
    this._EOLLength = eol.length;
    this._EOLNormalized = eolNormalized;
    let lastNode = null;
    for (let i3 = 0, len2 = chunks.length; i3 < len2; i3++) {
      if (chunks[i3].buffer.length > 0) {
        if (!chunks[i3].lineStarts) {
          chunks[i3].lineStarts = createLineStartsFast(chunks[i3].buffer);
        }
        let piece = new Piece(i3 + 1, {line: 0, column: 0}, {line: chunks[i3].lineStarts.length - 1, column: chunks[i3].buffer.length - chunks[i3].lineStarts[chunks[i3].lineStarts.length - 1]}, chunks[i3].lineStarts.length - 1, chunks[i3].buffer.length);
        this._buffers.push(chunks[i3]);
        lastNode = this.rbInsertRight(lastNode, piece);
      }
    }
    this._searchCache = new PieceTreeSearchCache(1);
    this._lastVisitedLine = {lineNumber: 0, value: ""};
    this.computeBufferMetadata();
  }
  normalizeEOL(eol) {
    let averageBufferSize = AverageBufferSize;
    let min2 = averageBufferSize - Math.floor(averageBufferSize / 3);
    let max2 = min2 * 2;
    let tempChunk = "";
    let tempChunkLen = 0;
    let chunks = [];
    this.iterate(this.root, (node) => {
      let str = this.getNodeContent(node);
      let len2 = str.length;
      if (tempChunkLen <= min2 || tempChunkLen + len2 < max2) {
        tempChunk += str;
        tempChunkLen += len2;
        return true;
      }
      let text = tempChunk.replace(/\r\n|\r|\n/g, eol);
      chunks.push(new StringBuffer(text, createLineStartsFast(text)));
      tempChunk = str;
      tempChunkLen = len2;
      return true;
    });
    if (tempChunkLen > 0) {
      let text = tempChunk.replace(/\r\n|\r|\n/g, eol);
      chunks.push(new StringBuffer(text, createLineStartsFast(text)));
    }
    this.create(chunks, eol, true);
  }
  getEOL() {
    return this._EOL;
  }
  setEOL(newEOL) {
    this._EOL = newEOL;
    this._EOLLength = this._EOL.length;
    this.normalizeEOL(newEOL);
  }
  createSnapshot(BOM) {
    return new PieceTreeSnapshot(this, BOM);
  }
  getOffsetAt(lineNumber, column) {
    let leftLen = 0;
    let x2 = this.root;
    while (x2 !== SENTINEL$1) {
      if (x2.left !== SENTINEL$1 && x2.lf_left + 1 >= lineNumber) {
        x2 = x2.left;
      } else if (x2.lf_left + x2.piece.lineFeedCnt + 1 >= lineNumber) {
        leftLen += x2.size_left;
        let accumualtedValInCurrentIndex = this.getAccumulatedValue(x2, lineNumber - x2.lf_left - 2);
        return leftLen += accumualtedValInCurrentIndex + column - 1;
      } else {
        lineNumber -= x2.lf_left + x2.piece.lineFeedCnt;
        leftLen += x2.size_left + x2.piece.length;
        x2 = x2.right;
      }
    }
    return leftLen;
  }
  getPositionAt(offset2) {
    offset2 = Math.floor(offset2);
    offset2 = Math.max(0, offset2);
    let x2 = this.root;
    let lfCnt = 0;
    let originalOffset = offset2;
    while (x2 !== SENTINEL$1) {
      if (x2.size_left !== 0 && x2.size_left >= offset2) {
        x2 = x2.left;
      } else if (x2.size_left + x2.piece.length >= offset2) {
        let out = this.getIndexOf(x2, offset2 - x2.size_left);
        lfCnt += x2.lf_left + out.index;
        if (out.index === 0) {
          let lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
          let column = originalOffset - lineStartOffset;
          return new Position(lfCnt + 1, column + 1);
        }
        return new Position(lfCnt + 1, out.remainder + 1);
      } else {
        offset2 -= x2.size_left + x2.piece.length;
        lfCnt += x2.lf_left + x2.piece.lineFeedCnt;
        if (x2.right === SENTINEL$1) {
          let lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
          let column = originalOffset - offset2 - lineStartOffset;
          return new Position(lfCnt + 1, column + 1);
        } else {
          x2 = x2.right;
        }
      }
    }
    return new Position(1, 1);
  }
  getValueInRange(range3, eol) {
    if (range3.startLineNumber === range3.endLineNumber && range3.startColumn === range3.endColumn) {
      return "";
    }
    let startPosition = this.nodeAt2(range3.startLineNumber, range3.startColumn);
    let endPosition = this.nodeAt2(range3.endLineNumber, range3.endColumn);
    let value = this.getValueInRange2(startPosition, endPosition);
    if (eol) {
      if (eol !== this._EOL || !this._EOLNormalized) {
        return value.replace(/\r\n|\r|\n/g, eol);
      }
      if (eol === this.getEOL() && this._EOLNormalized) {
        return value;
      }
      return value.replace(/\r\n|\r|\n/g, eol);
    }
    return value;
  }
  getValueInRange2(startPosition, endPosition) {
    if (startPosition.node === endPosition.node) {
      let node = startPosition.node;
      let buffer2 = this._buffers[node.piece.bufferIndex].buffer;
      let startOffset2 = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
      return buffer2.substring(startOffset2 + startPosition.remainder, startOffset2 + endPosition.remainder);
    }
    let x2 = startPosition.node;
    let buffer = this._buffers[x2.piece.bufferIndex].buffer;
    let startOffset = this.offsetInBuffer(x2.piece.bufferIndex, x2.piece.start);
    let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x2.piece.length);
    x2 = x2.next();
    while (x2 !== SENTINEL$1) {
      let buffer2 = this._buffers[x2.piece.bufferIndex].buffer;
      let startOffset2 = this.offsetInBuffer(x2.piece.bufferIndex, x2.piece.start);
      if (x2 === endPosition.node) {
        ret += buffer2.substring(startOffset2, startOffset2 + endPosition.remainder);
        break;
      } else {
        ret += buffer2.substr(startOffset2, x2.piece.length);
      }
      x2 = x2.next();
    }
    return ret;
  }
  getLinesContent() {
    let lines = [];
    let linesLength = 0;
    let currentLine = "";
    let danglingCR = false;
    this.iterate(this.root, (node) => {
      if (node === SENTINEL$1) {
        return true;
      }
      const piece = node.piece;
      let pieceLength = piece.length;
      if (pieceLength === 0) {
        return true;
      }
      const buffer = this._buffers[piece.bufferIndex].buffer;
      const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
      const pieceStartLine = piece.start.line;
      const pieceEndLine = piece.end.line;
      let pieceStartOffset = lineStarts[pieceStartLine] + piece.start.column;
      if (danglingCR) {
        if (buffer.charCodeAt(pieceStartOffset) === 10) {
          pieceStartOffset++;
          pieceLength--;
        }
        lines[linesLength++] = currentLine;
        currentLine = "";
        danglingCR = false;
        if (pieceLength === 0) {
          return true;
        }
      }
      if (pieceStartLine === pieceEndLine) {
        if (!this._EOLNormalized && buffer.charCodeAt(pieceStartOffset + pieceLength - 1) === 13) {
          danglingCR = true;
          currentLine += buffer.substr(pieceStartOffset, pieceLength - 1);
        } else {
          currentLine += buffer.substr(pieceStartOffset, pieceLength);
        }
        return true;
      }
      currentLine += this._EOLNormalized ? buffer.substring(pieceStartOffset, Math.max(pieceStartOffset, lineStarts[pieceStartLine + 1] - this._EOLLength)) : buffer.substring(pieceStartOffset, lineStarts[pieceStartLine + 1]).replace(/(\r\n|\r|\n)$/, "");
      lines[linesLength++] = currentLine;
      for (let line = pieceStartLine + 1; line < pieceEndLine; line++) {
        currentLine = this._EOLNormalized ? buffer.substring(lineStarts[line], lineStarts[line + 1] - this._EOLLength) : buffer.substring(lineStarts[line], lineStarts[line + 1]).replace(/(\r\n|\r|\n)$/, "");
        lines[linesLength++] = currentLine;
      }
      if (!this._EOLNormalized && buffer.charCodeAt(lineStarts[pieceEndLine] + piece.end.column - 1) === 13) {
        danglingCR = true;
        if (piece.end.column === 0) {
          linesLength--;
        } else {
          currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column - 1);
        }
      } else {
        currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column);
      }
      return true;
    });
    if (danglingCR) {
      lines[linesLength++] = currentLine;
      currentLine = "";
    }
    lines[linesLength++] = currentLine;
    return lines;
  }
  getLength() {
    return this._length;
  }
  getLineCount() {
    return this._lineCnt;
  }
  getLineContent(lineNumber) {
    if (this._lastVisitedLine.lineNumber === lineNumber) {
      return this._lastVisitedLine.value;
    }
    this._lastVisitedLine.lineNumber = lineNumber;
    if (lineNumber === this._lineCnt) {
      this._lastVisitedLine.value = this.getLineRawContent(lineNumber);
    } else if (this._EOLNormalized) {
      this._lastVisitedLine.value = this.getLineRawContent(lineNumber, this._EOLLength);
    } else {
      this._lastVisitedLine.value = this.getLineRawContent(lineNumber).replace(/(\r\n|\r|\n)$/, "");
    }
    return this._lastVisitedLine.value;
  }
  _getCharCode(nodePos) {
    if (nodePos.remainder === nodePos.node.piece.length) {
      let matchingNode = nodePos.node.next();
      if (!matchingNode) {
        return 0;
      }
      let buffer = this._buffers[matchingNode.piece.bufferIndex];
      let startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
      return buffer.buffer.charCodeAt(startOffset);
    } else {
      let buffer = this._buffers[nodePos.node.piece.bufferIndex];
      let startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
      let targetOffset = startOffset + nodePos.remainder;
      return buffer.buffer.charCodeAt(targetOffset);
    }
  }
  getLineCharCode(lineNumber, index3) {
    let nodePos = this.nodeAt2(lineNumber, index3 + 1);
    return this._getCharCode(nodePos);
  }
  getLineLength(lineNumber) {
    if (lineNumber === this.getLineCount()) {
      let startOffset = this.getOffsetAt(lineNumber, 1);
      return this.getLength() - startOffset;
    }
    return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength;
  }
  findMatchesInNode(node, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result) {
    let buffer = this._buffers[node.piece.bufferIndex];
    let startOffsetInBuffer = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
    let start3 = this.offsetInBuffer(node.piece.bufferIndex, startCursor);
    let end2 = this.offsetInBuffer(node.piece.bufferIndex, endCursor);
    let m2;
    let ret = {line: 0, column: 0};
    let searchText;
    let offsetInBuffer;
    if (searcher._wordSeparators) {
      searchText = buffer.buffer.substring(start3, end2);
      offsetInBuffer = (offset2) => offset2 + start3;
      searcher.reset(0);
    } else {
      searchText = buffer.buffer;
      offsetInBuffer = (offset2) => offset2;
      searcher.reset(start3);
    }
    do {
      m2 = searcher.next(searchText);
      if (m2) {
        if (offsetInBuffer(m2.index) >= end2) {
          return resultLen;
        }
        this.positionInBuffer(node, offsetInBuffer(m2.index) - startOffsetInBuffer, ret);
        let lineFeedCnt = this.getLineFeedCnt(node.piece.bufferIndex, startCursor, ret);
        let retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1;
        let retEndColumn = retStartColumn + m2[0].length;
        result[resultLen++] = createFindMatch(new Range(startLineNumber + lineFeedCnt, retStartColumn, startLineNumber + lineFeedCnt, retEndColumn), m2, captureMatches);
        if (offsetInBuffer(m2.index) + m2[0].length >= end2) {
          return resultLen;
        }
        if (resultLen >= limitResultCount) {
          return resultLen;
        }
      }
    } while (m2);
    return resultLen;
  }
  findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
    const result = [];
    let resultLen = 0;
    const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
    let startPosition = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn);
    if (startPosition === null) {
      return [];
    }
    let endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn);
    if (endPosition === null) {
      return [];
    }
    let start3 = this.positionInBuffer(startPosition.node, startPosition.remainder);
    let end2 = this.positionInBuffer(endPosition.node, endPosition.remainder);
    if (startPosition.node === endPosition.node) {
      this.findMatchesInNode(startPosition.node, searcher, searchRange.startLineNumber, searchRange.startColumn, start3, end2, searchData, captureMatches, limitResultCount, resultLen, result);
      return result;
    }
    let startLineNumber = searchRange.startLineNumber;
    let currentNode = startPosition.node;
    while (currentNode !== endPosition.node) {
      let lineBreakCnt = this.getLineFeedCnt(currentNode.piece.bufferIndex, start3, currentNode.piece.end);
      if (lineBreakCnt >= 1) {
        let lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts;
        let startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start);
        let nextLineStartOffset = lineStarts[start3.line + lineBreakCnt];
        let startColumn3 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
        resultLen = this.findMatchesInNode(currentNode, searcher, startLineNumber, startColumn3, start3, this.positionInBuffer(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result);
        if (resultLen >= limitResultCount) {
          return result;
        }
        startLineNumber += lineBreakCnt;
      }
      let startColumn2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
      if (startLineNumber === searchRange.endLineNumber) {
        const text = this.getLineContent(startLineNumber).substring(startColumn2, searchRange.endColumn - 1);
        resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
        return result;
      }
      resultLen = this._findMatchesInLine(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn2), startLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
      if (resultLen >= limitResultCount) {
        return result;
      }
      startLineNumber++;
      startPosition = this.nodeAt2(startLineNumber, 1);
      currentNode = startPosition.node;
      start3 = this.positionInBuffer(startPosition.node, startPosition.remainder);
    }
    if (startLineNumber === searchRange.endLineNumber) {
      let startColumn2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
      const text = this.getLineContent(startLineNumber).substring(startColumn2, searchRange.endColumn - 1);
      resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
      return result;
    }
    let startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
    resultLen = this.findMatchesInNode(endPosition.node, searcher, startLineNumber, startColumn, start3, end2, searchData, captureMatches, limitResultCount, resultLen, result);
    return result;
  }
  _findMatchesInLine(searchData, searcher, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
    const wordSeparators2 = searchData.wordSeparators;
    if (!captureMatches && searchData.simpleSearch) {
      const searchString = searchData.simpleSearch;
      const searchStringLen = searchString.length;
      const textLength = text.length;
      let lastMatchIndex = -searchStringLen;
      while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
        if (!wordSeparators2 || isValidMatch(wordSeparators2, text, textLength, lastMatchIndex, searchStringLen)) {
          result[resultLen++] = new FindMatch(new Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
          if (resultLen >= limitResultCount) {
            return resultLen;
          }
        }
      }
      return resultLen;
    }
    let m2;
    searcher.reset(0);
    do {
      m2 = searcher.next(text);
      if (m2) {
        result[resultLen++] = createFindMatch(new Range(lineNumber, m2.index + 1 + deltaOffset, lineNumber, m2.index + 1 + m2[0].length + deltaOffset), m2, captureMatches);
        if (resultLen >= limitResultCount) {
          return resultLen;
        }
      }
    } while (m2);
    return resultLen;
  }
  insert(offset2, value, eolNormalized = false) {
    this._EOLNormalized = this._EOLNormalized && eolNormalized;
    this._lastVisitedLine.lineNumber = 0;
    this._lastVisitedLine.value = "";
    if (this.root !== SENTINEL$1) {
      let {node, remainder, nodeStartOffset} = this.nodeAt(offset2);
      let piece = node.piece;
      let bufferIndex = piece.bufferIndex;
      let insertPosInBuffer = this.positionInBuffer(node, remainder);
      if (node.piece.bufferIndex === 0 && piece.end.line === this._lastChangeBufferPos.line && piece.end.column === this._lastChangeBufferPos.column && nodeStartOffset + piece.length === offset2 && value.length < AverageBufferSize) {
        this.appendToNode(node, value);
        this.computeBufferMetadata();
        return;
      }
      if (nodeStartOffset === offset2) {
        this.insertContentToNodeLeft(value, node);
        this._searchCache.validate(offset2);
      } else if (nodeStartOffset + node.piece.length > offset2) {
        let nodesToDel = [];
        let newRightPiece = new Piece(piece.bufferIndex, insertPosInBuffer, piece.end, this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end), this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer));
        if (this.shouldCheckCRLF() && this.endWithCR(value)) {
          let headOfRight = this.nodeCharCodeAt(node, remainder);
          if (headOfRight === 10) {
            let newStart = {line: newRightPiece.start.line + 1, column: 0};
            newRightPiece = new Piece(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.getLineFeedCnt(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1);
            value += "\n";
          }
        }
        if (this.shouldCheckCRLF() && this.startWithLF(value)) {
          let tailOfLeft = this.nodeCharCodeAt(node, remainder - 1);
          if (tailOfLeft === 13) {
            let previousPos = this.positionInBuffer(node, remainder - 1);
            this.deleteNodeTail(node, previousPos);
            value = "\r" + value;
            if (node.piece.length === 0) {
              nodesToDel.push(node);
            }
          } else {
            this.deleteNodeTail(node, insertPosInBuffer);
          }
        } else {
          this.deleteNodeTail(node, insertPosInBuffer);
        }
        let newPieces = this.createNewPieces(value);
        if (newRightPiece.length > 0) {
          this.rbInsertRight(node, newRightPiece);
        }
        let tmpNode = node;
        for (let k2 = 0; k2 < newPieces.length; k2++) {
          tmpNode = this.rbInsertRight(tmpNode, newPieces[k2]);
        }
        this.deleteNodes(nodesToDel);
      } else {
        this.insertContentToNodeRight(value, node);
      }
    } else {
      let pieces = this.createNewPieces(value);
      let node = this.rbInsertLeft(null, pieces[0]);
      for (let k2 = 1; k2 < pieces.length; k2++) {
        node = this.rbInsertRight(node, pieces[k2]);
      }
    }
    this.computeBufferMetadata();
  }
  delete(offset2, cnt) {
    this._lastVisitedLine.lineNumber = 0;
    this._lastVisitedLine.value = "";
    if (cnt <= 0 || this.root === SENTINEL$1) {
      return;
    }
    let startPosition = this.nodeAt(offset2);
    let endPosition = this.nodeAt(offset2 + cnt);
    let startNode = startPosition.node;
    let endNode = endPosition.node;
    if (startNode === endNode) {
      let startSplitPosInBuffer2 = this.positionInBuffer(startNode, startPosition.remainder);
      let endSplitPosInBuffer2 = this.positionInBuffer(startNode, endPosition.remainder);
      if (startPosition.nodeStartOffset === offset2) {
        if (cnt === startNode.piece.length) {
          let next = startNode.next();
          rbDelete(this, startNode);
          this.validateCRLFWithPrevNode(next);
          this.computeBufferMetadata();
          return;
        }
        this.deleteNodeHead(startNode, endSplitPosInBuffer2);
        this._searchCache.validate(offset2);
        this.validateCRLFWithPrevNode(startNode);
        this.computeBufferMetadata();
        return;
      }
      if (startPosition.nodeStartOffset + startNode.piece.length === offset2 + cnt) {
        this.deleteNodeTail(startNode, startSplitPosInBuffer2);
        this.validateCRLFWithNextNode(startNode);
        this.computeBufferMetadata();
        return;
      }
      this.shrinkNode(startNode, startSplitPosInBuffer2, endSplitPosInBuffer2);
      this.computeBufferMetadata();
      return;
    }
    let nodesToDel = [];
    let startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
    this.deleteNodeTail(startNode, startSplitPosInBuffer);
    this._searchCache.validate(offset2);
    if (startNode.piece.length === 0) {
      nodesToDel.push(startNode);
    }
    let endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder);
    this.deleteNodeHead(endNode, endSplitPosInBuffer);
    if (endNode.piece.length === 0) {
      nodesToDel.push(endNode);
    }
    let secondNode = startNode.next();
    for (let node = secondNode; node !== SENTINEL$1 && node !== endNode; node = node.next()) {
      nodesToDel.push(node);
    }
    let prev = startNode.piece.length === 0 ? startNode.prev() : startNode;
    this.deleteNodes(nodesToDel);
    this.validateCRLFWithNextNode(prev);
    this.computeBufferMetadata();
  }
  insertContentToNodeLeft(value, node) {
    let nodesToDel = [];
    if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) {
      let piece = node.piece;
      let newStart = {line: piece.start.line + 1, column: 0};
      let nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1);
      node.piece = nPiece;
      value += "\n";
      updateTreeMetadata(this, node, -1, -1);
      if (node.piece.length === 0) {
        nodesToDel.push(node);
      }
    }
    let newPieces = this.createNewPieces(value);
    let newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]);
    for (let k2 = newPieces.length - 2; k2 >= 0; k2--) {
      newNode = this.rbInsertLeft(newNode, newPieces[k2]);
    }
    this.validateCRLFWithPrevNode(newNode);
    this.deleteNodes(nodesToDel);
  }
  insertContentToNodeRight(value, node) {
    if (this.adjustCarriageReturnFromNext(value, node)) {
      value += "\n";
    }
    let newPieces = this.createNewPieces(value);
    let newNode = this.rbInsertRight(node, newPieces[0]);
    let tmpNode = newNode;
    for (let k2 = 1; k2 < newPieces.length; k2++) {
      tmpNode = this.rbInsertRight(tmpNode, newPieces[k2]);
    }
    this.validateCRLFWithPrevNode(newNode);
  }
  positionInBuffer(node, remainder, ret) {
    let piece = node.piece;
    let bufferIndex = node.piece.bufferIndex;
    let lineStarts = this._buffers[bufferIndex].lineStarts;
    let startOffset = lineStarts[piece.start.line] + piece.start.column;
    let offset2 = startOffset + remainder;
    let low = piece.start.line;
    let high = piece.end.line;
    let mid = 0;
    let midStop = 0;
    let midStart = 0;
    while (low <= high) {
      mid = low + (high - low) / 2 | 0;
      midStart = lineStarts[mid];
      if (mid === high) {
        break;
      }
      midStop = lineStarts[mid + 1];
      if (offset2 < midStart) {
        high = mid - 1;
      } else if (offset2 >= midStop) {
        low = mid + 1;
      } else {
        break;
      }
    }
    if (ret) {
      ret.line = mid;
      ret.column = offset2 - midStart;
      return null;
    }
    return {
      line: mid,
      column: offset2 - midStart
    };
  }
  getLineFeedCnt(bufferIndex, start3, end2) {
    if (end2.column === 0) {
      return end2.line - start3.line;
    }
    let lineStarts = this._buffers[bufferIndex].lineStarts;
    if (end2.line === lineStarts.length - 1) {
      return end2.line - start3.line;
    }
    let nextLineStartOffset = lineStarts[end2.line + 1];
    let endOffset = lineStarts[end2.line] + end2.column;
    if (nextLineStartOffset > endOffset + 1) {
      return end2.line - start3.line;
    }
    let previousCharOffset = endOffset - 1;
    let buffer = this._buffers[bufferIndex].buffer;
    if (buffer.charCodeAt(previousCharOffset) === 13) {
      return end2.line - start3.line + 1;
    } else {
      return end2.line - start3.line;
    }
  }
  offsetInBuffer(bufferIndex, cursor) {
    let lineStarts = this._buffers[bufferIndex].lineStarts;
    return lineStarts[cursor.line] + cursor.column;
  }
  deleteNodes(nodes) {
    for (let i3 = 0; i3 < nodes.length; i3++) {
      rbDelete(this, nodes[i3]);
    }
  }
  createNewPieces(text) {
    if (text.length > AverageBufferSize) {
      let newPieces = [];
      while (text.length > AverageBufferSize) {
        const lastChar = text.charCodeAt(AverageBufferSize - 1);
        let splitText;
        if (lastChar === 13 || lastChar >= 55296 && lastChar <= 56319) {
          splitText = text.substring(0, AverageBufferSize - 1);
          text = text.substring(AverageBufferSize - 1);
        } else {
          splitText = text.substring(0, AverageBufferSize);
          text = text.substring(AverageBufferSize);
        }
        let lineStarts3 = createLineStartsFast(splitText);
        newPieces.push(new Piece(this._buffers.length, {line: 0, column: 0}, {line: lineStarts3.length - 1, column: splitText.length - lineStarts3[lineStarts3.length - 1]}, lineStarts3.length - 1, splitText.length));
        this._buffers.push(new StringBuffer(splitText, lineStarts3));
      }
      let lineStarts2 = createLineStartsFast(text);
      newPieces.push(new Piece(this._buffers.length, {line: 0, column: 0}, {line: lineStarts2.length - 1, column: text.length - lineStarts2[lineStarts2.length - 1]}, lineStarts2.length - 1, text.length));
      this._buffers.push(new StringBuffer(text, lineStarts2));
      return newPieces;
    }
    let startOffset = this._buffers[0].buffer.length;
    const lineStarts = createLineStartsFast(text, false);
    let start3 = this._lastChangeBufferPos;
    if (this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 1] === startOffset && startOffset !== 0 && this.startWithLF(text) && this.endWithCR(this._buffers[0].buffer)) {
      this._lastChangeBufferPos = {line: this._lastChangeBufferPos.line, column: this._lastChangeBufferPos.column + 1};
      start3 = this._lastChangeBufferPos;
      for (let i3 = 0; i3 < lineStarts.length; i3++) {
        lineStarts[i3] += startOffset + 1;
      }
      this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
      this._buffers[0].buffer += "_" + text;
      startOffset += 1;
    } else {
      if (startOffset !== 0) {
        for (let i3 = 0; i3 < lineStarts.length; i3++) {
          lineStarts[i3] += startOffset;
        }
      }
      this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
      this._buffers[0].buffer += text;
    }
    const endOffset = this._buffers[0].buffer.length;
    let endIndex = this._buffers[0].lineStarts.length - 1;
    let endColumn = endOffset - this._buffers[0].lineStarts[endIndex];
    let endPos = {line: endIndex, column: endColumn};
    let newPiece = new Piece(0, start3, endPos, this.getLineFeedCnt(0, start3, endPos), endOffset - startOffset);
    this._lastChangeBufferPos = endPos;
    return [newPiece];
  }
  getLineRawContent(lineNumber, endOffset = 0) {
    let x2 = this.root;
    let ret = "";
    let cache3 = this._searchCache.get2(lineNumber);
    if (cache3) {
      x2 = cache3.node;
      let prevAccumulatedValue = this.getAccumulatedValue(x2, lineNumber - cache3.nodeStartLineNumber - 1);
      let buffer = this._buffers[x2.piece.bufferIndex].buffer;
      let startOffset = this.offsetInBuffer(x2.piece.bufferIndex, x2.piece.start);
      if (cache3.nodeStartLineNumber + x2.piece.lineFeedCnt === lineNumber) {
        ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x2.piece.length);
      } else {
        let accumulatedValue = this.getAccumulatedValue(x2, lineNumber - cache3.nodeStartLineNumber);
        return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
      }
    } else {
      let nodeStartOffset = 0;
      const originalLineNumber = lineNumber;
      while (x2 !== SENTINEL$1) {
        if (x2.left !== SENTINEL$1 && x2.lf_left >= lineNumber - 1) {
          x2 = x2.left;
        } else if (x2.lf_left + x2.piece.lineFeedCnt > lineNumber - 1) {
          let prevAccumulatedValue = this.getAccumulatedValue(x2, lineNumber - x2.lf_left - 2);
          let accumulatedValue = this.getAccumulatedValue(x2, lineNumber - x2.lf_left - 1);
          let buffer = this._buffers[x2.piece.bufferIndex].buffer;
          let startOffset = this.offsetInBuffer(x2.piece.bufferIndex, x2.piece.start);
          nodeStartOffset += x2.size_left;
          this._searchCache.set({
            node: x2,
            nodeStartOffset,
            nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x2.lf_left)
          });
          return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
        } else if (x2.lf_left + x2.piece.lineFeedCnt === lineNumber - 1) {
          let prevAccumulatedValue = this.getAccumulatedValue(x2, lineNumber - x2.lf_left - 2);
          let buffer = this._buffers[x2.piece.bufferIndex].buffer;
          let startOffset = this.offsetInBuffer(x2.piece.bufferIndex, x2.piece.start);
          ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x2.piece.length);
          break;
        } else {
          lineNumber -= x2.lf_left + x2.piece.lineFeedCnt;
          nodeStartOffset += x2.size_left + x2.piece.length;
          x2 = x2.right;
        }
      }
    }
    x2 = x2.next();
    while (x2 !== SENTINEL$1) {
      let buffer = this._buffers[x2.piece.bufferIndex].buffer;
      if (x2.piece.lineFeedCnt > 0) {
        let accumulatedValue = this.getAccumulatedValue(x2, 0);
        let startOffset = this.offsetInBuffer(x2.piece.bufferIndex, x2.piece.start);
        ret += buffer.substring(startOffset, startOffset + accumulatedValue - endOffset);
        return ret;
      } else {
        let startOffset = this.offsetInBuffer(x2.piece.bufferIndex, x2.piece.start);
        ret += buffer.substr(startOffset, x2.piece.length);
      }
      x2 = x2.next();
    }
    return ret;
  }
  computeBufferMetadata() {
    let x2 = this.root;
    let lfCnt = 1;
    let len2 = 0;
    while (x2 !== SENTINEL$1) {
      lfCnt += x2.lf_left + x2.piece.lineFeedCnt;
      len2 += x2.size_left + x2.piece.length;
      x2 = x2.right;
    }
    this._lineCnt = lfCnt;
    this._length = len2;
    this._searchCache.validate(this._length);
  }
  getIndexOf(node, accumulatedValue) {
    let piece = node.piece;
    let pos = this.positionInBuffer(node, accumulatedValue);
    let lineCnt = pos.line - piece.start.line;
    if (this.offsetInBuffer(piece.bufferIndex, piece.end) - this.offsetInBuffer(piece.bufferIndex, piece.start) === accumulatedValue) {
      let realLineCnt = this.getLineFeedCnt(node.piece.bufferIndex, piece.start, pos);
      if (realLineCnt !== lineCnt) {
        return {index: realLineCnt, remainder: 0};
      }
    }
    return {index: lineCnt, remainder: pos.column};
  }
  getAccumulatedValue(node, index3) {
    if (index3 < 0) {
      return 0;
    }
    let piece = node.piece;
    let lineStarts = this._buffers[piece.bufferIndex].lineStarts;
    let expectedLineStartIndex = piece.start.line + index3 + 1;
    if (expectedLineStartIndex > piece.end.line) {
      return lineStarts[piece.end.line] + piece.end.column - lineStarts[piece.start.line] - piece.start.column;
    } else {
      return lineStarts[expectedLineStartIndex] - lineStarts[piece.start.line] - piece.start.column;
    }
  }
  deleteNodeTail(node, pos) {
    const piece = node.piece;
    const originalLFCnt = piece.lineFeedCnt;
    const originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
    const newEnd = pos;
    const newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd);
    const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
    const lf_delta = newLineFeedCnt - originalLFCnt;
    const size_delta = newEndOffset - originalEndOffset;
    const newLength = piece.length + size_delta;
    node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
    updateTreeMetadata(this, node, size_delta, lf_delta);
  }
  deleteNodeHead(node, pos) {
    const piece = node.piece;
    const originalLFCnt = piece.lineFeedCnt;
    const originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
    const newStart = pos;
    const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
    const newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart);
    const lf_delta = newLineFeedCnt - originalLFCnt;
    const size_delta = originalStartOffset - newStartOffset;
    const newLength = piece.length + size_delta;
    node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
    updateTreeMetadata(this, node, size_delta, lf_delta);
  }
  shrinkNode(node, start3, end2) {
    const piece = node.piece;
    const originalStartPos = piece.start;
    const originalEndPos = piece.end;
    const oldLength = piece.length;
    const oldLFCnt = piece.lineFeedCnt;
    const newEnd = start3;
    const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
    const newLength = this.offsetInBuffer(piece.bufferIndex, start3) - this.offsetInBuffer(piece.bufferIndex, originalStartPos);
    node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
    updateTreeMetadata(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt);
    let newPiece = new Piece(piece.bufferIndex, end2, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end2, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end2));
    let newNode = this.rbInsertRight(node, newPiece);
    this.validateCRLFWithPrevNode(newNode);
  }
  appendToNode(node, value) {
    if (this.adjustCarriageReturnFromNext(value, node)) {
      value += "\n";
    }
    const hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node);
    const startOffset = this._buffers[0].buffer.length;
    this._buffers[0].buffer += value;
    const lineStarts = createLineStartsFast(value, false);
    for (let i3 = 0; i3 < lineStarts.length; i3++) {
      lineStarts[i3] += startOffset;
    }
    if (hitCRLF) {
      let prevStartOffset = this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 2];
      this._buffers[0].lineStarts.pop();
      this._lastChangeBufferPos = {line: this._lastChangeBufferPos.line - 1, column: startOffset - prevStartOffset};
    }
    this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
    const endIndex = this._buffers[0].lineStarts.length - 1;
    const endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex];
    const newEnd = {line: endIndex, column: endColumn};
    const newLength = node.piece.length + value.length;
    const oldLineFeedCnt = node.piece.lineFeedCnt;
    const newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd);
    const lf_delta = newLineFeedCnt - oldLineFeedCnt;
    node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength);
    this._lastChangeBufferPos = newEnd;
    updateTreeMetadata(this, node, value.length, lf_delta);
  }
  nodeAt(offset2) {
    let x2 = this.root;
    let cache3 = this._searchCache.get(offset2);
    if (cache3) {
      return {
        node: cache3.node,
        nodeStartOffset: cache3.nodeStartOffset,
        remainder: offset2 - cache3.nodeStartOffset
      };
    }
    let nodeStartOffset = 0;
    while (x2 !== SENTINEL$1) {
      if (x2.size_left > offset2) {
        x2 = x2.left;
      } else if (x2.size_left + x2.piece.length >= offset2) {
        nodeStartOffset += x2.size_left;
        let ret = {
          node: x2,
          remainder: offset2 - x2.size_left,
          nodeStartOffset
        };
        this._searchCache.set(ret);
        return ret;
      } else {
        offset2 -= x2.size_left + x2.piece.length;
        nodeStartOffset += x2.size_left + x2.piece.length;
        x2 = x2.right;
      }
    }
    return null;
  }
  nodeAt2(lineNumber, column) {
    let x2 = this.root;
    let nodeStartOffset = 0;
    while (x2 !== SENTINEL$1) {
      if (x2.left !== SENTINEL$1 && x2.lf_left >= lineNumber - 1) {
        x2 = x2.left;
      } else if (x2.lf_left + x2.piece.lineFeedCnt > lineNumber - 1) {
        let prevAccumualtedValue = this.getAccumulatedValue(x2, lineNumber - x2.lf_left - 2);
        let accumulatedValue = this.getAccumulatedValue(x2, lineNumber - x2.lf_left - 1);
        nodeStartOffset += x2.size_left;
        return {
          node: x2,
          remainder: Math.min(prevAccumualtedValue + column - 1, accumulatedValue),
          nodeStartOffset
        };
      } else if (x2.lf_left + x2.piece.lineFeedCnt === lineNumber - 1) {
        let prevAccumualtedValue = this.getAccumulatedValue(x2, lineNumber - x2.lf_left - 2);
        if (prevAccumualtedValue + column - 1 <= x2.piece.length) {
          return {
            node: x2,
            remainder: prevAccumualtedValue + column - 1,
            nodeStartOffset
          };
        } else {
          column -= x2.piece.length - prevAccumualtedValue;
          break;
        }
      } else {
        lineNumber -= x2.lf_left + x2.piece.lineFeedCnt;
        nodeStartOffset += x2.size_left + x2.piece.length;
        x2 = x2.right;
      }
    }
    x2 = x2.next();
    while (x2 !== SENTINEL$1) {
      if (x2.piece.lineFeedCnt > 0) {
        let accumulatedValue = this.getAccumulatedValue(x2, 0);
        let nodeStartOffset2 = this.offsetOfNode(x2);
        return {
          node: x2,
          remainder: Math.min(column - 1, accumulatedValue),
          nodeStartOffset: nodeStartOffset2
        };
      } else {
        if (x2.piece.length >= column - 1) {
          let nodeStartOffset2 = this.offsetOfNode(x2);
          return {
            node: x2,
            remainder: column - 1,
            nodeStartOffset: nodeStartOffset2
          };
        } else {
          column -= x2.piece.length;
        }
      }
      x2 = x2.next();
    }
    return null;
  }
  nodeCharCodeAt(node, offset2) {
    if (node.piece.lineFeedCnt < 1) {
      return -1;
    }
    let buffer = this._buffers[node.piece.bufferIndex];
    let newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset2;
    return buffer.buffer.charCodeAt(newOffset);
  }
  offsetOfNode(node) {
    if (!node) {
      return 0;
    }
    let pos = node.size_left;
    while (node !== this.root) {
      if (node.parent.right === node) {
        pos += node.parent.size_left + node.parent.piece.length;
      }
      node = node.parent;
    }
    return pos;
  }
  shouldCheckCRLF() {
    return !(this._EOLNormalized && this._EOL === "\n");
  }
  startWithLF(val) {
    if (typeof val === "string") {
      return val.charCodeAt(0) === 10;
    }
    if (val === SENTINEL$1 || val.piece.lineFeedCnt === 0) {
      return false;
    }
    let piece = val.piece;
    let lineStarts = this._buffers[piece.bufferIndex].lineStarts;
    let line = piece.start.line;
    let startOffset = lineStarts[line] + piece.start.column;
    if (line === lineStarts.length - 1) {
      return false;
    }
    let nextLineOffset = lineStarts[line + 1];
    if (nextLineOffset > startOffset + 1) {
      return false;
    }
    return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;
  }
  endWithCR(val) {
    if (typeof val === "string") {
      return val.charCodeAt(val.length - 1) === 13;
    }
    if (val === SENTINEL$1 || val.piece.lineFeedCnt === 0) {
      return false;
    }
    return this.nodeCharCodeAt(val, val.piece.length - 1) === 13;
  }
  validateCRLFWithPrevNode(nextNode) {
    if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) {
      let node = nextNode.prev();
      if (this.endWithCR(node)) {
        this.fixCRLF(node, nextNode);
      }
    }
  }
  validateCRLFWithNextNode(node) {
    if (this.shouldCheckCRLF() && this.endWithCR(node)) {
      let nextNode = node.next();
      if (this.startWithLF(nextNode)) {
        this.fixCRLF(node, nextNode);
      }
    }
  }
  fixCRLF(prev, next) {
    let nodesToDel = [];
    let lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts;
    let newEnd;
    if (prev.piece.end.column === 0) {
      newEnd = {line: prev.piece.end.line - 1, column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1};
    } else {
      newEnd = {line: prev.piece.end.line, column: prev.piece.end.column - 1};
    }
    const prevNewLength = prev.piece.length - 1;
    const prevNewLFCnt = prev.piece.lineFeedCnt - 1;
    prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);
    updateTreeMetadata(this, prev, -1, -1);
    if (prev.piece.length === 0) {
      nodesToDel.push(prev);
    }
    let newStart = {line: next.piece.start.line + 1, column: 0};
    const newLength = next.piece.length - 1;
    const newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end);
    next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);
    updateTreeMetadata(this, next, -1, -1);
    if (next.piece.length === 0) {
      nodesToDel.push(next);
    }
    let pieces = this.createNewPieces("\r\n");
    this.rbInsertRight(prev, pieces[0]);
    for (let i3 = 0; i3 < nodesToDel.length; i3++) {
      rbDelete(this, nodesToDel[i3]);
    }
  }
  adjustCarriageReturnFromNext(value, node) {
    if (this.shouldCheckCRLF() && this.endWithCR(value)) {
      let nextNode = node.next();
      if (this.startWithLF(nextNode)) {
        value += "\n";
        if (nextNode.piece.length === 1) {
          rbDelete(this, nextNode);
        } else {
          const piece = nextNode.piece;
          const newStart = {line: piece.start.line + 1, column: 0};
          const newLength = piece.length - 1;
          const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
          nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
          updateTreeMetadata(this, nextNode, -1, -1);
        }
        return true;
      }
    }
    return false;
  }
  iterate(node, callback) {
    if (node === SENTINEL$1) {
      return callback(SENTINEL$1);
    }
    let leftRet = this.iterate(node.left, callback);
    if (!leftRet) {
      return leftRet;
    }
    return callback(node) && this.iterate(node.right, callback);
  }
  getNodeContent(node) {
    if (node === SENTINEL$1) {
      return "";
    }
    let buffer = this._buffers[node.piece.bufferIndex];
    let currentContent;
    let piece = node.piece;
    let startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
    let endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
    currentContent = buffer.buffer.substring(startOffset, endOffset);
    return currentContent;
  }
  getPieceContent(piece) {
    let buffer = this._buffers[piece.bufferIndex];
    let startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
    let endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
    let currentContent = buffer.buffer.substring(startOffset, endOffset);
    return currentContent;
  }
  rbInsertRight(node, p2) {
    let z2 = new TreeNode(p2, 1);
    z2.left = SENTINEL$1;
    z2.right = SENTINEL$1;
    z2.parent = SENTINEL$1;
    z2.size_left = 0;
    z2.lf_left = 0;
    let x2 = this.root;
    if (x2 === SENTINEL$1) {
      this.root = z2;
      z2.color = 0;
    } else if (node.right === SENTINEL$1) {
      node.right = z2;
      z2.parent = node;
    } else {
      let nextNode = leftest$1(node.right);
      nextNode.left = z2;
      z2.parent = nextNode;
    }
    fixInsert(this, z2);
    return z2;
  }
  rbInsertLeft(node, p2) {
    let z2 = new TreeNode(p2, 1);
    z2.left = SENTINEL$1;
    z2.right = SENTINEL$1;
    z2.parent = SENTINEL$1;
    z2.size_left = 0;
    z2.lf_left = 0;
    if (this.root === SENTINEL$1) {
      this.root = z2;
      z2.color = 0;
    } else if (node.left === SENTINEL$1) {
      node.left = z2;
      z2.parent = node;
    } else {
      let prevNode = righttest(node.left);
      prevNode.right = z2;
      z2.parent = prevNode;
    }
    fixInsert(this, z2);
    return z2;
  }
};
function countEOL(text) {
  let eolCount = 0;
  let firstLineLength = 0;
  let lastLineStart = 0;
  let eol = 0;
  for (let i3 = 0, len2 = text.length; i3 < len2; i3++) {
    const chr = text.charCodeAt(i3);
    if (chr === 13) {
      if (eolCount === 0) {
        firstLineLength = i3;
      }
      eolCount++;
      if (i3 + 1 < len2 && text.charCodeAt(i3 + 1) === 10) {
        eol |= 2;
        i3++;
      } else {
        eol |= 3;
      }
      lastLineStart = i3 + 1;
    } else if (chr === 10) {
      eol |= 1;
      if (eolCount === 0) {
        firstLineLength = i3;
      }
      eolCount++;
      lastLineStart = i3 + 1;
    }
  }
  if (eolCount === 0) {
    firstLineLength = text.length;
  }
  return [eolCount, firstLineLength, text.length - lastLineStart, eol];
}
function getDefaultMetadata(topLevelLanguageId) {
  return (topLevelLanguageId << 0 | 0 << 8 | 0 << 11 | 1 << 14 | 2 << 23) >>> 0;
}
var EMPTY_LINE_TOKENS = new Uint32Array(0).buffer;
var MultilineTokensBuilder = class {
  constructor() {
    this.tokens = [];
  }
  add(lineNumber, lineTokens) {
    if (this.tokens.length > 0) {
      const last2 = this.tokens[this.tokens.length - 1];
      const lastLineNumber = last2.startLineNumber + last2.tokens.length - 1;
      if (lastLineNumber + 1 === lineNumber) {
        last2.tokens.push(lineTokens);
        return;
      }
    }
    this.tokens.push(new MultilineTokens(lineNumber, [lineTokens]));
  }
};
var SparseEncodedTokens = class {
  constructor(tokens) {
    this._tokens = tokens;
    this._tokenCount = tokens.length / 4;
  }
  toString(startLineNumber) {
    let pieces = [];
    for (let i3 = 0; i3 < this._tokenCount; i3++) {
      pieces.push(`(${this._getDeltaLine(i3) + startLineNumber},${this._getStartCharacter(i3)}-${this._getEndCharacter(i3)})`);
    }
    return `[${pieces.join(",")}]`;
  }
  getMaxDeltaLine() {
    const tokenCount = this._getTokenCount();
    if (tokenCount === 0) {
      return -1;
    }
    return this._getDeltaLine(tokenCount - 1);
  }
  getRange() {
    const tokenCount = this._getTokenCount();
    if (tokenCount === 0) {
      return null;
    }
    const startChar = this._getStartCharacter(0);
    const maxDeltaLine = this._getDeltaLine(tokenCount - 1);
    const endChar = this._getEndCharacter(tokenCount - 1);
    return new Range(0, startChar + 1, maxDeltaLine, endChar + 1);
  }
  _getTokenCount() {
    return this._tokenCount;
  }
  _getDeltaLine(tokenIndex) {
    return this._tokens[4 * tokenIndex];
  }
  _getStartCharacter(tokenIndex) {
    return this._tokens[4 * tokenIndex + 1];
  }
  _getEndCharacter(tokenIndex) {
    return this._tokens[4 * tokenIndex + 2];
  }
  isEmpty() {
    return this._getTokenCount() === 0;
  }
  getLineTokens(deltaLine) {
    let low = 0;
    let high = this._getTokenCount() - 1;
    while (low < high) {
      const mid = low + Math.floor((high - low) / 2);
      const midDeltaLine = this._getDeltaLine(mid);
      if (midDeltaLine < deltaLine) {
        low = mid + 1;
      } else if (midDeltaLine > deltaLine) {
        high = mid - 1;
      } else {
        let min2 = mid;
        while (min2 > low && this._getDeltaLine(min2 - 1) === deltaLine) {
          min2--;
        }
        let max2 = mid;
        while (max2 < high && this._getDeltaLine(max2 + 1) === deltaLine) {
          max2++;
        }
        return new LineTokens2(this._tokens.subarray(4 * min2, 4 * max2 + 4));
      }
    }
    if (this._getDeltaLine(low) === deltaLine) {
      return new LineTokens2(this._tokens.subarray(4 * low, 4 * low + 4));
    }
    return null;
  }
  clear() {
    this._tokenCount = 0;
  }
  removeTokens(startDeltaLine, startChar, endDeltaLine, endChar) {
    const tokens = this._tokens;
    const tokenCount = this._tokenCount;
    let newTokenCount = 0;
    let hasDeletedTokens = false;
    let firstDeltaLine = 0;
    for (let i3 = 0; i3 < tokenCount; i3++) {
      const srcOffset = 4 * i3;
      const tokenDeltaLine = tokens[srcOffset];
      const tokenStartCharacter = tokens[srcOffset + 1];
      const tokenEndCharacter = tokens[srcOffset + 2];
      const tokenMetadata = tokens[srcOffset + 3];
      if ((tokenDeltaLine > startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar) && (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar)) {
        hasDeletedTokens = true;
      } else {
        if (newTokenCount === 0) {
          firstDeltaLine = tokenDeltaLine;
        }
        if (hasDeletedTokens) {
          const destOffset = 4 * newTokenCount;
          tokens[destOffset] = tokenDeltaLine - firstDeltaLine;
          tokens[destOffset + 1] = tokenStartCharacter;
          tokens[destOffset + 2] = tokenEndCharacter;
          tokens[destOffset + 3] = tokenMetadata;
        }
        newTokenCount++;
      }
    }
    this._tokenCount = newTokenCount;
    return firstDeltaLine;
  }
  split(startDeltaLine, startChar, endDeltaLine, endChar) {
    const tokens = this._tokens;
    const tokenCount = this._tokenCount;
    let aTokens = [];
    let bTokens = [];
    let destTokens = aTokens;
    let destOffset = 0;
    let destFirstDeltaLine = 0;
    for (let i3 = 0; i3 < tokenCount; i3++) {
      const srcOffset = 4 * i3;
      const tokenDeltaLine = tokens[srcOffset];
      const tokenStartCharacter = tokens[srcOffset + 1];
      const tokenEndCharacter = tokens[srcOffset + 2];
      const tokenMetadata = tokens[srcOffset + 3];
      if (tokenDeltaLine > startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar) {
        if (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar) {
          continue;
        } else {
          if (destTokens !== bTokens) {
            destTokens = bTokens;
            destOffset = 0;
            destFirstDeltaLine = tokenDeltaLine;
          }
        }
      }
      destTokens[destOffset++] = tokenDeltaLine - destFirstDeltaLine;
      destTokens[destOffset++] = tokenStartCharacter;
      destTokens[destOffset++] = tokenEndCharacter;
      destTokens[destOffset++] = tokenMetadata;
    }
    return [new SparseEncodedTokens(new Uint32Array(aTokens)), new SparseEncodedTokens(new Uint32Array(bTokens)), destFirstDeltaLine];
  }
  acceptDeleteRange(horizontalShiftForFirstLineTokens, startDeltaLine, startCharacter, endDeltaLine, endCharacter) {
    const tokens = this._tokens;
    const tokenCount = this._tokenCount;
    const deletedLineCount = endDeltaLine - startDeltaLine;
    let newTokenCount = 0;
    let hasDeletedTokens = false;
    for (let i3 = 0; i3 < tokenCount; i3++) {
      const srcOffset = 4 * i3;
      let tokenDeltaLine = tokens[srcOffset];
      let tokenStartCharacter = tokens[srcOffset + 1];
      let tokenEndCharacter = tokens[srcOffset + 2];
      const tokenMetadata = tokens[srcOffset + 3];
      if (tokenDeltaLine < startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter <= startCharacter) {
        newTokenCount++;
        continue;
      } else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter < startCharacter) {
        if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
          tokenEndCharacter -= endCharacter - startCharacter;
        } else {
          tokenEndCharacter = startCharacter;
        }
      } else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter === startCharacter) {
        if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
          tokenEndCharacter -= endCharacter - startCharacter;
        } else {
          hasDeletedTokens = true;
          continue;
        }
      } else if (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter < endCharacter) {
        if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
          if (tokenDeltaLine === startDeltaLine) {
            tokenStartCharacter = startCharacter;
            tokenEndCharacter = tokenStartCharacter + (tokenEndCharacter - endCharacter);
          } else {
            tokenStartCharacter = 0;
            tokenEndCharacter = tokenStartCharacter + (tokenEndCharacter - endCharacter);
          }
        } else {
          hasDeletedTokens = true;
          continue;
        }
      } else if (tokenDeltaLine > endDeltaLine) {
        if (deletedLineCount === 0 && !hasDeletedTokens) {
          newTokenCount = tokenCount;
          break;
        }
        tokenDeltaLine -= deletedLineCount;
      } else if (tokenDeltaLine === endDeltaLine && tokenStartCharacter >= endCharacter) {
        if (horizontalShiftForFirstLineTokens && tokenDeltaLine === 0) {
          tokenStartCharacter += horizontalShiftForFirstLineTokens;
          tokenEndCharacter += horizontalShiftForFirstLineTokens;
        }
        tokenDeltaLine -= deletedLineCount;
        tokenStartCharacter -= endCharacter - startCharacter;
        tokenEndCharacter -= endCharacter - startCharacter;
      } else {
        throw new Error(`Not possible!`);
      }
      const destOffset = 4 * newTokenCount;
      tokens[destOffset] = tokenDeltaLine;
      tokens[destOffset + 1] = tokenStartCharacter;
      tokens[destOffset + 2] = tokenEndCharacter;
      tokens[destOffset + 3] = tokenMetadata;
      newTokenCount++;
    }
    this._tokenCount = newTokenCount;
  }
  acceptInsertText(deltaLine, character, eolCount, firstLineLength, lastLineLength, firstCharCode) {
    const isInsertingPreciselyOneWordCharacter = eolCount === 0 && firstLineLength === 1 && (firstCharCode >= 48 && firstCharCode <= 57 || firstCharCode >= 65 && firstCharCode <= 90 || firstCharCode >= 97 && firstCharCode <= 122);
    const tokens = this._tokens;
    const tokenCount = this._tokenCount;
    for (let i3 = 0; i3 < tokenCount; i3++) {
      const offset2 = 4 * i3;
      let tokenDeltaLine = tokens[offset2];
      let tokenStartCharacter = tokens[offset2 + 1];
      let tokenEndCharacter = tokens[offset2 + 2];
      if (tokenDeltaLine < deltaLine || tokenDeltaLine === deltaLine && tokenEndCharacter < character) {
        continue;
      } else if (tokenDeltaLine === deltaLine && tokenEndCharacter === character) {
        if (isInsertingPreciselyOneWordCharacter) {
          tokenEndCharacter += 1;
        } else {
          continue;
        }
      } else if (tokenDeltaLine === deltaLine && tokenStartCharacter < character && character < tokenEndCharacter) {
        if (eolCount === 0) {
          tokenEndCharacter += firstLineLength;
        } else {
          tokenEndCharacter = character;
        }
      } else {
        if (tokenDeltaLine === deltaLine && tokenStartCharacter === character) {
          if (isInsertingPreciselyOneWordCharacter) {
            continue;
          }
        }
        if (tokenDeltaLine === deltaLine) {
          tokenDeltaLine += eolCount;
          if (eolCount === 0) {
            tokenStartCharacter += firstLineLength;
            tokenEndCharacter += firstLineLength;
          } else {
            const tokenLength = tokenEndCharacter - tokenStartCharacter;
            tokenStartCharacter = lastLineLength + (tokenStartCharacter - character);
            tokenEndCharacter = tokenStartCharacter + tokenLength;
          }
        } else {
          tokenDeltaLine += eolCount;
        }
      }
      tokens[offset2] = tokenDeltaLine;
      tokens[offset2 + 1] = tokenStartCharacter;
      tokens[offset2 + 2] = tokenEndCharacter;
    }
  }
};
var LineTokens2 = class {
  constructor(tokens) {
    this._tokens = tokens;
  }
  getCount() {
    return this._tokens.length / 4;
  }
  getStartCharacter(tokenIndex) {
    return this._tokens[4 * tokenIndex + 1];
  }
  getEndCharacter(tokenIndex) {
    return this._tokens[4 * tokenIndex + 2];
  }
  getMetadata(tokenIndex) {
    return this._tokens[4 * tokenIndex + 3];
  }
};
var MultilineTokens2 = class {
  constructor(startLineNumber, tokens) {
    this.startLineNumber = startLineNumber;
    this.tokens = tokens;
    this.endLineNumber = this.startLineNumber + this.tokens.getMaxDeltaLine();
  }
  toString() {
    return this.tokens.toString(this.startLineNumber);
  }
  _updateEndLineNumber() {
    this.endLineNumber = this.startLineNumber + this.tokens.getMaxDeltaLine();
  }
  isEmpty() {
    return this.tokens.isEmpty();
  }
  getLineTokens(lineNumber) {
    if (this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber) {
      return this.tokens.getLineTokens(lineNumber - this.startLineNumber);
    }
    return null;
  }
  getRange() {
    const deltaRange = this.tokens.getRange();
    if (!deltaRange) {
      return deltaRange;
    }
    return new Range(this.startLineNumber + deltaRange.startLineNumber, deltaRange.startColumn, this.startLineNumber + deltaRange.endLineNumber, deltaRange.endColumn);
  }
  removeTokens(range3) {
    const startLineIndex = range3.startLineNumber - this.startLineNumber;
    const endLineIndex = range3.endLineNumber - this.startLineNumber;
    this.startLineNumber += this.tokens.removeTokens(startLineIndex, range3.startColumn - 1, endLineIndex, range3.endColumn - 1);
    this._updateEndLineNumber();
  }
  split(range3) {
    const startLineIndex = range3.startLineNumber - this.startLineNumber;
    const endLineIndex = range3.endLineNumber - this.startLineNumber;
    const [a2, b2, bDeltaLine] = this.tokens.split(startLineIndex, range3.startColumn - 1, endLineIndex, range3.endColumn - 1);
    return [new MultilineTokens2(this.startLineNumber, a2), new MultilineTokens2(this.startLineNumber + bDeltaLine, b2)];
  }
  applyEdit(range3, text) {
    const [eolCount, firstLineLength, lastLineLength] = countEOL(text);
    this.acceptEdit(range3, eolCount, firstLineLength, lastLineLength, text.length > 0 ? text.charCodeAt(0) : 0);
  }
  acceptEdit(range3, eolCount, firstLineLength, lastLineLength, firstCharCode) {
    this._acceptDeleteRange(range3);
    this._acceptInsertText(new Position(range3.startLineNumber, range3.startColumn), eolCount, firstLineLength, lastLineLength, firstCharCode);
    this._updateEndLineNumber();
  }
  _acceptDeleteRange(range3) {
    if (range3.startLineNumber === range3.endLineNumber && range3.startColumn === range3.endColumn) {
      return;
    }
    const firstLineIndex = range3.startLineNumber - this.startLineNumber;
    const lastLineIndex = range3.endLineNumber - this.startLineNumber;
    if (lastLineIndex < 0) {
      const deletedLinesCount = lastLineIndex - firstLineIndex;
      this.startLineNumber -= deletedLinesCount;
      return;
    }
    const tokenMaxDeltaLine = this.tokens.getMaxDeltaLine();
    if (firstLineIndex >= tokenMaxDeltaLine + 1) {
      return;
    }
    if (firstLineIndex < 0 && lastLineIndex >= tokenMaxDeltaLine + 1) {
      this.startLineNumber = 0;
      this.tokens.clear();
      return;
    }
    if (firstLineIndex < 0) {
      const deletedBefore = -firstLineIndex;
      this.startLineNumber -= deletedBefore;
      this.tokens.acceptDeleteRange(range3.startColumn - 1, 0, 0, lastLineIndex, range3.endColumn - 1);
    } else {
      this.tokens.acceptDeleteRange(0, firstLineIndex, range3.startColumn - 1, lastLineIndex, range3.endColumn - 1);
    }
  }
  _acceptInsertText(position2, eolCount, firstLineLength, lastLineLength, firstCharCode) {
    if (eolCount === 0 && firstLineLength === 0) {
      return;
    }
    const lineIndex = position2.lineNumber - this.startLineNumber;
    if (lineIndex < 0) {
      this.startLineNumber += eolCount;
      return;
    }
    const tokenMaxDeltaLine = this.tokens.getMaxDeltaLine();
    if (lineIndex >= tokenMaxDeltaLine + 1) {
      return;
    }
    this.tokens.acceptInsertText(lineIndex, position2.column - 1, eolCount, firstLineLength, lastLineLength, firstCharCode);
  }
};
var MultilineTokens = class {
  constructor(startLineNumber, tokens) {
    this.startLineNumber = startLineNumber;
    this.tokens = tokens;
  }
};
function toUint32Array(arr) {
  if (arr instanceof Uint32Array) {
    return arr;
  } else {
    return new Uint32Array(arr);
  }
}
var TokensStore2 = class {
  constructor() {
    this._pieces = [];
    this._isComplete = false;
  }
  flush() {
    this._pieces = [];
    this._isComplete = false;
  }
  set(pieces, isComplete) {
    this._pieces = pieces || [];
    this._isComplete = isComplete;
  }
  setPartial(_range, pieces) {
    let range3 = _range;
    if (pieces.length > 0) {
      const _firstRange = pieces[0].getRange();
      const _lastRange = pieces[pieces.length - 1].getRange();
      if (!_firstRange || !_lastRange) {
        return _range;
      }
      range3 = _range.plusRange(_firstRange).plusRange(_lastRange);
    }
    let insertPosition = null;
    for (let i3 = 0, len2 = this._pieces.length; i3 < len2; i3++) {
      const piece = this._pieces[i3];
      if (piece.endLineNumber < range3.startLineNumber) {
        continue;
      }
      if (piece.startLineNumber > range3.endLineNumber) {
        insertPosition = insertPosition || {index: i3};
        break;
      }
      piece.removeTokens(range3);
      if (piece.isEmpty()) {
        this._pieces.splice(i3, 1);
        i3--;
        len2--;
        continue;
      }
      if (piece.endLineNumber < range3.startLineNumber) {
        continue;
      }
      if (piece.startLineNumber > range3.endLineNumber) {
        insertPosition = insertPosition || {index: i3};
        continue;
      }
      const [a2, b2] = piece.split(range3);
      if (a2.isEmpty()) {
        insertPosition = insertPosition || {index: i3};
        continue;
      }
      if (b2.isEmpty()) {
        continue;
      }
      this._pieces.splice(i3, 1, a2, b2);
      i3++;
      len2++;
      insertPosition = insertPosition || {index: i3};
    }
    insertPosition = insertPosition || {index: this._pieces.length};
    if (pieces.length > 0) {
      this._pieces = arrayInsert(this._pieces, insertPosition.index, pieces);
    }
    return range3;
  }
  isComplete() {
    return this._isComplete;
  }
  addSemanticTokens(lineNumber, aTokens) {
    const pieces = this._pieces;
    if (pieces.length === 0) {
      return aTokens;
    }
    const pieceIndex = TokensStore2._findFirstPieceWithLine(pieces, lineNumber);
    const bTokens = pieces[pieceIndex].getLineTokens(lineNumber);
    if (!bTokens) {
      return aTokens;
    }
    const aLen = aTokens.getCount();
    const bLen = bTokens.getCount();
    let aIndex = 0;
    let result = [], resultLen = 0;
    let lastEndOffset = 0;
    const emitToken = (endOffset, metadata) => {
      if (endOffset === lastEndOffset) {
        return;
      }
      lastEndOffset = endOffset;
      result[resultLen++] = endOffset;
      result[resultLen++] = metadata;
    };
    for (let bIndex = 0; bIndex < bLen; bIndex++) {
      const bStartCharacter = bTokens.getStartCharacter(bIndex);
      const bEndCharacter = bTokens.getEndCharacter(bIndex);
      const bMetadata = bTokens.getMetadata(bIndex);
      const bMask = ((bMetadata & 1 ? 2048 : 0) | (bMetadata & 2 ? 4096 : 0) | (bMetadata & 4 ? 8192 : 0) | (bMetadata & 8 ? 8372224 : 0) | (bMetadata & 16 ? 4286578688 : 0)) >>> 0;
      const aMask = ~bMask >>> 0;
      while (aIndex < aLen && aTokens.getEndOffset(aIndex) <= bStartCharacter) {
        emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
        aIndex++;
      }
      if (aIndex < aLen && aTokens.getStartOffset(aIndex) < bStartCharacter) {
        emitToken(bStartCharacter, aTokens.getMetadata(aIndex));
      }
      while (aIndex < aLen && aTokens.getEndOffset(aIndex) < bEndCharacter) {
        emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex) & aMask | bMetadata & bMask);
        aIndex++;
      }
      if (aIndex < aLen) {
        emitToken(bEndCharacter, aTokens.getMetadata(aIndex) & aMask | bMetadata & bMask);
        if (aTokens.getEndOffset(aIndex) === bEndCharacter) {
          aIndex++;
        }
      } else {
        const aMergeIndex = Math.min(Math.max(0, aIndex - 1), aLen - 1);
        emitToken(bEndCharacter, aTokens.getMetadata(aMergeIndex) & aMask | bMetadata & bMask);
      }
    }
    while (aIndex < aLen) {
      emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
      aIndex++;
    }
    return new LineTokens(new Uint32Array(result), aTokens.getLineContent());
  }
  static _findFirstPieceWithLine(pieces, lineNumber) {
    let low = 0;
    let high = pieces.length - 1;
    while (low < high) {
      let mid = low + Math.floor((high - low) / 2);
      if (pieces[mid].endLineNumber < lineNumber) {
        low = mid + 1;
      } else if (pieces[mid].startLineNumber > lineNumber) {
        high = mid - 1;
      } else {
        while (mid > low && pieces[mid - 1].startLineNumber <= lineNumber && lineNumber <= pieces[mid - 1].endLineNumber) {
          mid--;
        }
        return mid;
      }
    }
    return low;
  }
  acceptEdit(range3, eolCount, firstLineLength, lastLineLength, firstCharCode) {
    for (const piece of this._pieces) {
      piece.acceptEdit(range3, eolCount, firstLineLength, lastLineLength, firstCharCode);
    }
  }
};
var TokensStore = class {
  constructor() {
    this._lineTokens = [];
    this._len = 0;
  }
  flush() {
    this._lineTokens = [];
    this._len = 0;
  }
  getTokens(topLevelLanguageId, lineIndex, lineText) {
    let rawLineTokens = null;
    if (lineIndex < this._len) {
      rawLineTokens = this._lineTokens[lineIndex];
    }
    if (rawLineTokens !== null && rawLineTokens !== EMPTY_LINE_TOKENS) {
      return new LineTokens(toUint32Array(rawLineTokens), lineText);
    }
    let lineTokens = new Uint32Array(2);
    lineTokens[0] = lineText.length;
    lineTokens[1] = getDefaultMetadata(topLevelLanguageId);
    return new LineTokens(lineTokens, lineText);
  }
  static _massageTokens(topLevelLanguageId, lineTextLength, _tokens) {
    const tokens = _tokens ? toUint32Array(_tokens) : null;
    if (lineTextLength === 0) {
      let hasDifferentLanguageId = false;
      if (tokens && tokens.length > 1) {
        hasDifferentLanguageId = TokenMetadata.getLanguageId(tokens[1]) !== topLevelLanguageId;
      }
      if (!hasDifferentLanguageId) {
        return EMPTY_LINE_TOKENS;
      }
    }
    if (!tokens || tokens.length === 0) {
      const tokens2 = new Uint32Array(2);
      tokens2[0] = lineTextLength;
      tokens2[1] = getDefaultMetadata(topLevelLanguageId);
      return tokens2.buffer;
    }
    tokens[tokens.length - 2] = lineTextLength;
    if (tokens.byteOffset === 0 && tokens.byteLength === tokens.buffer.byteLength) {
      return tokens.buffer;
    }
    return tokens;
  }
  _ensureLine(lineIndex) {
    while (lineIndex >= this._len) {
      this._lineTokens[this._len] = null;
      this._len++;
    }
  }
  _deleteLines(start3, deleteCount) {
    if (deleteCount === 0) {
      return;
    }
    if (start3 + deleteCount > this._len) {
      deleteCount = this._len - start3;
    }
    this._lineTokens.splice(start3, deleteCount);
    this._len -= deleteCount;
  }
  _insertLines(insertIndex, insertCount) {
    if (insertCount === 0) {
      return;
    }
    let lineTokens = [];
    for (let i3 = 0; i3 < insertCount; i3++) {
      lineTokens[i3] = null;
    }
    this._lineTokens = arrayInsert(this._lineTokens, insertIndex, lineTokens);
    this._len += insertCount;
  }
  setTokens(topLevelLanguageId, lineIndex, lineTextLength, _tokens, checkEquality) {
    const tokens = TokensStore._massageTokens(topLevelLanguageId, lineTextLength, _tokens);
    this._ensureLine(lineIndex);
    const oldTokens = this._lineTokens[lineIndex];
    this._lineTokens[lineIndex] = tokens;
    if (checkEquality) {
      return !TokensStore._equals(oldTokens, tokens);
    }
    return false;
  }
  static _equals(_a, _b) {
    if (!_a || !_b) {
      return !_a && !_b;
    }
    const a2 = toUint32Array(_a);
    const b2 = toUint32Array(_b);
    if (a2.length !== b2.length) {
      return false;
    }
    for (let i3 = 0, len2 = a2.length; i3 < len2; i3++) {
      if (a2[i3] !== b2[i3]) {
        return false;
      }
    }
    return true;
  }
  acceptEdit(range3, eolCount, firstLineLength) {
    this._acceptDeleteRange(range3);
    this._acceptInsertText(new Position(range3.startLineNumber, range3.startColumn), eolCount, firstLineLength);
  }
  _acceptDeleteRange(range3) {
    const firstLineIndex = range3.startLineNumber - 1;
    if (firstLineIndex >= this._len) {
      return;
    }
    if (range3.startLineNumber === range3.endLineNumber) {
      if (range3.startColumn === range3.endColumn) {
        return;
      }
      this._lineTokens[firstLineIndex] = TokensStore._delete(this._lineTokens[firstLineIndex], range3.startColumn - 1, range3.endColumn - 1);
      return;
    }
    this._lineTokens[firstLineIndex] = TokensStore._deleteEnding(this._lineTokens[firstLineIndex], range3.startColumn - 1);
    const lastLineIndex = range3.endLineNumber - 1;
    let lastLineTokens = null;
    if (lastLineIndex < this._len) {
      lastLineTokens = TokensStore._deleteBeginning(this._lineTokens[lastLineIndex], range3.endColumn - 1);
    }
    this._lineTokens[firstLineIndex] = TokensStore._append(this._lineTokens[firstLineIndex], lastLineTokens);
    this._deleteLines(range3.startLineNumber, range3.endLineNumber - range3.startLineNumber);
  }
  _acceptInsertText(position2, eolCount, firstLineLength) {
    if (eolCount === 0 && firstLineLength === 0) {
      return;
    }
    const lineIndex = position2.lineNumber - 1;
    if (lineIndex >= this._len) {
      return;
    }
    if (eolCount === 0) {
      this._lineTokens[lineIndex] = TokensStore._insert(this._lineTokens[lineIndex], position2.column - 1, firstLineLength);
      return;
    }
    this._lineTokens[lineIndex] = TokensStore._deleteEnding(this._lineTokens[lineIndex], position2.column - 1);
    this._lineTokens[lineIndex] = TokensStore._insert(this._lineTokens[lineIndex], position2.column - 1, firstLineLength);
    this._insertLines(position2.lineNumber, eolCount);
  }
  static _deleteBeginning(lineTokens, toChIndex) {
    if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
      return lineTokens;
    }
    return TokensStore._delete(lineTokens, 0, toChIndex);
  }
  static _deleteEnding(lineTokens, fromChIndex) {
    if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
      return lineTokens;
    }
    const tokens = toUint32Array(lineTokens);
    const lineTextLength = tokens[tokens.length - 2];
    return TokensStore._delete(lineTokens, fromChIndex, lineTextLength);
  }
  static _delete(lineTokens, fromChIndex, toChIndex) {
    if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS || fromChIndex === toChIndex) {
      return lineTokens;
    }
    const tokens = toUint32Array(lineTokens);
    const tokensCount = tokens.length >>> 1;
    if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) {
      return EMPTY_LINE_TOKENS;
    }
    const fromTokenIndex = LineTokens.findIndexInTokensArray(tokens, fromChIndex);
    const fromTokenStartOffset = fromTokenIndex > 0 ? tokens[fromTokenIndex - 1 << 1] : 0;
    const fromTokenEndOffset = tokens[fromTokenIndex << 1];
    if (toChIndex < fromTokenEndOffset) {
      const delta2 = toChIndex - fromChIndex;
      for (let i3 = fromTokenIndex; i3 < tokensCount; i3++) {
        tokens[i3 << 1] -= delta2;
      }
      return lineTokens;
    }
    let dest;
    let lastEnd;
    if (fromTokenStartOffset !== fromChIndex) {
      tokens[fromTokenIndex << 1] = fromChIndex;
      dest = fromTokenIndex + 1 << 1;
      lastEnd = fromChIndex;
    } else {
      dest = fromTokenIndex << 1;
      lastEnd = fromTokenStartOffset;
    }
    const delta = toChIndex - fromChIndex;
    for (let tokenIndex = fromTokenIndex + 1; tokenIndex < tokensCount; tokenIndex++) {
      const tokenEndOffset = tokens[tokenIndex << 1] - delta;
      if (tokenEndOffset > lastEnd) {
        tokens[dest++] = tokenEndOffset;
        tokens[dest++] = tokens[(tokenIndex << 1) + 1];
        lastEnd = tokenEndOffset;
      }
    }
    if (dest === tokens.length) {
      return lineTokens;
    }
    let tmp = new Uint32Array(dest);
    tmp.set(tokens.subarray(0, dest), 0);
    return tmp.buffer;
  }
  static _append(lineTokens, _otherTokens) {
    if (_otherTokens === EMPTY_LINE_TOKENS) {
      return lineTokens;
    }
    if (lineTokens === EMPTY_LINE_TOKENS) {
      return _otherTokens;
    }
    if (lineTokens === null) {
      return lineTokens;
    }
    if (_otherTokens === null) {
      return null;
    }
    const myTokens = toUint32Array(lineTokens);
    const otherTokens = toUint32Array(_otherTokens);
    const otherTokensCount = otherTokens.length >>> 1;
    let result = new Uint32Array(myTokens.length + otherTokens.length);
    result.set(myTokens, 0);
    let dest = myTokens.length;
    const delta = myTokens[myTokens.length - 2];
    for (let i3 = 0; i3 < otherTokensCount; i3++) {
      result[dest++] = otherTokens[i3 << 1] + delta;
      result[dest++] = otherTokens[(i3 << 1) + 1];
    }
    return result.buffer;
  }
  static _insert(lineTokens, chIndex, textLength) {
    if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
      return lineTokens;
    }
    const tokens = toUint32Array(lineTokens);
    const tokensCount = tokens.length >>> 1;
    let fromTokenIndex = LineTokens.findIndexInTokensArray(tokens, chIndex);
    if (fromTokenIndex > 0) {
      const fromTokenStartOffset = tokens[fromTokenIndex - 1 << 1];
      if (fromTokenStartOffset === chIndex) {
        fromTokenIndex--;
      }
    }
    for (let tokenIndex = fromTokenIndex; tokenIndex < tokensCount; tokenIndex++) {
      tokens[tokenIndex << 1] += textLength;
    }
    return lineTokens;
  }
};
var PieceTreeTextBuffer = class {
  constructor(chunks, BOM, eol, containsRTL2, containsUnusualLineTerminators2, isBasicASCII2, eolNormalized) {
    this._onDidChangeContent = new Emitter();
    this._BOM = BOM;
    this._mightContainNonBasicASCII = !isBasicASCII2;
    this._mightContainRTL = containsRTL2;
    this._mightContainUnusualLineTerminators = containsUnusualLineTerminators2;
    this._pieceTree = new PieceTreeBase(chunks, eol, eolNormalized);
  }
  dispose() {
    this._onDidChangeContent.dispose();
  }
  mightContainRTL() {
    return this._mightContainRTL;
  }
  mightContainUnusualLineTerminators() {
    return this._mightContainUnusualLineTerminators;
  }
  resetMightContainUnusualLineTerminators() {
    this._mightContainUnusualLineTerminators = false;
  }
  mightContainNonBasicASCII() {
    return this._mightContainNonBasicASCII;
  }
  getBOM() {
    return this._BOM;
  }
  getEOL() {
    return this._pieceTree.getEOL();
  }
  createSnapshot(preserveBOM) {
    return this._pieceTree.createSnapshot(preserveBOM ? this._BOM : "");
  }
  getOffsetAt(lineNumber, column) {
    return this._pieceTree.getOffsetAt(lineNumber, column);
  }
  getPositionAt(offset2) {
    return this._pieceTree.getPositionAt(offset2);
  }
  getRangeAt(start3, length) {
    let end2 = start3 + length;
    const startPosition = this.getPositionAt(start3);
    const endPosition = this.getPositionAt(end2);
    return new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
  }
  getValueInRange(range3, eol = 0) {
    if (range3.isEmpty()) {
      return "";
    }
    const lineEnding = this._getEndOfLine(eol);
    return this._pieceTree.getValueInRange(range3, lineEnding);
  }
  getValueLengthInRange(range3, eol = 0) {
    if (range3.isEmpty()) {
      return 0;
    }
    if (range3.startLineNumber === range3.endLineNumber) {
      return range3.endColumn - range3.startColumn;
    }
    let startOffset = this.getOffsetAt(range3.startLineNumber, range3.startColumn);
    let endOffset = this.getOffsetAt(range3.endLineNumber, range3.endColumn);
    return endOffset - startOffset;
  }
  getCharacterCountInRange(range3, eol = 0) {
    if (this._mightContainNonBasicASCII) {
      let result = 0;
      const fromLineNumber = range3.startLineNumber;
      const toLineNumber = range3.endLineNumber;
      for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
        const lineContent = this.getLineContent(lineNumber);
        const fromOffset = lineNumber === fromLineNumber ? range3.startColumn - 1 : 0;
        const toOffset = lineNumber === toLineNumber ? range3.endColumn - 1 : lineContent.length;
        for (let offset2 = fromOffset; offset2 < toOffset; offset2++) {
          if (isHighSurrogate(lineContent.charCodeAt(offset2))) {
            result = result + 1;
            offset2 = offset2 + 1;
          } else {
            result = result + 1;
          }
        }
      }
      result += this._getEndOfLine(eol).length * (toLineNumber - fromLineNumber);
      return result;
    }
    return this.getValueLengthInRange(range3, eol);
  }
  getLength() {
    return this._pieceTree.getLength();
  }
  getLineCount() {
    return this._pieceTree.getLineCount();
  }
  getLinesContent() {
    return this._pieceTree.getLinesContent();
  }
  getLineContent(lineNumber) {
    return this._pieceTree.getLineContent(lineNumber);
  }
  getLineCharCode(lineNumber, index3) {
    return this._pieceTree.getLineCharCode(lineNumber, index3);
  }
  getLineLength(lineNumber) {
    return this._pieceTree.getLineLength(lineNumber);
  }
  getLineFirstNonWhitespaceColumn(lineNumber) {
    const result = firstNonWhitespaceIndex(this.getLineContent(lineNumber));
    if (result === -1) {
      return 0;
    }
    return result + 1;
  }
  getLineLastNonWhitespaceColumn(lineNumber) {
    const result = lastNonWhitespaceIndex(this.getLineContent(lineNumber));
    if (result === -1) {
      return 0;
    }
    return result + 2;
  }
  _getEndOfLine(eol) {
    switch (eol) {
      case 1:
        return "\n";
      case 2:
        return "\r\n";
      case 0:
        return this.getEOL();
      default:
        throw new Error("Unknown EOL preference");
    }
  }
  setEOL(newEOL) {
    this._pieceTree.setEOL(newEOL);
  }
  applyEdits(rawOperations, recordTrimAutoWhitespace, computeUndoEdits) {
    let mightContainRTL = this._mightContainRTL;
    let mightContainUnusualLineTerminators = this._mightContainUnusualLineTerminators;
    let mightContainNonBasicASCII = this._mightContainNonBasicASCII;
    let canReduceOperations = true;
    let operations = [];
    for (let i3 = 0; i3 < rawOperations.length; i3++) {
      let op = rawOperations[i3];
      if (canReduceOperations && op._isTracked) {
        canReduceOperations = false;
      }
      let validatedRange = op.range;
      if (op.text) {
        let textMightContainNonBasicASCII = true;
        if (!mightContainNonBasicASCII) {
          textMightContainNonBasicASCII = !isBasicASCII(op.text);
          mightContainNonBasicASCII = textMightContainNonBasicASCII;
        }
        if (!mightContainRTL && textMightContainNonBasicASCII) {
          mightContainRTL = containsRTL(op.text);
        }
        if (!mightContainUnusualLineTerminators && textMightContainNonBasicASCII) {
          mightContainUnusualLineTerminators = containsUnusualLineTerminators(op.text);
        }
      }
      let validText = "";
      let eolCount = 0;
      let firstLineLength = 0;
      let lastLineLength = 0;
      if (op.text) {
        let strEOL;
        [eolCount, firstLineLength, lastLineLength, strEOL] = countEOL(op.text);
        const bufferEOL = this.getEOL();
        const expectedStrEOL = bufferEOL === "\r\n" ? 2 : 1;
        if (strEOL === 0 || strEOL === expectedStrEOL) {
          validText = op.text;
        } else {
          validText = op.text.replace(/\r\n|\r|\n/g, bufferEOL);
        }
      }
      operations[i3] = {
        sortIndex: i3,
        identifier: op.identifier || null,
        range: validatedRange,
        rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn),
        rangeLength: this.getValueLengthInRange(validatedRange),
        text: validText,
        eolCount,
        firstLineLength,
        lastLineLength,
        forceMoveMarkers: Boolean(op.forceMoveMarkers),
        isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false
      };
    }
    operations.sort(PieceTreeTextBuffer._sortOpsAscending);
    let hasTouchingRanges = false;
    for (let i3 = 0, count = operations.length - 1; i3 < count; i3++) {
      let rangeEnd = operations[i3].range.getEndPosition();
      let nextRangeStart = operations[i3 + 1].range.getStartPosition();
      if (nextRangeStart.isBeforeOrEqual(rangeEnd)) {
        if (nextRangeStart.isBefore(rangeEnd)) {
          throw new Error("Overlapping ranges are not allowed!");
        }
        hasTouchingRanges = true;
      }
    }
    if (canReduceOperations) {
      operations = this._reduceOperations(operations);
    }
    let reverseRanges = computeUndoEdits || recordTrimAutoWhitespace ? PieceTreeTextBuffer._getInverseEditRanges(operations) : [];
    let newTrimAutoWhitespaceCandidates = [];
    if (recordTrimAutoWhitespace) {
      for (let i3 = 0; i3 < operations.length; i3++) {
        let op = operations[i3];
        let reverseRange = reverseRanges[i3];
        if (op.isAutoWhitespaceEdit && op.range.isEmpty()) {
          for (let lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) {
            let currentLineContent = "";
            if (lineNumber === reverseRange.startLineNumber) {
              currentLineContent = this.getLineContent(op.range.startLineNumber);
              if (firstNonWhitespaceIndex(currentLineContent) !== -1) {
                continue;
              }
            }
            newTrimAutoWhitespaceCandidates.push({lineNumber, oldContent: currentLineContent});
          }
        }
      }
    }
    let reverseOperations = null;
    if (computeUndoEdits) {
      let reverseRangeDeltaOffset = 0;
      reverseOperations = [];
      for (let i3 = 0; i3 < operations.length; i3++) {
        const op = operations[i3];
        const reverseRange = reverseRanges[i3];
        const bufferText = this.getValueInRange(op.range);
        const reverseRangeOffset = op.rangeOffset + reverseRangeDeltaOffset;
        reverseRangeDeltaOffset += op.text.length - bufferText.length;
        reverseOperations[i3] = {
          sortIndex: op.sortIndex,
          identifier: op.identifier,
          range: reverseRange,
          text: bufferText,
          textChange: new TextChange(op.rangeOffset, bufferText, reverseRangeOffset, op.text)
        };
      }
      if (!hasTouchingRanges) {
        reverseOperations.sort((a2, b2) => a2.sortIndex - b2.sortIndex);
      }
    }
    this._mightContainRTL = mightContainRTL;
    this._mightContainUnusualLineTerminators = mightContainUnusualLineTerminators;
    this._mightContainNonBasicASCII = mightContainNonBasicASCII;
    const contentChanges = this._doApplyEdits(operations);
    let trimAutoWhitespaceLineNumbers = null;
    if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) {
      newTrimAutoWhitespaceCandidates.sort((a2, b2) => b2.lineNumber - a2.lineNumber);
      trimAutoWhitespaceLineNumbers = [];
      for (let i3 = 0, len2 = newTrimAutoWhitespaceCandidates.length; i3 < len2; i3++) {
        let lineNumber = newTrimAutoWhitespaceCandidates[i3].lineNumber;
        if (i3 > 0 && newTrimAutoWhitespaceCandidates[i3 - 1].lineNumber === lineNumber) {
          continue;
        }
        let prevContent = newTrimAutoWhitespaceCandidates[i3].oldContent;
        let lineContent = this.getLineContent(lineNumber);
        if (lineContent.length === 0 || lineContent === prevContent || firstNonWhitespaceIndex(lineContent) !== -1) {
          continue;
        }
        trimAutoWhitespaceLineNumbers.push(lineNumber);
      }
    }
    this._onDidChangeContent.fire();
    return new ApplyEditsResult(reverseOperations, contentChanges, trimAutoWhitespaceLineNumbers);
  }
  _reduceOperations(operations) {
    if (operations.length < 1e3) {
      return operations;
    }
    return [this._toSingleEditOperation(operations)];
  }
  _toSingleEditOperation(operations) {
    let forceMoveMarkers = false;
    const firstEditRange = operations[0].range;
    const lastEditRange = operations[operations.length - 1].range;
    const entireEditRange = new Range(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn);
    let lastEndLineNumber = firstEditRange.startLineNumber;
    let lastEndColumn = firstEditRange.startColumn;
    const result = [];
    for (let i3 = 0, len2 = operations.length; i3 < len2; i3++) {
      const operation = operations[i3];
      const range3 = operation.range;
      forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers;
      result.push(this.getValueInRange(new Range(lastEndLineNumber, lastEndColumn, range3.startLineNumber, range3.startColumn)));
      if (operation.text.length > 0) {
        result.push(operation.text);
      }
      lastEndLineNumber = range3.endLineNumber;
      lastEndColumn = range3.endColumn;
    }
    const text = result.join("");
    const [eolCount, firstLineLength, lastLineLength] = countEOL(text);
    return {
      sortIndex: 0,
      identifier: operations[0].identifier,
      range: entireEditRange,
      rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn),
      rangeLength: this.getValueLengthInRange(entireEditRange, 0),
      text,
      eolCount,
      firstLineLength,
      lastLineLength,
      forceMoveMarkers,
      isAutoWhitespaceEdit: false
    };
  }
  _doApplyEdits(operations) {
    operations.sort(PieceTreeTextBuffer._sortOpsDescending);
    let contentChanges = [];
    for (let i3 = 0; i3 < operations.length; i3++) {
      let op = operations[i3];
      const startLineNumber = op.range.startLineNumber;
      const startColumn = op.range.startColumn;
      const endLineNumber = op.range.endLineNumber;
      const endColumn = op.range.endColumn;
      if (startLineNumber === endLineNumber && startColumn === endColumn && op.text.length === 0) {
        continue;
      }
      if (op.text) {
        this._pieceTree.delete(op.rangeOffset, op.rangeLength);
        this._pieceTree.insert(op.rangeOffset, op.text, true);
      } else {
        this._pieceTree.delete(op.rangeOffset, op.rangeLength);
      }
      const contentChangeRange = new Range(startLineNumber, startColumn, endLineNumber, endColumn);
      contentChanges.push({
        range: contentChangeRange,
        rangeLength: op.rangeLength,
        text: op.text,
        rangeOffset: op.rangeOffset,
        forceMoveMarkers: op.forceMoveMarkers
      });
    }
    return contentChanges;
  }
  findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
    return this._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
  }
  static _getInverseEditRanges(operations) {
    let result = [];
    let prevOpEndLineNumber = 0;
    let prevOpEndColumn = 0;
    let prevOp = null;
    for (let i3 = 0, len2 = operations.length; i3 < len2; i3++) {
      let op = operations[i3];
      let startLineNumber;
      let startColumn;
      if (prevOp) {
        if (prevOp.range.endLineNumber === op.range.startLineNumber) {
          startLineNumber = prevOpEndLineNumber;
          startColumn = prevOpEndColumn + (op.range.startColumn - prevOp.range.endColumn);
        } else {
          startLineNumber = prevOpEndLineNumber + (op.range.startLineNumber - prevOp.range.endLineNumber);
          startColumn = op.range.startColumn;
        }
      } else {
        startLineNumber = op.range.startLineNumber;
        startColumn = op.range.startColumn;
      }
      let resultRange;
      if (op.text.length > 0) {
        const lineCount = op.eolCount + 1;
        if (lineCount === 1) {
          resultRange = new Range(startLineNumber, startColumn, startLineNumber, startColumn + op.firstLineLength);
        } else {
          resultRange = new Range(startLineNumber, startColumn, startLineNumber + lineCount - 1, op.lastLineLength + 1);
        }
      } else {
        resultRange = new Range(startLineNumber, startColumn, startLineNumber, startColumn);
      }
      prevOpEndLineNumber = resultRange.endLineNumber;
      prevOpEndColumn = resultRange.endColumn;
      result.push(resultRange);
      prevOp = op;
    }
    return result;
  }
  static _sortOpsAscending(a2, b2) {
    let r3 = Range.compareRangesUsingEnds(a2.range, b2.range);
    if (r3 === 0) {
      return a2.sortIndex - b2.sortIndex;
    }
    return r3;
  }
  static _sortOpsDescending(a2, b2) {
    let r3 = Range.compareRangesUsingEnds(a2.range, b2.range);
    if (r3 === 0) {
      return b2.sortIndex - a2.sortIndex;
    }
    return -r3;
  }
};
var PieceTreeTextBufferFactory = class {
  constructor(_chunks, _bom, _cr, _lf, _crlf, _containsRTL, _containsUnusualLineTerminators, _isBasicASCII, _normalizeEOL) {
    this._chunks = _chunks;
    this._bom = _bom;
    this._cr = _cr;
    this._lf = _lf;
    this._crlf = _crlf;
    this._containsRTL = _containsRTL;
    this._containsUnusualLineTerminators = _containsUnusualLineTerminators;
    this._isBasicASCII = _isBasicASCII;
    this._normalizeEOL = _normalizeEOL;
  }
  _getEOL(defaultEOL) {
    const totalEOLCount = this._cr + this._lf + this._crlf;
    const totalCRCount = this._cr + this._crlf;
    if (totalEOLCount === 0) {
      return defaultEOL === 1 ? "\n" : "\r\n";
    }
    if (totalCRCount > totalEOLCount / 2) {
      return "\r\n";
    }
    return "\n";
  }
  create(defaultEOL) {
    const eol = this._getEOL(defaultEOL);
    let chunks = this._chunks;
    if (this._normalizeEOL && (eol === "\r\n" && (this._cr > 0 || this._lf > 0) || eol === "\n" && (this._cr > 0 || this._crlf > 0))) {
      for (let i3 = 0, len2 = chunks.length; i3 < len2; i3++) {
        let str = chunks[i3].buffer.replace(/\r\n|\r|\n/g, eol);
        let newLineStart = createLineStartsFast(str);
        chunks[i3] = new StringBuffer(str, newLineStart);
      }
    }
    return new PieceTreeTextBuffer(chunks, this._bom, eol, this._containsRTL, this._containsUnusualLineTerminators, this._isBasicASCII, this._normalizeEOL);
  }
};
var PieceTreeTextBufferBuilder = class {
  constructor() {
    this.chunks = [];
    this.BOM = "";
    this._hasPreviousChar = false;
    this._previousChar = 0;
    this._tmpLineStarts = [];
    this.cr = 0;
    this.lf = 0;
    this.crlf = 0;
    this.containsRTL = false;
    this.containsUnusualLineTerminators = false;
    this.isBasicASCII = true;
  }
  acceptChunk(chunk) {
    if (chunk.length === 0) {
      return;
    }
    if (this.chunks.length === 0) {
      if (startsWithUTF8BOM(chunk)) {
        this.BOM = UTF8_BOM_CHARACTER;
        chunk = chunk.substr(1);
      }
    }
    const lastChar = chunk.charCodeAt(chunk.length - 1);
    if (lastChar === 13 || lastChar >= 55296 && lastChar <= 56319) {
      this._acceptChunk1(chunk.substr(0, chunk.length - 1), false);
      this._hasPreviousChar = true;
      this._previousChar = lastChar;
    } else {
      this._acceptChunk1(chunk, false);
      this._hasPreviousChar = false;
      this._previousChar = lastChar;
    }
  }
  _acceptChunk1(chunk, allowEmptyStrings) {
    if (!allowEmptyStrings && chunk.length === 0) {
      return;
    }
    if (this._hasPreviousChar) {
      this._acceptChunk2(String.fromCharCode(this._previousChar) + chunk);
    } else {
      this._acceptChunk2(chunk);
    }
  }
  _acceptChunk2(chunk) {
    const lineStarts = createLineStarts(this._tmpLineStarts, chunk);
    this.chunks.push(new StringBuffer(chunk, lineStarts.lineStarts));
    this.cr += lineStarts.cr;
    this.lf += lineStarts.lf;
    this.crlf += lineStarts.crlf;
    if (this.isBasicASCII) {
      this.isBasicASCII = lineStarts.isBasicASCII;
    }
    if (!this.isBasicASCII && !this.containsRTL) {
      this.containsRTL = containsRTL(chunk);
    }
    if (!this.isBasicASCII && !this.containsUnusualLineTerminators) {
      this.containsUnusualLineTerminators = containsUnusualLineTerminators(chunk);
    }
  }
  finish(normalizeEOL = true) {
    this._finish();
    return new PieceTreeTextBufferFactory(this.chunks, this.BOM, this.cr, this.lf, this.crlf, this.containsRTL, this.containsUnusualLineTerminators, this.isBasicASCII, normalizeEOL);
  }
  _finish() {
    if (this.chunks.length === 0) {
      this._acceptChunk1("", true);
    }
    if (this._hasPreviousChar) {
      this._hasPreviousChar = false;
      let lastChunk = this.chunks[this.chunks.length - 1];
      lastChunk.buffer += String.fromCharCode(this._previousChar);
      let newLineStarts = createLineStartsFast(lastChunk.buffer);
      lastChunk.lineStarts = newLineStarts;
      if (this._previousChar === 13) {
        this.cr++;
      }
    }
  }
};
var ModelRawFlush = class {
  constructor() {
    this.changeType = 1;
  }
};
var ModelRawLineChanged = class {
  constructor(lineNumber, detail) {
    this.changeType = 2;
    this.lineNumber = lineNumber;
    this.detail = detail;
  }
};
var ModelRawLinesDeleted = class {
  constructor(fromLineNumber, toLineNumber) {
    this.changeType = 3;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
  }
};
var ModelRawLinesInserted = class {
  constructor(fromLineNumber, toLineNumber, detail) {
    this.changeType = 4;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
    this.detail = detail;
  }
};
var ModelRawEOLChanged = class {
  constructor() {
    this.changeType = 5;
  }
};
var ModelRawContentChangedEvent = class {
  constructor(changes, versionId, isUndoing, isRedoing) {
    this.changes = changes;
    this.versionId = versionId;
    this.isUndoing = isUndoing;
    this.isRedoing = isRedoing;
    this.resultingSelection = null;
  }
  containsEvent(type) {
    for (let i3 = 0, len2 = this.changes.length; i3 < len2; i3++) {
      const change = this.changes[i3];
      if (change.changeType === type) {
        return true;
      }
    }
    return false;
  }
  static merge(a2, b2) {
    const changes = [].concat(a2.changes).concat(b2.changes);
    const versionId = b2.versionId;
    const isUndoing = a2.isUndoing || b2.isUndoing;
    const isRedoing = a2.isRedoing || b2.isRedoing;
    return new ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing);
  }
};
var InternalModelContentChangeEvent = class {
  constructor(rawContentChangedEvent, contentChangedEvent) {
    this.rawContentChangedEvent = rawContentChangedEvent;
    this.contentChangedEvent = contentChangedEvent;
  }
  merge(other) {
    const rawContentChangedEvent = ModelRawContentChangedEvent.merge(this.rawContentChangedEvent, other.rawContentChangedEvent);
    const contentChangedEvent = InternalModelContentChangeEvent._mergeChangeEvents(this.contentChangedEvent, other.contentChangedEvent);
    return new InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent);
  }
  static _mergeChangeEvents(a2, b2) {
    const changes = [].concat(a2.changes).concat(b2.changes);
    const eol = b2.eol;
    const versionId = b2.versionId;
    const isUndoing = a2.isUndoing || b2.isUndoing;
    const isRedoing = a2.isRedoing || b2.isRedoing;
    const isFlush = a2.isFlush || b2.isFlush;
    return {
      changes,
      eol,
      versionId,
      isUndoing,
      isRedoing,
      isFlush
    };
  }
};
var TokenizationStateStore = class {
  constructor() {
    this._beginState = [];
    this._valid = [];
    this._len = 0;
    this._invalidLineStartIndex = 0;
  }
  _reset(initialState3) {
    this._beginState = [];
    this._valid = [];
    this._len = 0;
    this._invalidLineStartIndex = 0;
    if (initialState3) {
      this._setBeginState(0, initialState3);
    }
  }
  flush(initialState3) {
    this._reset(initialState3);
  }
  get invalidLineStartIndex() {
    return this._invalidLineStartIndex;
  }
  _invalidateLine(lineIndex) {
    if (lineIndex < this._len) {
      this._valid[lineIndex] = false;
    }
    if (lineIndex < this._invalidLineStartIndex) {
      this._invalidLineStartIndex = lineIndex;
    }
  }
  _isValid(lineIndex) {
    if (lineIndex < this._len) {
      return this._valid[lineIndex];
    }
    return false;
  }
  getBeginState(lineIndex) {
    if (lineIndex < this._len) {
      return this._beginState[lineIndex];
    }
    return null;
  }
  _ensureLine(lineIndex) {
    while (lineIndex >= this._len) {
      this._beginState[this._len] = null;
      this._valid[this._len] = false;
      this._len++;
    }
  }
  _deleteLines(start3, deleteCount) {
    if (deleteCount === 0) {
      return;
    }
    if (start3 + deleteCount > this._len) {
      deleteCount = this._len - start3;
    }
    this._beginState.splice(start3, deleteCount);
    this._valid.splice(start3, deleteCount);
    this._len -= deleteCount;
  }
  _insertLines(insertIndex, insertCount) {
    if (insertCount === 0) {
      return;
    }
    let beginState = [];
    let valid = [];
    for (let i3 = 0; i3 < insertCount; i3++) {
      beginState[i3] = null;
      valid[i3] = false;
    }
    this._beginState = arrayInsert(this._beginState, insertIndex, beginState);
    this._valid = arrayInsert(this._valid, insertIndex, valid);
    this._len += insertCount;
  }
  _setValid(lineIndex, valid) {
    this._ensureLine(lineIndex);
    this._valid[lineIndex] = valid;
  }
  _setBeginState(lineIndex, beginState) {
    this._ensureLine(lineIndex);
    this._beginState[lineIndex] = beginState;
  }
  setEndState(linesLength, lineIndex, endState) {
    this._setValid(lineIndex, true);
    this._invalidLineStartIndex = lineIndex + 1;
    if (lineIndex === linesLength - 1) {
      return;
    }
    const previousEndState = this.getBeginState(lineIndex + 1);
    if (previousEndState === null || !endState.equals(previousEndState)) {
      this._setBeginState(lineIndex + 1, endState);
      this._invalidateLine(lineIndex + 1);
      return;
    }
    let i3 = lineIndex + 1;
    while (i3 < linesLength) {
      if (!this._isValid(i3)) {
        break;
      }
      i3++;
    }
    this._invalidLineStartIndex = i3;
  }
  setFakeTokens(lineIndex) {
    this._setValid(lineIndex, false);
  }
  applyEdits(range3, eolCount) {
    const deletingLinesCnt = range3.endLineNumber - range3.startLineNumber;
    const insertingLinesCnt = eolCount;
    const editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);
    for (let j = editingLinesCnt; j >= 0; j--) {
      this._invalidateLine(range3.startLineNumber + j - 1);
    }
    this._acceptDeleteRange(range3);
    this._acceptInsertText(new Position(range3.startLineNumber, range3.startColumn), eolCount);
  }
  _acceptDeleteRange(range3) {
    const firstLineIndex = range3.startLineNumber - 1;
    if (firstLineIndex >= this._len) {
      return;
    }
    this._deleteLines(range3.startLineNumber, range3.endLineNumber - range3.startLineNumber);
  }
  _acceptInsertText(position2, eolCount) {
    const lineIndex = position2.lineNumber - 1;
    if (lineIndex >= this._len) {
      return;
    }
    this._insertLines(position2.lineNumber, eolCount);
  }
};
var TextModelTokenization = class extends Disposable {
  constructor(textModel) {
    super();
    this._isDisposed = false;
    this._textModel = textModel;
    this._tokenizationStateStore = new TokenizationStateStore();
    this._tokenizationSupport = null;
    this._register(TokenizationRegistry.onDidChange((e2) => {
      const languageIdentifier = this._textModel.getLanguageIdentifier();
      if (e2.changedLanguages.indexOf(languageIdentifier.language) === -1) {
        return;
      }
      this._resetTokenizationState();
      this._textModel.clearTokens();
    }));
    this._register(this._textModel.onDidChangeRawContentFast((e2) => {
      if (e2.containsEvent(1)) {
        this._resetTokenizationState();
        return;
      }
    }));
    this._register(this._textModel.onDidChangeContentFast((e2) => {
      for (let i3 = 0, len2 = e2.changes.length; i3 < len2; i3++) {
        const change = e2.changes[i3];
        const [eolCount] = countEOL(change.text);
        this._tokenizationStateStore.applyEdits(change.range, eolCount);
      }
      this._beginBackgroundTokenization();
    }));
    this._register(this._textModel.onDidChangeAttached(() => {
      this._beginBackgroundTokenization();
    }));
    this._register(this._textModel.onDidChangeLanguage(() => {
      this._resetTokenizationState();
      this._textModel.clearTokens();
    }));
    this._resetTokenizationState();
  }
  dispose() {
    this._isDisposed = true;
    super.dispose();
  }
  _resetTokenizationState() {
    const [tokenizationSupport, initialState3] = initializeTokenization(this._textModel);
    this._tokenizationSupport = tokenizationSupport;
    this._tokenizationStateStore.flush(initialState3);
    this._beginBackgroundTokenization();
  }
  _beginBackgroundTokenization() {
    if (this._textModel.isAttachedToEditor() && this._hasLinesToTokenize()) {
      setImmediate(() => {
        if (this._isDisposed) {
          return;
        }
        this._revalidateTokensNow();
      });
    }
  }
  _revalidateTokensNow(toLineNumber = this._textModel.getLineCount()) {
    const MAX_ALLOWED_TIME = 1;
    const builder = new MultilineTokensBuilder();
    const sw = StopWatch.create(false);
    while (this._hasLinesToTokenize()) {
      if (sw.elapsed() > MAX_ALLOWED_TIME) {
        break;
      }
      const tokenizedLineNumber = this._tokenizeOneInvalidLine(builder);
      if (tokenizedLineNumber >= toLineNumber) {
        break;
      }
    }
    this._beginBackgroundTokenization();
    this._textModel.setTokens(builder.tokens);
  }
  tokenizeViewport(startLineNumber, endLineNumber) {
    const builder = new MultilineTokensBuilder();
    this._tokenizeViewport(builder, startLineNumber, endLineNumber);
    this._textModel.setTokens(builder.tokens);
  }
  reset() {
    this._resetTokenizationState();
    this._textModel.clearTokens();
  }
  forceTokenization(lineNumber) {
    const builder = new MultilineTokensBuilder();
    this._updateTokensUntilLine(builder, lineNumber);
    this._textModel.setTokens(builder.tokens);
  }
  isCheapToTokenize(lineNumber) {
    if (!this._tokenizationSupport) {
      return true;
    }
    const firstInvalidLineNumber = this._tokenizationStateStore.invalidLineStartIndex + 1;
    if (lineNumber > firstInvalidLineNumber) {
      return false;
    }
    if (lineNumber < firstInvalidLineNumber) {
      return true;
    }
    if (this._textModel.getLineLength(lineNumber) < 2048) {
      return true;
    }
    return false;
  }
  _hasLinesToTokenize() {
    if (!this._tokenizationSupport) {
      return false;
    }
    return this._tokenizationStateStore.invalidLineStartIndex < this._textModel.getLineCount();
  }
  _tokenizeOneInvalidLine(builder) {
    if (!this._hasLinesToTokenize()) {
      return this._textModel.getLineCount() + 1;
    }
    const lineNumber = this._tokenizationStateStore.invalidLineStartIndex + 1;
    this._updateTokensUntilLine(builder, lineNumber);
    return lineNumber;
  }
  _updateTokensUntilLine(builder, lineNumber) {
    if (!this._tokenizationSupport) {
      return;
    }
    const languageIdentifier = this._textModel.getLanguageIdentifier();
    const linesLength = this._textModel.getLineCount();
    const endLineIndex = lineNumber - 1;
    for (let lineIndex = this._tokenizationStateStore.invalidLineStartIndex; lineIndex <= endLineIndex; lineIndex++) {
      const text = this._textModel.getLineContent(lineIndex + 1);
      const lineStartState = this._tokenizationStateStore.getBeginState(lineIndex);
      const r3 = safeTokenize(languageIdentifier, this._tokenizationSupport, text, lineStartState);
      builder.add(lineIndex + 1, r3.tokens);
      this._tokenizationStateStore.setEndState(linesLength, lineIndex, r3.endState);
      lineIndex = this._tokenizationStateStore.invalidLineStartIndex - 1;
    }
  }
  _tokenizeViewport(builder, startLineNumber, endLineNumber) {
    if (!this._tokenizationSupport) {
      return;
    }
    if (endLineNumber <= this._tokenizationStateStore.invalidLineStartIndex) {
      return;
    }
    if (startLineNumber <= this._tokenizationStateStore.invalidLineStartIndex) {
      this._updateTokensUntilLine(builder, endLineNumber);
      return;
    }
    let nonWhitespaceColumn = this._textModel.getLineFirstNonWhitespaceColumn(startLineNumber);
    let fakeLines = [];
    let initialState3 = null;
    for (let i3 = startLineNumber - 1; nonWhitespaceColumn > 0 && i3 >= 1; i3--) {
      let newNonWhitespaceIndex = this._textModel.getLineFirstNonWhitespaceColumn(i3);
      if (newNonWhitespaceIndex === 0) {
        continue;
      }
      if (newNonWhitespaceIndex < nonWhitespaceColumn) {
        initialState3 = this._tokenizationStateStore.getBeginState(i3 - 1);
        if (initialState3) {
          break;
        }
        fakeLines.push(this._textModel.getLineContent(i3));
        nonWhitespaceColumn = newNonWhitespaceIndex;
      }
    }
    if (!initialState3) {
      initialState3 = this._tokenizationSupport.getInitialState();
    }
    const languageIdentifier = this._textModel.getLanguageIdentifier();
    let state = initialState3;
    for (let i3 = fakeLines.length - 1; i3 >= 0; i3--) {
      let r3 = safeTokenize(languageIdentifier, this._tokenizationSupport, fakeLines[i3], state);
      state = r3.endState;
    }
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      let text = this._textModel.getLineContent(lineNumber);
      let r3 = safeTokenize(languageIdentifier, this._tokenizationSupport, text, state);
      builder.add(lineNumber, r3.tokens);
      this._tokenizationStateStore.setFakeTokens(lineNumber - 1);
      state = r3.endState;
    }
  }
};
function initializeTokenization(textModel) {
  const languageIdentifier = textModel.getLanguageIdentifier();
  let tokenizationSupport = textModel.isTooLargeForTokenization() ? null : TokenizationRegistry.get(languageIdentifier.language);
  let initialState3 = null;
  if (tokenizationSupport) {
    try {
      initialState3 = tokenizationSupport.getInitialState();
    } catch (e2) {
      onUnexpectedError(e2);
      tokenizationSupport = null;
    }
  }
  return [tokenizationSupport, initialState3];
}
function safeTokenize(languageIdentifier, tokenizationSupport, text, state) {
  let r3 = null;
  if (tokenizationSupport) {
    try {
      r3 = tokenizationSupport.tokenize2(text, state.clone(), 0);
    } catch (e2) {
      onUnexpectedError(e2);
    }
  }
  if (!r3) {
    r3 = nullTokenize2(languageIdentifier.id, text, state, 0);
  }
  LineTokens.convertToEndOffset(r3.tokens, text.length);
  return r3;
}
function roundFloat(number, decimalPoints) {
  const decimal = Math.pow(10, decimalPoints);
  return Math.round(number * decimal) / decimal;
}
var RGBA = class {
  constructor(r3, g2, b2, a2 = 1) {
    this.r = Math.min(255, Math.max(0, r3)) | 0;
    this.g = Math.min(255, Math.max(0, g2)) | 0;
    this.b = Math.min(255, Math.max(0, b2)) | 0;
    this.a = roundFloat(Math.max(Math.min(1, a2), 0), 3);
  }
  static equals(a2, b2) {
    return a2.r === b2.r && a2.g === b2.g && a2.b === b2.b && a2.a === b2.a;
  }
};
var HSLA = class {
  constructor(h2, s2, l2, a2) {
    this.h = Math.max(Math.min(360, h2), 0) | 0;
    this.s = roundFloat(Math.max(Math.min(1, s2), 0), 3);
    this.l = roundFloat(Math.max(Math.min(1, l2), 0), 3);
    this.a = roundFloat(Math.max(Math.min(1, a2), 0), 3);
  }
  static equals(a2, b2) {
    return a2.h === b2.h && a2.s === b2.s && a2.l === b2.l && a2.a === b2.a;
  }
  static fromRGBA(rgba2) {
    const r3 = rgba2.r / 255;
    const g2 = rgba2.g / 255;
    const b2 = rgba2.b / 255;
    const a2 = rgba2.a;
    const max2 = Math.max(r3, g2, b2);
    const min2 = Math.min(r3, g2, b2);
    let h2 = 0;
    let s2 = 0;
    const l2 = (min2 + max2) / 2;
    const chroma = max2 - min2;
    if (chroma > 0) {
      s2 = Math.min(l2 <= 0.5 ? chroma / (2 * l2) : chroma / (2 - 2 * l2), 1);
      switch (max2) {
        case r3:
          h2 = (g2 - b2) / chroma + (g2 < b2 ? 6 : 0);
          break;
        case g2:
          h2 = (b2 - r3) / chroma + 2;
          break;
        case b2:
          h2 = (r3 - g2) / chroma + 4;
          break;
      }
      h2 *= 60;
      h2 = Math.round(h2);
    }
    return new HSLA(h2, s2, l2, a2);
  }
  static _hue2rgb(p2, q2, t5) {
    if (t5 < 0) {
      t5 += 1;
    }
    if (t5 > 1) {
      t5 -= 1;
    }
    if (t5 < 1 / 6) {
      return p2 + (q2 - p2) * 6 * t5;
    }
    if (t5 < 1 / 2) {
      return q2;
    }
    if (t5 < 2 / 3) {
      return p2 + (q2 - p2) * (2 / 3 - t5) * 6;
    }
    return p2;
  }
  static toRGBA(hsla2) {
    const h2 = hsla2.h / 360;
    const {s: s2, l: l2, a: a2} = hsla2;
    let r3, g2, b2;
    if (s2 === 0) {
      r3 = g2 = b2 = l2;
    } else {
      const q2 = l2 < 0.5 ? l2 * (1 + s2) : l2 + s2 - l2 * s2;
      const p2 = 2 * l2 - q2;
      r3 = HSLA._hue2rgb(p2, q2, h2 + 1 / 3);
      g2 = HSLA._hue2rgb(p2, q2, h2);
      b2 = HSLA._hue2rgb(p2, q2, h2 - 1 / 3);
    }
    return new RGBA(Math.round(r3 * 255), Math.round(g2 * 255), Math.round(b2 * 255), a2);
  }
};
var HSVA = class {
  constructor(h2, s2, v2, a2) {
    this.h = Math.max(Math.min(360, h2), 0) | 0;
    this.s = roundFloat(Math.max(Math.min(1, s2), 0), 3);
    this.v = roundFloat(Math.max(Math.min(1, v2), 0), 3);
    this.a = roundFloat(Math.max(Math.min(1, a2), 0), 3);
  }
  static equals(a2, b2) {
    return a2.h === b2.h && a2.s === b2.s && a2.v === b2.v && a2.a === b2.a;
  }
  static fromRGBA(rgba2) {
    const r3 = rgba2.r / 255;
    const g2 = rgba2.g / 255;
    const b2 = rgba2.b / 255;
    const cmax = Math.max(r3, g2, b2);
    const cmin = Math.min(r3, g2, b2);
    const delta = cmax - cmin;
    const s2 = cmax === 0 ? 0 : delta / cmax;
    let m2;
    if (delta === 0) {
      m2 = 0;
    } else if (cmax === r3) {
      m2 = ((g2 - b2) / delta % 6 + 6) % 6;
    } else if (cmax === g2) {
      m2 = (b2 - r3) / delta + 2;
    } else {
      m2 = (r3 - g2) / delta + 4;
    }
    return new HSVA(Math.round(m2 * 60), s2, cmax, rgba2.a);
  }
  static toRGBA(hsva) {
    const {h: h2, s: s2, v: v2, a: a2} = hsva;
    const c3 = v2 * s2;
    const x2 = c3 * (1 - Math.abs(h2 / 60 % 2 - 1));
    const m2 = v2 - c3;
    let [r3, g2, b2] = [0, 0, 0];
    if (h2 < 60) {
      r3 = c3;
      g2 = x2;
    } else if (h2 < 120) {
      r3 = x2;
      g2 = c3;
    } else if (h2 < 180) {
      g2 = c3;
      b2 = x2;
    } else if (h2 < 240) {
      g2 = x2;
      b2 = c3;
    } else if (h2 < 300) {
      r3 = x2;
      b2 = c3;
    } else if (h2 < 360) {
      r3 = c3;
      b2 = x2;
    }
    r3 = Math.round((r3 + m2) * 255);
    g2 = Math.round((g2 + m2) * 255);
    b2 = Math.round((b2 + m2) * 255);
    return new RGBA(r3, g2, b2, a2);
  }
};
var Color = class {
  constructor(arg) {
    if (!arg) {
      throw new Error("Color needs a value");
    } else if (arg instanceof RGBA) {
      this.rgba = arg;
    } else if (arg instanceof HSLA) {
      this._hsla = arg;
      this.rgba = HSLA.toRGBA(arg);
    } else if (arg instanceof HSVA) {
      this._hsva = arg;
      this.rgba = HSVA.toRGBA(arg);
    } else {
      throw new Error("Invalid color ctor argument");
    }
  }
  static fromHex(hex2) {
    return Color.Format.CSS.parseHex(hex2) || Color.red;
  }
  get hsla() {
    if (this._hsla) {
      return this._hsla;
    } else {
      return HSLA.fromRGBA(this.rgba);
    }
  }
  get hsva() {
    if (this._hsva) {
      return this._hsva;
    }
    return HSVA.fromRGBA(this.rgba);
  }
  equals(other) {
    return !!other && RGBA.equals(this.rgba, other.rgba) && HSLA.equals(this.hsla, other.hsla) && HSVA.equals(this.hsva, other.hsva);
  }
  getRelativeLuminance() {
    const R2 = Color._relativeLuminanceForComponent(this.rgba.r);
    const G2 = Color._relativeLuminanceForComponent(this.rgba.g);
    const B2 = Color._relativeLuminanceForComponent(this.rgba.b);
    const luminance = 0.2126 * R2 + 0.7152 * G2 + 0.0722 * B2;
    return roundFloat(luminance, 4);
  }
  static _relativeLuminanceForComponent(color2) {
    const c3 = color2 / 255;
    return c3 <= 0.03928 ? c3 / 12.92 : Math.pow((c3 + 0.055) / 1.055, 2.4);
  }
  isLighter() {
    const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1e3;
    return yiq >= 128;
  }
  isLighterThan(another) {
    const lum1 = this.getRelativeLuminance();
    const lum2 = another.getRelativeLuminance();
    return lum1 > lum2;
  }
  isDarkerThan(another) {
    const lum1 = this.getRelativeLuminance();
    const lum2 = another.getRelativeLuminance();
    return lum1 < lum2;
  }
  lighten(factor) {
    return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l + this.hsla.l * factor, this.hsla.a));
  }
  darken(factor) {
    return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l - this.hsla.l * factor, this.hsla.a));
  }
  transparent(factor) {
    const {r: r3, g: g2, b: b2, a: a2} = this.rgba;
    return new Color(new RGBA(r3, g2, b2, a2 * factor));
  }
  isTransparent() {
    return this.rgba.a === 0;
  }
  isOpaque() {
    return this.rgba.a === 1;
  }
  opposite() {
    return new Color(new RGBA(255 - this.rgba.r, 255 - this.rgba.g, 255 - this.rgba.b, this.rgba.a));
  }
  toString() {
    return "" + Color.Format.CSS.format(this);
  }
  static getLighterColor(of2, relative2, factor) {
    if (of2.isLighterThan(relative2)) {
      return of2;
    }
    factor = factor ? factor : 0.5;
    const lum1 = of2.getRelativeLuminance();
    const lum2 = relative2.getRelativeLuminance();
    factor = factor * (lum2 - lum1) / lum2;
    return of2.lighten(factor);
  }
  static getDarkerColor(of2, relative2, factor) {
    if (of2.isDarkerThan(relative2)) {
      return of2;
    }
    factor = factor ? factor : 0.5;
    const lum1 = of2.getRelativeLuminance();
    const lum2 = relative2.getRelativeLuminance();
    factor = factor * (lum1 - lum2) / lum1;
    return of2.darken(factor);
  }
};
Color.white = new Color(new RGBA(255, 255, 255, 1));
Color.black = new Color(new RGBA(0, 0, 0, 1));
Color.red = new Color(new RGBA(255, 0, 0, 1));
Color.blue = new Color(new RGBA(0, 0, 255, 1));
Color.cyan = new Color(new RGBA(0, 255, 255, 1));
Color.lightgrey = new Color(new RGBA(211, 211, 211, 1));
Color.transparent = new Color(new RGBA(0, 0, 0, 0));
(function(Color3) {
  (function(Format) {
    (function(CSS) {
      function formatRGB(color2) {
        if (color2.rgba.a === 1) {
          return `rgb(${color2.rgba.r}, ${color2.rgba.g}, ${color2.rgba.b})`;
        }
        return Color3.Format.CSS.formatRGBA(color2);
      }
      CSS.formatRGB = formatRGB;
      function formatRGBA(color2) {
        return `rgba(${color2.rgba.r}, ${color2.rgba.g}, ${color2.rgba.b}, ${+color2.rgba.a.toFixed(2)})`;
      }
      CSS.formatRGBA = formatRGBA;
      function formatHSL(color2) {
        if (color2.hsla.a === 1) {
          return `hsl(${color2.hsla.h}, ${(color2.hsla.s * 100).toFixed(2)}%, ${(color2.hsla.l * 100).toFixed(2)}%)`;
        }
        return Color3.Format.CSS.formatHSLA(color2);
      }
      CSS.formatHSL = formatHSL;
      function formatHSLA(color2) {
        return `hsla(${color2.hsla.h}, ${(color2.hsla.s * 100).toFixed(2)}%, ${(color2.hsla.l * 100).toFixed(2)}%, ${color2.hsla.a.toFixed(2)})`;
      }
      CSS.formatHSLA = formatHSLA;
      function _toTwoDigitHex(n3) {
        const r3 = n3.toString(16);
        return r3.length !== 2 ? "0" + r3 : r3;
      }
      function formatHex(color2) {
        return `#${_toTwoDigitHex(color2.rgba.r)}${_toTwoDigitHex(color2.rgba.g)}${_toTwoDigitHex(color2.rgba.b)}`;
      }
      CSS.formatHex = formatHex;
      function formatHexA(color2, compact2 = false) {
        if (compact2 && color2.rgba.a === 1) {
          return Color3.Format.CSS.formatHex(color2);
        }
        return `#${_toTwoDigitHex(color2.rgba.r)}${_toTwoDigitHex(color2.rgba.g)}${_toTwoDigitHex(color2.rgba.b)}${_toTwoDigitHex(Math.round(color2.rgba.a * 255))}`;
      }
      CSS.formatHexA = formatHexA;
      function format2(color2) {
        if (color2.isOpaque()) {
          return Color3.Format.CSS.formatHex(color2);
        }
        return Color3.Format.CSS.formatRGBA(color2);
      }
      CSS.format = format2;
      function parseHex(hex2) {
        const length = hex2.length;
        if (length === 0) {
          return null;
        }
        if (hex2.charCodeAt(0) !== 35) {
          return null;
        }
        if (length === 7) {
          const r3 = 16 * _parseHexDigit(hex2.charCodeAt(1)) + _parseHexDigit(hex2.charCodeAt(2));
          const g2 = 16 * _parseHexDigit(hex2.charCodeAt(3)) + _parseHexDigit(hex2.charCodeAt(4));
          const b2 = 16 * _parseHexDigit(hex2.charCodeAt(5)) + _parseHexDigit(hex2.charCodeAt(6));
          return new Color3(new RGBA(r3, g2, b2, 1));
        }
        if (length === 9) {
          const r3 = 16 * _parseHexDigit(hex2.charCodeAt(1)) + _parseHexDigit(hex2.charCodeAt(2));
          const g2 = 16 * _parseHexDigit(hex2.charCodeAt(3)) + _parseHexDigit(hex2.charCodeAt(4));
          const b2 = 16 * _parseHexDigit(hex2.charCodeAt(5)) + _parseHexDigit(hex2.charCodeAt(6));
          const a2 = 16 * _parseHexDigit(hex2.charCodeAt(7)) + _parseHexDigit(hex2.charCodeAt(8));
          return new Color3(new RGBA(r3, g2, b2, a2 / 255));
        }
        if (length === 4) {
          const r3 = _parseHexDigit(hex2.charCodeAt(1));
          const g2 = _parseHexDigit(hex2.charCodeAt(2));
          const b2 = _parseHexDigit(hex2.charCodeAt(3));
          return new Color3(new RGBA(16 * r3 + r3, 16 * g2 + g2, 16 * b2 + b2));
        }
        if (length === 5) {
          const r3 = _parseHexDigit(hex2.charCodeAt(1));
          const g2 = _parseHexDigit(hex2.charCodeAt(2));
          const b2 = _parseHexDigit(hex2.charCodeAt(3));
          const a2 = _parseHexDigit(hex2.charCodeAt(4));
          return new Color3(new RGBA(16 * r3 + r3, 16 * g2 + g2, 16 * b2 + b2, (16 * a2 + a2) / 255));
        }
        return null;
      }
      CSS.parseHex = parseHex;
      function _parseHexDigit(charCode) {
        switch (charCode) {
          case 48:
            return 0;
          case 49:
            return 1;
          case 50:
            return 2;
          case 51:
            return 3;
          case 52:
            return 4;
          case 53:
            return 5;
          case 54:
            return 6;
          case 55:
            return 7;
          case 56:
            return 8;
          case 57:
            return 9;
          case 97:
            return 10;
          case 65:
            return 10;
          case 98:
            return 11;
          case 66:
            return 11;
          case 99:
            return 12;
          case 67:
            return 12;
          case 100:
            return 13;
          case 68:
            return 13;
          case 101:
            return 14;
          case 69:
            return 14;
          case 102:
            return 15;
          case 70:
            return 15;
        }
        return 0;
      }
    })(Format.CSS || (Format.CSS = {}));
  })(Color3.Format || (Color3.Format = {}));
})(Color || (Color = {}));
function createTextBufferBuilder() {
  return new PieceTreeTextBufferBuilder();
}
function createTextBufferFactory(text) {
  const builder = createTextBufferBuilder();
  builder.acceptChunk(text);
  return builder.finish();
}
function createTextBuffer(value, defaultEOL) {
  const factory = typeof value === "string" ? createTextBufferFactory(value) : value;
  return factory.create(defaultEOL);
}
var MODEL_ID = 0;
var LIMIT_FIND_COUNT$1 = 999;
var LONG_LINE_BOUNDARY = 1e4;
var TextModelSnapshot = class {
  constructor(source2) {
    this._source = source2;
    this._eos = false;
  }
  read() {
    if (this._eos) {
      return null;
    }
    let result = [], resultCnt = 0, resultLength = 0;
    do {
      let tmp = this._source.read();
      if (tmp === null) {
        this._eos = true;
        if (resultCnt === 0) {
          return null;
        } else {
          return result.join("");
        }
      }
      if (tmp.length > 0) {
        result[resultCnt++] = tmp;
        resultLength += tmp.length;
      }
      if (resultLength >= 64 * 1024) {
        return result.join("");
      }
    } while (true);
  }
};
var invalidFunc = () => {
  throw new Error(`Invalid change accessor`);
};
var BracketSearchCanceled = class {
  constructor() {
    this._searchCanceledBrand = void 0;
  }
};
BracketSearchCanceled.INSTANCE = new BracketSearchCanceled();
function stripBracketSearchCanceled(result) {
  if (result instanceof BracketSearchCanceled) {
    return null;
  }
  return result;
}
var TextModel = class extends Disposable {
  constructor(source2, creationOptions, languageIdentifier, associatedResource = null, undoRedoService) {
    super();
    this._onWillDispose = this._register(new Emitter());
    this.onWillDispose = this._onWillDispose.event;
    this._onDidChangeDecorations = this._register(new DidChangeDecorationsEmitter());
    this.onDidChangeDecorations = this._onDidChangeDecorations.event;
    this._onDidChangeLanguage = this._register(new Emitter());
    this.onDidChangeLanguage = this._onDidChangeLanguage.event;
    this._onDidChangeLanguageConfiguration = this._register(new Emitter());
    this.onDidChangeLanguageConfiguration = this._onDidChangeLanguageConfiguration.event;
    this._onDidChangeTokens = this._register(new Emitter());
    this.onDidChangeTokens = this._onDidChangeTokens.event;
    this._onDidChangeOptions = this._register(new Emitter());
    this.onDidChangeOptions = this._onDidChangeOptions.event;
    this._onDidChangeAttached = this._register(new Emitter());
    this.onDidChangeAttached = this._onDidChangeAttached.event;
    this._eventEmitter = this._register(new DidChangeContentEmitter());
    MODEL_ID++;
    this.id = "$model" + MODEL_ID;
    this.isForSimpleWidget = creationOptions.isForSimpleWidget;
    if (typeof associatedResource === "undefined" || associatedResource === null) {
      this._associatedResource = URI.parse("inmemory://model/" + MODEL_ID);
    } else {
      this._associatedResource = associatedResource;
    }
    this._undoRedoService = undoRedoService;
    this._attachedEditorCount = 0;
    this._buffer = createTextBuffer(source2, creationOptions.defaultEOL);
    this._options = TextModel.resolveOptions(this._buffer, creationOptions);
    const bufferLineCount = this._buffer.getLineCount();
    const bufferTextLength = this._buffer.getValueLengthInRange(new Range(1, 1, bufferLineCount, this._buffer.getLineLength(bufferLineCount) + 1), 0);
    if (creationOptions.largeFileOptimizations) {
      this._isTooLargeForTokenization = bufferTextLength > TextModel.LARGE_FILE_SIZE_THRESHOLD || bufferLineCount > TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD;
    } else {
      this._isTooLargeForTokenization = false;
    }
    this._isTooLargeForSyncing = bufferTextLength > TextModel.MODEL_SYNC_LIMIT;
    this._versionId = 1;
    this._alternativeVersionId = 1;
    this._initialUndoRedoSnapshot = null;
    this._isDisposed = false;
    this._isDisposing = false;
    this._languageIdentifier = languageIdentifier || NULL_LANGUAGE_IDENTIFIER;
    this._languageRegistryListener = LanguageConfigurationRegistry.onDidChange((e2) => {
      if (e2.languageIdentifier.id === this._languageIdentifier.id) {
        this._onDidChangeLanguageConfiguration.fire({});
      }
    });
    this._instanceId = singleLetterHash(MODEL_ID);
    this._lastDecorationId = 0;
    this._decorations = Object.create(null);
    this._decorationsTree = new DecorationsTrees();
    this._commandManager = new EditStack(this, undoRedoService);
    this._isUndoing = false;
    this._isRedoing = false;
    this._trimAutoWhitespaceLines = null;
    this._tokens = new TokensStore();
    this._tokens2 = new TokensStore2();
    this._tokenization = new TextModelTokenization(this);
  }
  static resolveOptions(textBuffer, options) {
    if (options.detectIndentation) {
      const guessedIndentation = guessIndentation(textBuffer, options.tabSize, options.insertSpaces);
      return new TextModelResolvedOptions({
        tabSize: guessedIndentation.tabSize,
        indentSize: guessedIndentation.tabSize,
        insertSpaces: guessedIndentation.insertSpaces,
        trimAutoWhitespace: options.trimAutoWhitespace,
        defaultEOL: options.defaultEOL
      });
    }
    return new TextModelResolvedOptions({
      tabSize: options.tabSize,
      indentSize: options.indentSize,
      insertSpaces: options.insertSpaces,
      trimAutoWhitespace: options.trimAutoWhitespace,
      defaultEOL: options.defaultEOL
    });
  }
  onDidChangeRawContentFast(listener) {
    return this._eventEmitter.fastEvent((e2) => listener(e2.rawContentChangedEvent));
  }
  onDidChangeContentFast(listener) {
    return this._eventEmitter.fastEvent((e2) => listener(e2.contentChangedEvent));
  }
  onDidChangeContent(listener) {
    return this._eventEmitter.slowEvent((e2) => listener(e2.contentChangedEvent));
  }
  dispose() {
    this._isDisposing = true;
    this._onWillDispose.fire();
    this._languageRegistryListener.dispose();
    this._tokenization.dispose();
    this._isDisposed = true;
    super.dispose();
    this._isDisposing = false;
  }
  _assertNotDisposed() {
    if (this._isDisposed) {
      throw new Error("Model is disposed!");
    }
  }
  _emitContentChangedEvent(rawChange, change) {
    if (this._isDisposing) {
      return;
    }
    this._eventEmitter.fire(new InternalModelContentChangeEvent(rawChange, change));
  }
  setValue(value) {
    this._assertNotDisposed();
    if (value === null) {
      return;
    }
    const textBuffer = createTextBuffer(value, this._options.defaultEOL);
    this.setValueFromTextBuffer(textBuffer);
  }
  _createContentChanged2(range3, rangeOffset, rangeLength, text, isUndoing, isRedoing, isFlush) {
    return {
      changes: [{
        range: range3,
        rangeOffset,
        rangeLength,
        text
      }],
      eol: this._buffer.getEOL(),
      versionId: this.getVersionId(),
      isUndoing,
      isRedoing,
      isFlush
    };
  }
  setValueFromTextBuffer(textBuffer) {
    this._assertNotDisposed();
    if (textBuffer === null) {
      return;
    }
    const oldFullModelRange = this.getFullModelRange();
    const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
    const endLineNumber = this.getLineCount();
    const endColumn = this.getLineMaxColumn(endLineNumber);
    this._buffer = textBuffer;
    this._increaseVersionId();
    this._tokens.flush();
    this._tokens2.flush();
    this._decorations = Object.create(null);
    this._decorationsTree = new DecorationsTrees();
    this._commandManager.clear();
    this._trimAutoWhitespaceLines = null;
    this._emitContentChangedEvent(new ModelRawContentChangedEvent([
      new ModelRawFlush()
    ], this._versionId, false, false), this._createContentChanged2(new Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, true));
  }
  setEOL(eol) {
    this._assertNotDisposed();
    const newEOL = eol === 1 ? "\r\n" : "\n";
    if (this._buffer.getEOL() === newEOL) {
      return;
    }
    const oldFullModelRange = this.getFullModelRange();
    const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
    const endLineNumber = this.getLineCount();
    const endColumn = this.getLineMaxColumn(endLineNumber);
    this._onBeforeEOLChange();
    this._buffer.setEOL(newEOL);
    this._increaseVersionId();
    this._onAfterEOLChange();
    this._emitContentChangedEvent(new ModelRawContentChangedEvent([
      new ModelRawEOLChanged()
    ], this._versionId, false, false), this._createContentChanged2(new Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, false));
  }
  _onBeforeEOLChange() {
    const versionId = this.getVersionId();
    const allDecorations = this._decorationsTree.search(0, false, false, versionId);
    this._ensureNodesHaveRanges(allDecorations);
  }
  _onAfterEOLChange() {
    const versionId = this.getVersionId();
    const allDecorations = this._decorationsTree.collectNodesPostOrder();
    for (let i3 = 0, len2 = allDecorations.length; i3 < len2; i3++) {
      const node = allDecorations[i3];
      const delta = node.cachedAbsoluteStart - node.start;
      const startOffset = this._buffer.getOffsetAt(node.range.startLineNumber, node.range.startColumn);
      const endOffset = this._buffer.getOffsetAt(node.range.endLineNumber, node.range.endColumn);
      node.cachedAbsoluteStart = startOffset;
      node.cachedAbsoluteEnd = endOffset;
      node.cachedVersionId = versionId;
      node.start = startOffset - delta;
      node.end = endOffset - delta;
      recomputeMaxEnd(node);
    }
  }
  onBeforeAttached() {
    this._attachedEditorCount++;
    if (this._attachedEditorCount === 1) {
      this._onDidChangeAttached.fire(void 0);
    }
  }
  onBeforeDetached() {
    this._attachedEditorCount--;
    if (this._attachedEditorCount === 0) {
      this._onDidChangeAttached.fire(void 0);
    }
  }
  isAttachedToEditor() {
    return this._attachedEditorCount > 0;
  }
  getAttachedEditorCount() {
    return this._attachedEditorCount;
  }
  isTooLargeForSyncing() {
    return this._isTooLargeForSyncing;
  }
  isTooLargeForTokenization() {
    return this._isTooLargeForTokenization;
  }
  isDisposed() {
    return this._isDisposed;
  }
  isDominatedByLongLines() {
    this._assertNotDisposed();
    if (this.isTooLargeForTokenization()) {
      return false;
    }
    let smallLineCharCount = 0;
    let longLineCharCount = 0;
    const lineCount = this._buffer.getLineCount();
    for (let lineNumber = 1; lineNumber <= lineCount; lineNumber++) {
      const lineLength = this._buffer.getLineLength(lineNumber);
      if (lineLength >= LONG_LINE_BOUNDARY) {
        longLineCharCount += lineLength;
      } else {
        smallLineCharCount += lineLength;
      }
    }
    return longLineCharCount > smallLineCharCount;
  }
  get uri() {
    return this._associatedResource;
  }
  getOptions() {
    this._assertNotDisposed();
    return this._options;
  }
  getFormattingOptions() {
    return {
      tabSize: this._options.indentSize,
      insertSpaces: this._options.insertSpaces
    };
  }
  updateOptions(_newOpts) {
    this._assertNotDisposed();
    let tabSize = typeof _newOpts.tabSize !== "undefined" ? _newOpts.tabSize : this._options.tabSize;
    let indentSize = typeof _newOpts.indentSize !== "undefined" ? _newOpts.indentSize : this._options.indentSize;
    let insertSpaces = typeof _newOpts.insertSpaces !== "undefined" ? _newOpts.insertSpaces : this._options.insertSpaces;
    let trimAutoWhitespace = typeof _newOpts.trimAutoWhitespace !== "undefined" ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace;
    let newOpts = new TextModelResolvedOptions({
      tabSize,
      indentSize,
      insertSpaces,
      defaultEOL: this._options.defaultEOL,
      trimAutoWhitespace
    });
    if (this._options.equals(newOpts)) {
      return;
    }
    let e2 = this._options.createChangeEvent(newOpts);
    this._options = newOpts;
    this._onDidChangeOptions.fire(e2);
  }
  detectIndentation(defaultInsertSpaces, defaultTabSize) {
    this._assertNotDisposed();
    let guessedIndentation = guessIndentation(this._buffer, defaultTabSize, defaultInsertSpaces);
    this.updateOptions({
      insertSpaces: guessedIndentation.insertSpaces,
      tabSize: guessedIndentation.tabSize,
      indentSize: guessedIndentation.tabSize
    });
  }
  static _normalizeIndentationFromWhitespace(str, indentSize, insertSpaces) {
    let spacesCnt = 0;
    for (let i3 = 0; i3 < str.length; i3++) {
      if (str.charAt(i3) === "	") {
        spacesCnt += indentSize;
      } else {
        spacesCnt++;
      }
    }
    let result = "";
    if (!insertSpaces) {
      let tabsCnt = Math.floor(spacesCnt / indentSize);
      spacesCnt = spacesCnt % indentSize;
      for (let i3 = 0; i3 < tabsCnt; i3++) {
        result += "	";
      }
    }
    for (let i3 = 0; i3 < spacesCnt; i3++) {
      result += " ";
    }
    return result;
  }
  static normalizeIndentation(str, indentSize, insertSpaces) {
    let firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(str);
    if (firstNonWhitespaceIndex$1 === -1) {
      firstNonWhitespaceIndex$1 = str.length;
    }
    return TextModel._normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex$1), indentSize, insertSpaces) + str.substring(firstNonWhitespaceIndex$1);
  }
  normalizeIndentation(str) {
    this._assertNotDisposed();
    return TextModel.normalizeIndentation(str, this._options.indentSize, this._options.insertSpaces);
  }
  getVersionId() {
    this._assertNotDisposed();
    return this._versionId;
  }
  mightContainRTL() {
    return this._buffer.mightContainRTL();
  }
  mightContainUnusualLineTerminators() {
    return this._buffer.mightContainUnusualLineTerminators();
  }
  removeUnusualLineTerminators(selections = null) {
    const matches2 = this.findMatches(UNUSUAL_LINE_TERMINATORS.source, false, true, false, null, false, 1073741824);
    this._buffer.resetMightContainUnusualLineTerminators();
    this.pushEditOperations(selections, matches2.map((m2) => ({range: m2.range, text: null})), () => null);
  }
  mightContainNonBasicASCII() {
    return this._buffer.mightContainNonBasicASCII();
  }
  getAlternativeVersionId() {
    this._assertNotDisposed();
    return this._alternativeVersionId;
  }
  getOffsetAt(rawPosition) {
    this._assertNotDisposed();
    let position2 = this._validatePosition(rawPosition.lineNumber, rawPosition.column, 0);
    return this._buffer.getOffsetAt(position2.lineNumber, position2.column);
  }
  getPositionAt(rawOffset) {
    this._assertNotDisposed();
    let offset2 = Math.min(this._buffer.getLength(), Math.max(0, rawOffset));
    return this._buffer.getPositionAt(offset2);
  }
  _increaseVersionId() {
    this._versionId = this._versionId + 1;
    this._alternativeVersionId = this._versionId;
  }
  _overwriteVersionId(versionId) {
    this._versionId = versionId;
  }
  _overwriteAlternativeVersionId(newAlternativeVersionId) {
    this._alternativeVersionId = newAlternativeVersionId;
  }
  _overwriteInitialUndoRedoSnapshot(newInitialUndoRedoSnapshot) {
    this._initialUndoRedoSnapshot = newInitialUndoRedoSnapshot;
  }
  getValue(eol, preserveBOM = false) {
    this._assertNotDisposed();
    const fullModelRange = this.getFullModelRange();
    const fullModelValue = this.getValueInRange(fullModelRange, eol);
    if (preserveBOM) {
      return this._buffer.getBOM() + fullModelValue;
    }
    return fullModelValue;
  }
  createSnapshot(preserveBOM = false) {
    return new TextModelSnapshot(this._buffer.createSnapshot(preserveBOM));
  }
  getValueLength(eol, preserveBOM = false) {
    this._assertNotDisposed();
    const fullModelRange = this.getFullModelRange();
    const fullModelValue = this.getValueLengthInRange(fullModelRange, eol);
    if (preserveBOM) {
      return this._buffer.getBOM().length + fullModelValue;
    }
    return fullModelValue;
  }
  getValueInRange(rawRange, eol = 0) {
    this._assertNotDisposed();
    return this._buffer.getValueInRange(this.validateRange(rawRange), eol);
  }
  getValueLengthInRange(rawRange, eol = 0) {
    this._assertNotDisposed();
    return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol);
  }
  getCharacterCountInRange(rawRange, eol = 0) {
    this._assertNotDisposed();
    return this._buffer.getCharacterCountInRange(this.validateRange(rawRange), eol);
  }
  getLineCount() {
    this._assertNotDisposed();
    return this._buffer.getLineCount();
  }
  getLineContent(lineNumber) {
    this._assertNotDisposed();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new Error("Illegal value for lineNumber");
    }
    return this._buffer.getLineContent(lineNumber);
  }
  getLineLength(lineNumber) {
    this._assertNotDisposed();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new Error("Illegal value for lineNumber");
    }
    return this._buffer.getLineLength(lineNumber);
  }
  getLinesContent() {
    this._assertNotDisposed();
    return this._buffer.getLinesContent();
  }
  getEOL() {
    this._assertNotDisposed();
    return this._buffer.getEOL();
  }
  getLineMinColumn(lineNumber) {
    this._assertNotDisposed();
    return 1;
  }
  getLineMaxColumn(lineNumber) {
    this._assertNotDisposed();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new Error("Illegal value for lineNumber");
    }
    return this._buffer.getLineLength(lineNumber) + 1;
  }
  getLineFirstNonWhitespaceColumn(lineNumber) {
    this._assertNotDisposed();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new Error("Illegal value for lineNumber");
    }
    return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber);
  }
  getLineLastNonWhitespaceColumn(lineNumber) {
    this._assertNotDisposed();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new Error("Illegal value for lineNumber");
    }
    return this._buffer.getLineLastNonWhitespaceColumn(lineNumber);
  }
  _validateRangeRelaxedNoAllocations(range3) {
    const linesCount = this._buffer.getLineCount();
    const initialStartLineNumber = range3.startLineNumber;
    const initialStartColumn = range3.startColumn;
    let startLineNumber;
    let startColumn;
    if (initialStartLineNumber < 1) {
      startLineNumber = 1;
      startColumn = 1;
    } else if (initialStartLineNumber > linesCount) {
      startLineNumber = linesCount;
      startColumn = this.getLineMaxColumn(startLineNumber);
    } else {
      startLineNumber = initialStartLineNumber | 0;
      if (initialStartColumn <= 1) {
        startColumn = 1;
      } else {
        const maxColumn = this.getLineMaxColumn(startLineNumber);
        if (initialStartColumn >= maxColumn) {
          startColumn = maxColumn;
        } else {
          startColumn = initialStartColumn | 0;
        }
      }
    }
    const initialEndLineNumber = range3.endLineNumber;
    const initialEndColumn = range3.endColumn;
    let endLineNumber;
    let endColumn;
    if (initialEndLineNumber < 1) {
      endLineNumber = 1;
      endColumn = 1;
    } else if (initialEndLineNumber > linesCount) {
      endLineNumber = linesCount;
      endColumn = this.getLineMaxColumn(endLineNumber);
    } else {
      endLineNumber = initialEndLineNumber | 0;
      if (initialEndColumn <= 1) {
        endColumn = 1;
      } else {
        const maxColumn = this.getLineMaxColumn(endLineNumber);
        if (initialEndColumn >= maxColumn) {
          endColumn = maxColumn;
        } else {
          endColumn = initialEndColumn | 0;
        }
      }
    }
    if (initialStartLineNumber === startLineNumber && initialStartColumn === startColumn && initialEndLineNumber === endLineNumber && initialEndColumn === endColumn && range3 instanceof Range && !(range3 instanceof Selection)) {
      return range3;
    }
    return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
  }
  _isValidPosition(lineNumber, column, validationType) {
    if (typeof lineNumber !== "number" || typeof column !== "number") {
      return false;
    }
    if (isNaN(lineNumber) || isNaN(column)) {
      return false;
    }
    if (lineNumber < 1 || column < 1) {
      return false;
    }
    if ((lineNumber | 0) !== lineNumber || (column | 0) !== column) {
      return false;
    }
    const lineCount = this._buffer.getLineCount();
    if (lineNumber > lineCount) {
      return false;
    }
    if (column === 1) {
      return true;
    }
    const maxColumn = this.getLineMaxColumn(lineNumber);
    if (column > maxColumn) {
      return false;
    }
    if (validationType === 1) {
      const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
      if (isHighSurrogate(charCodeBefore)) {
        return false;
      }
    }
    return true;
  }
  _validatePosition(_lineNumber, _column, validationType) {
    const lineNumber = Math.floor(typeof _lineNumber === "number" && !isNaN(_lineNumber) ? _lineNumber : 1);
    const column = Math.floor(typeof _column === "number" && !isNaN(_column) ? _column : 1);
    const lineCount = this._buffer.getLineCount();
    if (lineNumber < 1) {
      return new Position(1, 1);
    }
    if (lineNumber > lineCount) {
      return new Position(lineCount, this.getLineMaxColumn(lineCount));
    }
    if (column <= 1) {
      return new Position(lineNumber, 1);
    }
    const maxColumn = this.getLineMaxColumn(lineNumber);
    if (column >= maxColumn) {
      return new Position(lineNumber, maxColumn);
    }
    if (validationType === 1) {
      const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
      if (isHighSurrogate(charCodeBefore)) {
        return new Position(lineNumber, column - 1);
      }
    }
    return new Position(lineNumber, column);
  }
  validatePosition(position2) {
    const validationType = 1;
    this._assertNotDisposed();
    if (position2 instanceof Position) {
      if (this._isValidPosition(position2.lineNumber, position2.column, validationType)) {
        return position2;
      }
    }
    return this._validatePosition(position2.lineNumber, position2.column, validationType);
  }
  _isValidRange(range3, validationType) {
    const startLineNumber = range3.startLineNumber;
    const startColumn = range3.startColumn;
    const endLineNumber = range3.endLineNumber;
    const endColumn = range3.endColumn;
    if (!this._isValidPosition(startLineNumber, startColumn, 0)) {
      return false;
    }
    if (!this._isValidPosition(endLineNumber, endColumn, 0)) {
      return false;
    }
    if (validationType === 1) {
      const charCodeBeforeStart = startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0;
      const charCodeBeforeEnd = endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0;
      const startInsideSurrogatePair = isHighSurrogate(charCodeBeforeStart);
      const endInsideSurrogatePair = isHighSurrogate(charCodeBeforeEnd);
      if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
        return true;
      }
      return false;
    }
    return true;
  }
  validateRange(_range) {
    const validationType = 1;
    this._assertNotDisposed();
    if (_range instanceof Range && !(_range instanceof Selection)) {
      if (this._isValidRange(_range, validationType)) {
        return _range;
      }
    }
    const start3 = this._validatePosition(_range.startLineNumber, _range.startColumn, 0);
    const end2 = this._validatePosition(_range.endLineNumber, _range.endColumn, 0);
    const startLineNumber = start3.lineNumber;
    const startColumn = start3.column;
    const endLineNumber = end2.lineNumber;
    const endColumn = end2.column;
    {
      const charCodeBeforeStart = startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0;
      const charCodeBeforeEnd = endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0;
      const startInsideSurrogatePair = isHighSurrogate(charCodeBeforeStart);
      const endInsideSurrogatePair = isHighSurrogate(charCodeBeforeEnd);
      if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
        return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
      }
      if (startLineNumber === endLineNumber && startColumn === endColumn) {
        return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn - 1);
      }
      if (startInsideSurrogatePair && endInsideSurrogatePair) {
        return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn + 1);
      }
      if (startInsideSurrogatePair) {
        return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn);
      }
      return new Range(startLineNumber, startColumn, endLineNumber, endColumn + 1);
    }
  }
  modifyPosition(rawPosition, offset2) {
    this._assertNotDisposed();
    let candidate = this.getOffsetAt(rawPosition) + offset2;
    return this.getPositionAt(Math.min(this._buffer.getLength(), Math.max(0, candidate)));
  }
  getFullModelRange() {
    this._assertNotDisposed();
    const lineCount = this.getLineCount();
    return new Range(1, 1, lineCount, this.getLineMaxColumn(lineCount));
  }
  findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
    return this._buffer.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
  }
  findMatches(searchString, rawSearchScope, isRegex2, matchCase, wordSeparators2, captureMatches, limitResultCount = LIMIT_FIND_COUNT$1) {
    this._assertNotDisposed();
    let searchRanges = null;
    if (rawSearchScope !== null) {
      if (!Array.isArray(rawSearchScope)) {
        rawSearchScope = [rawSearchScope];
      }
      if (rawSearchScope.every((searchScope) => Range.isIRange(searchScope))) {
        searchRanges = rawSearchScope.map((searchScope) => this.validateRange(searchScope));
      }
    }
    if (searchRanges === null) {
      searchRanges = [this.getFullModelRange()];
    }
    searchRanges = searchRanges.sort((d1, d2) => d1.startLineNumber - d2.startLineNumber || d1.startColumn - d2.startColumn);
    const uniqueSearchRanges = [];
    uniqueSearchRanges.push(searchRanges.reduce((prev, curr) => {
      if (Range.areIntersecting(prev, curr)) {
        return prev.plusRange(curr);
      }
      uniqueSearchRanges.push(prev);
      return curr;
    }));
    let matchMapper;
    if (!isRegex2 && searchString.indexOf("\n") < 0) {
      const searchParams = new SearchParams(searchString, isRegex2, matchCase, wordSeparators2);
      const searchData = searchParams.parseSearchRequest();
      if (!searchData) {
        return [];
      }
      matchMapper = (searchRange) => this.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
    } else {
      matchMapper = (searchRange) => TextModelSearch.findMatches(this, new SearchParams(searchString, isRegex2, matchCase, wordSeparators2), searchRange, captureMatches, limitResultCount);
    }
    return uniqueSearchRanges.map(matchMapper).reduce((arr, matches2) => arr.concat(matches2), []);
  }
  findNextMatch(searchString, rawSearchStart, isRegex2, matchCase, wordSeparators2, captureMatches) {
    this._assertNotDisposed();
    const searchStart = this.validatePosition(rawSearchStart);
    if (!isRegex2 && searchString.indexOf("\n") < 0) {
      const searchParams = new SearchParams(searchString, isRegex2, matchCase, wordSeparators2);
      const searchData = searchParams.parseSearchRequest();
      if (!searchData) {
        return null;
      }
      const lineCount = this.getLineCount();
      let searchRange = new Range(searchStart.lineNumber, searchStart.column, lineCount, this.getLineMaxColumn(lineCount));
      let ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
      TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex2, matchCase, wordSeparators2), searchStart, captureMatches);
      if (ret.length > 0) {
        return ret[0];
      }
      searchRange = new Range(1, 1, searchStart.lineNumber, this.getLineMaxColumn(searchStart.lineNumber));
      ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
      if (ret.length > 0) {
        return ret[0];
      }
      return null;
    }
    return TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex2, matchCase, wordSeparators2), searchStart, captureMatches);
  }
  findPreviousMatch(searchString, rawSearchStart, isRegex2, matchCase, wordSeparators2, captureMatches) {
    this._assertNotDisposed();
    const searchStart = this.validatePosition(rawSearchStart);
    return TextModelSearch.findPreviousMatch(this, new SearchParams(searchString, isRegex2, matchCase, wordSeparators2), searchStart, captureMatches);
  }
  pushStackElement() {
    this._commandManager.pushStackElement();
  }
  pushEOL(eol) {
    const currentEOL = this.getEOL() === "\n" ? 0 : 1;
    if (currentEOL === eol) {
      return;
    }
    try {
      this._onDidChangeDecorations.beginDeferredEmit();
      this._eventEmitter.beginDeferredEmit();
      if (this._initialUndoRedoSnapshot === null) {
        this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
      }
      this._commandManager.pushEOL(eol);
    } finally {
      this._eventEmitter.endDeferredEmit();
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  _validateEditOperation(rawOperation) {
    if (rawOperation instanceof ValidAnnotatedEditOperation) {
      return rawOperation;
    }
    return new ValidAnnotatedEditOperation(rawOperation.identifier || null, this.validateRange(rawOperation.range), rawOperation.text, rawOperation.forceMoveMarkers || false, rawOperation.isAutoWhitespaceEdit || false, rawOperation._isTracked || false);
  }
  _validateEditOperations(rawOperations) {
    const result = [];
    for (let i3 = 0, len2 = rawOperations.length; i3 < len2; i3++) {
      result[i3] = this._validateEditOperation(rawOperations[i3]);
    }
    return result;
  }
  pushEditOperations(beforeCursorState, editOperations, cursorStateComputer) {
    try {
      this._onDidChangeDecorations.beginDeferredEmit();
      this._eventEmitter.beginDeferredEmit();
      return this._pushEditOperations(beforeCursorState, this._validateEditOperations(editOperations), cursorStateComputer);
    } finally {
      this._eventEmitter.endDeferredEmit();
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  _pushEditOperations(beforeCursorState, editOperations, cursorStateComputer) {
    if (this._options.trimAutoWhitespace && this._trimAutoWhitespaceLines) {
      let incomingEdits = editOperations.map((op) => {
        return {
          range: this.validateRange(op.range),
          text: op.text
        };
      });
      let editsAreNearCursors = true;
      if (beforeCursorState) {
        for (let i3 = 0, len2 = beforeCursorState.length; i3 < len2; i3++) {
          let sel = beforeCursorState[i3];
          let foundEditNearSel = false;
          for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
            let editRange = incomingEdits[j].range;
            let selIsAbove = editRange.startLineNumber > sel.endLineNumber;
            let selIsBelow = sel.startLineNumber > editRange.endLineNumber;
            if (!selIsAbove && !selIsBelow) {
              foundEditNearSel = true;
              break;
            }
          }
          if (!foundEditNearSel) {
            editsAreNearCursors = false;
            break;
          }
        }
      }
      if (editsAreNearCursors) {
        for (let i3 = 0, len2 = this._trimAutoWhitespaceLines.length; i3 < len2; i3++) {
          let trimLineNumber = this._trimAutoWhitespaceLines[i3];
          let maxLineColumn = this.getLineMaxColumn(trimLineNumber);
          let allowTrimLine = true;
          for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
            let editRange = incomingEdits[j].range;
            let editText = incomingEdits[j].text;
            if (trimLineNumber < editRange.startLineNumber || trimLineNumber > editRange.endLineNumber) {
              continue;
            }
            if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === maxLineColumn && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(0) === "\n") {
              continue;
            }
            if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === 1 && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(editText.length - 1) === "\n") {
              continue;
            }
            allowTrimLine = false;
            break;
          }
          if (allowTrimLine) {
            const trimRange = new Range(trimLineNumber, 1, trimLineNumber, maxLineColumn);
            editOperations.push(new ValidAnnotatedEditOperation(null, trimRange, null, false, false, false));
          }
        }
      }
      this._trimAutoWhitespaceLines = null;
    }
    if (this._initialUndoRedoSnapshot === null) {
      this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
    }
    return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer);
  }
  _applyUndo(changes, eol, resultingAlternativeVersionId, resultingSelection) {
    const edits = changes.map((change) => {
      const rangeStart = this.getPositionAt(change.newPosition);
      const rangeEnd = this.getPositionAt(change.newEnd);
      return {
        range: new Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
        text: change.oldText
      };
    });
    this._applyUndoRedoEdits(edits, eol, true, false, resultingAlternativeVersionId, resultingSelection);
  }
  _applyRedo(changes, eol, resultingAlternativeVersionId, resultingSelection) {
    const edits = changes.map((change) => {
      const rangeStart = this.getPositionAt(change.oldPosition);
      const rangeEnd = this.getPositionAt(change.oldEnd);
      return {
        range: new Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
        text: change.newText
      };
    });
    this._applyUndoRedoEdits(edits, eol, false, true, resultingAlternativeVersionId, resultingSelection);
  }
  _applyUndoRedoEdits(edits, eol, isUndoing, isRedoing, resultingAlternativeVersionId, resultingSelection) {
    try {
      this._onDidChangeDecorations.beginDeferredEmit();
      this._eventEmitter.beginDeferredEmit();
      this._isUndoing = isUndoing;
      this._isRedoing = isRedoing;
      this.applyEdits(edits, false);
      this.setEOL(eol);
      this._overwriteAlternativeVersionId(resultingAlternativeVersionId);
    } finally {
      this._isUndoing = false;
      this._isRedoing = false;
      this._eventEmitter.endDeferredEmit(resultingSelection);
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  applyEdits(rawOperations, computeUndoEdits = false) {
    try {
      this._onDidChangeDecorations.beginDeferredEmit();
      this._eventEmitter.beginDeferredEmit();
      const operations = this._validateEditOperations(rawOperations);
      return this._doApplyEdits(operations, computeUndoEdits);
    } finally {
      this._eventEmitter.endDeferredEmit();
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  _doApplyEdits(rawOperations, computeUndoEdits) {
    const oldLineCount = this._buffer.getLineCount();
    const result = this._buffer.applyEdits(rawOperations, this._options.trimAutoWhitespace, computeUndoEdits);
    const newLineCount = this._buffer.getLineCount();
    const contentChanges = result.changes;
    this._trimAutoWhitespaceLines = result.trimAutoWhitespaceLineNumbers;
    if (contentChanges.length !== 0) {
      let rawContentChanges = [];
      let lineCount = oldLineCount;
      for (let i3 = 0, len2 = contentChanges.length; i3 < len2; i3++) {
        const change = contentChanges[i3];
        const [eolCount, firstLineLength, lastLineLength] = countEOL(change.text);
        this._tokens.acceptEdit(change.range, eolCount, firstLineLength);
        this._tokens2.acceptEdit(change.range, eolCount, firstLineLength, lastLineLength, change.text.length > 0 ? change.text.charCodeAt(0) : 0);
        this._onDidChangeDecorations.fire();
        this._decorationsTree.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers);
        const startLineNumber = change.range.startLineNumber;
        const endLineNumber = change.range.endLineNumber;
        const deletingLinesCnt = endLineNumber - startLineNumber;
        const insertingLinesCnt = eolCount;
        const editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);
        const changeLineCountDelta = insertingLinesCnt - deletingLinesCnt;
        for (let j = editingLinesCnt; j >= 0; j--) {
          const editLineNumber = startLineNumber + j;
          const currentEditLineNumber = newLineCount - lineCount - changeLineCountDelta + editLineNumber;
          rawContentChanges.push(new ModelRawLineChanged(editLineNumber, this.getLineContent(currentEditLineNumber)));
        }
        if (editingLinesCnt < deletingLinesCnt) {
          const spliceStartLineNumber = startLineNumber + editingLinesCnt;
          rawContentChanges.push(new ModelRawLinesDeleted(spliceStartLineNumber + 1, endLineNumber));
        }
        if (editingLinesCnt < insertingLinesCnt) {
          const spliceLineNumber = startLineNumber + editingLinesCnt;
          const cnt = insertingLinesCnt - editingLinesCnt;
          const fromLineNumber = newLineCount - lineCount - cnt + spliceLineNumber + 1;
          let newLines = [];
          for (let i4 = 0; i4 < cnt; i4++) {
            let lineNumber = fromLineNumber + i4;
            newLines[lineNumber - fromLineNumber] = this.getLineContent(lineNumber);
          }
          rawContentChanges.push(new ModelRawLinesInserted(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLines));
        }
        lineCount += changeLineCountDelta;
      }
      this._increaseVersionId();
      this._emitContentChangedEvent(new ModelRawContentChangedEvent(rawContentChanges, this.getVersionId(), this._isUndoing, this._isRedoing), {
        changes: contentChanges,
        eol: this._buffer.getEOL(),
        versionId: this.getVersionId(),
        isUndoing: this._isUndoing,
        isRedoing: this._isRedoing,
        isFlush: false
      });
    }
    return result.reverseEdits === null ? void 0 : result.reverseEdits;
  }
  undo() {
    this._undoRedoService.undo(this.uri);
  }
  canUndo() {
    return this._undoRedoService.canUndo(this.uri);
  }
  redo() {
    this._undoRedoService.redo(this.uri);
  }
  canRedo() {
    return this._undoRedoService.canRedo(this.uri);
  }
  changeDecorations(callback, ownerId = 0) {
    this._assertNotDisposed();
    try {
      this._onDidChangeDecorations.beginDeferredEmit();
      return this._changeDecorations(ownerId, callback);
    } finally {
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  _changeDecorations(ownerId, callback) {
    let changeAccessor = {
      addDecoration: (range3, options) => {
        return this._deltaDecorationsImpl(ownerId, [], [{range: range3, options}])[0];
      },
      changeDecoration: (id3, newRange) => {
        this._changeDecorationImpl(id3, newRange);
      },
      changeDecorationOptions: (id3, options) => {
        this._changeDecorationOptionsImpl(id3, _normalizeOptions(options));
      },
      removeDecoration: (id3) => {
        this._deltaDecorationsImpl(ownerId, [id3], []);
      },
      deltaDecorations: (oldDecorations, newDecorations) => {
        if (oldDecorations.length === 0 && newDecorations.length === 0) {
          return [];
        }
        return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
      }
    };
    let result = null;
    try {
      result = callback(changeAccessor);
    } catch (e2) {
      onUnexpectedError(e2);
    }
    changeAccessor.addDecoration = invalidFunc;
    changeAccessor.changeDecoration = invalidFunc;
    changeAccessor.changeDecorationOptions = invalidFunc;
    changeAccessor.removeDecoration = invalidFunc;
    changeAccessor.deltaDecorations = invalidFunc;
    return result;
  }
  deltaDecorations(oldDecorations, newDecorations, ownerId = 0) {
    this._assertNotDisposed();
    if (!oldDecorations) {
      oldDecorations = [];
    }
    if (oldDecorations.length === 0 && newDecorations.length === 0) {
      return [];
    }
    try {
      this._onDidChangeDecorations.beginDeferredEmit();
      return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
    } finally {
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  _getTrackedRange(id3) {
    return this.getDecorationRange(id3);
  }
  _setTrackedRange(id3, newRange, newStickiness) {
    const node = id3 ? this._decorations[id3] : null;
    if (!node) {
      if (!newRange) {
        return null;
      }
      return this._deltaDecorationsImpl(0, [], [{range: newRange, options: TRACKED_RANGE_OPTIONS[newStickiness]}])[0];
    }
    if (!newRange) {
      this._decorationsTree.delete(node);
      delete this._decorations[node.id];
      return null;
    }
    const range3 = this._validateRangeRelaxedNoAllocations(newRange);
    const startOffset = this._buffer.getOffsetAt(range3.startLineNumber, range3.startColumn);
    const endOffset = this._buffer.getOffsetAt(range3.endLineNumber, range3.endColumn);
    this._decorationsTree.delete(node);
    node.reset(this.getVersionId(), startOffset, endOffset, range3);
    node.setOptions(TRACKED_RANGE_OPTIONS[newStickiness]);
    this._decorationsTree.insert(node);
    return node.id;
  }
  removeAllDecorationsWithOwnerId(ownerId) {
    if (this._isDisposed) {
      return;
    }
    const nodes = this._decorationsTree.collectNodesFromOwner(ownerId);
    for (let i3 = 0, len2 = nodes.length; i3 < len2; i3++) {
      const node = nodes[i3];
      this._decorationsTree.delete(node);
      delete this._decorations[node.id];
    }
  }
  getDecorationOptions(decorationId) {
    const node = this._decorations[decorationId];
    if (!node) {
      return null;
    }
    return node.options;
  }
  getDecorationRange(decorationId) {
    const node = this._decorations[decorationId];
    if (!node) {
      return null;
    }
    const versionId = this.getVersionId();
    if (node.cachedVersionId !== versionId) {
      this._decorationsTree.resolveNode(node, versionId);
    }
    if (node.range === null) {
      node.range = this._getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
    }
    return node.range;
  }
  getLineDecorations(lineNumber, ownerId = 0, filterOutValidation = false) {
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      return [];
    }
    return this.getLinesDecorations(lineNumber, lineNumber, ownerId, filterOutValidation);
  }
  getLinesDecorations(_startLineNumber, _endLineNumber, ownerId = 0, filterOutValidation = false) {
    let lineCount = this.getLineCount();
    let startLineNumber = Math.min(lineCount, Math.max(1, _startLineNumber));
    let endLineNumber = Math.min(lineCount, Math.max(1, _endLineNumber));
    let endColumn = this.getLineMaxColumn(endLineNumber);
    return this._getDecorationsInRange(new Range(startLineNumber, 1, endLineNumber, endColumn), ownerId, filterOutValidation);
  }
  getDecorationsInRange(range3, ownerId = 0, filterOutValidation = false) {
    let validatedRange = this.validateRange(range3);
    return this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation);
  }
  getOverviewRulerDecorations(ownerId = 0, filterOutValidation = false) {
    const versionId = this.getVersionId();
    const result = this._decorationsTree.search(ownerId, filterOutValidation, true, versionId);
    return this._ensureNodesHaveRanges(result);
  }
  getAllDecorations(ownerId = 0, filterOutValidation = false) {
    const versionId = this.getVersionId();
    const result = this._decorationsTree.search(ownerId, filterOutValidation, false, versionId);
    return this._ensureNodesHaveRanges(result);
  }
  _getDecorationsInRange(filterRange, filterOwnerId, filterOutValidation) {
    const startOffset = this._buffer.getOffsetAt(filterRange.startLineNumber, filterRange.startColumn);
    const endOffset = this._buffer.getOffsetAt(filterRange.endLineNumber, filterRange.endColumn);
    const versionId = this.getVersionId();
    const result = this._decorationsTree.intervalSearch(startOffset, endOffset, filterOwnerId, filterOutValidation, versionId);
    return this._ensureNodesHaveRanges(result);
  }
  _ensureNodesHaveRanges(nodes) {
    for (let i3 = 0, len2 = nodes.length; i3 < len2; i3++) {
      const node = nodes[i3];
      if (node.range === null) {
        node.range = this._getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
      }
    }
    return nodes;
  }
  _getRangeAt(start3, end2) {
    return this._buffer.getRangeAt(start3, end2 - start3);
  }
  _changeDecorationImpl(decorationId, _range) {
    const node = this._decorations[decorationId];
    if (!node) {
      return;
    }
    const range3 = this._validateRangeRelaxedNoAllocations(_range);
    const startOffset = this._buffer.getOffsetAt(range3.startLineNumber, range3.startColumn);
    const endOffset = this._buffer.getOffsetAt(range3.endLineNumber, range3.endColumn);
    this._decorationsTree.delete(node);
    node.reset(this.getVersionId(), startOffset, endOffset, range3);
    this._decorationsTree.insert(node);
    this._onDidChangeDecorations.checkAffectedAndFire(node.options);
  }
  _changeDecorationOptionsImpl(decorationId, options) {
    const node = this._decorations[decorationId];
    if (!node) {
      return;
    }
    const nodeWasInOverviewRuler = node.options.overviewRuler && node.options.overviewRuler.color ? true : false;
    const nodeIsInOverviewRuler = options.overviewRuler && options.overviewRuler.color ? true : false;
    this._onDidChangeDecorations.checkAffectedAndFire(node.options);
    this._onDidChangeDecorations.checkAffectedAndFire(options);
    if (nodeWasInOverviewRuler !== nodeIsInOverviewRuler) {
      this._decorationsTree.delete(node);
      node.setOptions(options);
      this._decorationsTree.insert(node);
    } else {
      node.setOptions(options);
    }
  }
  _deltaDecorationsImpl(ownerId, oldDecorationsIds, newDecorations) {
    const versionId = this.getVersionId();
    const oldDecorationsLen = oldDecorationsIds.length;
    let oldDecorationIndex = 0;
    const newDecorationsLen = newDecorations.length;
    let newDecorationIndex = 0;
    let result = new Array(newDecorationsLen);
    while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) {
      let node = null;
      if (oldDecorationIndex < oldDecorationsLen) {
        do {
          node = this._decorations[oldDecorationsIds[oldDecorationIndex++]];
        } while (!node && oldDecorationIndex < oldDecorationsLen);
        if (node) {
          this._decorationsTree.delete(node);
          this._onDidChangeDecorations.checkAffectedAndFire(node.options);
        }
      }
      if (newDecorationIndex < newDecorationsLen) {
        if (!node) {
          const internalDecorationId = ++this._lastDecorationId;
          const decorationId = `${this._instanceId};${internalDecorationId}`;
          node = new IntervalNode(decorationId, 0, 0);
          this._decorations[decorationId] = node;
        }
        const newDecoration = newDecorations[newDecorationIndex];
        const range3 = this._validateRangeRelaxedNoAllocations(newDecoration.range);
        const options = _normalizeOptions(newDecoration.options);
        const startOffset = this._buffer.getOffsetAt(range3.startLineNumber, range3.startColumn);
        const endOffset = this._buffer.getOffsetAt(range3.endLineNumber, range3.endColumn);
        node.ownerId = ownerId;
        node.reset(versionId, startOffset, endOffset, range3);
        node.setOptions(options);
        this._onDidChangeDecorations.checkAffectedAndFire(options);
        this._decorationsTree.insert(node);
        result[newDecorationIndex] = node.id;
        newDecorationIndex++;
      } else {
        if (node) {
          delete this._decorations[node.id];
        }
      }
    }
    return result;
  }
  setTokens(tokens) {
    if (tokens.length === 0) {
      return;
    }
    let ranges = [];
    for (let i3 = 0, len2 = tokens.length; i3 < len2; i3++) {
      const element = tokens[i3];
      let minChangedLineNumber = 0;
      let maxChangedLineNumber = 0;
      let hasChange = false;
      for (let j = 0, lenJ = element.tokens.length; j < lenJ; j++) {
        const lineNumber = element.startLineNumber + j;
        if (hasChange) {
          this._tokens.setTokens(this._languageIdentifier.id, lineNumber - 1, this._buffer.getLineLength(lineNumber), element.tokens[j], false);
          maxChangedLineNumber = lineNumber;
        } else {
          const lineHasChange = this._tokens.setTokens(this._languageIdentifier.id, lineNumber - 1, this._buffer.getLineLength(lineNumber), element.tokens[j], true);
          if (lineHasChange) {
            hasChange = true;
            minChangedLineNumber = lineNumber;
            maxChangedLineNumber = lineNumber;
          }
        }
      }
      if (hasChange) {
        ranges.push({fromLineNumber: minChangedLineNumber, toLineNumber: maxChangedLineNumber});
      }
    }
    if (ranges.length > 0) {
      this._emitModelTokensChangedEvent({
        tokenizationSupportChanged: false,
        semanticTokensApplied: false,
        ranges
      });
    }
  }
  setSemanticTokens(tokens, isComplete) {
    this._tokens2.set(tokens, isComplete);
    this._emitModelTokensChangedEvent({
      tokenizationSupportChanged: false,
      semanticTokensApplied: tokens !== null,
      ranges: [{fromLineNumber: 1, toLineNumber: this.getLineCount()}]
    });
  }
  hasSemanticTokens() {
    return this._tokens2.isComplete();
  }
  setPartialSemanticTokens(range3, tokens) {
    if (this.hasSemanticTokens()) {
      return;
    }
    const changedRange = this._tokens2.setPartial(range3, tokens);
    this._emitModelTokensChangedEvent({
      tokenizationSupportChanged: false,
      semanticTokensApplied: true,
      ranges: [{fromLineNumber: changedRange.startLineNumber, toLineNumber: changedRange.endLineNumber}]
    });
  }
  tokenizeViewport(startLineNumber, endLineNumber) {
    startLineNumber = Math.max(1, startLineNumber);
    endLineNumber = Math.min(this._buffer.getLineCount(), endLineNumber);
    this._tokenization.tokenizeViewport(startLineNumber, endLineNumber);
  }
  clearTokens() {
    this._tokens.flush();
    this._emitModelTokensChangedEvent({
      tokenizationSupportChanged: true,
      semanticTokensApplied: false,
      ranges: [{
        fromLineNumber: 1,
        toLineNumber: this._buffer.getLineCount()
      }]
    });
  }
  _emitModelTokensChangedEvent(e2) {
    if (!this._isDisposing) {
      this._onDidChangeTokens.fire(e2);
    }
  }
  resetTokenization() {
    this._tokenization.reset();
  }
  forceTokenization(lineNumber) {
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new Error("Illegal value for lineNumber");
    }
    this._tokenization.forceTokenization(lineNumber);
  }
  isCheapToTokenize(lineNumber) {
    return this._tokenization.isCheapToTokenize(lineNumber);
  }
  tokenizeIfCheap(lineNumber) {
    if (this.isCheapToTokenize(lineNumber)) {
      this.forceTokenization(lineNumber);
    }
  }
  getLineTokens(lineNumber) {
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new Error("Illegal value for lineNumber");
    }
    return this._getLineTokens(lineNumber);
  }
  _getLineTokens(lineNumber) {
    const lineText = this.getLineContent(lineNumber);
    const syntacticTokens = this._tokens.getTokens(this._languageIdentifier.id, lineNumber - 1, lineText);
    return this._tokens2.addSemanticTokens(lineNumber, syntacticTokens);
  }
  getLanguageIdentifier() {
    return this._languageIdentifier;
  }
  getModeId() {
    return this._languageIdentifier.language;
  }
  setMode(languageIdentifier) {
    if (this._languageIdentifier.id === languageIdentifier.id) {
      return;
    }
    let e2 = {
      oldLanguage: this._languageIdentifier.language,
      newLanguage: languageIdentifier.language
    };
    this._languageIdentifier = languageIdentifier;
    this._onDidChangeLanguage.fire(e2);
    this._onDidChangeLanguageConfiguration.fire({});
  }
  getLanguageIdAtPosition(lineNumber, column) {
    const position2 = this.validatePosition(new Position(lineNumber, column));
    const lineTokens = this.getLineTokens(position2.lineNumber);
    return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position2.column - 1));
  }
  getWordAtPosition(_position) {
    this._assertNotDisposed();
    const position2 = this.validatePosition(_position);
    const lineContent = this.getLineContent(position2.lineNumber);
    const lineTokens = this._getLineTokens(position2.lineNumber);
    const tokenIndex = lineTokens.findTokenIndexAtOffset(position2.column - 1);
    const [rbStartOffset, rbEndOffset] = TextModel._findLanguageBoundaries(lineTokens, tokenIndex);
    const rightBiasedWord = getWordAtText(position2.column, LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex)), lineContent.substring(rbStartOffset, rbEndOffset), rbStartOffset);
    if (rightBiasedWord && rightBiasedWord.startColumn <= _position.column && _position.column <= rightBiasedWord.endColumn) {
      return rightBiasedWord;
    }
    if (tokenIndex > 0 && rbStartOffset === position2.column - 1) {
      const [lbStartOffset, lbEndOffset] = TextModel._findLanguageBoundaries(lineTokens, tokenIndex - 1);
      const leftBiasedWord = getWordAtText(position2.column, LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex - 1)), lineContent.substring(lbStartOffset, lbEndOffset), lbStartOffset);
      if (leftBiasedWord && leftBiasedWord.startColumn <= _position.column && _position.column <= leftBiasedWord.endColumn) {
        return leftBiasedWord;
      }
    }
    return null;
  }
  static _findLanguageBoundaries(lineTokens, tokenIndex) {
    const languageId = lineTokens.getLanguageId(tokenIndex);
    let startOffset = 0;
    for (let i3 = tokenIndex; i3 >= 0 && lineTokens.getLanguageId(i3) === languageId; i3--) {
      startOffset = lineTokens.getStartOffset(i3);
    }
    let endOffset = lineTokens.getLineContent().length;
    for (let i3 = tokenIndex, tokenCount = lineTokens.getCount(); i3 < tokenCount && lineTokens.getLanguageId(i3) === languageId; i3++) {
      endOffset = lineTokens.getEndOffset(i3);
    }
    return [startOffset, endOffset];
  }
  getWordUntilPosition(position2) {
    const wordAtPosition = this.getWordAtPosition(position2);
    if (!wordAtPosition) {
      return {
        word: "",
        startColumn: position2.column,
        endColumn: position2.column
      };
    }
    return {
      word: wordAtPosition.word.substr(0, position2.column - wordAtPosition.startColumn),
      startColumn: wordAtPosition.startColumn,
      endColumn: position2.column
    };
  }
  findMatchingBracketUp(_bracket, _position) {
    let bracket = _bracket.toLowerCase();
    let position2 = this.validatePosition(_position);
    let lineTokens = this._getLineTokens(position2.lineNumber);
    let languageId = lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position2.column - 1));
    let bracketsSupport = LanguageConfigurationRegistry.getBracketsSupport(languageId);
    if (!bracketsSupport) {
      return null;
    }
    let data2 = bracketsSupport.textIsBracket[bracket];
    if (!data2) {
      return null;
    }
    return stripBracketSearchCanceled(this._findMatchingBracketUp(data2, position2, null));
  }
  matchBracket(position2) {
    return this._matchBracket(this.validatePosition(position2));
  }
  _matchBracket(position2) {
    const lineNumber = position2.lineNumber;
    const lineTokens = this._getLineTokens(lineNumber);
    const tokenCount = lineTokens.getCount();
    const lineText = this._buffer.getLineContent(lineNumber);
    const tokenIndex = lineTokens.findTokenIndexAtOffset(position2.column - 1);
    if (tokenIndex < 0) {
      return null;
    }
    const currentModeBrackets = LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(tokenIndex));
    if (currentModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex))) {
      let searchStartOffset = Math.max(0, position2.column - 1 - currentModeBrackets.maxBracketLength);
      for (let i3 = tokenIndex - 1; i3 >= 0; i3--) {
        const tokenEndOffset = lineTokens.getEndOffset(i3);
        if (tokenEndOffset <= searchStartOffset) {
          break;
        }
        if (ignoreBracketsInToken(lineTokens.getStandardTokenType(i3))) {
          searchStartOffset = tokenEndOffset;
        }
      }
      const searchEndOffset = Math.min(lineText.length, position2.column - 1 + currentModeBrackets.maxBracketLength);
      let bestResult = null;
      while (true) {
        const foundBracket = BracketsUtils.findNextBracketInRange(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!foundBracket) {
          break;
        }
        if (foundBracket.startColumn <= position2.column && position2.column <= foundBracket.endColumn) {
          const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
          const r3 = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText], null);
          if (r3) {
            if (r3 instanceof BracketSearchCanceled) {
              return null;
            }
            bestResult = r3;
          }
        }
        searchStartOffset = foundBracket.endColumn - 1;
      }
      if (bestResult) {
        return bestResult;
      }
    }
    if (tokenIndex > 0 && lineTokens.getStartOffset(tokenIndex) === position2.column - 1) {
      const prevTokenIndex = tokenIndex - 1;
      const prevModeBrackets = LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(prevTokenIndex));
      if (prevModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(prevTokenIndex))) {
        const searchStartOffset = Math.max(0, position2.column - 1 - prevModeBrackets.maxBracketLength);
        let searchEndOffset = Math.min(lineText.length, position2.column - 1 + prevModeBrackets.maxBracketLength);
        for (let i3 = prevTokenIndex + 1; i3 < tokenCount; i3++) {
          const tokenStartOffset = lineTokens.getStartOffset(i3);
          if (tokenStartOffset >= searchEndOffset) {
            break;
          }
          if (ignoreBracketsInToken(lineTokens.getStandardTokenType(i3))) {
            searchEndOffset = tokenStartOffset;
          }
        }
        const foundBracket = BracketsUtils.findPrevBracketInRange(prevModeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (foundBracket && foundBracket.startColumn <= position2.column && position2.column <= foundBracket.endColumn) {
          const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
          const r3 = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText], null);
          if (r3) {
            if (r3 instanceof BracketSearchCanceled) {
              return null;
            }
            return r3;
          }
        }
      }
    }
    return null;
  }
  _matchFoundBracket(foundBracket, data2, isOpen, continueSearchPredicate) {
    if (!data2) {
      return null;
    }
    const matched = isOpen ? this._findMatchingBracketDown(data2, foundBracket.getEndPosition(), continueSearchPredicate) : this._findMatchingBracketUp(data2, foundBracket.getStartPosition(), continueSearchPredicate);
    if (!matched) {
      return null;
    }
    if (matched instanceof BracketSearchCanceled) {
      return matched;
    }
    return [foundBracket, matched];
  }
  _findMatchingBracketUp(bracket, position2, continueSearchPredicate) {
    const languageId = bracket.languageIdentifier.id;
    const reversedBracketRegex = bracket.reversedRegex;
    let count = -1;
    let totalCallCount = 0;
    const searchPrevMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => {
      while (true) {
        if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
          return BracketSearchCanceled.INSTANCE;
        }
        const r3 = BracketsUtils.findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!r3) {
          break;
        }
        const hitText = lineText.substring(r3.startColumn - 1, r3.endColumn - 1).toLowerCase();
        if (bracket.isOpen(hitText)) {
          count++;
        } else if (bracket.isClose(hitText)) {
          count--;
        }
        if (count === 0) {
          return r3;
        }
        searchEndOffset = r3.startColumn - 1;
      }
      return null;
    };
    for (let lineNumber = position2.lineNumber; lineNumber >= 1; lineNumber--) {
      const lineTokens = this._getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this._buffer.getLineContent(lineNumber);
      let tokenIndex = tokenCount - 1;
      let searchStartOffset = lineText.length;
      let searchEndOffset = lineText.length;
      if (lineNumber === position2.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position2.column - 1);
        searchStartOffset = position2.column - 1;
        searchEndOffset = position2.column - 1;
      }
      let prevSearchInToken = true;
      for (; tokenIndex >= 0; tokenIndex--) {
        const searchInToken = lineTokens.getLanguageId(tokenIndex) === languageId && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r3 = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r3) {
              return r3;
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r3 = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r3) {
          return r3;
        }
      }
    }
    return null;
  }
  _findMatchingBracketDown(bracket, position2, continueSearchPredicate) {
    const languageId = bracket.languageIdentifier.id;
    const bracketRegex = bracket.forwardRegex;
    let count = 1;
    let totalCallCount = 0;
    const searchNextMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => {
      while (true) {
        if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
          return BracketSearchCanceled.INSTANCE;
        }
        const r3 = BracketsUtils.findNextBracketInRange(bracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!r3) {
          break;
        }
        const hitText = lineText.substring(r3.startColumn - 1, r3.endColumn - 1).toLowerCase();
        if (bracket.isOpen(hitText)) {
          count++;
        } else if (bracket.isClose(hitText)) {
          count--;
        }
        if (count === 0) {
          return r3;
        }
        searchStartOffset = r3.endColumn - 1;
      }
      return null;
    };
    const lineCount = this.getLineCount();
    for (let lineNumber = position2.lineNumber; lineNumber <= lineCount; lineNumber++) {
      const lineTokens = this._getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this._buffer.getLineContent(lineNumber);
      let tokenIndex = 0;
      let searchStartOffset = 0;
      let searchEndOffset = 0;
      if (lineNumber === position2.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position2.column - 1);
        searchStartOffset = position2.column - 1;
        searchEndOffset = position2.column - 1;
      }
      let prevSearchInToken = true;
      for (; tokenIndex < tokenCount; tokenIndex++) {
        const searchInToken = lineTokens.getLanguageId(tokenIndex) === languageId && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r3 = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r3) {
              return r3;
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r3 = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r3) {
          return r3;
        }
      }
    }
    return null;
  }
  findPrevBracket(_position) {
    const position2 = this.validatePosition(_position);
    let languageId = -1;
    let modeBrackets = null;
    for (let lineNumber = position2.lineNumber; lineNumber >= 1; lineNumber--) {
      const lineTokens = this._getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this._buffer.getLineContent(lineNumber);
      let tokenIndex = tokenCount - 1;
      let searchStartOffset = lineText.length;
      let searchEndOffset = lineText.length;
      if (lineNumber === position2.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position2.column - 1);
        searchStartOffset = position2.column - 1;
        searchEndOffset = position2.column - 1;
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          languageId = tokenLanguageId;
          modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
        }
      }
      let prevSearchInToken = true;
      for (; tokenIndex >= 0; tokenIndex--) {
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r3 = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r3) {
              return this._toFoundBracket(modeBrackets, r3);
            }
            prevSearchInToken = false;
          }
          languageId = tokenLanguageId;
          modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
        }
        const searchInToken = !!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r3 = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r3) {
              return this._toFoundBracket(modeBrackets, r3);
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r3 = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r3) {
          return this._toFoundBracket(modeBrackets, r3);
        }
      }
    }
    return null;
  }
  findNextBracket(_position) {
    const position2 = this.validatePosition(_position);
    const lineCount = this.getLineCount();
    let languageId = -1;
    let modeBrackets = null;
    for (let lineNumber = position2.lineNumber; lineNumber <= lineCount; lineNumber++) {
      const lineTokens = this._getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this._buffer.getLineContent(lineNumber);
      let tokenIndex = 0;
      let searchStartOffset = 0;
      let searchEndOffset = 0;
      if (lineNumber === position2.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position2.column - 1);
        searchStartOffset = position2.column - 1;
        searchEndOffset = position2.column - 1;
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          languageId = tokenLanguageId;
          modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
        }
      }
      let prevSearchInToken = true;
      for (; tokenIndex < tokenCount; tokenIndex++) {
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r3 = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r3) {
              return this._toFoundBracket(modeBrackets, r3);
            }
            prevSearchInToken = false;
          }
          languageId = tokenLanguageId;
          modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
        }
        const searchInToken = !!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r3 = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r3) {
              return this._toFoundBracket(modeBrackets, r3);
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r3 = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r3) {
          return this._toFoundBracket(modeBrackets, r3);
        }
      }
    }
    return null;
  }
  findEnclosingBrackets(_position, maxDuration) {
    let continueSearchPredicate;
    if (typeof maxDuration === "undefined") {
      continueSearchPredicate = null;
    } else {
      const startTime2 = Date.now();
      continueSearchPredicate = () => {
        return Date.now() - startTime2 <= maxDuration;
      };
    }
    const position2 = this.validatePosition(_position);
    const lineCount = this.getLineCount();
    const savedCounts = new Map();
    let counts = [];
    const resetCounts = (languageId2, modeBrackets2) => {
      if (!savedCounts.has(languageId2)) {
        let tmp = [];
        for (let i3 = 0, len2 = modeBrackets2 ? modeBrackets2.brackets.length : 0; i3 < len2; i3++) {
          tmp[i3] = 0;
        }
        savedCounts.set(languageId2, tmp);
      }
      counts = savedCounts.get(languageId2);
    };
    let totalCallCount = 0;
    const searchInRange = (modeBrackets2, lineNumber, lineText, searchStartOffset, searchEndOffset) => {
      while (true) {
        if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
          return BracketSearchCanceled.INSTANCE;
        }
        const r3 = BracketsUtils.findNextBracketInRange(modeBrackets2.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!r3) {
          break;
        }
        const hitText = lineText.substring(r3.startColumn - 1, r3.endColumn - 1).toLowerCase();
        const bracket = modeBrackets2.textIsBracket[hitText];
        if (bracket) {
          if (bracket.isOpen(hitText)) {
            counts[bracket.index]++;
          } else if (bracket.isClose(hitText)) {
            counts[bracket.index]--;
          }
          if (counts[bracket.index] === -1) {
            return this._matchFoundBracket(r3, bracket, false, continueSearchPredicate);
          }
        }
        searchStartOffset = r3.endColumn - 1;
      }
      return null;
    };
    let languageId = -1;
    let modeBrackets = null;
    for (let lineNumber = position2.lineNumber; lineNumber <= lineCount; lineNumber++) {
      const lineTokens = this._getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this._buffer.getLineContent(lineNumber);
      let tokenIndex = 0;
      let searchStartOffset = 0;
      let searchEndOffset = 0;
      if (lineNumber === position2.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position2.column - 1);
        searchStartOffset = position2.column - 1;
        searchEndOffset = position2.column - 1;
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          languageId = tokenLanguageId;
          modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
          resetCounts(languageId, modeBrackets);
        }
      }
      let prevSearchInToken = true;
      for (; tokenIndex < tokenCount; tokenIndex++) {
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r3 = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r3) {
              return stripBracketSearchCanceled(r3);
            }
            prevSearchInToken = false;
          }
          languageId = tokenLanguageId;
          modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
          resetCounts(languageId, modeBrackets);
        }
        const searchInToken = !!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r3 = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r3) {
              return stripBracketSearchCanceled(r3);
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r3 = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r3) {
          return stripBracketSearchCanceled(r3);
        }
      }
    }
    return null;
  }
  _toFoundBracket(modeBrackets, r3) {
    if (!r3) {
      return null;
    }
    let text = this.getValueInRange(r3);
    text = text.toLowerCase();
    let data2 = modeBrackets.textIsBracket[text];
    if (!data2) {
      return null;
    }
    return {
      range: r3,
      open: data2.open,
      close: data2.close,
      isOpen: modeBrackets.textIsOpenBracket[text]
    };
  }
  static computeIndentLevel(line, tabSize) {
    let indent = 0;
    let i3 = 0;
    let len2 = line.length;
    while (i3 < len2) {
      let chCode = line.charCodeAt(i3);
      if (chCode === 32) {
        indent++;
      } else if (chCode === 9) {
        indent = indent - indent % tabSize + tabSize;
      } else {
        break;
      }
      i3++;
    }
    if (i3 === len2) {
      return -1;
    }
    return indent;
  }
  _computeIndentLevel(lineIndex) {
    return TextModel.computeIndentLevel(this._buffer.getLineContent(lineIndex + 1), this._options.tabSize);
  }
  getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
    this._assertNotDisposed();
    const lineCount = this.getLineCount();
    if (lineNumber < 1 || lineNumber > lineCount) {
      throw new Error("Illegal value for lineNumber");
    }
    const foldingRules = LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id);
    const offSide = Boolean(foldingRules && foldingRules.offSide);
    let up_aboveContentLineIndex = -2;
    let up_aboveContentLineIndent = -1;
    let up_belowContentLineIndex = -2;
    let up_belowContentLineIndent = -1;
    const up_resolveIndents = (lineNumber2) => {
      if (up_aboveContentLineIndex !== -1 && (up_aboveContentLineIndex === -2 || up_aboveContentLineIndex > lineNumber2 - 1)) {
        up_aboveContentLineIndex = -1;
        up_aboveContentLineIndent = -1;
        for (let lineIndex = lineNumber2 - 2; lineIndex >= 0; lineIndex--) {
          let indent2 = this._computeIndentLevel(lineIndex);
          if (indent2 >= 0) {
            up_aboveContentLineIndex = lineIndex;
            up_aboveContentLineIndent = indent2;
            break;
          }
        }
      }
      if (up_belowContentLineIndex === -2) {
        up_belowContentLineIndex = -1;
        up_belowContentLineIndent = -1;
        for (let lineIndex = lineNumber2; lineIndex < lineCount; lineIndex++) {
          let indent2 = this._computeIndentLevel(lineIndex);
          if (indent2 >= 0) {
            up_belowContentLineIndex = lineIndex;
            up_belowContentLineIndent = indent2;
            break;
          }
        }
      }
    };
    let down_aboveContentLineIndex = -2;
    let down_aboveContentLineIndent = -1;
    let down_belowContentLineIndex = -2;
    let down_belowContentLineIndent = -1;
    const down_resolveIndents = (lineNumber2) => {
      if (down_aboveContentLineIndex === -2) {
        down_aboveContentLineIndex = -1;
        down_aboveContentLineIndent = -1;
        for (let lineIndex = lineNumber2 - 2; lineIndex >= 0; lineIndex--) {
          let indent2 = this._computeIndentLevel(lineIndex);
          if (indent2 >= 0) {
            down_aboveContentLineIndex = lineIndex;
            down_aboveContentLineIndent = indent2;
            break;
          }
        }
      }
      if (down_belowContentLineIndex !== -1 && (down_belowContentLineIndex === -2 || down_belowContentLineIndex < lineNumber2 - 1)) {
        down_belowContentLineIndex = -1;
        down_belowContentLineIndent = -1;
        for (let lineIndex = lineNumber2; lineIndex < lineCount; lineIndex++) {
          let indent2 = this._computeIndentLevel(lineIndex);
          if (indent2 >= 0) {
            down_belowContentLineIndex = lineIndex;
            down_belowContentLineIndent = indent2;
            break;
          }
        }
      }
    };
    let startLineNumber = 0;
    let goUp = true;
    let endLineNumber = 0;
    let goDown = true;
    let indent = 0;
    let initialIndent = 0;
    for (let distance = 0; goUp || goDown; distance++) {
      const upLineNumber = lineNumber - distance;
      const downLineNumber = lineNumber + distance;
      if (distance > 1 && (upLineNumber < 1 || upLineNumber < minLineNumber)) {
        goUp = false;
      }
      if (distance > 1 && (downLineNumber > lineCount || downLineNumber > maxLineNumber)) {
        goDown = false;
      }
      if (distance > 5e4) {
        goUp = false;
        goDown = false;
      }
      let upLineIndentLevel = -1;
      if (goUp) {
        const currentIndent = this._computeIndentLevel(upLineNumber - 1);
        if (currentIndent >= 0) {
          up_belowContentLineIndex = upLineNumber - 1;
          up_belowContentLineIndent = currentIndent;
          upLineIndentLevel = Math.ceil(currentIndent / this._options.indentSize);
        } else {
          up_resolveIndents(upLineNumber);
          upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent);
        }
      }
      let downLineIndentLevel = -1;
      if (goDown) {
        const currentIndent = this._computeIndentLevel(downLineNumber - 1);
        if (currentIndent >= 0) {
          down_aboveContentLineIndex = downLineNumber - 1;
          down_aboveContentLineIndent = currentIndent;
          downLineIndentLevel = Math.ceil(currentIndent / this._options.indentSize);
        } else {
          down_resolveIndents(downLineNumber);
          downLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, down_aboveContentLineIndent, down_belowContentLineIndent);
        }
      }
      if (distance === 0) {
        initialIndent = upLineIndentLevel;
        continue;
      }
      if (distance === 1) {
        if (downLineNumber <= lineCount && downLineIndentLevel >= 0 && initialIndent + 1 === downLineIndentLevel) {
          goUp = false;
          startLineNumber = downLineNumber;
          endLineNumber = downLineNumber;
          indent = downLineIndentLevel;
          continue;
        }
        if (upLineNumber >= 1 && upLineIndentLevel >= 0 && upLineIndentLevel - 1 === initialIndent) {
          goDown = false;
          startLineNumber = upLineNumber;
          endLineNumber = upLineNumber;
          indent = upLineIndentLevel;
          continue;
        }
        startLineNumber = lineNumber;
        endLineNumber = lineNumber;
        indent = initialIndent;
        if (indent === 0) {
          return {startLineNumber, endLineNumber, indent};
        }
      }
      if (goUp) {
        if (upLineIndentLevel >= indent) {
          startLineNumber = upLineNumber;
        } else {
          goUp = false;
        }
      }
      if (goDown) {
        if (downLineIndentLevel >= indent) {
          endLineNumber = downLineNumber;
        } else {
          goDown = false;
        }
      }
    }
    return {startLineNumber, endLineNumber, indent};
  }
  getLinesIndentGuides(startLineNumber, endLineNumber) {
    this._assertNotDisposed();
    const lineCount = this.getLineCount();
    if (startLineNumber < 1 || startLineNumber > lineCount) {
      throw new Error("Illegal value for startLineNumber");
    }
    if (endLineNumber < 1 || endLineNumber > lineCount) {
      throw new Error("Illegal value for endLineNumber");
    }
    const foldingRules = LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id);
    const offSide = Boolean(foldingRules && foldingRules.offSide);
    let result = new Array(endLineNumber - startLineNumber + 1);
    let aboveContentLineIndex = -2;
    let aboveContentLineIndent = -1;
    let belowContentLineIndex = -2;
    let belowContentLineIndent = -1;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      let resultIndex = lineNumber - startLineNumber;
      const currentIndent = this._computeIndentLevel(lineNumber - 1);
      if (currentIndent >= 0) {
        aboveContentLineIndex = lineNumber - 1;
        aboveContentLineIndent = currentIndent;
        result[resultIndex] = Math.ceil(currentIndent / this._options.indentSize);
        continue;
      }
      if (aboveContentLineIndex === -2) {
        aboveContentLineIndex = -1;
        aboveContentLineIndent = -1;
        for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
          let indent = this._computeIndentLevel(lineIndex);
          if (indent >= 0) {
            aboveContentLineIndex = lineIndex;
            aboveContentLineIndent = indent;
            break;
          }
        }
      }
      if (belowContentLineIndex !== -1 && (belowContentLineIndex === -2 || belowContentLineIndex < lineNumber - 1)) {
        belowContentLineIndex = -1;
        belowContentLineIndent = -1;
        for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
          let indent = this._computeIndentLevel(lineIndex);
          if (indent >= 0) {
            belowContentLineIndex = lineIndex;
            belowContentLineIndent = indent;
            break;
          }
        }
      }
      result[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent);
    }
    return result;
  }
  _getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent) {
    if (aboveContentLineIndent === -1 || belowContentLineIndent === -1) {
      return 0;
    } else if (aboveContentLineIndent < belowContentLineIndent) {
      return 1 + Math.floor(aboveContentLineIndent / this._options.indentSize);
    } else if (aboveContentLineIndent === belowContentLineIndent) {
      return Math.ceil(belowContentLineIndent / this._options.indentSize);
    } else {
      if (offSide) {
        return Math.ceil(belowContentLineIndent / this._options.indentSize);
      } else {
        return 1 + Math.floor(belowContentLineIndent / this._options.indentSize);
      }
    }
  }
};
TextModel.MODEL_SYNC_LIMIT = 50 * 1024 * 1024;
TextModel.LARGE_FILE_SIZE_THRESHOLD = 20 * 1024 * 1024;
TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD = 300 * 1e3;
TextModel.DEFAULT_CREATION_OPTIONS = {
  isForSimpleWidget: false,
  tabSize: EDITOR_MODEL_DEFAULTS.tabSize,
  indentSize: EDITOR_MODEL_DEFAULTS.indentSize,
  insertSpaces: EDITOR_MODEL_DEFAULTS.insertSpaces,
  detectIndentation: false,
  defaultEOL: 1,
  trimAutoWhitespace: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
  largeFileOptimizations: EDITOR_MODEL_DEFAULTS.largeFileOptimizations
};
var DecorationsTrees = class {
  constructor() {
    this._decorationsTree0 = new IntervalTree();
    this._decorationsTree1 = new IntervalTree();
  }
  intervalSearch(start3, end2, filterOwnerId, filterOutValidation, cachedVersionId) {
    const r0 = this._decorationsTree0.intervalSearch(start3, end2, filterOwnerId, filterOutValidation, cachedVersionId);
    const r1 = this._decorationsTree1.intervalSearch(start3, end2, filterOwnerId, filterOutValidation, cachedVersionId);
    return r0.concat(r1);
  }
  search(filterOwnerId, filterOutValidation, overviewRulerOnly, cachedVersionId) {
    if (overviewRulerOnly) {
      return this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);
    } else {
      const r0 = this._decorationsTree0.search(filterOwnerId, filterOutValidation, cachedVersionId);
      const r1 = this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);
      return r0.concat(r1);
    }
  }
  collectNodesFromOwner(ownerId) {
    const r0 = this._decorationsTree0.collectNodesFromOwner(ownerId);
    const r1 = this._decorationsTree1.collectNodesFromOwner(ownerId);
    return r0.concat(r1);
  }
  collectNodesPostOrder() {
    const r0 = this._decorationsTree0.collectNodesPostOrder();
    const r1 = this._decorationsTree1.collectNodesPostOrder();
    return r0.concat(r1);
  }
  insert(node) {
    if (getNodeIsInOverviewRuler(node)) {
      this._decorationsTree1.insert(node);
    } else {
      this._decorationsTree0.insert(node);
    }
  }
  delete(node) {
    if (getNodeIsInOverviewRuler(node)) {
      this._decorationsTree1.delete(node);
    } else {
      this._decorationsTree0.delete(node);
    }
  }
  resolveNode(node, cachedVersionId) {
    if (getNodeIsInOverviewRuler(node)) {
      this._decorationsTree1.resolveNode(node, cachedVersionId);
    } else {
      this._decorationsTree0.resolveNode(node, cachedVersionId);
    }
  }
  acceptReplace(offset2, length, textLength, forceMoveMarkers) {
    this._decorationsTree0.acceptReplace(offset2, length, textLength, forceMoveMarkers);
    this._decorationsTree1.acceptReplace(offset2, length, textLength, forceMoveMarkers);
  }
};
function cleanClassName(className) {
  return className.replace(/[^a-z0-9\-_]/gi, " ");
}
var DecorationOptions = class {
  constructor(options) {
    this.color = options.color || "";
    this.darkColor = options.darkColor || "";
  }
};
var ModelDecorationOverviewRulerOptions = class extends DecorationOptions {
  constructor(options) {
    super(options);
    this._resolvedColor = null;
    this.position = typeof options.position === "number" ? options.position : OverviewRulerLane$1.Center;
  }
  getColor(theme) {
    if (!this._resolvedColor) {
      if (theme.type !== "light" && this.darkColor) {
        this._resolvedColor = this._resolveColor(this.darkColor, theme);
      } else {
        this._resolvedColor = this._resolveColor(this.color, theme);
      }
    }
    return this._resolvedColor;
  }
  invalidateCachedColor() {
    this._resolvedColor = null;
  }
  _resolveColor(color2, theme) {
    if (typeof color2 === "string") {
      return color2;
    }
    let c3 = color2 ? theme.getColor(color2.id) : null;
    if (!c3) {
      return "";
    }
    return c3.toString();
  }
};
var ModelDecorationMinimapOptions = class extends DecorationOptions {
  constructor(options) {
    super(options);
    this.position = options.position;
  }
  getColor(theme) {
    if (!this._resolvedColor) {
      if (theme.type !== "light" && this.darkColor) {
        this._resolvedColor = this._resolveColor(this.darkColor, theme);
      } else {
        this._resolvedColor = this._resolveColor(this.color, theme);
      }
    }
    return this._resolvedColor;
  }
  invalidateCachedColor() {
    this._resolvedColor = void 0;
  }
  _resolveColor(color2, theme) {
    if (typeof color2 === "string") {
      return Color.fromHex(color2);
    }
    return theme.getColor(color2.id);
  }
};
var ModelDecorationOptions = class {
  constructor(options) {
    this.stickiness = options.stickiness || 0;
    this.zIndex = options.zIndex || 0;
    this.className = options.className ? cleanClassName(options.className) : null;
    this.hoverMessage = options.hoverMessage || null;
    this.glyphMarginHoverMessage = options.glyphMarginHoverMessage || null;
    this.isWholeLine = options.isWholeLine || false;
    this.showIfCollapsed = options.showIfCollapsed || false;
    this.collapseOnReplaceEdit = options.collapseOnReplaceEdit || false;
    this.overviewRuler = options.overviewRuler ? new ModelDecorationOverviewRulerOptions(options.overviewRuler) : null;
    this.minimap = options.minimap ? new ModelDecorationMinimapOptions(options.minimap) : null;
    this.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : null;
    this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : null;
    this.firstLineDecorationClassName = options.firstLineDecorationClassName ? cleanClassName(options.firstLineDecorationClassName) : null;
    this.marginClassName = options.marginClassName ? cleanClassName(options.marginClassName) : null;
    this.inlineClassName = options.inlineClassName ? cleanClassName(options.inlineClassName) : null;
    this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
    this.beforeContentClassName = options.beforeContentClassName ? cleanClassName(options.beforeContentClassName) : null;
    this.afterContentClassName = options.afterContentClassName ? cleanClassName(options.afterContentClassName) : null;
  }
  static register(options) {
    return new ModelDecorationOptions(options);
  }
  static createDynamic(options) {
    return new ModelDecorationOptions(options);
  }
};
ModelDecorationOptions.EMPTY = ModelDecorationOptions.register({});
var TRACKED_RANGE_OPTIONS = [
  ModelDecorationOptions.register({stickiness: 0}),
  ModelDecorationOptions.register({stickiness: 1}),
  ModelDecorationOptions.register({stickiness: 2}),
  ModelDecorationOptions.register({stickiness: 3})
];
function _normalizeOptions(options) {
  if (options instanceof ModelDecorationOptions) {
    return options;
  }
  return ModelDecorationOptions.createDynamic(options);
}
var DidChangeDecorationsEmitter = class extends Disposable {
  constructor() {
    super();
    this._actual = this._register(new Emitter());
    this.event = this._actual.event;
    this._deferredCnt = 0;
    this._shouldFire = false;
    this._affectsMinimap = false;
    this._affectsOverviewRuler = false;
  }
  beginDeferredEmit() {
    this._deferredCnt++;
  }
  endDeferredEmit() {
    this._deferredCnt--;
    if (this._deferredCnt === 0) {
      if (this._shouldFire) {
        const event = {
          affectsMinimap: this._affectsMinimap,
          affectsOverviewRuler: this._affectsOverviewRuler
        };
        this._shouldFire = false;
        this._affectsMinimap = false;
        this._affectsOverviewRuler = false;
        this._actual.fire(event);
      }
    }
  }
  checkAffectedAndFire(options) {
    if (!this._affectsMinimap) {
      this._affectsMinimap = options.minimap && options.minimap.position ? true : false;
    }
    if (!this._affectsOverviewRuler) {
      this._affectsOverviewRuler = options.overviewRuler && options.overviewRuler.color ? true : false;
    }
    this._shouldFire = true;
  }
  fire() {
    this._affectsMinimap = true;
    this._affectsOverviewRuler = true;
    this._shouldFire = true;
  }
};
var DidChangeContentEmitter = class extends Disposable {
  constructor() {
    super();
    this._fastEmitter = this._register(new Emitter());
    this.fastEvent = this._fastEmitter.event;
    this._slowEmitter = this._register(new Emitter());
    this.slowEvent = this._slowEmitter.event;
    this._deferredCnt = 0;
    this._deferredEvent = null;
  }
  beginDeferredEmit() {
    this._deferredCnt++;
  }
  endDeferredEmit(resultingSelection = null) {
    this._deferredCnt--;
    if (this._deferredCnt === 0) {
      if (this._deferredEvent !== null) {
        this._deferredEvent.rawContentChangedEvent.resultingSelection = resultingSelection;
        const e2 = this._deferredEvent;
        this._deferredEvent = null;
        this._fastEmitter.fire(e2);
        this._slowEmitter.fire(e2);
      }
    }
  }
  fire(e2) {
    if (this._deferredCnt > 0) {
      if (this._deferredEvent) {
        this._deferredEvent = this._deferredEvent.merge(e2);
      } else {
        this._deferredEvent = e2;
      }
      return;
    }
    this._fastEmitter.fire(e2);
    this._slowEmitter.fire(e2);
  }
};
var autoCloseAlways = () => true;
var autoCloseNever = () => false;
var autoCloseBeforeWhitespace = (chr) => chr === " " || chr === "	";
function appendEntry(target, key, value) {
  if (target.has(key)) {
    target.get(key).push(value);
  } else {
    target.set(key, [value]);
  }
}
var CursorConfiguration = class {
  constructor(languageIdentifier, modelOptions, configuration) {
    this._languageIdentifier = languageIdentifier;
    const options = configuration.options;
    const layoutInfo = options.get(117);
    this.readOnly = options.get(72);
    this.tabSize = modelOptions.tabSize;
    this.indentSize = modelOptions.indentSize;
    this.insertSpaces = modelOptions.insertSpaces;
    this.lineHeight = options.get(51);
    this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2);
    this.useTabStops = options.get(104);
    this.wordSeparators = options.get(105);
    this.emptySelectionClipboard = options.get(26);
    this.copyWithSyntaxHighlighting = options.get(16);
    this.multiCursorMergeOverlapping = options.get(60);
    this.multiCursorPaste = options.get(62);
    this.autoClosingBrackets = options.get(5);
    this.autoClosingQuotes = options.get(7);
    this.autoClosingOvertype = options.get(6);
    this.autoSurround = options.get(10);
    this.autoIndent = options.get(8);
    this.autoClosingPairsOpen2 = new Map();
    this.autoClosingPairsClose2 = new Map();
    this.surroundingPairs = {};
    this._electricChars = null;
    this.shouldAutoCloseBefore = {
      quote: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingQuotes),
      bracket: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingBrackets)
    };
    let autoClosingPairs = CursorConfiguration._getAutoClosingPairs(languageIdentifier);
    if (autoClosingPairs) {
      for (const pair of autoClosingPairs) {
        appendEntry(this.autoClosingPairsOpen2, pair.open.charAt(pair.open.length - 1), pair);
        if (pair.close.length === 1) {
          appendEntry(this.autoClosingPairsClose2, pair.close, pair);
        }
      }
    }
    let surroundingPairs = CursorConfiguration._getSurroundingPairs(languageIdentifier);
    if (surroundingPairs) {
      for (const pair of surroundingPairs) {
        this.surroundingPairs[pair.open] = pair.close;
      }
    }
  }
  static shouldRecreate(e2) {
    return e2.hasChanged(117) || e2.hasChanged(105) || e2.hasChanged(26) || e2.hasChanged(60) || e2.hasChanged(62) || e2.hasChanged(5) || e2.hasChanged(7) || e2.hasChanged(6) || e2.hasChanged(10) || e2.hasChanged(104) || e2.hasChanged(51) || e2.hasChanged(72);
  }
  get electricChars() {
    if (!this._electricChars) {
      this._electricChars = {};
      let electricChars = CursorConfiguration._getElectricCharacters(this._languageIdentifier);
      if (electricChars) {
        for (const char of electricChars) {
          this._electricChars[char] = true;
        }
      }
    }
    return this._electricChars;
  }
  normalizeIndentation(str) {
    return TextModel.normalizeIndentation(str, this.indentSize, this.insertSpaces);
  }
  static _getElectricCharacters(languageIdentifier) {
    try {
      return LanguageConfigurationRegistry.getElectricCharacters(languageIdentifier.id);
    } catch (e2) {
      onUnexpectedError(e2);
      return null;
    }
  }
  static _getAutoClosingPairs(languageIdentifier) {
    try {
      return LanguageConfigurationRegistry.getAutoClosingPairs(languageIdentifier.id);
    } catch (e2) {
      onUnexpectedError(e2);
      return null;
    }
  }
  static _getShouldAutoClose(languageIdentifier, autoCloseConfig) {
    switch (autoCloseConfig) {
      case "beforeWhitespace":
        return autoCloseBeforeWhitespace;
      case "languageDefined":
        return CursorConfiguration._getLanguageDefinedShouldAutoClose(languageIdentifier);
      case "always":
        return autoCloseAlways;
      case "never":
        return autoCloseNever;
    }
  }
  static _getLanguageDefinedShouldAutoClose(languageIdentifier) {
    try {
      const autoCloseBeforeSet = LanguageConfigurationRegistry.getAutoCloseBeforeSet(languageIdentifier.id);
      return (c3) => autoCloseBeforeSet.indexOf(c3) !== -1;
    } catch (e2) {
      onUnexpectedError(e2);
      return autoCloseNever;
    }
  }
  static _getSurroundingPairs(languageIdentifier) {
    try {
      return LanguageConfigurationRegistry.getSurroundingPairs(languageIdentifier.id);
    } catch (e2) {
      onUnexpectedError(e2);
      return null;
    }
  }
};
var SingleCursorState = class {
  constructor(selectionStart, selectionStartLeftoverVisibleColumns, position2, leftoverVisibleColumns) {
    this.selectionStart = selectionStart;
    this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns;
    this.position = position2;
    this.leftoverVisibleColumns = leftoverVisibleColumns;
    this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position);
  }
  equals(other) {
    return this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns && this.leftoverVisibleColumns === other.leftoverVisibleColumns && this.position.equals(other.position) && this.selectionStart.equalsRange(other.selectionStart);
  }
  hasSelection() {
    return !this.selection.isEmpty() || !this.selectionStart.isEmpty();
  }
  move(inSelectionMode, lineNumber, column, leftoverVisibleColumns) {
    if (inSelectionMode) {
      return new SingleCursorState(this.selectionStart, this.selectionStartLeftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns);
    } else {
      return new SingleCursorState(new Range(lineNumber, column, lineNumber, column), leftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns);
    }
  }
  static _computeSelection(selectionStart, position2) {
    let startLineNumber, startColumn, endLineNumber, endColumn;
    if (selectionStart.isEmpty()) {
      startLineNumber = selectionStart.startLineNumber;
      startColumn = selectionStart.startColumn;
      endLineNumber = position2.lineNumber;
      endColumn = position2.column;
    } else {
      if (position2.isBeforeOrEqual(selectionStart.getStartPosition())) {
        startLineNumber = selectionStart.endLineNumber;
        startColumn = selectionStart.endColumn;
        endLineNumber = position2.lineNumber;
        endColumn = position2.column;
      } else {
        startLineNumber = selectionStart.startLineNumber;
        startColumn = selectionStart.startColumn;
        endLineNumber = position2.lineNumber;
        endColumn = position2.column;
      }
    }
    return new Selection(startLineNumber, startColumn, endLineNumber, endColumn);
  }
};
var CursorContext = class {
  constructor(model, coordinatesConverter, cursorConfig) {
    this.model = model;
    this.coordinatesConverter = coordinatesConverter;
    this.cursorConfig = cursorConfig;
  }
};
var PartialModelCursorState = class {
  constructor(modelState) {
    this.modelState = modelState;
    this.viewState = null;
  }
};
var PartialViewCursorState = class {
  constructor(viewState) {
    this.modelState = null;
    this.viewState = viewState;
  }
};
var CursorState = class {
  constructor(modelState, viewState) {
    this.modelState = modelState;
    this.viewState = viewState;
  }
  static fromModelState(modelState) {
    return new PartialModelCursorState(modelState);
  }
  static fromViewState(viewState) {
    return new PartialViewCursorState(viewState);
  }
  static fromModelSelection(modelSelection) {
    const selectionStartLineNumber = modelSelection.selectionStartLineNumber;
    const selectionStartColumn = modelSelection.selectionStartColumn;
    const positionLineNumber = modelSelection.positionLineNumber;
    const positionColumn = modelSelection.positionColumn;
    const modelState = new SingleCursorState(new Range(selectionStartLineNumber, selectionStartColumn, selectionStartLineNumber, selectionStartColumn), 0, new Position(positionLineNumber, positionColumn), 0);
    return CursorState.fromModelState(modelState);
  }
  static fromModelSelections(modelSelections) {
    let states = [];
    for (let i3 = 0, len2 = modelSelections.length; i3 < len2; i3++) {
      states[i3] = this.fromModelSelection(modelSelections[i3]);
    }
    return states;
  }
  equals(other) {
    return this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState);
  }
};
var EditOperationResult = class {
  constructor(type, commands, opts) {
    this.type = type;
    this.commands = commands;
    this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore;
    this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter;
  }
};
var CursorColumns = class {
  static visibleColumnFromColumn(lineContent, column, tabSize) {
    const lineContentLength = lineContent.length;
    const endOffset = column - 1 < lineContentLength ? column - 1 : lineContentLength;
    let result = 0;
    let i3 = 0;
    while (i3 < endOffset) {
      const codePoint = getNextCodePoint(lineContent, endOffset, i3);
      i3 += codePoint >= 65536 ? 2 : 1;
      if (codePoint === 9) {
        result = CursorColumns.nextRenderTabStop(result, tabSize);
      } else {
        let graphemeBreakType = getGraphemeBreakType(codePoint);
        while (i3 < endOffset) {
          const nextCodePoint = getNextCodePoint(lineContent, endOffset, i3);
          const nextGraphemeBreakType = getGraphemeBreakType(nextCodePoint);
          if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
            break;
          }
          i3 += nextCodePoint >= 65536 ? 2 : 1;
          graphemeBreakType = nextGraphemeBreakType;
        }
        if (isFullWidthCharacter(codePoint) || isEmojiImprecise(codePoint)) {
          result = result + 2;
        } else {
          result = result + 1;
        }
      }
    }
    return result;
  }
  static visibleColumnFromColumn2(config2, model, position2) {
    return this.visibleColumnFromColumn(model.getLineContent(position2.lineNumber), position2.column, config2.tabSize);
  }
  static columnFromVisibleColumn(lineContent, visibleColumn, tabSize) {
    if (visibleColumn <= 0) {
      return 1;
    }
    const lineLength = lineContent.length;
    let beforeVisibleColumn = 0;
    let beforeColumn = 1;
    let i3 = 0;
    while (i3 < lineLength) {
      const codePoint = getNextCodePoint(lineContent, lineLength, i3);
      i3 += codePoint >= 65536 ? 2 : 1;
      let afterVisibleColumn;
      if (codePoint === 9) {
        afterVisibleColumn = CursorColumns.nextRenderTabStop(beforeVisibleColumn, tabSize);
      } else {
        let graphemeBreakType = getGraphemeBreakType(codePoint);
        while (i3 < lineLength) {
          const nextCodePoint = getNextCodePoint(lineContent, lineLength, i3);
          const nextGraphemeBreakType = getGraphemeBreakType(nextCodePoint);
          if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
            break;
          }
          i3 += nextCodePoint >= 65536 ? 2 : 1;
          graphemeBreakType = nextGraphemeBreakType;
        }
        if (isFullWidthCharacter(codePoint) || isEmojiImprecise(codePoint)) {
          afterVisibleColumn = beforeVisibleColumn + 2;
        } else {
          afterVisibleColumn = beforeVisibleColumn + 1;
        }
      }
      const afterColumn = i3 + 1;
      if (afterVisibleColumn >= visibleColumn) {
        const beforeDelta = visibleColumn - beforeVisibleColumn;
        const afterDelta = afterVisibleColumn - visibleColumn;
        if (afterDelta < beforeDelta) {
          return afterColumn;
        } else {
          return beforeColumn;
        }
      }
      beforeVisibleColumn = afterVisibleColumn;
      beforeColumn = afterColumn;
    }
    return lineLength + 1;
  }
  static columnFromVisibleColumn2(config2, model, lineNumber, visibleColumn) {
    let result = this.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, config2.tabSize);
    let minColumn = model.getLineMinColumn(lineNumber);
    if (result < minColumn) {
      return minColumn;
    }
    let maxColumn = model.getLineMaxColumn(lineNumber);
    if (result > maxColumn) {
      return maxColumn;
    }
    return result;
  }
  static nextRenderTabStop(visibleColumn, tabSize) {
    return visibleColumn + tabSize - visibleColumn % tabSize;
  }
  static nextIndentTabStop(visibleColumn, indentSize) {
    return visibleColumn + indentSize - visibleColumn % indentSize;
  }
  static prevRenderTabStop(column, tabSize) {
    return column - 1 - (column - 1) % tabSize;
  }
  static prevIndentTabStop(column, indentSize) {
    return column - 1 - (column - 1) % indentSize;
  }
};
function isQuote(ch2) {
  return ch2 === "'" || ch2 === '"' || ch2 === "`";
}
var PointerHandlerLastRenderData = class {
  constructor(lastViewCursorsRenderData, lastTextareaPosition) {
    this.lastViewCursorsRenderData = lastViewCursorsRenderData;
    this.lastTextareaPosition = lastTextareaPosition;
  }
};
var MouseTarget = class {
  constructor(element, type, mouseColumn = 0, position2 = null, range3 = null, detail = null) {
    this.element = element;
    this.type = type;
    this.mouseColumn = mouseColumn;
    this.position = position2;
    if (!range3 && position2) {
      range3 = new Range(position2.lineNumber, position2.column, position2.lineNumber, position2.column);
    }
    this.range = range3;
    this.detail = detail;
  }
  static _typeToString(type) {
    if (type === 1) {
      return "TEXTAREA";
    }
    if (type === 2) {
      return "GUTTER_GLYPH_MARGIN";
    }
    if (type === 3) {
      return "GUTTER_LINE_NUMBERS";
    }
    if (type === 4) {
      return "GUTTER_LINE_DECORATIONS";
    }
    if (type === 5) {
      return "GUTTER_VIEW_ZONE";
    }
    if (type === 6) {
      return "CONTENT_TEXT";
    }
    if (type === 7) {
      return "CONTENT_EMPTY";
    }
    if (type === 8) {
      return "CONTENT_VIEW_ZONE";
    }
    if (type === 9) {
      return "CONTENT_WIDGET";
    }
    if (type === 10) {
      return "OVERVIEW_RULER";
    }
    if (type === 11) {
      return "SCROLLBAR";
    }
    if (type === 12) {
      return "OVERLAY_WIDGET";
    }
    return "UNKNOWN";
  }
  static toString(target) {
    return this._typeToString(target.type) + ": " + target.position + " - " + target.range + " - " + target.detail;
  }
  toString() {
    return MouseTarget.toString(this);
  }
};
var ElementPath = class {
  static isTextArea(path) {
    return path.length === 2 && path[0] === 3 && path[1] === 6;
  }
  static isChildOfViewLines(path) {
    return path.length >= 4 && path[0] === 3 && path[3] === 7;
  }
  static isStrictChildOfViewLines(path) {
    return path.length > 4 && path[0] === 3 && path[3] === 7;
  }
  static isChildOfScrollableElement(path) {
    return path.length >= 2 && path[0] === 3 && path[1] === 5;
  }
  static isChildOfMinimap(path) {
    return path.length >= 2 && path[0] === 3 && path[1] === 8;
  }
  static isChildOfContentWidgets(path) {
    return path.length >= 4 && path[0] === 3 && path[3] === 1;
  }
  static isChildOfOverflowingContentWidgets(path) {
    return path.length >= 1 && path[0] === 2;
  }
  static isChildOfOverlayWidgets(path) {
    return path.length >= 2 && path[0] === 3 && path[1] === 4;
  }
};
var HitTestContext = class {
  constructor(context2, viewHelper, lastRenderData) {
    this.model = context2.model;
    const options = context2.configuration.options;
    this.layoutInfo = options.get(117);
    this.viewDomNode = viewHelper.viewDomNode;
    this.lineHeight = options.get(51);
    this.typicalHalfwidthCharacterWidth = options.get(36).typicalHalfwidthCharacterWidth;
    this.lastRenderData = lastRenderData;
    this._context = context2;
    this._viewHelper = viewHelper;
  }
  getZoneAtCoord(mouseVerticalOffset) {
    return HitTestContext.getZoneAtCoord(this._context, mouseVerticalOffset);
  }
  static getZoneAtCoord(context2, mouseVerticalOffset) {
    const viewZoneWhitespace = context2.viewLayout.getWhitespaceAtVerticalOffset(mouseVerticalOffset);
    if (viewZoneWhitespace) {
      let viewZoneMiddle = viewZoneWhitespace.verticalOffset + viewZoneWhitespace.height / 2, lineCount = context2.model.getLineCount(), positionBefore = null, position2, positionAfter = null;
      if (viewZoneWhitespace.afterLineNumber !== lineCount) {
        positionAfter = new Position(viewZoneWhitespace.afterLineNumber + 1, 1);
      }
      if (viewZoneWhitespace.afterLineNumber > 0) {
        positionBefore = new Position(viewZoneWhitespace.afterLineNumber, context2.model.getLineMaxColumn(viewZoneWhitespace.afterLineNumber));
      }
      if (positionAfter === null) {
        position2 = positionBefore;
      } else if (positionBefore === null) {
        position2 = positionAfter;
      } else if (mouseVerticalOffset < viewZoneMiddle) {
        position2 = positionBefore;
      } else {
        position2 = positionAfter;
      }
      return {
        viewZoneId: viewZoneWhitespace.id,
        afterLineNumber: viewZoneWhitespace.afterLineNumber,
        positionBefore,
        positionAfter,
        position: position2
      };
    }
    return null;
  }
  getFullLineRangeAtCoord(mouseVerticalOffset) {
    if (this._context.viewLayout.isAfterLines(mouseVerticalOffset)) {
      const lineNumber2 = this._context.model.getLineCount();
      const maxLineColumn2 = this._context.model.getLineMaxColumn(lineNumber2);
      return {
        range: new Range(lineNumber2, maxLineColumn2, lineNumber2, maxLineColumn2),
        isAfterLines: true
      };
    }
    const lineNumber = this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
    const maxLineColumn = this._context.model.getLineMaxColumn(lineNumber);
    return {
      range: new Range(lineNumber, 1, lineNumber, maxLineColumn),
      isAfterLines: false
    };
  }
  getLineNumberAtVerticalOffset(mouseVerticalOffset) {
    return this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
  }
  isAfterLines(mouseVerticalOffset) {
    return this._context.viewLayout.isAfterLines(mouseVerticalOffset);
  }
  getVerticalOffsetForLineNumber(lineNumber) {
    return this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber);
  }
  findAttribute(element, attr2) {
    return HitTestContext._findAttribute(element, attr2, this._viewHelper.viewDomNode);
  }
  static _findAttribute(element, attr2, stopAt) {
    while (element && element !== document.body) {
      if (element.hasAttribute && element.hasAttribute(attr2)) {
        return element.getAttribute(attr2);
      }
      if (element === stopAt) {
        return null;
      }
      element = element.parentNode;
    }
    return null;
  }
  getLineWidth(lineNumber) {
    return this._viewHelper.getLineWidth(lineNumber);
  }
  visibleRangeForPosition(lineNumber, column) {
    return this._viewHelper.visibleRangeForPosition(lineNumber, column);
  }
  getPositionFromDOMInfo(spanNode, offset2) {
    return this._viewHelper.getPositionFromDOMInfo(spanNode, offset2);
  }
  getCurrentScrollTop() {
    return this._context.viewLayout.getCurrentScrollTop();
  }
  getCurrentScrollLeft() {
    return this._context.viewLayout.getCurrentScrollLeft();
  }
};
var BareHitTestRequest = class {
  constructor(ctx, editorPos, pos) {
    this.editorPos = editorPos;
    this.pos = pos;
    this.mouseVerticalOffset = Math.max(0, ctx.getCurrentScrollTop() + pos.y - editorPos.y);
    this.mouseContentHorizontalOffset = ctx.getCurrentScrollLeft() + pos.x - editorPos.x - ctx.layoutInfo.contentLeft;
    this.isInMarginArea = pos.x - editorPos.x < ctx.layoutInfo.contentLeft && pos.x - editorPos.x >= ctx.layoutInfo.glyphMarginLeft;
    this.isInContentArea = !this.isInMarginArea;
    this.mouseColumn = Math.max(0, MouseTargetFactory._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth));
  }
};
var HitTestRequest = class extends BareHitTestRequest {
  constructor(ctx, editorPos, pos, target) {
    super(ctx, editorPos, pos);
    this._ctx = ctx;
    if (target) {
      this.target = target;
      this.targetPath = PartFingerprints.collect(target, ctx.viewDomNode);
    } else {
      this.target = null;
      this.targetPath = new Uint8Array(0);
    }
  }
  toString() {
    return `pos(${this.pos.x},${this.pos.y}), editorPos(${this.editorPos.x},${this.editorPos.y}), mouseVerticalOffset: ${this.mouseVerticalOffset}, mouseContentHorizontalOffset: ${this.mouseContentHorizontalOffset}
	target: ${this.target ? this.target.outerHTML : null}`;
  }
  fulfill(type, position2 = null, range3 = null, detail = null) {
    let mouseColumn = this.mouseColumn;
    if (position2 && position2.column < this._ctx.model.getLineMaxColumn(position2.lineNumber)) {
      mouseColumn = CursorColumns.visibleColumnFromColumn(this._ctx.model.getLineContent(position2.lineNumber), position2.column, this._ctx.model.getTextModelOptions().tabSize) + 1;
    }
    return new MouseTarget(this.target, type, mouseColumn, position2, range3, detail);
  }
  withTarget(target) {
    return new HitTestRequest(this._ctx, this.editorPos, this.pos, target);
  }
};
var EMPTY_CONTENT_AFTER_LINES = {isAfterLines: true};
function createEmptyContentDataInLines(horizontalDistanceToText) {
  return {
    isAfterLines: false,
    horizontalDistanceToText
  };
}
var MouseTargetFactory = class {
  constructor(context2, viewHelper) {
    this._context = context2;
    this._viewHelper = viewHelper;
  }
  mouseTargetIsWidget(e2) {
    const t5 = e2.target;
    const path = PartFingerprints.collect(t5, this._viewHelper.viewDomNode);
    if (ElementPath.isChildOfContentWidgets(path) || ElementPath.isChildOfOverflowingContentWidgets(path)) {
      return true;
    }
    if (ElementPath.isChildOfOverlayWidgets(path)) {
      return true;
    }
    return false;
  }
  createMouseTarget(lastRenderData, editorPos, pos, target) {
    const ctx = new HitTestContext(this._context, this._viewHelper, lastRenderData);
    const request2 = new HitTestRequest(ctx, editorPos, pos, target);
    try {
      const r3 = MouseTargetFactory._createMouseTarget(ctx, request2, false);
      return r3;
    } catch (err) {
      return request2.fulfill(0);
    }
  }
  static _createMouseTarget(ctx, request2, domHitTestExecuted) {
    if (request2.target === null) {
      if (domHitTestExecuted) {
        return request2.fulfill(0);
      }
      const hitTestResult = MouseTargetFactory._doHitTest(ctx, request2);
      if (hitTestResult.position) {
        return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request2, hitTestResult.position.lineNumber, hitTestResult.position.column);
      }
      return this._createMouseTarget(ctx, request2.withTarget(hitTestResult.hitTarget), true);
    }
    const resolvedRequest = request2;
    let result = null;
    result = result || MouseTargetFactory._hitTestContentWidget(ctx, resolvedRequest);
    result = result || MouseTargetFactory._hitTestOverlayWidget(ctx, resolvedRequest);
    result = result || MouseTargetFactory._hitTestMinimap(ctx, resolvedRequest);
    result = result || MouseTargetFactory._hitTestScrollbarSlider(ctx, resolvedRequest);
    result = result || MouseTargetFactory._hitTestViewZone(ctx, resolvedRequest);
    result = result || MouseTargetFactory._hitTestMargin(ctx, resolvedRequest);
    result = result || MouseTargetFactory._hitTestViewCursor(ctx, resolvedRequest);
    result = result || MouseTargetFactory._hitTestTextArea(ctx, resolvedRequest);
    result = result || MouseTargetFactory._hitTestViewLines(ctx, resolvedRequest, domHitTestExecuted);
    result = result || MouseTargetFactory._hitTestScrollbar(ctx, resolvedRequest);
    return result || request2.fulfill(0);
  }
  static _hitTestContentWidget(ctx, request2) {
    if (ElementPath.isChildOfContentWidgets(request2.targetPath) || ElementPath.isChildOfOverflowingContentWidgets(request2.targetPath)) {
      const widgetId = ctx.findAttribute(request2.target, "widgetId");
      if (widgetId) {
        return request2.fulfill(9, null, null, widgetId);
      } else {
        return request2.fulfill(0);
      }
    }
    return null;
  }
  static _hitTestOverlayWidget(ctx, request2) {
    if (ElementPath.isChildOfOverlayWidgets(request2.targetPath)) {
      const widgetId = ctx.findAttribute(request2.target, "widgetId");
      if (widgetId) {
        return request2.fulfill(12, null, null, widgetId);
      } else {
        return request2.fulfill(0);
      }
    }
    return null;
  }
  static _hitTestViewCursor(ctx, request2) {
    if (request2.target) {
      const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData;
      for (const d2 of lastViewCursorsRenderData) {
        if (request2.target === d2.domNode) {
          return request2.fulfill(6, d2.position);
        }
      }
    }
    if (request2.isInContentArea) {
      const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData;
      const mouseContentHorizontalOffset = request2.mouseContentHorizontalOffset;
      const mouseVerticalOffset = request2.mouseVerticalOffset;
      for (const d2 of lastViewCursorsRenderData) {
        if (mouseContentHorizontalOffset < d2.contentLeft) {
          continue;
        }
        if (mouseContentHorizontalOffset > d2.contentLeft + d2.width) {
          continue;
        }
        const cursorVerticalOffset = ctx.getVerticalOffsetForLineNumber(d2.position.lineNumber);
        if (cursorVerticalOffset <= mouseVerticalOffset && mouseVerticalOffset <= cursorVerticalOffset + d2.height) {
          return request2.fulfill(6, d2.position);
        }
      }
    }
    return null;
  }
  static _hitTestViewZone(ctx, request2) {
    const viewZoneData = ctx.getZoneAtCoord(request2.mouseVerticalOffset);
    if (viewZoneData) {
      const mouseTargetType = request2.isInContentArea ? 8 : 5;
      return request2.fulfill(mouseTargetType, viewZoneData.position, null, viewZoneData);
    }
    return null;
  }
  static _hitTestTextArea(ctx, request2) {
    if (ElementPath.isTextArea(request2.targetPath)) {
      if (ctx.lastRenderData.lastTextareaPosition) {
        return request2.fulfill(6, ctx.lastRenderData.lastTextareaPosition);
      }
      return request2.fulfill(1, ctx.lastRenderData.lastTextareaPosition);
    }
    return null;
  }
  static _hitTestMargin(ctx, request2) {
    if (request2.isInMarginArea) {
      const res = ctx.getFullLineRangeAtCoord(request2.mouseVerticalOffset);
      const pos = res.range.getStartPosition();
      let offset2 = Math.abs(request2.pos.x - request2.editorPos.x);
      const detail = {
        isAfterLines: res.isAfterLines,
        glyphMarginLeft: ctx.layoutInfo.glyphMarginLeft,
        glyphMarginWidth: ctx.layoutInfo.glyphMarginWidth,
        lineNumbersWidth: ctx.layoutInfo.lineNumbersWidth,
        offsetX: offset2
      };
      offset2 -= ctx.layoutInfo.glyphMarginLeft;
      if (offset2 <= ctx.layoutInfo.glyphMarginWidth) {
        return request2.fulfill(2, pos, res.range, detail);
      }
      offset2 -= ctx.layoutInfo.glyphMarginWidth;
      if (offset2 <= ctx.layoutInfo.lineNumbersWidth) {
        return request2.fulfill(3, pos, res.range, detail);
      }
      offset2 -= ctx.layoutInfo.lineNumbersWidth;
      return request2.fulfill(4, pos, res.range, detail);
    }
    return null;
  }
  static _hitTestViewLines(ctx, request2, domHitTestExecuted) {
    if (!ElementPath.isChildOfViewLines(request2.targetPath)) {
      return null;
    }
    if (ctx.isAfterLines(request2.mouseVerticalOffset)) {
      const lineCount = ctx.model.getLineCount();
      const maxLineColumn = ctx.model.getLineMaxColumn(lineCount);
      return request2.fulfill(7, new Position(lineCount, maxLineColumn), void 0, EMPTY_CONTENT_AFTER_LINES);
    }
    if (domHitTestExecuted) {
      if (ElementPath.isStrictChildOfViewLines(request2.targetPath)) {
        const lineNumber = ctx.getLineNumberAtVerticalOffset(request2.mouseVerticalOffset);
        if (ctx.model.getLineLength(lineNumber) === 0) {
          const lineWidth2 = ctx.getLineWidth(lineNumber);
          const detail = createEmptyContentDataInLines(request2.mouseContentHorizontalOffset - lineWidth2);
          return request2.fulfill(7, new Position(lineNumber, 1), void 0, detail);
        }
        const lineWidth = ctx.getLineWidth(lineNumber);
        if (request2.mouseContentHorizontalOffset >= lineWidth) {
          const detail = createEmptyContentDataInLines(request2.mouseContentHorizontalOffset - lineWidth);
          const pos = new Position(lineNumber, ctx.model.getLineMaxColumn(lineNumber));
          return request2.fulfill(7, pos, void 0, detail);
        }
      }
      return request2.fulfill(0);
    }
    const hitTestResult = MouseTargetFactory._doHitTest(ctx, request2);
    if (hitTestResult.position) {
      return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request2, hitTestResult.position.lineNumber, hitTestResult.position.column);
    }
    return this._createMouseTarget(ctx, request2.withTarget(hitTestResult.hitTarget), true);
  }
  static _hitTestMinimap(ctx, request2) {
    if (ElementPath.isChildOfMinimap(request2.targetPath)) {
      const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request2.mouseVerticalOffset);
      const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber);
      return request2.fulfill(11, new Position(possibleLineNumber, maxColumn));
    }
    return null;
  }
  static _hitTestScrollbarSlider(ctx, request2) {
    if (ElementPath.isChildOfScrollableElement(request2.targetPath)) {
      if (request2.target && request2.target.nodeType === 1) {
        const className = request2.target.className;
        if (className && /\b(slider|scrollbar)\b/.test(className)) {
          const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request2.mouseVerticalOffset);
          const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber);
          return request2.fulfill(11, new Position(possibleLineNumber, maxColumn));
        }
      }
    }
    return null;
  }
  static _hitTestScrollbar(ctx, request2) {
    if (ElementPath.isChildOfScrollableElement(request2.targetPath)) {
      const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request2.mouseVerticalOffset);
      const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber);
      return request2.fulfill(11, new Position(possibleLineNumber, maxColumn));
    }
    return null;
  }
  getMouseColumn(editorPos, pos) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    const mouseContentHorizontalOffset = this._context.viewLayout.getCurrentScrollLeft() + pos.x - editorPos.x - layoutInfo.contentLeft;
    return MouseTargetFactory._getMouseColumn(mouseContentHorizontalOffset, options.get(36).typicalHalfwidthCharacterWidth);
  }
  static _getMouseColumn(mouseContentHorizontalOffset, typicalHalfwidthCharacterWidth) {
    if (mouseContentHorizontalOffset < 0) {
      return 1;
    }
    const chars2 = Math.round(mouseContentHorizontalOffset / typicalHalfwidthCharacterWidth);
    return chars2 + 1;
  }
  static createMouseTargetFromHitTestPosition(ctx, request2, lineNumber, column) {
    const pos = new Position(lineNumber, column);
    const lineWidth = ctx.getLineWidth(lineNumber);
    if (request2.mouseContentHorizontalOffset > lineWidth) {
      if (isEdge2 && pos.column === 1) {
        const detail2 = createEmptyContentDataInLines(request2.mouseContentHorizontalOffset - lineWidth);
        return request2.fulfill(7, new Position(lineNumber, ctx.model.getLineMaxColumn(lineNumber)), void 0, detail2);
      }
      const detail = createEmptyContentDataInLines(request2.mouseContentHorizontalOffset - lineWidth);
      return request2.fulfill(7, pos, void 0, detail);
    }
    const visibleRange = ctx.visibleRangeForPosition(lineNumber, column);
    if (!visibleRange) {
      return request2.fulfill(0, pos);
    }
    const columnHorizontalOffset = visibleRange.left;
    if (request2.mouseContentHorizontalOffset === columnHorizontalOffset) {
      return request2.fulfill(6, pos);
    }
    const points = [];
    points.push({offset: visibleRange.left, column});
    if (column > 1) {
      const visibleRange2 = ctx.visibleRangeForPosition(lineNumber, column - 1);
      if (visibleRange2) {
        points.push({offset: visibleRange2.left, column: column - 1});
      }
    }
    const lineMaxColumn = ctx.model.getLineMaxColumn(lineNumber);
    if (column < lineMaxColumn) {
      const visibleRange2 = ctx.visibleRangeForPosition(lineNumber, column + 1);
      if (visibleRange2) {
        points.push({offset: visibleRange2.left, column: column + 1});
      }
    }
    points.sort((a2, b2) => a2.offset - b2.offset);
    for (let i3 = 1; i3 < points.length; i3++) {
      const prev = points[i3 - 1];
      const curr = points[i3];
      if (prev.offset <= request2.mouseContentHorizontalOffset && request2.mouseContentHorizontalOffset <= curr.offset) {
        const rng = new Range(lineNumber, prev.column, lineNumber, curr.column);
        return request2.fulfill(6, pos, rng);
      }
    }
    return request2.fulfill(6, pos);
  }
  static _doHitTestWithCaretRangeFromPoint(ctx, request2) {
    const lineNumber = ctx.getLineNumberAtVerticalOffset(request2.mouseVerticalOffset);
    const lineVerticalOffset = ctx.getVerticalOffsetForLineNumber(lineNumber);
    const lineCenteredVerticalOffset = lineVerticalOffset + Math.floor(ctx.lineHeight / 2);
    let adjustedPageY = request2.pos.y + (lineCenteredVerticalOffset - request2.mouseVerticalOffset);
    if (adjustedPageY <= request2.editorPos.y) {
      adjustedPageY = request2.editorPos.y + 1;
    }
    if (adjustedPageY >= request2.editorPos.y + ctx.layoutInfo.height) {
      adjustedPageY = request2.editorPos.y + ctx.layoutInfo.height - 1;
    }
    const adjustedPage = new PageCoordinates(request2.pos.x, adjustedPageY);
    const r3 = this._actualDoHitTestWithCaretRangeFromPoint(ctx, adjustedPage.toClientCoordinates());
    if (r3.position) {
      return r3;
    }
    return this._actualDoHitTestWithCaretRangeFromPoint(ctx, request2.pos.toClientCoordinates());
  }
  static _actualDoHitTestWithCaretRangeFromPoint(ctx, coords) {
    const shadowRoot = getShadowRoot(ctx.viewDomNode);
    let range3;
    if (shadowRoot) {
      if (typeof shadowRoot.caretRangeFromPoint === "undefined") {
        range3 = shadowCaretRangeFromPoint(shadowRoot, coords.clientX, coords.clientY);
      } else {
        range3 = shadowRoot.caretRangeFromPoint(coords.clientX, coords.clientY);
      }
    } else {
      range3 = document.caretRangeFromPoint(coords.clientX, coords.clientY);
    }
    if (!range3 || !range3.startContainer) {
      return {
        position: null,
        hitTarget: null
      };
    }
    const startContainer = range3.startContainer;
    let hitTarget = null;
    if (startContainer.nodeType === startContainer.TEXT_NODE) {
      const parent1 = startContainer.parentNode;
      const parent2 = parent1 ? parent1.parentNode : null;
      const parent3 = parent2 ? parent2.parentNode : null;
      const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
      if (parent3ClassName === ViewLine.CLASS_NAME) {
        const p2 = ctx.getPositionFromDOMInfo(parent1, range3.startOffset);
        return {
          position: p2,
          hitTarget: null
        };
      } else {
        hitTarget = startContainer.parentNode;
      }
    } else if (startContainer.nodeType === startContainer.ELEMENT_NODE) {
      const parent1 = startContainer.parentNode;
      const parent2 = parent1 ? parent1.parentNode : null;
      const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null;
      if (parent2ClassName === ViewLine.CLASS_NAME) {
        const p2 = ctx.getPositionFromDOMInfo(startContainer, startContainer.textContent.length);
        return {
          position: p2,
          hitTarget: null
        };
      } else {
        hitTarget = startContainer;
      }
    }
    return {
      position: null,
      hitTarget
    };
  }
  static _doHitTestWithCaretPositionFromPoint(ctx, coords) {
    const hitResult = document.caretPositionFromPoint(coords.clientX, coords.clientY);
    if (hitResult.offsetNode.nodeType === hitResult.offsetNode.TEXT_NODE) {
      const parent1 = hitResult.offsetNode.parentNode;
      const parent2 = parent1 ? parent1.parentNode : null;
      const parent3 = parent2 ? parent2.parentNode : null;
      const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
      if (parent3ClassName === ViewLine.CLASS_NAME) {
        const p2 = ctx.getPositionFromDOMInfo(hitResult.offsetNode.parentNode, hitResult.offset);
        return {
          position: p2,
          hitTarget: null
        };
      } else {
        return {
          position: null,
          hitTarget: hitResult.offsetNode.parentNode
        };
      }
    }
    if (hitResult.offsetNode.nodeType === hitResult.offsetNode.ELEMENT_NODE) {
      const parent1 = hitResult.offsetNode.parentNode;
      const parent1ClassName = parent1 && parent1.nodeType === parent1.ELEMENT_NODE ? parent1.className : null;
      if (parent1ClassName === ViewLine.CLASS_NAME) {
        const tokenSpan = hitResult.offsetNode.childNodes[Math.min(hitResult.offset, hitResult.offsetNode.childNodes.length - 1)];
        if (tokenSpan) {
          const p2 = ctx.getPositionFromDOMInfo(tokenSpan, 0);
          return {
            position: p2,
            hitTarget: null
          };
        }
      }
    }
    return {
      position: null,
      hitTarget: hitResult.offsetNode
    };
  }
  static _doHitTestWithMoveToPoint(ctx, coords) {
    let resultPosition = null;
    let resultHitTarget = null;
    const textRange = document.body.createTextRange();
    try {
      textRange.moveToPoint(coords.clientX, coords.clientY);
    } catch (err) {
      return {
        position: null,
        hitTarget: null
      };
    }
    textRange.collapse(true);
    const parentElement = textRange ? textRange.parentElement() : null;
    const parent1 = parentElement ? parentElement.parentNode : null;
    const parent2 = parent1 ? parent1.parentNode : null;
    const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : "";
    if (parent2ClassName === ViewLine.CLASS_NAME) {
      const rangeToContainEntireSpan = textRange.duplicate();
      rangeToContainEntireSpan.moveToElementText(parentElement);
      rangeToContainEntireSpan.setEndPoint("EndToStart", textRange);
      resultPosition = ctx.getPositionFromDOMInfo(parentElement, rangeToContainEntireSpan.text.length);
      rangeToContainEntireSpan.moveToElementText(ctx.viewDomNode);
    } else {
      resultHitTarget = parentElement;
    }
    textRange.moveToElementText(ctx.viewDomNode);
    return {
      position: resultPosition,
      hitTarget: resultHitTarget
    };
  }
  static _doHitTest(ctx, request2) {
    if (typeof document.caretRangeFromPoint === "function") {
      return this._doHitTestWithCaretRangeFromPoint(ctx, request2);
    } else if (document.caretPositionFromPoint) {
      return this._doHitTestWithCaretPositionFromPoint(ctx, request2.pos.toClientCoordinates());
    } else if (document.body.createTextRange) {
      return this._doHitTestWithMoveToPoint(ctx, request2.pos.toClientCoordinates());
    }
    return {
      position: null,
      hitTarget: null
    };
  }
};
function shadowCaretRangeFromPoint(shadowRoot, x2, y3) {
  const range3 = document.createRange();
  let el = shadowRoot.elementFromPoint(x2, y3);
  if (el !== null) {
    while (el && el.firstChild && el.firstChild.nodeType !== el.firstChild.TEXT_NODE) {
      el = el.lastChild;
    }
    const rect = el.getBoundingClientRect();
    const font = window.getComputedStyle(el, null).getPropertyValue("font");
    const text = el.innerText;
    let pixelCursor = rect.left;
    let offset2 = 0;
    let step;
    if (x2 > rect.left + rect.width) {
      offset2 = text.length;
    } else {
      const charWidthReader = CharWidthReader.getInstance();
      for (let i3 = 0; i3 < text.length + 1; i3++) {
        step = charWidthReader.getCharWidth(text.charAt(i3), font) / 2;
        pixelCursor += step;
        if (x2 < pixelCursor) {
          offset2 = i3;
          break;
        }
        pixelCursor += step;
      }
    }
    range3.setStart(el.firstChild, offset2);
    range3.setEnd(el.firstChild, offset2);
  }
  return range3;
}
var CharWidthReader = class {
  constructor() {
    this._cache = {};
    this._canvas = document.createElement("canvas");
  }
  static getInstance() {
    if (!CharWidthReader._INSTANCE) {
      CharWidthReader._INSTANCE = new CharWidthReader();
    }
    return CharWidthReader._INSTANCE;
  }
  getCharWidth(char, font) {
    const cacheKey = char + font;
    if (this._cache[cacheKey]) {
      return this._cache[cacheKey];
    }
    const context2 = this._canvas.getContext("2d");
    context2.font = font;
    const metrics = context2.measureText(char);
    const width2 = metrics.width;
    this._cache[cacheKey] = width2;
    return width2;
  }
};
CharWidthReader._INSTANCE = null;
function createMouseMoveEventMerger(mouseTargetFactory) {
  return function(lastEvent, currentEvent) {
    let targetIsWidget = false;
    if (mouseTargetFactory) {
      targetIsWidget = mouseTargetFactory.mouseTargetIsWidget(currentEvent);
    }
    if (!targetIsWidget) {
      currentEvent.preventDefault();
    }
    return currentEvent;
  };
}
var MouseHandler = class extends ViewEventHandler {
  constructor(context2, viewController, viewHelper) {
    super();
    this._context = context2;
    this.viewController = viewController;
    this.viewHelper = viewHelper;
    this.mouseTargetFactory = new MouseTargetFactory(this._context, viewHelper);
    this._mouseDownOperation = this._register(new MouseDownOperation(this._context, this.viewController, this.viewHelper, (e2, testEventTarget) => this._createMouseTarget(e2, testEventTarget), (e2) => this._getMouseColumn(e2)));
    this.lastMouseLeaveTime = -1;
    const mouseEvents = new EditorMouseEventFactory(this.viewHelper.viewDomNode);
    this._register(mouseEvents.onContextMenu(this.viewHelper.viewDomNode, (e2) => this._onContextMenu(e2, true)));
    this._register(mouseEvents.onMouseMoveThrottled(this.viewHelper.viewDomNode, (e2) => this._onMouseMove(e2), createMouseMoveEventMerger(this.mouseTargetFactory), MouseHandler.MOUSE_MOVE_MINIMUM_TIME));
    this._register(mouseEvents.onMouseUp(this.viewHelper.viewDomNode, (e2) => this._onMouseUp(e2)));
    this._register(mouseEvents.onMouseLeave(this.viewHelper.viewDomNode, (e2) => this._onMouseLeave(e2)));
    this._register(mouseEvents.onMouseDown(this.viewHelper.viewDomNode, (e2) => this._onMouseDown(e2)));
    const onMouseWheel = (browserEvent) => {
      this.viewController.emitMouseWheel(browserEvent);
      if (!this._context.configuration.options.get(59)) {
        return;
      }
      const e2 = new StandardWheelEvent(browserEvent);
      if (e2.browserEvent.ctrlKey || e2.browserEvent.metaKey) {
        const zoomLevel = EditorZoom.getZoomLevel();
        const delta = e2.deltaY > 0 ? 1 : -1;
        EditorZoom.setZoomLevel(zoomLevel + delta);
        e2.preventDefault();
        e2.stopPropagation();
      }
    };
    this._register(addDisposableListener(this.viewHelper.viewDomNode, EventType.MOUSE_WHEEL, onMouseWheel, {capture: true, passive: false}));
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    super.dispose();
  }
  onCursorStateChanged(e2) {
    this._mouseDownOperation.onCursorStateChanged(e2);
    return false;
  }
  onFocusChanged(e2) {
    return false;
  }
  onScrollChanged(e2) {
    this._mouseDownOperation.onScrollChanged();
    return false;
  }
  getTargetAtClientPoint(clientX, clientY) {
    const clientPos = new ClientCoordinates(clientX, clientY);
    const pos = clientPos.toPageCoordinates();
    const editorPos = createEditorPagePosition(this.viewHelper.viewDomNode);
    if (pos.y < editorPos.y || pos.y > editorPos.y + editorPos.height || pos.x < editorPos.x || pos.x > editorPos.x + editorPos.width) {
      return null;
    }
    return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), editorPos, pos, null);
  }
  _createMouseTarget(e2, testEventTarget) {
    return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), e2.editorPos, e2.pos, testEventTarget ? e2.target : null);
  }
  _getMouseColumn(e2) {
    return this.mouseTargetFactory.getMouseColumn(e2.editorPos, e2.pos);
  }
  _onContextMenu(e2, testEventTarget) {
    this.viewController.emitContextMenu({
      event: e2,
      target: this._createMouseTarget(e2, testEventTarget)
    });
  }
  _onMouseMove(e2) {
    if (this._mouseDownOperation.isActive()) {
      return;
    }
    const actualMouseMoveTime = e2.timestamp;
    if (actualMouseMoveTime < this.lastMouseLeaveTime) {
      return;
    }
    this.viewController.emitMouseMove({
      event: e2,
      target: this._createMouseTarget(e2, true)
    });
  }
  _onMouseLeave(e2) {
    this.lastMouseLeaveTime = new Date().getTime();
    this.viewController.emitMouseLeave({
      event: e2,
      target: null
    });
  }
  _onMouseUp(e2) {
    this.viewController.emitMouseUp({
      event: e2,
      target: this._createMouseTarget(e2, true)
    });
  }
  _onMouseDown(e2) {
    const t5 = this._createMouseTarget(e2, true);
    const targetIsContent = t5.type === 6 || t5.type === 7;
    const targetIsGutter = t5.type === 2 || t5.type === 3 || t5.type === 4;
    const targetIsLineNumbers = t5.type === 3;
    const selectOnLineNumbers = this._context.configuration.options.get(90);
    const targetIsViewZone = t5.type === 8 || t5.type === 5;
    const targetIsWidget = t5.type === 9;
    let shouldHandle = e2.leftButton || e2.middleButton;
    if (isMacintosh && e2.leftButton && e2.ctrlKey) {
      shouldHandle = false;
    }
    const focus = () => {
      e2.preventDefault();
      this.viewHelper.focusTextArea();
    };
    if (shouldHandle && (targetIsContent || targetIsLineNumbers && selectOnLineNumbers)) {
      focus();
      this._mouseDownOperation.start(t5.type, e2);
    } else if (targetIsGutter) {
      e2.preventDefault();
    } else if (targetIsViewZone) {
      const viewZoneData = t5.detail;
      if (this.viewHelper.shouldSuppressMouseDownOnViewZone(viewZoneData.viewZoneId)) {
        focus();
        this._mouseDownOperation.start(t5.type, e2);
        e2.preventDefault();
      }
    } else if (targetIsWidget && this.viewHelper.shouldSuppressMouseDownOnWidget(t5.detail)) {
      focus();
      e2.preventDefault();
    }
    this.viewController.emitMouseDown({
      event: e2,
      target: t5
    });
  }
};
MouseHandler.MOUSE_MOVE_MINIMUM_TIME = 100;
var MouseDownOperation = class extends Disposable {
  constructor(context2, viewController, viewHelper, createMouseTarget, getMouseColumn) {
    super();
    this._context = context2;
    this._viewController = viewController;
    this._viewHelper = viewHelper;
    this._createMouseTarget = createMouseTarget;
    this._getMouseColumn = getMouseColumn;
    this._mouseMoveMonitor = this._register(new GlobalEditorMouseMoveMonitor(this._viewHelper.viewDomNode));
    this._onScrollTimeout = this._register(new TimeoutTimer());
    this._mouseState = new MouseDownState();
    this._currentSelection = new Selection(1, 1, 1, 1);
    this._isActive = false;
    this._lastMouseEvent = null;
  }
  dispose() {
    super.dispose();
  }
  isActive() {
    return this._isActive;
  }
  _onMouseDownThenMove(e2) {
    this._lastMouseEvent = e2;
    this._mouseState.setModifiers(e2);
    const position2 = this._findMousePosition(e2, true);
    if (!position2) {
      return;
    }
    if (this._mouseState.isDragAndDrop) {
      this._viewController.emitMouseDrag({
        event: e2,
        target: position2
      });
    } else {
      this._dispatchMouse(position2, true);
    }
  }
  start(targetType, e2) {
    this._lastMouseEvent = e2;
    this._mouseState.setStartedOnLineNumbers(targetType === 3);
    this._mouseState.setStartButtons(e2);
    this._mouseState.setModifiers(e2);
    const position2 = this._findMousePosition(e2, true);
    if (!position2 || !position2.position) {
      return;
    }
    this._mouseState.trySetCount(e2.detail, position2.position);
    e2.detail = this._mouseState.count;
    const options = this._context.configuration.options;
    if (!options.get(72) && options.get(25) && !options.get(13) && !this._mouseState.altKey && e2.detail < 2 && !this._isActive && !this._currentSelection.isEmpty() && position2.type === 6 && position2.position && this._currentSelection.containsPosition(position2.position)) {
      this._mouseState.isDragAndDrop = true;
      this._isActive = true;
      this._mouseMoveMonitor.startMonitoring(e2.target, e2.buttons, createMouseMoveEventMerger(null), (e3) => this._onMouseDownThenMove(e3), () => {
        const position3 = this._findMousePosition(this._lastMouseEvent, true);
        this._viewController.emitMouseDrop({
          event: this._lastMouseEvent,
          target: position3 ? this._createMouseTarget(this._lastMouseEvent, true) : null
        });
        this._stop();
      });
      return;
    }
    this._mouseState.isDragAndDrop = false;
    this._dispatchMouse(position2, e2.shiftKey);
    if (!this._isActive) {
      this._isActive = true;
      this._mouseMoveMonitor.startMonitoring(e2.target, e2.buttons, createMouseMoveEventMerger(null), (e3) => this._onMouseDownThenMove(e3), () => this._stop());
    }
  }
  _stop() {
    this._isActive = false;
    this._onScrollTimeout.cancel();
  }
  onScrollChanged() {
    if (!this._isActive) {
      return;
    }
    this._onScrollTimeout.setIfNotSet(() => {
      if (!this._lastMouseEvent) {
        return;
      }
      const position2 = this._findMousePosition(this._lastMouseEvent, false);
      if (!position2) {
        return;
      }
      if (this._mouseState.isDragAndDrop) {
        return;
      }
      this._dispatchMouse(position2, true);
    }, 10);
  }
  onCursorStateChanged(e2) {
    this._currentSelection = e2.selections[0];
  }
  _getPositionOutsideEditor(e2) {
    const editorContent = e2.editorPos;
    const model = this._context.model;
    const viewLayout = this._context.viewLayout;
    const mouseColumn = this._getMouseColumn(e2);
    if (e2.posy < editorContent.y) {
      const verticalOffset = Math.max(viewLayout.getCurrentScrollTop() - (editorContent.y - e2.posy), 0);
      const viewZoneData = HitTestContext.getZoneAtCoord(this._context, verticalOffset);
      if (viewZoneData) {
        const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
        if (newPosition) {
          return new MouseTarget(null, 13, mouseColumn, newPosition);
        }
      }
      const aboveLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
      return new MouseTarget(null, 13, mouseColumn, new Position(aboveLineNumber, 1));
    }
    if (e2.posy > editorContent.y + editorContent.height) {
      const verticalOffset = viewLayout.getCurrentScrollTop() + (e2.posy - editorContent.y);
      const viewZoneData = HitTestContext.getZoneAtCoord(this._context, verticalOffset);
      if (viewZoneData) {
        const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
        if (newPosition) {
          return new MouseTarget(null, 13, mouseColumn, newPosition);
        }
      }
      const belowLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
      return new MouseTarget(null, 13, mouseColumn, new Position(belowLineNumber, model.getLineMaxColumn(belowLineNumber)));
    }
    const possibleLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getCurrentScrollTop() + (e2.posy - editorContent.y));
    if (e2.posx < editorContent.x) {
      return new MouseTarget(null, 13, mouseColumn, new Position(possibleLineNumber, 1));
    }
    if (e2.posx > editorContent.x + editorContent.width) {
      return new MouseTarget(null, 13, mouseColumn, new Position(possibleLineNumber, model.getLineMaxColumn(possibleLineNumber)));
    }
    return null;
  }
  _findMousePosition(e2, testEventTarget) {
    const positionOutsideEditor = this._getPositionOutsideEditor(e2);
    if (positionOutsideEditor) {
      return positionOutsideEditor;
    }
    const t5 = this._createMouseTarget(e2, testEventTarget);
    const hintedPosition = t5.position;
    if (!hintedPosition) {
      return null;
    }
    if (t5.type === 8 || t5.type === 5) {
      const newPosition = this._helpPositionJumpOverViewZone(t5.detail);
      if (newPosition) {
        return new MouseTarget(t5.element, t5.type, t5.mouseColumn, newPosition, null, t5.detail);
      }
    }
    return t5;
  }
  _helpPositionJumpOverViewZone(viewZoneData) {
    const selectionStart = new Position(this._currentSelection.selectionStartLineNumber, this._currentSelection.selectionStartColumn);
    const positionBefore = viewZoneData.positionBefore;
    const positionAfter = viewZoneData.positionAfter;
    if (positionBefore && positionAfter) {
      if (positionBefore.isBefore(selectionStart)) {
        return positionBefore;
      } else {
        return positionAfter;
      }
    }
    return null;
  }
  _dispatchMouse(position2, inSelectionMode) {
    if (!position2.position) {
      return;
    }
    this._viewController.dispatchMouse({
      position: position2.position,
      mouseColumn: position2.mouseColumn,
      startedOnLineNumbers: this._mouseState.startedOnLineNumbers,
      inSelectionMode,
      mouseDownCount: this._mouseState.count,
      altKey: this._mouseState.altKey,
      ctrlKey: this._mouseState.ctrlKey,
      metaKey: this._mouseState.metaKey,
      shiftKey: this._mouseState.shiftKey,
      leftButton: this._mouseState.leftButton,
      middleButton: this._mouseState.middleButton
    });
  }
};
var MouseDownState = class {
  constructor() {
    this._altKey = false;
    this._ctrlKey = false;
    this._metaKey = false;
    this._shiftKey = false;
    this._leftButton = false;
    this._middleButton = false;
    this._startedOnLineNumbers = false;
    this._lastMouseDownPosition = null;
    this._lastMouseDownPositionEqualCount = 0;
    this._lastMouseDownCount = 0;
    this._lastSetMouseDownCountTime = 0;
    this.isDragAndDrop = false;
  }
  get altKey() {
    return this._altKey;
  }
  get ctrlKey() {
    return this._ctrlKey;
  }
  get metaKey() {
    return this._metaKey;
  }
  get shiftKey() {
    return this._shiftKey;
  }
  get leftButton() {
    return this._leftButton;
  }
  get middleButton() {
    return this._middleButton;
  }
  get startedOnLineNumbers() {
    return this._startedOnLineNumbers;
  }
  get count() {
    return this._lastMouseDownCount;
  }
  setModifiers(source2) {
    this._altKey = source2.altKey;
    this._ctrlKey = source2.ctrlKey;
    this._metaKey = source2.metaKey;
    this._shiftKey = source2.shiftKey;
  }
  setStartButtons(source2) {
    this._leftButton = source2.leftButton;
    this._middleButton = source2.middleButton;
  }
  setStartedOnLineNumbers(startedOnLineNumbers) {
    this._startedOnLineNumbers = startedOnLineNumbers;
  }
  trySetCount(setMouseDownCount, newMouseDownPosition) {
    const currentTime = new Date().getTime();
    if (currentTime - this._lastSetMouseDownCountTime > MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME) {
      setMouseDownCount = 1;
    }
    this._lastSetMouseDownCountTime = currentTime;
    if (setMouseDownCount > this._lastMouseDownCount + 1) {
      setMouseDownCount = this._lastMouseDownCount + 1;
    }
    if (this._lastMouseDownPosition && this._lastMouseDownPosition.equals(newMouseDownPosition)) {
      this._lastMouseDownPositionEqualCount++;
    } else {
      this._lastMouseDownPositionEqualCount = 1;
    }
    this._lastMouseDownPosition = newMouseDownPosition;
    this._lastMouseDownCount = Math.min(setMouseDownCount, this._lastMouseDownPositionEqualCount);
  }
};
MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME = 400;
function gestureChangeEventMerger(lastEvent, currentEvent) {
  const r3 = {
    translationY: currentEvent.translationY,
    translationX: currentEvent.translationX
  };
  if (lastEvent) {
    r3.translationY += lastEvent.translationY;
    r3.translationX += lastEvent.translationX;
  }
  return r3;
}
var StandardPointerHandler = class extends MouseHandler {
  constructor(context2, viewController, viewHelper) {
    super(context2, viewController, viewHelper);
    this.viewHelper.linesContentDomNode.style.touchAction = "none";
    this._installGestureHandlerTimeout = window.setTimeout(() => {
      this._installGestureHandlerTimeout = -1;
      if (window.MSGesture) {
        const touchGesture = new MSGesture();
        const penGesture = new MSGesture();
        touchGesture.target = this.viewHelper.linesContentDomNode;
        penGesture.target = this.viewHelper.linesContentDomNode;
        this.viewHelper.linesContentDomNode.addEventListener("pointerdown", (e2) => {
          const pointerType = e2.pointerType;
          if (pointerType === "mouse") {
            this._lastPointerType = "mouse";
            return;
          } else if (pointerType === "touch") {
            this._lastPointerType = "touch";
            touchGesture.addPointer(e2.pointerId);
          } else {
            this._lastPointerType = "pen";
            penGesture.addPointer(e2.pointerId);
          }
        });
        this._register(addDisposableThrottledListener(this.viewHelper.linesContentDomNode, "MSGestureChange", (e2) => this._onGestureChange(e2), gestureChangeEventMerger));
        this._register(addDisposableListener(this.viewHelper.linesContentDomNode, "MSGestureTap", (e2) => this._onCaptureGestureTap(e2), true));
      }
    }, 100);
    this._lastPointerType = "mouse";
  }
  _onMouseDown(e2) {
    if (this._lastPointerType === "mouse") {
      super._onMouseDown(e2);
    }
  }
  _onCaptureGestureTap(rawEvent) {
    const e2 = new EditorMouseEvent(rawEvent, this.viewHelper.viewDomNode);
    const t5 = this._createMouseTarget(e2, false);
    if (t5.position) {
      this.viewController.moveTo(t5.position);
    }
    if (e2.browserEvent.fromElement) {
      e2.preventDefault();
      this.viewHelper.focusTextArea();
    } else {
      setTimeout(() => {
        this.viewHelper.focusTextArea();
      });
    }
  }
  _onGestureChange(e2) {
    this._context.model.deltaScrollNow(-e2.translationX, -e2.translationY);
  }
  dispose() {
    window.clearTimeout(this._installGestureHandlerTimeout);
    super.dispose();
  }
};
var PointerEventHandler = class extends MouseHandler {
  constructor(context2, viewController, viewHelper) {
    super(context2, viewController, viewHelper);
    this._register(Gesture.addTarget(this.viewHelper.linesContentDomNode));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType$1.Tap, (e2) => this.onTap(e2)));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType$1.Change, (e2) => this.onChange(e2)));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType$1.Contextmenu, (e2) => this._onContextMenu(new EditorMouseEvent(e2, this.viewHelper.viewDomNode), false)));
    this._lastPointerType = "mouse";
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, "pointerdown", (e2) => {
      const pointerType = e2.pointerType;
      if (pointerType === "mouse") {
        this._lastPointerType = "mouse";
        return;
      } else if (pointerType === "touch") {
        this._lastPointerType = "touch";
      } else {
        this._lastPointerType = "pen";
      }
    }));
    const pointerEvents = new EditorPointerEventFactory(this.viewHelper.viewDomNode);
    this._register(pointerEvents.onPointerMoveThrottled(this.viewHelper.viewDomNode, (e2) => this._onMouseMove(e2), createMouseMoveEventMerger(this.mouseTargetFactory), MouseHandler.MOUSE_MOVE_MINIMUM_TIME));
    this._register(pointerEvents.onPointerUp(this.viewHelper.viewDomNode, (e2) => this._onMouseUp(e2)));
    this._register(pointerEvents.onPointerLeave(this.viewHelper.viewDomNode, (e2) => this._onMouseLeave(e2)));
    this._register(pointerEvents.onPointerDown(this.viewHelper.viewDomNode, (e2) => this._onMouseDown(e2)));
  }
  onTap(event) {
    if (!event.initialTarget || !this.viewHelper.linesContentDomNode.contains(event.initialTarget)) {
      return;
    }
    event.preventDefault();
    this.viewHelper.focusTextArea();
    const target = this._createMouseTarget(new EditorMouseEvent(event, this.viewHelper.viewDomNode), false);
    if (target.position) {
      this.viewController.dispatchMouse({
        position: target.position,
        mouseColumn: target.position.column,
        startedOnLineNumbers: false,
        mouseDownCount: event.tapCount,
        inSelectionMode: false,
        altKey: false,
        ctrlKey: false,
        metaKey: false,
        shiftKey: false,
        leftButton: false,
        middleButton: false
      });
    }
  }
  onChange(e2) {
    if (this._lastPointerType === "touch") {
      this._context.model.deltaScrollNow(-e2.translationX, -e2.translationY);
    }
  }
  _onMouseDown(e2) {
    if (e2.target && this.viewHelper.linesContentDomNode.contains(e2.target) && this._lastPointerType === "touch") {
      return;
    }
    super._onMouseDown(e2);
  }
};
var TouchHandler = class extends MouseHandler {
  constructor(context2, viewController, viewHelper) {
    super(context2, viewController, viewHelper);
    this._register(Gesture.addTarget(this.viewHelper.linesContentDomNode));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType$1.Tap, (e2) => this.onTap(e2)));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType$1.Change, (e2) => this.onChange(e2)));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType$1.Contextmenu, (e2) => this._onContextMenu(new EditorMouseEvent(e2, this.viewHelper.viewDomNode), false)));
  }
  onTap(event) {
    event.preventDefault();
    this.viewHelper.focusTextArea();
    const target = this._createMouseTarget(new EditorMouseEvent(event, this.viewHelper.viewDomNode), false);
    if (target.position) {
      this.viewController.moveTo(target.position);
    }
  }
  onChange(e2) {
    this._context.model.deltaScrollNow(-e2.translationX, -e2.translationY);
  }
};
var PointerHandler = class extends Disposable {
  constructor(context2, viewController, viewHelper) {
    super();
    if (isIOS && BrowserFeatures.pointerEvents) {
      this.handler = this._register(new PointerEventHandler(context2, viewController, viewHelper));
    } else if (window.TouchEvent) {
      this.handler = this._register(new TouchHandler(context2, viewController, viewHelper));
    } else if (window.navigator.pointerEnabled || window.PointerEvent) {
      this.handler = this._register(new StandardPointerHandler(context2, viewController, viewHelper));
    } else {
      this.handler = this._register(new MouseHandler(context2, viewController, viewHelper));
    }
  }
  getTargetAtClientPoint(clientX, clientY) {
    return this.handler.getTargetAtClientPoint(clientX, clientY);
  }
};
function __snowpack__injectStyle$3(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$3("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-editor .inputarea {\r\n	min-width: 0;\r\n	min-height: 0;\r\n	margin: 0;\r\n	padding: 0;\r\n	position: absolute;\r\n	outline: none !important;\r\n	resize: none;\r\n	border: none;\r\n	overflow: hidden;\r\n	color: transparent;\r\n	background-color: transparent;\r\n}\r\n/*.monaco-editor .inputarea {\r\n	position: fixed !important;\r\n	width: 800px !important;\r\n	height: 500px !important;\r\n	top: initial !important;\r\n	left: initial !important;\r\n	bottom: 0 !important;\r\n	right: 0 !important;\r\n	color: black !important;\r\n	background: white !important;\r\n	line-height: 15px !important;\r\n	font-size: 14px !important;\r\n}*/\r\n.monaco-editor .inputarea.ime-input {\r\n	z-index: 10;\r\n}\r\n");
var TextAreaState = class {
  constructor(value, selectionStart, selectionEnd, selectionStartPosition, selectionEndPosition) {
    this.value = value;
    this.selectionStart = selectionStart;
    this.selectionEnd = selectionEnd;
    this.selectionStartPosition = selectionStartPosition;
    this.selectionEndPosition = selectionEndPosition;
  }
  toString() {
    return "[ <" + this.value + ">, selectionStart: " + this.selectionStart + ", selectionEnd: " + this.selectionEnd + "]";
  }
  static readFromTextArea(textArea) {
    return new TextAreaState(textArea.getValue(), textArea.getSelectionStart(), textArea.getSelectionEnd(), null, null);
  }
  collapseSelection() {
    return new TextAreaState(this.value, this.value.length, this.value.length, null, null);
  }
  writeToTextArea(reason, textArea, select3) {
    textArea.setValue(reason, this.value);
    if (select3) {
      textArea.setSelectionRange(reason, this.selectionStart, this.selectionEnd);
    }
  }
  deduceEditorPosition(offset2) {
    if (offset2 <= this.selectionStart) {
      const str = this.value.substring(offset2, this.selectionStart);
      return this._finishDeduceEditorPosition(this.selectionStartPosition, str, -1);
    }
    if (offset2 >= this.selectionEnd) {
      const str = this.value.substring(this.selectionEnd, offset2);
      return this._finishDeduceEditorPosition(this.selectionEndPosition, str, 1);
    }
    const str1 = this.value.substring(this.selectionStart, offset2);
    if (str1.indexOf(String.fromCharCode(8230)) === -1) {
      return this._finishDeduceEditorPosition(this.selectionStartPosition, str1, 1);
    }
    const str2 = this.value.substring(offset2, this.selectionEnd);
    return this._finishDeduceEditorPosition(this.selectionEndPosition, str2, -1);
  }
  _finishDeduceEditorPosition(anchor, deltaText, signum) {
    let lineFeedCnt = 0;
    let lastLineFeedIndex = -1;
    while ((lastLineFeedIndex = deltaText.indexOf("\n", lastLineFeedIndex + 1)) !== -1) {
      lineFeedCnt++;
    }
    return [anchor, signum * deltaText.length, lineFeedCnt];
  }
  static selectedText(text) {
    return new TextAreaState(text, 0, text.length, null, null);
  }
  static deduceInput(previousState, currentState, couldBeEmojiInput) {
    if (!previousState) {
      return {
        text: "",
        replaceCharCnt: 0
      };
    }
    let previousValue = previousState.value;
    let previousSelectionStart = previousState.selectionStart;
    let previousSelectionEnd = previousState.selectionEnd;
    let currentValue = currentState.value;
    let currentSelectionStart = currentState.selectionStart;
    let currentSelectionEnd = currentState.selectionEnd;
    const previousSuffix = previousValue.substring(previousSelectionEnd);
    const currentSuffix = currentValue.substring(currentSelectionEnd);
    const suffixLength = commonSuffixLength(previousSuffix, currentSuffix);
    currentValue = currentValue.substring(0, currentValue.length - suffixLength);
    previousValue = previousValue.substring(0, previousValue.length - suffixLength);
    const previousPrefix = previousValue.substring(0, previousSelectionStart);
    const currentPrefix = currentValue.substring(0, currentSelectionStart);
    const prefixLength = commonPrefixLength(previousPrefix, currentPrefix);
    currentValue = currentValue.substring(prefixLength);
    previousValue = previousValue.substring(prefixLength);
    currentSelectionStart -= prefixLength;
    previousSelectionStart -= prefixLength;
    currentSelectionEnd -= prefixLength;
    previousSelectionEnd -= prefixLength;
    if (couldBeEmojiInput && currentSelectionStart === currentSelectionEnd && previousValue.length > 0) {
      let potentialEmojiInput = null;
      if (currentSelectionStart === currentValue.length) {
        if (startsWith(currentValue, previousValue)) {
          potentialEmojiInput = currentValue.substring(previousValue.length);
        }
      } else {
        if (endsWith(currentValue, previousValue)) {
          potentialEmojiInput = currentValue.substring(0, currentValue.length - previousValue.length);
        }
      }
      if (potentialEmojiInput !== null && potentialEmojiInput.length > 0) {
        if (/\uFE0F/.test(potentialEmojiInput) || containsEmoji(potentialEmojiInput)) {
          return {
            text: potentialEmojiInput,
            replaceCharCnt: 0
          };
        }
      }
    }
    if (currentSelectionStart === currentSelectionEnd) {
      if (previousValue === currentValue && previousSelectionStart === 0 && previousSelectionEnd === previousValue.length && currentSelectionStart === currentValue.length && currentValue.indexOf("\n") === -1) {
        if (containsFullWidthCharacter(currentValue)) {
          return {
            text: "",
            replaceCharCnt: 0
          };
        }
      }
      const replacePreviousCharacters2 = previousPrefix.length - prefixLength;
      return {
        text: currentValue,
        replaceCharCnt: replacePreviousCharacters2
      };
    }
    const replacePreviousCharacters = previousSelectionEnd - previousSelectionStart;
    return {
      text: currentValue,
      replaceCharCnt: replacePreviousCharacters
    };
  }
};
TextAreaState.EMPTY = new TextAreaState("", 0, 0, null, null);
var PagedScreenReaderStrategy = class {
  static _getPageOfLine(lineNumber, linesPerPage) {
    return Math.floor((lineNumber - 1) / linesPerPage);
  }
  static _getRangeForPage(page2, linesPerPage) {
    const offset2 = page2 * linesPerPage;
    const startLineNumber = offset2 + 1;
    const endLineNumber = offset2 + linesPerPage;
    return new Range(startLineNumber, 1, endLineNumber + 1, 1);
  }
  static fromEditorSelection(previousState, model, selection2, linesPerPage, trimLongText) {
    const selectionStartPage = PagedScreenReaderStrategy._getPageOfLine(selection2.startLineNumber, linesPerPage);
    const selectionStartPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionStartPage, linesPerPage);
    const selectionEndPage = PagedScreenReaderStrategy._getPageOfLine(selection2.endLineNumber, linesPerPage);
    const selectionEndPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionEndPage, linesPerPage);
    const pretextRange = selectionStartPageRange.intersectRanges(new Range(1, 1, selection2.startLineNumber, selection2.startColumn));
    let pretext = model.getValueInRange(pretextRange, 1);
    const lastLine = model.getLineCount();
    const lastLineMaxColumn = model.getLineMaxColumn(lastLine);
    const posttextRange = selectionEndPageRange.intersectRanges(new Range(selection2.endLineNumber, selection2.endColumn, lastLine, lastLineMaxColumn));
    let posttext = model.getValueInRange(posttextRange, 1);
    let text;
    if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) {
      text = model.getValueInRange(selection2, 1);
    } else {
      const selectionRange1 = selectionStartPageRange.intersectRanges(selection2);
      const selectionRange2 = selectionEndPageRange.intersectRanges(selection2);
      text = model.getValueInRange(selectionRange1, 1) + String.fromCharCode(8230) + model.getValueInRange(selectionRange2, 1);
    }
    if (trimLongText) {
      const LIMIT_CHARS = 500;
      if (pretext.length > LIMIT_CHARS) {
        pretext = pretext.substring(pretext.length - LIMIT_CHARS, pretext.length);
      }
      if (posttext.length > LIMIT_CHARS) {
        posttext = posttext.substring(0, LIMIT_CHARS);
      }
      if (text.length > 2 * LIMIT_CHARS) {
        text = text.substring(0, LIMIT_CHARS) + String.fromCharCode(8230) + text.substring(text.length - LIMIT_CHARS, text.length);
      }
    }
    return new TextAreaState(pretext + text + posttext, pretext.length, pretext.length + text.length, new Position(selection2.startLineNumber, selection2.startColumn), new Position(selection2.endLineNumber, selection2.endColumn));
  }
};
var InMemoryClipboardMetadataManager = class {
  constructor() {
    this._lastState = null;
  }
  set(lastCopiedValue, data2) {
    this._lastState = {lastCopiedValue, data: data2};
  }
  get(pastedText) {
    if (this._lastState && this._lastState.lastCopiedValue === pastedText) {
      return this._lastState.data;
    }
    this._lastState = null;
    return null;
  }
};
InMemoryClipboardMetadataManager.INSTANCE = new InMemoryClipboardMetadataManager();
var TextAreaInput = class extends Disposable {
  constructor(host, textArea) {
    super();
    this.textArea = textArea;
    this._onFocus = this._register(new Emitter());
    this.onFocus = this._onFocus.event;
    this._onBlur = this._register(new Emitter());
    this.onBlur = this._onBlur.event;
    this._onKeyDown = this._register(new Emitter());
    this.onKeyDown = this._onKeyDown.event;
    this._onKeyUp = this._register(new Emitter());
    this.onKeyUp = this._onKeyUp.event;
    this._onCut = this._register(new Emitter());
    this.onCut = this._onCut.event;
    this._onPaste = this._register(new Emitter());
    this.onPaste = this._onPaste.event;
    this._onType = this._register(new Emitter());
    this.onType = this._onType.event;
    this._onCompositionStart = this._register(new Emitter());
    this.onCompositionStart = this._onCompositionStart.event;
    this._onCompositionUpdate = this._register(new Emitter());
    this.onCompositionUpdate = this._onCompositionUpdate.event;
    this._onCompositionEnd = this._register(new Emitter());
    this.onCompositionEnd = this._onCompositionEnd.event;
    this._onSelectionChangeRequest = this._register(new Emitter());
    this.onSelectionChangeRequest = this._onSelectionChangeRequest.event;
    this._host = host;
    this._textArea = this._register(new TextAreaWrapper(textArea));
    this._asyncTriggerCut = this._register(new RunOnceScheduler(() => this._onCut.fire(), 0));
    this._textAreaState = TextAreaState.EMPTY;
    this._selectionChangeListener = null;
    this.writeScreenReaderContent("ctor");
    this._hasFocus = false;
    this._isDoingComposition = false;
    this._nextCommand = 0;
    let lastKeyDown = null;
    this._register(addStandardDisposableListener(textArea.domNode, "keydown", (e2) => {
      if (e2.keyCode === 109 || this._isDoingComposition && e2.keyCode === 1) {
        e2.stopPropagation();
      }
      if (e2.equals(9)) {
        e2.preventDefault();
      }
      lastKeyDown = e2;
      this._onKeyDown.fire(e2);
    }));
    this._register(addStandardDisposableListener(textArea.domNode, "keyup", (e2) => {
      this._onKeyUp.fire(e2);
    }));
    this._register(addDisposableListener(textArea.domNode, "compositionstart", (e2) => {
      if (this._isDoingComposition) {
        return;
      }
      this._isDoingComposition = true;
      let moveOneCharacterLeft = false;
      if (isMacintosh && lastKeyDown && lastKeyDown.equals(109) && this._textAreaState.selectionStart === this._textAreaState.selectionEnd && this._textAreaState.selectionStart > 0 && this._textAreaState.value.substr(this._textAreaState.selectionStart - 1, 1) === e2.data) {
        if (lastKeyDown.code === "ArrowRight" || lastKeyDown.code === "ArrowLeft") {
          moveOneCharacterLeft = true;
        }
      }
      if (moveOneCharacterLeft) {
        this._textAreaState = new TextAreaState(this._textAreaState.value, this._textAreaState.selectionStart - 1, this._textAreaState.selectionEnd, this._textAreaState.selectionStartPosition ? new Position(this._textAreaState.selectionStartPosition.lineNumber, this._textAreaState.selectionStartPosition.column - 1) : null, this._textAreaState.selectionEndPosition);
      } else if (!isEdge2) {
        this._setAndWriteTextAreaState("compositionstart", TextAreaState.EMPTY);
      }
      this._onCompositionStart.fire({moveOneCharacterLeft});
    }));
    const deduceInputFromTextAreaValue = (couldBeEmojiInput) => {
      const oldState = this._textAreaState;
      const newState = TextAreaState.readFromTextArea(this._textArea);
      return [newState, TextAreaState.deduceInput(oldState, newState, couldBeEmojiInput)];
    };
    const deduceComposition = (text) => {
      const oldState = this._textAreaState;
      const newState = TextAreaState.selectedText(text);
      const typeInput = {
        text: newState.value,
        replaceCharCnt: oldState.selectionEnd - oldState.selectionStart
      };
      return [newState, typeInput];
    };
    const compositionDataInValid = (locale) => {
      if (isEdge2 && locale === "ja") {
        return true;
      }
      return false;
    };
    this._register(addDisposableListener(textArea.domNode, "compositionupdate", (e2) => {
      if (compositionDataInValid(e2.locale)) {
        const [newState2, typeInput2] = deduceInputFromTextAreaValue(false);
        this._textAreaState = newState2;
        this._onType.fire(typeInput2);
        this._onCompositionUpdate.fire(e2);
        return;
      }
      const [newState, typeInput] = deduceComposition(e2.data || "");
      this._textAreaState = newState;
      this._onType.fire(typeInput);
      this._onCompositionUpdate.fire(e2);
    }));
    this._register(addDisposableListener(textArea.domNode, "compositionend", (e2) => {
      if (!this._isDoingComposition) {
        return;
      }
      if (compositionDataInValid(e2.locale)) {
        const [newState, typeInput] = deduceInputFromTextAreaValue(false);
        this._textAreaState = newState;
        this._onType.fire(typeInput);
      } else {
        const [newState, typeInput] = deduceComposition(e2.data || "");
        this._textAreaState = newState;
        this._onType.fire(typeInput);
      }
      if (isEdge2 || isChrome) {
        this._textAreaState = TextAreaState.readFromTextArea(this._textArea);
      }
      if (!this._isDoingComposition) {
        return;
      }
      this._isDoingComposition = false;
      this._onCompositionEnd.fire();
    }));
    this._register(addDisposableListener(textArea.domNode, "input", () => {
      this._textArea.setIgnoreSelectionChangeTime("received input event");
      if (this._isDoingComposition) {
        return;
      }
      const [newState, typeInput] = deduceInputFromTextAreaValue(isMacintosh);
      if (typeInput.replaceCharCnt === 0 && typeInput.text.length === 1 && isHighSurrogate(typeInput.text.charCodeAt(0))) {
        return;
      }
      this._textAreaState = newState;
      if (this._nextCommand === 0) {
        if (typeInput.text !== "") {
          this._onType.fire(typeInput);
        }
      } else {
        if (typeInput.text !== "" || typeInput.replaceCharCnt !== 0) {
          this._firePaste(typeInput.text, null);
        }
        this._nextCommand = 0;
      }
    }));
    this._register(addDisposableListener(textArea.domNode, "cut", (e2) => {
      this._textArea.setIgnoreSelectionChangeTime("received cut event");
      this._ensureClipboardGetsEditorSelection(e2);
      this._asyncTriggerCut.schedule();
    }));
    this._register(addDisposableListener(textArea.domNode, "copy", (e2) => {
      this._ensureClipboardGetsEditorSelection(e2);
    }));
    this._register(addDisposableListener(textArea.domNode, "paste", (e2) => {
      this._textArea.setIgnoreSelectionChangeTime("received paste event");
      if (ClipboardEventUtils.canUseTextData(e2)) {
        const [pastePlainText, metadata] = ClipboardEventUtils.getTextData(e2);
        if (pastePlainText !== "") {
          this._firePaste(pastePlainText, metadata);
        }
      } else {
        if (this._textArea.getSelectionStart() !== this._textArea.getSelectionEnd()) {
          this._setAndWriteTextAreaState("paste", TextAreaState.EMPTY);
        }
        this._nextCommand = 1;
      }
    }));
    this._register(addDisposableListener(textArea.domNode, "focus", () => {
      this._setHasFocus(true);
    }));
    this._register(addDisposableListener(textArea.domNode, "blur", () => {
      this._setHasFocus(false);
    }));
  }
  _installSelectionChangeListener() {
    let previousSelectionChangeEventTime = 0;
    return addDisposableListener(document, "selectionchange", (e2) => {
      if (!this._hasFocus) {
        return;
      }
      if (this._isDoingComposition) {
        return;
      }
      if (!isChrome) {
        return;
      }
      const now3 = Date.now();
      const delta1 = now3 - previousSelectionChangeEventTime;
      previousSelectionChangeEventTime = now3;
      if (delta1 < 5) {
        return;
      }
      const delta2 = now3 - this._textArea.getIgnoreSelectionChangeTime();
      this._textArea.resetSelectionChangeTime();
      if (delta2 < 100) {
        return;
      }
      if (!this._textAreaState.selectionStartPosition || !this._textAreaState.selectionEndPosition) {
        return;
      }
      const newValue = this._textArea.getValue();
      if (this._textAreaState.value !== newValue) {
        return;
      }
      const newSelectionStart = this._textArea.getSelectionStart();
      const newSelectionEnd = this._textArea.getSelectionEnd();
      if (this._textAreaState.selectionStart === newSelectionStart && this._textAreaState.selectionEnd === newSelectionEnd) {
        return;
      }
      const _newSelectionStartPosition = this._textAreaState.deduceEditorPosition(newSelectionStart);
      const newSelectionStartPosition = this._host.deduceModelPosition(_newSelectionStartPosition[0], _newSelectionStartPosition[1], _newSelectionStartPosition[2]);
      const _newSelectionEndPosition = this._textAreaState.deduceEditorPosition(newSelectionEnd);
      const newSelectionEndPosition = this._host.deduceModelPosition(_newSelectionEndPosition[0], _newSelectionEndPosition[1], _newSelectionEndPosition[2]);
      const newSelection = new Selection(newSelectionStartPosition.lineNumber, newSelectionStartPosition.column, newSelectionEndPosition.lineNumber, newSelectionEndPosition.column);
      this._onSelectionChangeRequest.fire(newSelection);
    });
  }
  dispose() {
    super.dispose();
    if (this._selectionChangeListener) {
      this._selectionChangeListener.dispose();
      this._selectionChangeListener = null;
    }
  }
  focusTextArea() {
    this._setHasFocus(true);
    this.refreshFocusState();
  }
  isFocused() {
    return this._hasFocus;
  }
  refreshFocusState() {
    const shadowRoot = getShadowRoot(this.textArea.domNode);
    if (shadowRoot) {
      this._setHasFocus(shadowRoot.activeElement === this.textArea.domNode);
    } else if (isInDOM(this.textArea.domNode)) {
      this._setHasFocus(document.activeElement === this.textArea.domNode);
    } else {
      this._setHasFocus(false);
    }
  }
  _setHasFocus(newHasFocus) {
    if (this._hasFocus === newHasFocus) {
      return;
    }
    this._hasFocus = newHasFocus;
    if (this._selectionChangeListener) {
      this._selectionChangeListener.dispose();
      this._selectionChangeListener = null;
    }
    if (this._hasFocus) {
      this._selectionChangeListener = this._installSelectionChangeListener();
    }
    if (this._hasFocus) {
      if (isEdge2) {
        this._setAndWriteTextAreaState("focusgain", TextAreaState.EMPTY);
      } else {
        this.writeScreenReaderContent("focusgain");
      }
    }
    if (this._hasFocus) {
      this._onFocus.fire();
    } else {
      this._onBlur.fire();
    }
  }
  _setAndWriteTextAreaState(reason, textAreaState) {
    if (!this._hasFocus) {
      textAreaState = textAreaState.collapseSelection();
    }
    textAreaState.writeToTextArea(reason, this._textArea, this._hasFocus);
    this._textAreaState = textAreaState;
  }
  writeScreenReaderContent(reason) {
    if (this._isDoingComposition) {
      return;
    }
    this._setAndWriteTextAreaState(reason, this._host.getScreenReaderContent(this._textAreaState));
  }
  _ensureClipboardGetsEditorSelection(e2) {
    const dataToCopy = this._host.getDataToCopy(ClipboardEventUtils.canUseTextData(e2) && BrowserFeatures.clipboard.richText);
    const storedMetadata = {
      version: 1,
      isFromEmptySelection: dataToCopy.isFromEmptySelection,
      multicursorText: dataToCopy.multicursorText,
      mode: dataToCopy.mode
    };
    InMemoryClipboardMetadataManager.INSTANCE.set(isFirefox ? dataToCopy.text.replace(/\r\n/g, "\n") : dataToCopy.text, storedMetadata);
    if (!ClipboardEventUtils.canUseTextData(e2)) {
      this._setAndWriteTextAreaState("copy or cut", TextAreaState.selectedText(dataToCopy.text));
      return;
    }
    ClipboardEventUtils.setTextData(e2, dataToCopy.text, dataToCopy.html, storedMetadata);
  }
  _firePaste(text, metadata) {
    if (!metadata) {
      metadata = InMemoryClipboardMetadataManager.INSTANCE.get(text);
    }
    this._onPaste.fire({
      text,
      metadata
    });
  }
};
var ClipboardEventUtils = class {
  static canUseTextData(e2) {
    if (e2.clipboardData) {
      return true;
    }
    if (window.clipboardData) {
      return true;
    }
    return false;
  }
  static getTextData(e2) {
    if (e2.clipboardData) {
      e2.preventDefault();
      const text = e2.clipboardData.getData("text/plain");
      let metadata = null;
      const rawmetadata = e2.clipboardData.getData("vscode-editor-data");
      if (typeof rawmetadata === "string") {
        try {
          metadata = JSON.parse(rawmetadata);
          if (metadata.version !== 1) {
            metadata = null;
          }
        } catch (err) {
        }
      }
      return [text, metadata];
    }
    if (window.clipboardData) {
      e2.preventDefault();
      const text = window.clipboardData.getData("Text");
      return [text, null];
    }
    throw new Error("ClipboardEventUtils.getTextData: Cannot use text data!");
  }
  static setTextData(e2, text, html, metadata) {
    if (e2.clipboardData) {
      e2.clipboardData.setData("text/plain", text);
      if (typeof html === "string") {
        e2.clipboardData.setData("text/html", html);
      }
      e2.clipboardData.setData("vscode-editor-data", JSON.stringify(metadata));
      e2.preventDefault();
      return;
    }
    if (window.clipboardData) {
      window.clipboardData.setData("Text", text);
      e2.preventDefault();
      return;
    }
    throw new Error("ClipboardEventUtils.setTextData: Cannot use text data!");
  }
};
var TextAreaWrapper = class extends Disposable {
  constructor(_textArea) {
    super();
    this._actual = _textArea;
    this._ignoreSelectionChangeTime = 0;
  }
  setIgnoreSelectionChangeTime(reason) {
    this._ignoreSelectionChangeTime = Date.now();
  }
  getIgnoreSelectionChangeTime() {
    return this._ignoreSelectionChangeTime;
  }
  resetSelectionChangeTime() {
    this._ignoreSelectionChangeTime = 0;
  }
  getValue() {
    return this._actual.domNode.value;
  }
  setValue(reason, value) {
    const textArea = this._actual.domNode;
    if (textArea.value === value) {
      return;
    }
    this.setIgnoreSelectionChangeTime("setValue");
    textArea.value = value;
  }
  getSelectionStart() {
    return this._actual.domNode.selectionStart;
  }
  getSelectionEnd() {
    return this._actual.domNode.selectionEnd;
  }
  setSelectionRange(reason, selectionStart, selectionEnd) {
    const textArea = this._actual.domNode;
    let activeElement = null;
    const shadowRoot = getShadowRoot(textArea);
    if (shadowRoot) {
      activeElement = shadowRoot.activeElement;
    } else {
      activeElement = document.activeElement;
    }
    const currentIsFocused = activeElement === textArea;
    const currentSelectionStart = textArea.selectionStart;
    const currentSelectionEnd = textArea.selectionEnd;
    if (currentIsFocused && currentSelectionStart === selectionStart && currentSelectionEnd === selectionEnd) {
      if (isFirefox && window.parent !== window) {
        textArea.focus();
      }
      return;
    }
    if (currentIsFocused) {
      this.setIgnoreSelectionChangeTime("setSelectionRange");
      textArea.setSelectionRange(selectionStart, selectionEnd);
      if (isFirefox && window.parent !== window) {
        textArea.focus();
      }
      return;
    }
    try {
      const scrollState = saveParentsScrollTop(textArea);
      this.setIgnoreSelectionChangeTime("setSelectionRange");
      textArea.focus();
      textArea.setSelectionRange(selectionStart, selectionEnd);
      restoreParentsScrollTop(textArea, scrollState);
    } catch (e2) {
    }
  }
};
function __snowpack__injectStyle$4(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$4("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-editor .margin-view-overlays .line-numbers {\r\n	font-variant-numeric: tabular-nums;\r\n	position: absolute;\r\n	text-align: right;\r\n	display: inline-block;\r\n	vertical-align: middle;\r\n	box-sizing: border-box;\r\n	cursor: default;\r\n	height: 100%;\r\n}\r\n\r\n.monaco-editor .relative-current-line-number {\r\n	text-align: left;\r\n	display: inline-block;\r\n	width: 100%;\r\n}\r\n\r\n.monaco-editor .margin-view-overlays .line-numbers.lh-odd {\r\n	margin-top: 1px;\r\n}\r\n");
var DynamicViewOverlay = class extends ViewEventHandler {
};
var Extensions$5 = {
  ColorContribution: "base.contributions.colors"
};
var ColorRegistry = class {
  constructor() {
    this._onDidChangeSchema = new Emitter();
    this.onDidChangeSchema = this._onDidChangeSchema.event;
    this.colorSchema = {type: "object", properties: {}};
    this.colorReferenceSchema = {type: "string", enum: [], enumDescriptions: []};
    this.colorsById = {};
  }
  registerColor(id3, defaults3, description, needsTransparency = false, deprecationMessage) {
    let colorContribution = {id: id3, description, defaults: defaults3, needsTransparency, deprecationMessage};
    this.colorsById[id3] = colorContribution;
    let propertySchema = {type: "string", description, format: "color-hex", defaultSnippets: [{body: "${1:#ff0000}"}]};
    if (deprecationMessage) {
      propertySchema.deprecationMessage = deprecationMessage;
    }
    this.colorSchema.properties[id3] = propertySchema;
    this.colorReferenceSchema.enum.push(id3);
    this.colorReferenceSchema.enumDescriptions.push(description);
    this._onDidChangeSchema.fire();
    return id3;
  }
  resolveDefaultColor(id3, theme) {
    const colorDesc = this.colorsById[id3];
    if (colorDesc && colorDesc.defaults) {
      const colorValue = colorDesc.defaults[theme.type];
      return resolveColorValue(colorValue, theme);
    }
    return void 0;
  }
  getColorSchema() {
    return this.colorSchema;
  }
  toString() {
    let sorter2 = (a2, b2) => {
      let cat1 = a2.indexOf(".") === -1 ? 0 : 1;
      let cat2 = b2.indexOf(".") === -1 ? 0 : 1;
      if (cat1 !== cat2) {
        return cat1 - cat2;
      }
      return a2.localeCompare(b2);
    };
    return Object.keys(this.colorsById).sort(sorter2).map((k2) => `- \`${k2}\`: ${this.colorsById[k2].description}`).join("\n");
  }
};
var colorRegistry = new ColorRegistry();
Registry$1.add(Extensions$5.ColorContribution, colorRegistry);
function registerColor(id3, defaults3, description, needsTransparency, deprecationMessage) {
  return colorRegistry.registerColor(id3, defaults3, description, needsTransparency, deprecationMessage);
}
var foreground = registerColor("foreground", {dark: "#CCCCCC", light: "#616161", hc: "#FFFFFF"}, localize("foreground", "Overall foreground color. This color is only used if not overridden by a component."));
var errorForeground = registerColor("errorForeground", {dark: "#F48771", light: "#A1260D", hc: "#F48771"}, localize("errorForeground", "Overall foreground color for error messages. This color is only used if not overridden by a component."));
var iconForeground = registerColor("icon.foreground", {dark: "#C5C5C5", light: "#424242", hc: "#FFFFFF"}, localize("iconForeground", "The default color for icons in the workbench."));
var focusBorder = registerColor("focusBorder", {dark: "#007FD4", light: "#0090F1", hc: "#F38518"}, localize("focusBorder", "Overall border color for focused elements. This color is only used if not overridden by a component."));
var contrastBorder = registerColor("contrastBorder", {light: null, dark: null, hc: "#6FC3DF"}, localize("contrastBorder", "An extra border around elements to separate them from others for greater contrast."));
var activeContrastBorder = registerColor("contrastActiveBorder", {light: null, dark: null, hc: focusBorder}, localize("activeContrastBorder", "An extra border around active elements to separate them from others for greater contrast."));
var textLinkForeground = registerColor("textLink.foreground", {light: "#006AB1", dark: "#3794FF", hc: "#3794FF"}, localize("textLinkForeground", "Foreground color for links in text."));
var textCodeBlockBackground = registerColor("textCodeBlock.background", {light: "#dcdcdc66", dark: "#0a0a0a66", hc: Color.black}, localize("textCodeBlockBackground", "Background color for code blocks in text."));
var widgetShadow = registerColor("widget.shadow", {dark: "#000000", light: "#A8A8A8", hc: null}, localize("widgetShadow", "Shadow color of widgets such as find/replace inside the editor."));
var inputBackground = registerColor("input.background", {dark: "#3C3C3C", light: Color.white, hc: Color.black}, localize("inputBoxBackground", "Input box background."));
var inputForeground = registerColor("input.foreground", {dark: foreground, light: foreground, hc: foreground}, localize("inputBoxForeground", "Input box foreground."));
var inputBorder = registerColor("input.border", {dark: null, light: null, hc: contrastBorder}, localize("inputBoxBorder", "Input box border."));
var inputActiveOptionBorder = registerColor("inputOption.activeBorder", {dark: "#007ACC00", light: "#007ACC00", hc: contrastBorder}, localize("inputBoxActiveOptionBorder", "Border color of activated options in input fields."));
var inputActiveOptionBackground = registerColor("inputOption.activeBackground", {dark: transparent(focusBorder, 0.4), light: transparent(focusBorder, 0.2), hc: Color.transparent}, localize("inputOption.activeBackground", "Background color of activated options in input fields."));
var inputActiveOptionForeground = registerColor("inputOption.activeForeground", {dark: Color.white, light: Color.black, hc: null}, localize("inputOption.activeForeground", "Foreground color of activated options in input fields."));
var inputValidationInfoBackground = registerColor("inputValidation.infoBackground", {dark: "#063B49", light: "#D6ECF2", hc: Color.black}, localize("inputValidationInfoBackground", "Input validation background color for information severity."));
var inputValidationInfoForeground = registerColor("inputValidation.infoForeground", {dark: null, light: null, hc: null}, localize("inputValidationInfoForeground", "Input validation foreground color for information severity."));
var inputValidationInfoBorder = registerColor("inputValidation.infoBorder", {dark: "#007acc", light: "#007acc", hc: contrastBorder}, localize("inputValidationInfoBorder", "Input validation border color for information severity."));
var inputValidationWarningBackground = registerColor("inputValidation.warningBackground", {dark: "#352A05", light: "#F6F5D2", hc: Color.black}, localize("inputValidationWarningBackground", "Input validation background color for warning severity."));
var inputValidationWarningForeground = registerColor("inputValidation.warningForeground", {dark: null, light: null, hc: null}, localize("inputValidationWarningForeground", "Input validation foreground color for warning severity."));
var inputValidationWarningBorder = registerColor("inputValidation.warningBorder", {dark: "#B89500", light: "#B89500", hc: contrastBorder}, localize("inputValidationWarningBorder", "Input validation border color for warning severity."));
var inputValidationErrorBackground = registerColor("inputValidation.errorBackground", {dark: "#5A1D1D", light: "#F2DEDE", hc: Color.black}, localize("inputValidationErrorBackground", "Input validation background color for error severity."));
var inputValidationErrorForeground = registerColor("inputValidation.errorForeground", {dark: null, light: null, hc: null}, localize("inputValidationErrorForeground", "Input validation foreground color for error severity."));
var inputValidationErrorBorder = registerColor("inputValidation.errorBorder", {dark: "#BE1100", light: "#BE1100", hc: contrastBorder}, localize("inputValidationErrorBorder", "Input validation border color for error severity."));
var selectBackground = registerColor("dropdown.background", {dark: "#3C3C3C", light: Color.white, hc: Color.black}, localize("dropdownBackground", "Dropdown background."));
var selectForeground = registerColor("dropdown.foreground", {dark: "#F0F0F0", light: null, hc: Color.white}, localize("dropdownForeground", "Dropdown foreground."));
var buttonForeground = registerColor("button.foreground", {dark: Color.white, light: Color.white, hc: Color.white}, localize("buttonForeground", "Button foreground color."));
var buttonBackground = registerColor("button.background", {dark: "#0E639C", light: "#007ACC", hc: null}, localize("buttonBackground", "Button background color."));
var buttonHoverBackground = registerColor("button.hoverBackground", {dark: lighten(buttonBackground, 0.2), light: darken(buttonBackground, 0.2), hc: null}, localize("buttonHoverBackground", "Button background color when hovering."));
var badgeBackground = registerColor("badge.background", {dark: "#4D4D4D", light: "#C4C4C4", hc: Color.black}, localize("badgeBackground", "Badge background color. Badges are small information labels, e.g. for search results count."));
var badgeForeground = registerColor("badge.foreground", {dark: Color.white, light: "#333", hc: Color.white}, localize("badgeForeground", "Badge foreground color. Badges are small information labels, e.g. for search results count."));
var scrollbarShadow = registerColor("scrollbar.shadow", {dark: "#000000", light: "#DDDDDD", hc: null}, localize("scrollbarShadow", "Scrollbar shadow to indicate that the view is scrolled."));
var scrollbarSliderBackground = registerColor("scrollbarSlider.background", {dark: Color.fromHex("#797979").transparent(0.4), light: Color.fromHex("#646464").transparent(0.4), hc: transparent(contrastBorder, 0.6)}, localize("scrollbarSliderBackground", "Scrollbar slider background color."));
var scrollbarSliderHoverBackground = registerColor("scrollbarSlider.hoverBackground", {dark: Color.fromHex("#646464").transparent(0.7), light: Color.fromHex("#646464").transparent(0.7), hc: transparent(contrastBorder, 0.8)}, localize("scrollbarSliderHoverBackground", "Scrollbar slider background color when hovering."));
var scrollbarSliderActiveBackground = registerColor("scrollbarSlider.activeBackground", {dark: Color.fromHex("#BFBFBF").transparent(0.4), light: Color.fromHex("#000000").transparent(0.6), hc: contrastBorder}, localize("scrollbarSliderActiveBackground", "Scrollbar slider background color when clicked on."));
var progressBarBackground = registerColor("progressBar.background", {dark: Color.fromHex("#0E70C0"), light: Color.fromHex("#0E70C0"), hc: contrastBorder}, localize("progressBarBackground", "Background color of the progress bar that can show for long running operations."));
var editorErrorForeground = registerColor("editorError.foreground", {dark: "#F48771", light: "#E51400", hc: null}, localize("editorError.foreground", "Foreground color of error squigglies in the editor."));
var editorErrorBorder = registerColor("editorError.border", {dark: null, light: null, hc: Color.fromHex("#E47777").transparent(0.8)}, localize("errorBorder", "Border color of error boxes in the editor."));
var editorWarningForeground = registerColor("editorWarning.foreground", {dark: "#CCA700", light: "#E9A700", hc: null}, localize("editorWarning.foreground", "Foreground color of warning squigglies in the editor."));
var editorWarningBorder = registerColor("editorWarning.border", {dark: null, light: null, hc: Color.fromHex("#FFCC00").transparent(0.8)}, localize("warningBorder", "Border color of warning boxes in the editor."));
var editorInfoForeground = registerColor("editorInfo.foreground", {dark: "#75BEFF", light: "#75BEFF", hc: null}, localize("editorInfo.foreground", "Foreground color of info squigglies in the editor."));
var editorInfoBorder = registerColor("editorInfo.border", {dark: null, light: null, hc: Color.fromHex("#75BEFF").transparent(0.8)}, localize("infoBorder", "Border color of info boxes in the editor."));
var editorHintForeground = registerColor("editorHint.foreground", {dark: Color.fromHex("#eeeeee").transparent(0.7), light: "#6c6c6c", hc: null}, localize("editorHint.foreground", "Foreground color of hint squigglies in the editor."));
var editorHintBorder = registerColor("editorHint.border", {dark: null, light: null, hc: Color.fromHex("#eeeeee").transparent(0.8)}, localize("hintBorder", "Border color of hint boxes in the editor."));
var editorBackground = registerColor("editor.background", {light: "#fffffe", dark: "#1E1E1E", hc: Color.black}, localize("editorBackground", "Editor background color."));
var editorForeground = registerColor("editor.foreground", {light: "#333333", dark: "#BBBBBB", hc: Color.white}, localize("editorForeground", "Editor default foreground color."));
var editorWidgetBackground = registerColor("editorWidget.background", {dark: "#252526", light: "#F3F3F3", hc: "#0C141F"}, localize("editorWidgetBackground", "Background color of editor widgets, such as find/replace."));
var editorWidgetForeground = registerColor("editorWidget.foreground", {dark: foreground, light: foreground, hc: foreground}, localize("editorWidgetForeground", "Foreground color of editor widgets, such as find/replace."));
var editorWidgetBorder = registerColor("editorWidget.border", {dark: "#454545", light: "#C8C8C8", hc: contrastBorder}, localize("editorWidgetBorder", "Border color of editor widgets. The color is only used if the widget chooses to have a border and if the color is not overridden by a widget."));
var editorWidgetResizeBorder = registerColor("editorWidget.resizeBorder", {light: null, dark: null, hc: null}, localize("editorWidgetResizeBorder", "Border color of the resize bar of editor widgets. The color is only used if the widget chooses to have a resize border and if the color is not overridden by a widget."));
var quickInputBackground = registerColor("quickInput.background", {dark: editorWidgetBackground, light: editorWidgetBackground, hc: editorWidgetBackground}, localize("pickerBackground", "Quick picker background color. The quick picker widget is the container for pickers like the command palette."));
var quickInputForeground = registerColor("quickInput.foreground", {dark: editorWidgetForeground, light: editorWidgetForeground, hc: editorWidgetForeground}, localize("pickerForeground", "Quick picker foreground color. The quick picker widget is the container for pickers like the command palette."));
var quickInputTitleBackground = registerColor("quickInputTitle.background", {dark: new Color(new RGBA(255, 255, 255, 0.105)), light: new Color(new RGBA(0, 0, 0, 0.06)), hc: "#000000"}, localize("pickerTitleBackground", "Quick picker title background color. The quick picker widget is the container for pickers like the command palette."));
var pickerGroupForeground = registerColor("pickerGroup.foreground", {dark: "#3794FF", light: "#0066BF", hc: Color.white}, localize("pickerGroupForeground", "Quick picker color for grouping labels."));
var pickerGroupBorder = registerColor("pickerGroup.border", {dark: "#3F3F46", light: "#CCCEDB", hc: Color.white}, localize("pickerGroupBorder", "Quick picker color for grouping borders."));
var editorSelectionBackground = registerColor("editor.selectionBackground", {light: "#ADD6FF", dark: "#264F78", hc: "#f3f518"}, localize("editorSelectionBackground", "Color of the editor selection."));
var editorSelectionForeground = registerColor("editor.selectionForeground", {light: null, dark: null, hc: "#000000"}, localize("editorSelectionForeground", "Color of the selected text for high contrast."));
var editorInactiveSelection = registerColor("editor.inactiveSelectionBackground", {light: transparent(editorSelectionBackground, 0.5), dark: transparent(editorSelectionBackground, 0.5), hc: transparent(editorSelectionBackground, 0.5)}, localize("editorInactiveSelection", "Color of the selection in an inactive editor. The color must not be opaque so as not to hide underlying decorations."), true);
var editorSelectionHighlight = registerColor("editor.selectionHighlightBackground", {light: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), dark: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), hc: null}, localize("editorSelectionHighlight", "Color for regions with the same content as the selection. The color must not be opaque so as not to hide underlying decorations."), true);
var editorSelectionHighlightBorder = registerColor("editor.selectionHighlightBorder", {light: null, dark: null, hc: activeContrastBorder}, localize("editorSelectionHighlightBorder", "Border color for regions with the same content as the selection."));
var editorFindMatch = registerColor("editor.findMatchBackground", {light: "#A8AC94", dark: "#515C6A", hc: null}, localize("editorFindMatch", "Color of the current search match."));
var editorFindMatchHighlight = registerColor("editor.findMatchHighlightBackground", {light: "#EA5C0055", dark: "#EA5C0055", hc: null}, localize("findMatchHighlight", "Color of the other search matches. The color must not be opaque so as not to hide underlying decorations."), true);
var editorFindRangeHighlight = registerColor("editor.findRangeHighlightBackground", {dark: "#3a3d4166", light: "#b4b4b44d", hc: null}, localize("findRangeHighlight", "Color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true);
var editorFindMatchBorder = registerColor("editor.findMatchBorder", {light: null, dark: null, hc: activeContrastBorder}, localize("editorFindMatchBorder", "Border color of the current search match."));
var editorFindMatchHighlightBorder = registerColor("editor.findMatchHighlightBorder", {light: null, dark: null, hc: activeContrastBorder}, localize("findMatchHighlightBorder", "Border color of the other search matches."));
var editorFindRangeHighlightBorder = registerColor("editor.findRangeHighlightBorder", {dark: null, light: null, hc: transparent(activeContrastBorder, 0.4)}, localize("findRangeHighlightBorder", "Border color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true);
var editorHoverHighlight = registerColor("editor.hoverHighlightBackground", {light: "#ADD6FF26", dark: "#264f7840", hc: "#ADD6FF26"}, localize("hoverHighlight", "Highlight below the word for which a hover is shown. The color must not be opaque so as not to hide underlying decorations."), true);
var editorHoverBackground = registerColor("editorHoverWidget.background", {light: editorWidgetBackground, dark: editorWidgetBackground, hc: editorWidgetBackground}, localize("hoverBackground", "Background color of the editor hover."));
var editorHoverForeground = registerColor("editorHoverWidget.foreground", {light: editorWidgetForeground, dark: editorWidgetForeground, hc: editorWidgetForeground}, localize("hoverForeground", "Foreground color of the editor hover."));
var editorHoverBorder = registerColor("editorHoverWidget.border", {light: editorWidgetBorder, dark: editorWidgetBorder, hc: editorWidgetBorder}, localize("hoverBorder", "Border color of the editor hover."));
var editorHoverStatusBarBackground = registerColor("editorHoverWidget.statusBarBackground", {dark: lighten(editorHoverBackground, 0.2), light: darken(editorHoverBackground, 0.05), hc: editorWidgetBackground}, localize("statusBarBackground", "Background color of the editor hover status bar."));
var editorActiveLinkForeground = registerColor("editorLink.activeForeground", {dark: "#4E94CE", light: Color.blue, hc: Color.cyan}, localize("activeLinkForeground", "Color of active links."));
var editorLightBulbForeground = registerColor("editorLightBulb.foreground", {dark: "#FFCC00", light: "#DDB100", hc: "#FFCC00"}, localize("editorLightBulbForeground", "The color used for the lightbulb actions icon."));
var editorLightBulbAutoFixForeground = registerColor("editorLightBulbAutoFix.foreground", {dark: "#75BEFF", light: "#007ACC", hc: "#75BEFF"}, localize("editorLightBulbAutoFixForeground", "The color used for the lightbulb auto fix actions icon."));
var defaultInsertColor = new Color(new RGBA(155, 185, 85, 0.2));
var defaultRemoveColor = new Color(new RGBA(255, 0, 0, 0.2));
var diffInserted = registerColor("diffEditor.insertedTextBackground", {dark: defaultInsertColor, light: defaultInsertColor, hc: null}, localize("diffEditorInserted", "Background color for text that got inserted. The color must not be opaque so as not to hide underlying decorations."), true);
var diffRemoved = registerColor("diffEditor.removedTextBackground", {dark: defaultRemoveColor, light: defaultRemoveColor, hc: null}, localize("diffEditorRemoved", "Background color for text that got removed. The color must not be opaque so as not to hide underlying decorations."), true);
var diffInsertedOutline = registerColor("diffEditor.insertedTextBorder", {dark: null, light: null, hc: "#33ff2eff"}, localize("diffEditorInsertedOutline", "Outline color for the text that got inserted."));
var diffRemovedOutline = registerColor("diffEditor.removedTextBorder", {dark: null, light: null, hc: "#FF008F"}, localize("diffEditorRemovedOutline", "Outline color for text that got removed."));
var diffBorder = registerColor("diffEditor.border", {dark: null, light: null, hc: contrastBorder}, localize("diffEditorBorder", "Border color between the two text editors."));
var diffDiagonalFill = registerColor("diffEditor.diagonalFill", {dark: "#cccccc33", light: "#22222233", hc: null}, localize("diffDiagonalFill", "Color of the diff editor's diagonal fill. The diagonal fill is used in side-by-side diff views."));
var listFocusBackground = registerColor("list.focusBackground", {dark: "#062F4A", light: "#D6EBFF", hc: null}, localize("listFocusBackground", "List/Tree background color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
var listFocusForeground = registerColor("list.focusForeground", {dark: null, light: null, hc: null}, localize("listFocusForeground", "List/Tree foreground color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
var listActiveSelectionBackground = registerColor("list.activeSelectionBackground", {dark: "#094771", light: "#0074E8", hc: null}, localize("listActiveSelectionBackground", "List/Tree background color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
var listActiveSelectionForeground = registerColor("list.activeSelectionForeground", {dark: Color.white, light: Color.white, hc: null}, localize("listActiveSelectionForeground", "List/Tree foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
var listInactiveSelectionBackground = registerColor("list.inactiveSelectionBackground", {dark: "#37373D", light: "#E4E6F1", hc: null}, localize("listInactiveSelectionBackground", "List/Tree background color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
var listInactiveSelectionForeground = registerColor("list.inactiveSelectionForeground", {dark: null, light: null, hc: null}, localize("listInactiveSelectionForeground", "List/Tree foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
var listInactiveFocusBackground = registerColor("list.inactiveFocusBackground", {dark: null, light: null, hc: null}, localize("listInactiveFocusBackground", "List/Tree background color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
var listHoverBackground = registerColor("list.hoverBackground", {dark: "#2A2D2E", light: "#F0F0F0", hc: null}, localize("listHoverBackground", "List/Tree background when hovering over items using the mouse."));
var listHoverForeground = registerColor("list.hoverForeground", {dark: null, light: null, hc: null}, localize("listHoverForeground", "List/Tree foreground when hovering over items using the mouse."));
var listDropBackground = registerColor("list.dropBackground", {dark: listFocusBackground, light: listFocusBackground, hc: null}, localize("listDropBackground", "List/Tree drag and drop background when moving items around using the mouse."));
var listHighlightForeground = registerColor("list.highlightForeground", {dark: "#0097fb", light: "#0066BF", hc: focusBorder}, localize("highlight", "List/Tree foreground color of the match highlights when searching inside the list/tree."));
var listFilterWidgetBackground = registerColor("listFilterWidget.background", {light: "#efc1ad", dark: "#653723", hc: Color.black}, localize("listFilterWidgetBackground", "Background color of the type filter widget in lists and trees."));
var listFilterWidgetOutline = registerColor("listFilterWidget.outline", {dark: Color.transparent, light: Color.transparent, hc: "#f38518"}, localize("listFilterWidgetOutline", "Outline color of the type filter widget in lists and trees."));
var listFilterWidgetNoMatchesOutline = registerColor("listFilterWidget.noMatchesOutline", {dark: "#BE1100", light: "#BE1100", hc: contrastBorder}, localize("listFilterWidgetNoMatchesOutline", "Outline color of the type filter widget in lists and trees, when there are no matches."));
var treeIndentGuidesStroke = registerColor("tree.indentGuidesStroke", {dark: "#585858", light: "#a9a9a9", hc: "#a9a9a9"}, localize("treeIndentGuidesStroke", "Tree stroke color for the indentation guides."));
var menuBorder = registerColor("menu.border", {dark: null, light: null, hc: contrastBorder}, localize("menuBorder", "Border color of menus."));
var menuForeground = registerColor("menu.foreground", {dark: selectForeground, light: foreground, hc: selectForeground}, localize("menuForeground", "Foreground color of menu items."));
var menuBackground = registerColor("menu.background", {dark: selectBackground, light: selectBackground, hc: selectBackground}, localize("menuBackground", "Background color of menu items."));
var menuSelectionForeground = registerColor("menu.selectionForeground", {dark: listActiveSelectionForeground, light: listActiveSelectionForeground, hc: listActiveSelectionForeground}, localize("menuSelectionForeground", "Foreground color of the selected menu item in menus."));
var menuSelectionBackground = registerColor("menu.selectionBackground", {dark: listActiveSelectionBackground, light: listActiveSelectionBackground, hc: listActiveSelectionBackground}, localize("menuSelectionBackground", "Background color of the selected menu item in menus."));
var menuSelectionBorder = registerColor("menu.selectionBorder", {dark: null, light: null, hc: activeContrastBorder}, localize("menuSelectionBorder", "Border color of the selected menu item in menus."));
var menuSeparatorBackground = registerColor("menu.separatorBackground", {dark: "#BBBBBB", light: "#888888", hc: contrastBorder}, localize("menuSeparatorBackground", "Color of a separator menu item in menus."));
var snippetTabstopHighlightBackground = registerColor("editor.snippetTabstopHighlightBackground", {dark: new Color(new RGBA(124, 124, 124, 0.3)), light: new Color(new RGBA(10, 50, 100, 0.2)), hc: new Color(new RGBA(124, 124, 124, 0.3))}, localize("snippetTabstopHighlightBackground", "Highlight background color of a snippet tabstop."));
var snippetTabstopHighlightBorder = registerColor("editor.snippetTabstopHighlightBorder", {dark: null, light: null, hc: null}, localize("snippetTabstopHighlightBorder", "Highlight border color of a snippet tabstop."));
var snippetFinalTabstopHighlightBackground = registerColor("editor.snippetFinalTabstopHighlightBackground", {dark: null, light: null, hc: null}, localize("snippetFinalTabstopHighlightBackground", "Highlight background color of the final tabstop of a snippet."));
var snippetFinalTabstopHighlightBorder = registerColor("editor.snippetFinalTabstopHighlightBorder", {dark: "#525252", light: new Color(new RGBA(10, 50, 100, 0.5)), hc: "#525252"}, localize("snippetFinalTabstopHighlightBorder", "Highlight border color of the final tabstop of a snippet."));
var overviewRulerFindMatchForeground = registerColor("editorOverviewRuler.findMatchForeground", {dark: "#d186167e", light: "#d186167e", hc: "#AB5A00"}, localize("overviewRulerFindMatchForeground", "Overview ruler marker color for find matches. The color must not be opaque so as not to hide underlying decorations."), true);
var overviewRulerSelectionHighlightForeground = registerColor("editorOverviewRuler.selectionHighlightForeground", {dark: "#A0A0A0CC", light: "#A0A0A0CC", hc: "#A0A0A0CC"}, localize("overviewRulerSelectionHighlightForeground", "Overview ruler marker color for selection highlights. The color must not be opaque so as not to hide underlying decorations."), true);
var minimapFindMatch = registerColor("minimap.findMatchHighlight", {light: "#d18616", dark: "#d18616", hc: "#AB5A00"}, localize("minimapFindMatchHighlight", "Minimap marker color for find matches."), true);
var minimapSelection = registerColor("minimap.selectionHighlight", {light: "#ADD6FF", dark: "#264F78", hc: "#ffffff"}, localize("minimapSelectionHighlight", "Minimap marker color for the editor selection."), true);
var minimapError = registerColor("minimap.errorHighlight", {dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hc: new Color(new RGBA(255, 50, 50, 1))}, localize("minimapError", "Minimap marker color for errors."));
var minimapWarning = registerColor("minimap.warningHighlight", {dark: editorWarningForeground, light: editorWarningForeground, hc: editorWarningBorder}, localize("overviewRuleWarning", "Minimap marker color for warnings."));
var minimapBackground = registerColor("minimap.background", {dark: null, light: null, hc: null}, localize("minimapBackground", "Minimap background color."));
var minimapSliderBackground = registerColor("minimapSlider.background", {light: transparent(scrollbarSliderBackground, 0.5), dark: transparent(scrollbarSliderBackground, 0.5), hc: transparent(scrollbarSliderBackground, 0.5)}, localize("minimapSliderBackground", "Minimap slider background color."));
var minimapSliderHoverBackground = registerColor("minimapSlider.hoverBackground", {light: transparent(scrollbarSliderHoverBackground, 0.5), dark: transparent(scrollbarSliderHoverBackground, 0.5), hc: transparent(scrollbarSliderHoverBackground, 0.5)}, localize("minimapSliderHoverBackground", "Minimap slider background color when hovering."));
var minimapSliderActiveBackground = registerColor("minimapSlider.activeBackground", {light: transparent(scrollbarSliderActiveBackground, 0.5), dark: transparent(scrollbarSliderActiveBackground, 0.5), hc: transparent(scrollbarSliderActiveBackground, 0.5)}, localize("minimapSliderActiveBackground", "Minimap slider background color when clicked on."));
var problemsErrorIconForeground = registerColor("problemsErrorIcon.foreground", {dark: editorErrorForeground, light: editorErrorForeground, hc: editorErrorForeground}, localize("problemsErrorIconForeground", "The color used for the problems error icon."));
var problemsWarningIconForeground = registerColor("problemsWarningIcon.foreground", {dark: editorWarningForeground, light: editorWarningForeground, hc: editorWarningForeground}, localize("problemsWarningIconForeground", "The color used for the problems warning icon."));
var problemsInfoIconForeground = registerColor("problemsInfoIcon.foreground", {dark: editorInfoForeground, light: editorInfoForeground, hc: editorInfoForeground}, localize("problemsInfoIconForeground", "The color used for the problems info icon."));
function darken(colorValue, factor) {
  return (theme) => {
    let color2 = resolveColorValue(colorValue, theme);
    if (color2) {
      return color2.darken(factor);
    }
    return void 0;
  };
}
function lighten(colorValue, factor) {
  return (theme) => {
    let color2 = resolveColorValue(colorValue, theme);
    if (color2) {
      return color2.lighten(factor);
    }
    return void 0;
  };
}
function transparent(colorValue, factor) {
  return (theme) => {
    let color2 = resolveColorValue(colorValue, theme);
    if (color2) {
      return color2.transparent(factor);
    }
    return void 0;
  };
}
function lessProminent(colorValue, backgroundColorValue, factor, transparency) {
  return (theme) => {
    let from = resolveColorValue(colorValue, theme);
    if (from) {
      let backgroundColor = resolveColorValue(backgroundColorValue, theme);
      if (backgroundColor) {
        if (from.isDarkerThan(backgroundColor)) {
          return Color.getLighterColor(from, backgroundColor, factor).transparent(transparency);
        }
        return Color.getDarkerColor(from, backgroundColor, factor).transparent(transparency);
      }
      return from.transparent(factor * transparency);
    }
    return void 0;
  };
}
function resolveColorValue(colorValue, theme) {
  if (colorValue === null) {
    return void 0;
  } else if (typeof colorValue === "string") {
    if (colorValue[0] === "#") {
      return Color.fromHex(colorValue);
    }
    return theme.getColor(colorValue);
  } else if (colorValue instanceof Color) {
    return colorValue;
  } else if (typeof colorValue === "function") {
    return colorValue(theme);
  }
  return void 0;
}
var workbenchColorsSchemaId = "vscode://schemas/workbench-colors";
var schemaRegistry = Registry$1.as(Extensions.JSONContribution);
schemaRegistry.registerSchema(workbenchColorsSchemaId, colorRegistry.getColorSchema());
var delayer = new RunOnceScheduler(() => schemaRegistry.notifySchemaChanged(workbenchColorsSchemaId), 200);
colorRegistry.onDidChangeSchema(() => {
  if (!delayer.isScheduled()) {
    delayer.schedule();
  }
});
var editorLineHighlight = registerColor("editor.lineHighlightBackground", {dark: null, light: null, hc: null}, localize("lineHighlight", "Background color for the highlight of line at the cursor position."));
var editorLineHighlightBorder = registerColor("editor.lineHighlightBorder", {dark: "#282828", light: "#eeeeee", hc: "#f38518"}, localize("lineHighlightBorderBox", "Background color for the border around the line at the cursor position."));
var editorRangeHighlight = registerColor("editor.rangeHighlightBackground", {dark: "#ffffff0b", light: "#fdff0033", hc: null}, localize("rangeHighlight", "Background color of highlighted ranges, like by quick open and find features. The color must not be opaque so as not to hide underlying decorations."), true);
var editorRangeHighlightBorder = registerColor("editor.rangeHighlightBorder", {dark: null, light: null, hc: activeContrastBorder}, localize("rangeHighlightBorder", "Background color of the border around highlighted ranges."), true);
var editorSymbolHighlight = registerColor("editor.symbolHighlightBackground", {dark: editorFindMatchHighlight, light: editorFindMatchHighlight, hc: null}, localize("symbolHighlight", "Background color of highlighted symbol, like for go to definition or go next/previous symbol. The color must not be opaque so as not to hide underlying decorations."), true);
var editorSymbolHighlightBorder = registerColor("editor.symbolHighlightBorder", {dark: null, light: null, hc: activeContrastBorder}, localize("symbolHighlightBorder", "Background color of the border around highlighted symbols."), true);
var editorCursorForeground = registerColor("editorCursor.foreground", {dark: "#AEAFAD", light: Color.black, hc: Color.white}, localize("caret", "Color of the editor cursor."));
var editorCursorBackground = registerColor("editorCursor.background", null, localize("editorCursorBackground", "The background color of the editor cursor. Allows customizing the color of a character overlapped by a block cursor."));
var editorWhitespaces = registerColor("editorWhitespace.foreground", {dark: "#e3e4e229", light: "#33333333", hc: "#e3e4e229"}, localize("editorWhitespaces", "Color of whitespace characters in the editor."));
var editorIndentGuides = registerColor("editorIndentGuide.background", {dark: editorWhitespaces, light: editorWhitespaces, hc: editorWhitespaces}, localize("editorIndentGuides", "Color of the editor indentation guides."));
var editorActiveIndentGuides = registerColor("editorIndentGuide.activeBackground", {dark: editorWhitespaces, light: editorWhitespaces, hc: editorWhitespaces}, localize("editorActiveIndentGuide", "Color of the active editor indentation guides."));
var editorLineNumbers = registerColor("editorLineNumber.foreground", {dark: "#858585", light: "#237893", hc: Color.white}, localize("editorLineNumbers", "Color of editor line numbers."));
var deprecatedEditorActiveLineNumber = registerColor("editorActiveLineNumber.foreground", {dark: "#c6c6c6", light: "#0B216F", hc: activeContrastBorder}, localize("editorActiveLineNumber", "Color of editor active line number"), false, localize("deprecatedEditorActiveLineNumber", "Id is deprecated. Use 'editorLineNumber.activeForeground' instead."));
var editorActiveLineNumber = registerColor("editorLineNumber.activeForeground", {dark: deprecatedEditorActiveLineNumber, light: deprecatedEditorActiveLineNumber, hc: deprecatedEditorActiveLineNumber}, localize("editorActiveLineNumber", "Color of editor active line number"));
var editorRuler = registerColor("editorRuler.foreground", {dark: "#5A5A5A", light: Color.lightgrey, hc: Color.white}, localize("editorRuler", "Color of the editor rulers."));
var editorCodeLensForeground = registerColor("editorCodeLens.foreground", {dark: "#999999", light: "#999999", hc: "#999999"}, localize("editorCodeLensForeground", "Foreground color of editor CodeLens"));
var editorBracketMatchBackground = registerColor("editorBracketMatch.background", {dark: "#0064001a", light: "#0064001a", hc: "#0064001a"}, localize("editorBracketMatchBackground", "Background color behind matching brackets"));
var editorBracketMatchBorder = registerColor("editorBracketMatch.border", {dark: "#888", light: "#B9B9B9", hc: contrastBorder}, localize("editorBracketMatchBorder", "Color for matching brackets boxes"));
var editorOverviewRulerBorder = registerColor("editorOverviewRuler.border", {dark: "#7f7f7f4d", light: "#7f7f7f4d", hc: "#7f7f7f4d"}, localize("editorOverviewRulerBorder", "Color of the overview ruler border."));
var editorOverviewRulerBackground = registerColor("editorOverviewRuler.background", null, localize("editorOverviewRulerBackground", "Background color of the editor overview ruler. Only used when the minimap is enabled and placed on the right side of the editor."));
var editorGutter = registerColor("editorGutter.background", {dark: editorBackground, light: editorBackground, hc: editorBackground}, localize("editorGutter", "Background color of the editor gutter. The gutter contains the glyph margins and the line numbers."));
var editorUnnecessaryCodeBorder = registerColor("editorUnnecessaryCode.border", {dark: null, light: null, hc: Color.fromHex("#fff").transparent(0.8)}, localize("unnecessaryCodeBorder", "Border color of unnecessary (unused) source code in the editor."));
var editorUnnecessaryCodeOpacity = registerColor("editorUnnecessaryCode.opacity", {dark: Color.fromHex("#000a"), light: Color.fromHex("#0007"), hc: null}, localize("unnecessaryCodeOpacity", `Opacity of unnecessary (unused) source code in the editor. For example, "#000000c0" will render the code with 75% opacity. For high contrast themes, use the  'editorUnnecessaryCode.border' theme color to underline unnecessary code instead of fading it out.`));
var rulerRangeDefault = new Color(new RGBA(0, 122, 204, 0.6));
var overviewRulerRangeHighlight = registerColor("editorOverviewRuler.rangeHighlightForeground", {dark: rulerRangeDefault, light: rulerRangeDefault, hc: rulerRangeDefault}, localize("overviewRulerRangeHighlight", "Overview ruler marker color for range highlights. The color must not be opaque so as not to hide underlying decorations."), true);
var overviewRulerError = registerColor("editorOverviewRuler.errorForeground", {dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hc: new Color(new RGBA(255, 50, 50, 1))}, localize("overviewRuleError", "Overview ruler marker color for errors."));
var overviewRulerWarning = registerColor("editorOverviewRuler.warningForeground", {dark: editorWarningForeground, light: editorWarningForeground, hc: editorWarningBorder}, localize("overviewRuleWarning", "Overview ruler marker color for warnings."));
var overviewRulerInfo = registerColor("editorOverviewRuler.infoForeground", {dark: editorInfoForeground, light: editorInfoForeground, hc: editorInfoBorder}, localize("overviewRuleInfo", "Overview ruler marker color for infos."));
registerThemingParticipant((theme, collector) => {
  const background = theme.getColor(editorBackground);
  if (background) {
    collector.addRule(`.monaco-editor, .monaco-editor-background, .monaco-editor .inputarea.ime-input { background-color: ${background}; }`);
  }
  const foreground2 = theme.getColor(editorForeground);
  if (foreground2) {
    collector.addRule(`.monaco-editor, .monaco-editor .inputarea.ime-input { color: ${foreground2}; }`);
  }
  const gutter = theme.getColor(editorGutter);
  if (gutter) {
    collector.addRule(`.monaco-editor .margin { background-color: ${gutter}; }`);
  }
  const rangeHighlight = theme.getColor(editorRangeHighlight);
  if (rangeHighlight) {
    collector.addRule(`.monaco-editor .rangeHighlight { background-color: ${rangeHighlight}; }`);
  }
  const rangeHighlightBorder = theme.getColor(editorRangeHighlightBorder);
  if (rangeHighlightBorder) {
    collector.addRule(`.monaco-editor .rangeHighlight { border: 1px ${theme.type === "hc" ? "dotted" : "solid"} ${rangeHighlightBorder}; }`);
  }
  const symbolHighlight = theme.getColor(editorSymbolHighlight);
  if (symbolHighlight) {
    collector.addRule(`.monaco-editor .symbolHighlight { background-color: ${symbolHighlight}; }`);
  }
  const symbolHighlightBorder = theme.getColor(editorSymbolHighlightBorder);
  if (symbolHighlightBorder) {
    collector.addRule(`.monaco-editor .symbolHighlight { border: 1px ${theme.type === "hc" ? "dotted" : "solid"} ${symbolHighlightBorder}; }`);
  }
  const invisibles = theme.getColor(editorWhitespaces);
  if (invisibles) {
    collector.addRule(`.monaco-editor .mtkw { color: ${invisibles} !important; }`);
    collector.addRule(`.monaco-editor .mtkz { color: ${invisibles} !important; }`);
  }
});
var LineNumbersOverlay = class extends DynamicViewOverlay {
  constructor(context2) {
    super();
    this._context = context2;
    this._readConfig();
    this._lastCursorModelPosition = new Position(1, 1);
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  _readConfig() {
    const options = this._context.configuration.options;
    this._lineHeight = options.get(51);
    const lineNumbers = options.get(52);
    this._renderLineNumbers = lineNumbers.renderType;
    this._renderCustomLineNumbers = lineNumbers.renderFn;
    this._renderFinalNewline = options.get(76);
    const layoutInfo = options.get(117);
    this._lineNumbersLeft = layoutInfo.lineNumbersLeft;
    this._lineNumbersWidth = layoutInfo.lineNumbersWidth;
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  onConfigurationChanged(e2) {
    this._readConfig();
    return true;
  }
  onCursorStateChanged(e2) {
    const primaryViewPosition = e2.selections[0].getPosition();
    this._lastCursorModelPosition = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(primaryViewPosition);
    if (this._renderLineNumbers === 2 || this._renderLineNumbers === 3) {
      return true;
    }
    return false;
  }
  onFlushed(e2) {
    return true;
  }
  onLinesChanged(e2) {
    return true;
  }
  onLinesDeleted(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollTopChanged;
  }
  onZonesChanged(e2) {
    return true;
  }
  _getLineRenderLineNumber(viewLineNumber) {
    const modelPosition = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new Position(viewLineNumber, 1));
    if (modelPosition.column !== 1) {
      return "";
    }
    const modelLineNumber = modelPosition.lineNumber;
    if (this._renderCustomLineNumbers) {
      return this._renderCustomLineNumbers(modelLineNumber);
    }
    if (this._renderLineNumbers === 2) {
      const diff = Math.abs(this._lastCursorModelPosition.lineNumber - modelLineNumber);
      if (diff === 0) {
        return '<span class="relative-current-line-number">' + modelLineNumber + "</span>";
      }
      return String(diff);
    }
    if (this._renderLineNumbers === 3) {
      if (this._lastCursorModelPosition.lineNumber === modelLineNumber) {
        return String(modelLineNumber);
      }
      if (modelLineNumber % 10 === 0) {
        return String(modelLineNumber);
      }
      return "";
    }
    return String(modelLineNumber);
  }
  prepareRender(ctx) {
    if (this._renderLineNumbers === 0) {
      this._renderResult = null;
      return;
    }
    const lineHeightClassName = isLinux ? this._lineHeight % 2 === 0 ? " lh-even" : " lh-odd" : "";
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const common = '<div class="' + LineNumbersOverlay.CLASS_NAME + lineHeightClassName + '" style="left:' + this._lineNumbersLeft.toString() + "px;width:" + this._lineNumbersWidth.toString() + 'px;">';
    const lineCount = this._context.model.getLineCount();
    const output2 = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      if (!this._renderFinalNewline) {
        if (lineNumber === lineCount && this._context.model.getLineLength(lineNumber) === 0) {
          output2[lineIndex] = "";
          continue;
        }
      }
      const renderLineNumber = this._getLineRenderLineNumber(lineNumber);
      if (renderLineNumber) {
        output2[lineIndex] = common + renderLineNumber + "</div>";
      } else {
        output2[lineIndex] = "";
      }
    }
    this._renderResult = output2;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
      return "";
    }
    return this._renderResult[lineIndex];
  }
};
LineNumbersOverlay.CLASS_NAME = "line-numbers";
registerThemingParticipant((theme, collector) => {
  const lineNumbers = theme.getColor(editorLineNumbers);
  if (lineNumbers) {
    collector.addRule(`.monaco-editor .line-numbers { color: ${lineNumbers}; }`);
  }
  const activeLineNumber = theme.getColor(editorActiveLineNumber);
  if (activeLineNumber) {
    collector.addRule(`.monaco-editor .current-line ~ .line-numbers { color: ${activeLineNumber}; }`);
  }
});
var Margin = class extends ViewPart {
  constructor(context2) {
    super(context2);
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._canUseLayerHinting = !options.get(23);
    this._contentLeft = layoutInfo.contentLeft;
    this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
    this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
    this._domNode = createFastDomNode(document.createElement("div"));
    this._domNode.setClassName(Margin.OUTER_CLASS_NAME);
    this._domNode.setPosition("absolute");
    this._domNode.setAttribute("role", "presentation");
    this._domNode.setAttribute("aria-hidden", "true");
    this._glyphMarginBackgroundDomNode = createFastDomNode(document.createElement("div"));
    this._glyphMarginBackgroundDomNode.setClassName(Margin.CLASS_NAME);
    this._domNode.appendChild(this._glyphMarginBackgroundDomNode);
  }
  dispose() {
    super.dispose();
  }
  getDomNode() {
    return this._domNode;
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._canUseLayerHinting = !options.get(23);
    this._contentLeft = layoutInfo.contentLeft;
    this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
    this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
    return true;
  }
  onScrollChanged(e2) {
    return super.onScrollChanged(e2) || e2.scrollTopChanged;
  }
  prepareRender(ctx) {
  }
  render(ctx) {
    this._domNode.setLayerHinting(this._canUseLayerHinting);
    this._domNode.setContain("strict");
    const adjustedScrollTop = ctx.scrollTop - ctx.bigNumbersDelta;
    this._domNode.setTop(-adjustedScrollTop);
    const height = Math.min(ctx.scrollHeight, 1e6);
    this._domNode.setHeight(height);
    this._domNode.setWidth(this._contentLeft);
    this._glyphMarginBackgroundDomNode.setLeft(this._glyphMarginLeft);
    this._glyphMarginBackgroundDomNode.setWidth(this._glyphMarginWidth);
    this._glyphMarginBackgroundDomNode.setHeight(height);
  }
};
Margin.CLASS_NAME = "glyph-margin";
Margin.OUTER_CLASS_NAME = "margin";
function __snowpack__injectStyle$5(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$5("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-mouse-cursor-text {\r\n	cursor: text;\r\n}\r\n\r\n/* The following selector looks a bit funny, but that is needed to cover all the workbench and the editor!! */\r\n.vs-dark .mac .monaco-mouse-cursor-text, .hc-black .mac .monaco-mouse-cursor-text,\r\n.vs-dark.mac .monaco-mouse-cursor-text, .hc-black.mac .monaco-mouse-cursor-text {\r\n	cursor: -webkit-image-set(url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAAL0lEQVQoz2NgCD3x//9/BhBYBWdhgFVAiVW4JBFKGIa4AqD0//9D3pt4I4tAdAMAHTQ/j5Zom30AAAAASUVORK5CYII=) 1x, url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAAz0lEQVRIx2NgYGBY/R8I/vx5eelX3n82IJ9FxGf6tksvf/8FiTMQAcAGQMDvSwu09abffY8QYSAScNk45G198eX//yev73/4///701eh//kZSARckrNBRvz//+8+6ZohwCzjGNjdgQxkAg7B9WADeBjIBqtJCbhRA0YNoIkBSNmaPEMoNmA0FkYNoFKhapJ6FGyAH3nauaSmPfwI0v/3OukVi0CIZ+F25KrtYcx/CTIy0e+rC7R1Z4KMICVTQQ14feVXIbR695u14+Ir4gwAAD49E54wc1kWAAAAAElFTkSuQmCC) 2x) 5 8, text;\r\n}\r\n");
var MOUSE_CURSOR_TEXT_CSS_CLASS_NAME = `monaco-mouse-cursor-text`;
var VisibleTextAreaData = class {
  constructor(top2, left2, width2) {
    this.top = top2;
    this.left = left2;
    this.width = width2;
  }
  setWidth(width2) {
    return new VisibleTextAreaData(this.top, this.left, width2);
  }
};
var canUseZeroSizeTextarea = isEdge2 || isFirefox;
var TextAreaHandler = class extends ViewPart {
  constructor(context2, viewController, viewHelper) {
    super(context2);
    this._primaryCursorPosition = new Position(1, 1);
    this._primaryCursorVisibleRange = null;
    this._viewController = viewController;
    this._viewHelper = viewHelper;
    this._scrollLeft = 0;
    this._scrollTop = 0;
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._setAccessibilityOptions(options);
    this._contentLeft = layoutInfo.contentLeft;
    this._contentWidth = layoutInfo.contentWidth;
    this._contentHeight = layoutInfo.height;
    this._fontInfo = options.get(36);
    this._lineHeight = options.get(51);
    this._emptySelectionClipboard = options.get(26);
    this._copyWithSyntaxHighlighting = options.get(16);
    this._visibleTextArea = null;
    this._selections = [new Selection(1, 1, 1, 1)];
    this._modelSelections = [new Selection(1, 1, 1, 1)];
    this._lastRenderPosition = null;
    this.textArea = createFastDomNode(document.createElement("textarea"));
    PartFingerprints.write(this.textArea, 6);
    this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
    this.textArea.setAttribute("wrap", "off");
    this.textArea.setAttribute("autocorrect", "off");
    this.textArea.setAttribute("autocapitalize", "off");
    this.textArea.setAttribute("autocomplete", "off");
    this.textArea.setAttribute("spellcheck", "false");
    this.textArea.setAttribute("aria-label", this._getAriaLabel(options));
    this.textArea.setAttribute("tabindex", String(options.get(102)));
    this.textArea.setAttribute("role", "textbox");
    this.textArea.setAttribute("aria-roledescription", localize("editor", "editor"));
    this.textArea.setAttribute("aria-multiline", "true");
    this.textArea.setAttribute("aria-haspopup", "false");
    this.textArea.setAttribute("aria-autocomplete", "both");
    if (isWeb2 && options.get(72)) {
      this.textArea.setAttribute("readonly", "true");
    }
    this.textAreaCover = createFastDomNode(document.createElement("div"));
    this.textAreaCover.setPosition("absolute");
    const simpleModel = {
      getLineCount: () => {
        return this._context.model.getLineCount();
      },
      getLineMaxColumn: (lineNumber) => {
        return this._context.model.getLineMaxColumn(lineNumber);
      },
      getValueInRange: (range3, eol) => {
        return this._context.model.getValueInRange(range3, eol);
      }
    };
    const textAreaInputHost = {
      getDataToCopy: (generateHTML) => {
        const rawTextToCopy = this._context.model.getPlainTextToCopy(this._modelSelections, this._emptySelectionClipboard, isWindows);
        const newLineCharacter = this._context.model.getEOL();
        const isFromEmptySelection = this._emptySelectionClipboard && this._modelSelections.length === 1 && this._modelSelections[0].isEmpty();
        const multicursorText = Array.isArray(rawTextToCopy) ? rawTextToCopy : null;
        const text = Array.isArray(rawTextToCopy) ? rawTextToCopy.join(newLineCharacter) : rawTextToCopy;
        let html = void 0;
        let mode = null;
        if (generateHTML) {
          if (this._copyWithSyntaxHighlighting && text.length < 65536) {
            const richText = this._context.model.getRichTextToCopy(this._modelSelections, this._emptySelectionClipboard);
            if (richText) {
              html = richText.html;
              mode = richText.mode;
            }
          }
        }
        return {
          isFromEmptySelection,
          multicursorText,
          text,
          html,
          mode
        };
      },
      getScreenReaderContent: (currentState) => {
        if (this._accessibilitySupport === 1) {
          if (isMacintosh) {
            const selection2 = this._selections[0];
            if (selection2.isEmpty()) {
              const position2 = selection2.getStartPosition();
              let textBefore = this._getWordBeforePosition(position2);
              if (textBefore.length === 0) {
                textBefore = this._getCharacterBeforePosition(position2);
              }
              if (textBefore.length > 0) {
                return new TextAreaState(textBefore, textBefore.length, textBefore.length, position2, position2);
              }
            }
          }
          return TextAreaState.EMPTY;
        }
        return PagedScreenReaderStrategy.fromEditorSelection(currentState, simpleModel, this._selections[0], this._accessibilityPageSize, this._accessibilitySupport === 0);
      },
      deduceModelPosition: (viewAnchorPosition, deltaOffset, lineFeedCnt) => {
        return this._context.model.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt);
      }
    };
    this._textAreaInput = this._register(new TextAreaInput(textAreaInputHost, this.textArea));
    this._register(this._textAreaInput.onKeyDown((e2) => {
      this._viewController.emitKeyDown(e2);
    }));
    this._register(this._textAreaInput.onKeyUp((e2) => {
      this._viewController.emitKeyUp(e2);
    }));
    this._register(this._textAreaInput.onPaste((e2) => {
      let pasteOnNewLine = false;
      let multicursorText = null;
      let mode = null;
      if (e2.metadata) {
        pasteOnNewLine = this._emptySelectionClipboard && !!e2.metadata.isFromEmptySelection;
        multicursorText = typeof e2.metadata.multicursorText !== "undefined" ? e2.metadata.multicursorText : null;
        mode = e2.metadata.mode;
      }
      this._viewController.paste(e2.text, pasteOnNewLine, multicursorText, mode);
    }));
    this._register(this._textAreaInput.onCut(() => {
      this._viewController.cut();
    }));
    this._register(this._textAreaInput.onType((e2) => {
      if (e2.replaceCharCnt) {
        this._viewController.replacePreviousChar(e2.text, e2.replaceCharCnt);
      } else {
        this._viewController.type(e2.text);
      }
    }));
    this._register(this._textAreaInput.onSelectionChangeRequest((modelSelection) => {
      this._viewController.setSelection(modelSelection);
    }));
    this._register(this._textAreaInput.onCompositionStart((e2) => {
      const lineNumber = this._selections[0].startLineNumber;
      const column = this._selections[0].startColumn - (e2.moveOneCharacterLeft ? 1 : 0);
      this._context.model.revealRange("keyboard", true, new Range(lineNumber, column, lineNumber, column), 0, 1);
      const visibleRange = this._viewHelper.visibleRangeForPositionRelativeToEditor(lineNumber, column);
      if (visibleRange) {
        this._visibleTextArea = new VisibleTextAreaData(this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber), visibleRange.left, canUseZeroSizeTextarea ? 0 : 1);
        this._render();
      }
      this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ime-input`);
      this._viewController.compositionStart();
    }));
    this._register(this._textAreaInput.onCompositionUpdate((e2) => {
      if (isEdge2) {
        this._visibleTextArea = this._visibleTextArea.setWidth(0);
      } else {
        this._visibleTextArea = this._visibleTextArea.setWidth(measureText(e2.data, this._fontInfo));
      }
      this._render();
    }));
    this._register(this._textAreaInput.onCompositionEnd(() => {
      this._visibleTextArea = null;
      this._render();
      this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
      this._viewController.compositionEnd();
    }));
    this._register(this._textAreaInput.onFocus(() => {
      this._context.model.setHasFocus(true);
    }));
    this._register(this._textAreaInput.onBlur(() => {
      this._context.model.setHasFocus(false);
    }));
  }
  dispose() {
    super.dispose();
  }
  _getWordBeforePosition(position2) {
    const lineContent = this._context.model.getLineContent(position2.lineNumber);
    const wordSeparators2 = getMapForWordSeparators(this._context.configuration.options.get(105));
    let column = position2.column;
    let distance = 0;
    while (column > 1) {
      const charCode = lineContent.charCodeAt(column - 2);
      const charClass = wordSeparators2.get(charCode);
      if (charClass !== 0 || distance > 50) {
        return lineContent.substring(column - 1, position2.column - 1);
      }
      distance++;
      column--;
    }
    return lineContent.substring(0, position2.column - 1);
  }
  _getCharacterBeforePosition(position2) {
    if (position2.column > 1) {
      const lineContent = this._context.model.getLineContent(position2.lineNumber);
      const charBefore = lineContent.charAt(position2.column - 2);
      if (!isHighSurrogate(charBefore.charCodeAt(0))) {
        return charBefore;
      }
    }
    return "";
  }
  _getAriaLabel(options) {
    const accessibilitySupport = options.get(2);
    if (accessibilitySupport === 1) {
      return localize("accessibilityOffAriaLabel", "The editor is not accessible at this time. Press {0} for options.", isLinux ? "Shift+Alt+F1" : "Alt+F1");
    }
    return options.get(4);
  }
  _setAccessibilityOptions(options) {
    this._accessibilitySupport = options.get(2);
    const accessibilityPageSize = options.get(3);
    if (this._accessibilitySupport === 2 && accessibilityPageSize === EditorOptions.accessibilityPageSize.defaultValue) {
      this._accessibilityPageSize = 100;
    } else {
      this._accessibilityPageSize = accessibilityPageSize;
    }
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._setAccessibilityOptions(options);
    this._contentLeft = layoutInfo.contentLeft;
    this._contentWidth = layoutInfo.contentWidth;
    this._contentHeight = layoutInfo.height;
    this._fontInfo = options.get(36);
    this._lineHeight = options.get(51);
    this._emptySelectionClipboard = options.get(26);
    this._copyWithSyntaxHighlighting = options.get(16);
    this.textArea.setAttribute("aria-label", this._getAriaLabel(options));
    this.textArea.setAttribute("tabindex", String(options.get(102)));
    if (isWeb2 && e2.hasChanged(72)) {
      if (options.get(72)) {
        this.textArea.setAttribute("readonly", "true");
      } else {
        this.textArea.removeAttribute("readonly");
      }
    }
    if (e2.hasChanged(2)) {
      this._textAreaInput.writeScreenReaderContent("strategy changed");
    }
    return true;
  }
  onCursorStateChanged(e2) {
    this._selections = e2.selections.slice(0);
    this._modelSelections = e2.modelSelections.slice(0);
    this._textAreaInput.writeScreenReaderContent("selection changed");
    return true;
  }
  onDecorationsChanged(e2) {
    return true;
  }
  onFlushed(e2) {
    return true;
  }
  onLinesChanged(e2) {
    return true;
  }
  onLinesDeleted(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    this._scrollLeft = e2.scrollLeft;
    this._scrollTop = e2.scrollTop;
    return true;
  }
  onZonesChanged(e2) {
    return true;
  }
  isFocused() {
    return this._textAreaInput.isFocused();
  }
  focusTextArea() {
    this._textAreaInput.focusTextArea();
  }
  getLastRenderData() {
    return this._lastRenderPosition;
  }
  setAriaOptions(options) {
    if (options.activeDescendant) {
      this.textArea.setAttribute("aria-haspopup", "true");
      this.textArea.setAttribute("aria-autocomplete", "list");
      this.textArea.setAttribute("aria-activedescendant", options.activeDescendant);
    } else {
      this.textArea.setAttribute("aria-haspopup", "false");
      this.textArea.setAttribute("aria-autocomplete", "both");
      this.textArea.removeAttribute("aria-activedescendant");
    }
    if (options.role) {
      this.textArea.setAttribute("role", options.role);
    }
  }
  prepareRender(ctx) {
    this._primaryCursorPosition = new Position(this._selections[0].positionLineNumber, this._selections[0].positionColumn);
    this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(this._primaryCursorPosition);
  }
  render(ctx) {
    this._textAreaInput.writeScreenReaderContent("render");
    this._render();
  }
  _render() {
    if (this._visibleTextArea) {
      this._renderInsideEditor(null, this._visibleTextArea.top - this._scrollTop, this._contentLeft + this._visibleTextArea.left - this._scrollLeft, this._visibleTextArea.width, this._lineHeight);
      return;
    }
    if (!this._primaryCursorVisibleRange) {
      this._renderAtTopLeft();
      return;
    }
    const left2 = this._contentLeft + this._primaryCursorVisibleRange.left - this._scrollLeft;
    if (left2 < this._contentLeft || left2 > this._contentLeft + this._contentWidth) {
      this._renderAtTopLeft();
      return;
    }
    const top2 = this._context.viewLayout.getVerticalOffsetForLineNumber(this._selections[0].positionLineNumber) - this._scrollTop;
    if (top2 < 0 || top2 > this._contentHeight) {
      this._renderAtTopLeft();
      return;
    }
    if (isMacintosh) {
      this._renderInsideEditor(this._primaryCursorPosition, top2, left2, canUseZeroSizeTextarea ? 0 : 1, this._lineHeight);
      return;
    }
    this._renderInsideEditor(this._primaryCursorPosition, top2, left2, canUseZeroSizeTextarea ? 0 : 1, canUseZeroSizeTextarea ? 0 : 1);
  }
  _renderInsideEditor(renderedPosition, top2, left2, width2, height) {
    this._lastRenderPosition = renderedPosition;
    const ta2 = this.textArea;
    const tac = this.textAreaCover;
    Configuration$1.applyFontInfo(ta2, this._fontInfo);
    ta2.setTop(top2);
    ta2.setLeft(left2);
    ta2.setWidth(width2);
    ta2.setHeight(height);
    tac.setTop(0);
    tac.setLeft(0);
    tac.setWidth(0);
    tac.setHeight(0);
  }
  _renderAtTopLeft() {
    this._lastRenderPosition = null;
    const ta2 = this.textArea;
    const tac = this.textAreaCover;
    Configuration$1.applyFontInfo(ta2, this._fontInfo);
    ta2.setTop(0);
    ta2.setLeft(0);
    tac.setTop(0);
    tac.setLeft(0);
    if (canUseZeroSizeTextarea) {
      ta2.setWidth(0);
      ta2.setHeight(0);
      tac.setWidth(0);
      tac.setHeight(0);
      return;
    }
    ta2.setWidth(1);
    ta2.setHeight(1);
    tac.setWidth(1);
    tac.setHeight(1);
    const options = this._context.configuration.options;
    if (options.get(42)) {
      tac.setClassName("monaco-editor-background textAreaCover " + Margin.OUTER_CLASS_NAME);
    } else {
      if (options.get(52).renderType !== 0) {
        tac.setClassName("monaco-editor-background textAreaCover " + LineNumbersOverlay.CLASS_NAME);
      } else {
        tac.setClassName("monaco-editor-background textAreaCover");
      }
    }
  }
};
function measureText(text, fontInfo) {
  const canvasElem = document.createElement("canvas");
  const context2 = canvasElem.getContext("2d");
  context2.font = createFontString(fontInfo);
  const metrics = context2.measureText(text);
  if (isFirefox) {
    return metrics.width + 2;
  } else {
    return metrics.width;
  }
}
function createFontString(bareFontInfo) {
  return doCreateFontString("normal", bareFontInfo.fontWeight, bareFontInfo.fontSize, bareFontInfo.lineHeight, bareFontInfo.fontFamily);
}
function doCreateFontString(fontStyle, fontWeight, fontSize, lineHeight, fontFamily) {
  return `${fontStyle} normal ${fontWeight} ${fontSize}px / ${lineHeight}px ${fontFamily}`;
}
var ColumnSelection = class {
  static columnSelect(config2, model, fromLineNumber, fromVisibleColumn, toLineNumber, toVisibleColumn) {
    let lineCount = Math.abs(toLineNumber - fromLineNumber) + 1;
    let reversed = fromLineNumber > toLineNumber;
    let isRTL = fromVisibleColumn > toVisibleColumn;
    let isLTR = fromVisibleColumn < toVisibleColumn;
    let result = [];
    for (let i3 = 0; i3 < lineCount; i3++) {
      let lineNumber = fromLineNumber + (reversed ? -i3 : i3);
      let startColumn = CursorColumns.columnFromVisibleColumn2(config2, model, lineNumber, fromVisibleColumn);
      let endColumn = CursorColumns.columnFromVisibleColumn2(config2, model, lineNumber, toVisibleColumn);
      let visibleStartColumn = CursorColumns.visibleColumnFromColumn2(config2, model, new Position(lineNumber, startColumn));
      let visibleEndColumn = CursorColumns.visibleColumnFromColumn2(config2, model, new Position(lineNumber, endColumn));
      if (isLTR) {
        if (visibleStartColumn > toVisibleColumn) {
          continue;
        }
        if (visibleEndColumn < fromVisibleColumn) {
          continue;
        }
      }
      if (isRTL) {
        if (visibleEndColumn > fromVisibleColumn) {
          continue;
        }
        if (visibleStartColumn < toVisibleColumn) {
          continue;
        }
      }
      result.push(new SingleCursorState(new Range(lineNumber, startColumn, lineNumber, startColumn), 0, new Position(lineNumber, endColumn), 0));
    }
    if (result.length === 0) {
      for (let i3 = 0; i3 < lineCount; i3++) {
        const lineNumber = fromLineNumber + (reversed ? -i3 : i3);
        const maxColumn = model.getLineMaxColumn(lineNumber);
        result.push(new SingleCursorState(new Range(lineNumber, maxColumn, lineNumber, maxColumn), 0, new Position(lineNumber, maxColumn), 0));
      }
    }
    return {
      viewStates: result,
      reversed,
      fromLineNumber,
      fromVisualColumn: fromVisibleColumn,
      toLineNumber,
      toVisualColumn: toVisibleColumn
    };
  }
  static columnSelectLeft(config2, model, prevColumnSelectData) {
    let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn;
    if (toViewVisualColumn > 1) {
      toViewVisualColumn--;
    }
    return ColumnSelection.columnSelect(config2, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn);
  }
  static columnSelectRight(config2, model, prevColumnSelectData) {
    let maxVisualViewColumn = 0;
    const minViewLineNumber = Math.min(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber);
    const maxViewLineNumber = Math.max(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber);
    for (let lineNumber = minViewLineNumber; lineNumber <= maxViewLineNumber; lineNumber++) {
      const lineMaxViewColumn = model.getLineMaxColumn(lineNumber);
      const lineMaxVisualViewColumn = CursorColumns.visibleColumnFromColumn2(config2, model, new Position(lineNumber, lineMaxViewColumn));
      maxVisualViewColumn = Math.max(maxVisualViewColumn, lineMaxVisualViewColumn);
    }
    let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn;
    if (toViewVisualColumn < maxVisualViewColumn) {
      toViewVisualColumn++;
    }
    return this.columnSelect(config2, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn);
  }
  static columnSelectUp(config2, model, prevColumnSelectData, isPaged) {
    const linesCount = isPaged ? config2.pageSize : 1;
    const toViewLineNumber = Math.max(1, prevColumnSelectData.toViewLineNumber - linesCount);
    return this.columnSelect(config2, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn);
  }
  static columnSelectDown(config2, model, prevColumnSelectData, isPaged) {
    const linesCount = isPaged ? config2.pageSize : 1;
    const toViewLineNumber = Math.min(model.getLineCount(), prevColumnSelectData.toViewLineNumber + linesCount);
    return this.columnSelect(config2, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn);
  }
};
var ReplaceCommand = class {
  constructor(range3, text, insertsAutoWhitespace = false) {
    this._range = range3;
    this._text = text;
    this.insertsAutoWhitespace = insertsAutoWhitespace;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this._range, this._text);
  }
  computeCursorState(model, helper) {
    let inverseEditOperations = helper.getInverseEditOperations();
    let srcRange = inverseEditOperations[0].range;
    return new Selection(srcRange.endLineNumber, srcRange.endColumn, srcRange.endLineNumber, srcRange.endColumn);
  }
};
var ReplaceCommandWithoutChangingPosition = class {
  constructor(range3, text, insertsAutoWhitespace = false) {
    this._range = range3;
    this._text = text;
    this.insertsAutoWhitespace = insertsAutoWhitespace;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this._range, this._text);
  }
  computeCursorState(model, helper) {
    let inverseEditOperations = helper.getInverseEditOperations();
    let srcRange = inverseEditOperations[0].range;
    return new Selection(srcRange.startLineNumber, srcRange.startColumn, srcRange.startLineNumber, srcRange.startColumn);
  }
};
var ReplaceCommandWithOffsetCursorState = class {
  constructor(range3, text, lineNumberDeltaOffset, columnDeltaOffset, insertsAutoWhitespace = false) {
    this._range = range3;
    this._text = text;
    this._columnDeltaOffset = columnDeltaOffset;
    this._lineNumberDeltaOffset = lineNumberDeltaOffset;
    this.insertsAutoWhitespace = insertsAutoWhitespace;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this._range, this._text);
  }
  computeCursorState(model, helper) {
    let inverseEditOperations = helper.getInverseEditOperations();
    let srcRange = inverseEditOperations[0].range;
    return new Selection(srcRange.endLineNumber + this._lineNumberDeltaOffset, srcRange.endColumn + this._columnDeltaOffset, srcRange.endLineNumber + this._lineNumberDeltaOffset, srcRange.endColumn + this._columnDeltaOffset);
  }
};
var ReplaceCommandThatPreservesSelection = class {
  constructor(editRange, text, initialSelection, forceMoveMarkers = false) {
    this._range = editRange;
    this._text = text;
    this._initialSelection = initialSelection;
    this._forceMoveMarkers = forceMoveMarkers;
    this._selectionId = null;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this._range, this._text, this._forceMoveMarkers);
    this._selectionId = builder.trackSelection(this._initialSelection);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this._selectionId);
  }
};
var CursorPosition = class {
  constructor(lineNumber, column, leftoverVisibleColumns) {
    this.lineNumber = lineNumber;
    this.column = column;
    this.leftoverVisibleColumns = leftoverVisibleColumns;
  }
};
var MoveOperations = class {
  static leftPosition(model, lineNumber, column) {
    if (column > model.getLineMinColumn(lineNumber)) {
      column = column - prevCharLength(model.getLineContent(lineNumber), column - 1);
    } else if (lineNumber > 1) {
      lineNumber = lineNumber - 1;
      column = model.getLineMaxColumn(lineNumber);
    }
    return new Position(lineNumber, column);
  }
  static left(config2, model, lineNumber, column) {
    const pos = MoveOperations.leftPosition(model, lineNumber, column);
    return new CursorPosition(pos.lineNumber, pos.column, 0);
  }
  static moveLeft(config2, model, cursor, inSelectionMode, noOfColumns) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.startLineNumber;
      column = cursor.selection.startColumn;
    } else {
      let r3 = MoveOperations.left(config2, model, cursor.position.lineNumber, cursor.position.column - (noOfColumns - 1));
      lineNumber = r3.lineNumber;
      column = r3.column;
    }
    return cursor.move(inSelectionMode, lineNumber, column, 0);
  }
  static rightPosition(model, lineNumber, column) {
    if (column < model.getLineMaxColumn(lineNumber)) {
      column = column + nextCharLength(model.getLineContent(lineNumber), column - 1);
    } else if (lineNumber < model.getLineCount()) {
      lineNumber = lineNumber + 1;
      column = model.getLineMinColumn(lineNumber);
    }
    return new Position(lineNumber, column);
  }
  static right(config2, model, lineNumber, column) {
    const pos = MoveOperations.rightPosition(model, lineNumber, column);
    return new CursorPosition(pos.lineNumber, pos.column, 0);
  }
  static moveRight(config2, model, cursor, inSelectionMode, noOfColumns) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.endLineNumber;
      column = cursor.selection.endColumn;
    } else {
      let r3 = MoveOperations.right(config2, model, cursor.position.lineNumber, cursor.position.column + (noOfColumns - 1));
      lineNumber = r3.lineNumber;
      column = r3.column;
    }
    return cursor.move(inSelectionMode, lineNumber, column, 0);
  }
  static down(config2, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnLastLine) {
    const currentVisibleColumn = CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config2.tabSize) + leftoverVisibleColumns;
    const lineCount = model.getLineCount();
    const wasOnLastPosition = lineNumber === lineCount && column === model.getLineMaxColumn(lineNumber);
    lineNumber = lineNumber + count;
    if (lineNumber > lineCount) {
      lineNumber = lineCount;
      if (allowMoveOnLastLine) {
        column = model.getLineMaxColumn(lineNumber);
      } else {
        column = Math.min(model.getLineMaxColumn(lineNumber), column);
      }
    } else {
      column = CursorColumns.columnFromVisibleColumn2(config2, model, lineNumber, currentVisibleColumn);
    }
    if (wasOnLastPosition) {
      leftoverVisibleColumns = 0;
    } else {
      leftoverVisibleColumns = currentVisibleColumn - CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config2.tabSize);
    }
    return new CursorPosition(lineNumber, column, leftoverVisibleColumns);
  }
  static moveDown(config2, model, cursor, inSelectionMode, linesCount) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.endLineNumber;
      column = cursor.selection.endColumn;
    } else {
      lineNumber = cursor.position.lineNumber;
      column = cursor.position.column;
    }
    let r3 = MoveOperations.down(config2, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);
    return cursor.move(inSelectionMode, r3.lineNumber, r3.column, r3.leftoverVisibleColumns);
  }
  static translateDown(config2, model, cursor) {
    let selection2 = cursor.selection;
    let selectionStart = MoveOperations.down(config2, model, selection2.selectionStartLineNumber, selection2.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
    let position2 = MoveOperations.down(config2, model, selection2.positionLineNumber, selection2.positionColumn, cursor.leftoverVisibleColumns, 1, false);
    return new SingleCursorState(new Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new Position(position2.lineNumber, position2.column), position2.leftoverVisibleColumns);
  }
  static up(config2, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnFirstLine) {
    const currentVisibleColumn = CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config2.tabSize) + leftoverVisibleColumns;
    const wasOnFirstPosition = lineNumber === 1 && column === 1;
    lineNumber = lineNumber - count;
    if (lineNumber < 1) {
      lineNumber = 1;
      if (allowMoveOnFirstLine) {
        column = model.getLineMinColumn(lineNumber);
      } else {
        column = Math.min(model.getLineMaxColumn(lineNumber), column);
      }
    } else {
      column = CursorColumns.columnFromVisibleColumn2(config2, model, lineNumber, currentVisibleColumn);
    }
    if (wasOnFirstPosition) {
      leftoverVisibleColumns = 0;
    } else {
      leftoverVisibleColumns = currentVisibleColumn - CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config2.tabSize);
    }
    return new CursorPosition(lineNumber, column, leftoverVisibleColumns);
  }
  static moveUp(config2, model, cursor, inSelectionMode, linesCount) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.startLineNumber;
      column = cursor.selection.startColumn;
    } else {
      lineNumber = cursor.position.lineNumber;
      column = cursor.position.column;
    }
    let r3 = MoveOperations.up(config2, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);
    return cursor.move(inSelectionMode, r3.lineNumber, r3.column, r3.leftoverVisibleColumns);
  }
  static translateUp(config2, model, cursor) {
    let selection2 = cursor.selection;
    let selectionStart = MoveOperations.up(config2, model, selection2.selectionStartLineNumber, selection2.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
    let position2 = MoveOperations.up(config2, model, selection2.positionLineNumber, selection2.positionColumn, cursor.leftoverVisibleColumns, 1, false);
    return new SingleCursorState(new Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new Position(position2.lineNumber, position2.column), position2.leftoverVisibleColumns);
  }
  static moveToBeginningOfLine(config2, model, cursor, inSelectionMode) {
    let lineNumber = cursor.position.lineNumber;
    let minColumn = model.getLineMinColumn(lineNumber);
    let firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn;
    let column;
    let relevantColumnNumber = cursor.position.column;
    if (relevantColumnNumber === firstNonBlankColumn) {
      column = minColumn;
    } else {
      column = firstNonBlankColumn;
    }
    return cursor.move(inSelectionMode, lineNumber, column, 0);
  }
  static moveToEndOfLine(config2, model, cursor, inSelectionMode, sticky) {
    let lineNumber = cursor.position.lineNumber;
    let maxColumn = model.getLineMaxColumn(lineNumber);
    return cursor.move(inSelectionMode, lineNumber, maxColumn, sticky ? 1073741824 - maxColumn : 0);
  }
  static moveToBeginningOfBuffer(config2, model, cursor, inSelectionMode) {
    return cursor.move(inSelectionMode, 1, 1, 0);
  }
  static moveToEndOfBuffer(config2, model, cursor, inSelectionMode) {
    let lastLineNumber = model.getLineCount();
    let lastColumn = model.getLineMaxColumn(lastLineNumber);
    return cursor.move(inSelectionMode, lastLineNumber, lastColumn, 0);
  }
};
var DeleteOperations = class {
  static deleteRight(prevEditOperationType, config2, model, selections) {
    let commands = [];
    let shouldPushStackElementBefore = prevEditOperationType !== 3;
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      let deleteSelection = selection2;
      if (deleteSelection.isEmpty()) {
        let position2 = selection2.getPosition();
        let rightOfPosition = MoveOperations.right(config2, model, position2.lineNumber, position2.column);
        deleteSelection = new Range(rightOfPosition.lineNumber, rightOfPosition.column, position2.lineNumber, position2.column);
      }
      if (deleteSelection.isEmpty()) {
        commands[i3] = null;
        continue;
      }
      if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) {
        shouldPushStackElementBefore = true;
      }
      commands[i3] = new ReplaceCommand(deleteSelection, "");
    }
    return [shouldPushStackElementBefore, commands];
  }
  static _isAutoClosingPairDelete(config2, model, selections) {
    if (config2.autoClosingBrackets === "never" && config2.autoClosingQuotes === "never") {
      return false;
    }
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      const position2 = selection2.getPosition();
      if (!selection2.isEmpty()) {
        return false;
      }
      const lineText = model.getLineContent(position2.lineNumber);
      const character = lineText[position2.column - 2];
      const autoClosingPairCandidates = config2.autoClosingPairsOpen2.get(character);
      if (!autoClosingPairCandidates) {
        return false;
      }
      if (isQuote(character)) {
        if (config2.autoClosingQuotes === "never") {
          return false;
        }
      } else {
        if (config2.autoClosingBrackets === "never") {
          return false;
        }
      }
      const afterCharacter = lineText[position2.column - 1];
      let foundAutoClosingPair = false;
      for (const autoClosingPairCandidate of autoClosingPairCandidates) {
        if (autoClosingPairCandidate.open === character && autoClosingPairCandidate.close === afterCharacter) {
          foundAutoClosingPair = true;
        }
      }
      if (!foundAutoClosingPair) {
        return false;
      }
    }
    return true;
  }
  static _runAutoClosingPairDelete(config2, model, selections) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const position2 = selections[i3].getPosition();
      const deleteSelection = new Range(position2.lineNumber, position2.column - 1, position2.lineNumber, position2.column + 1);
      commands[i3] = new ReplaceCommand(deleteSelection, "");
    }
    return [true, commands];
  }
  static deleteLeft(prevEditOperationType, config2, model, selections) {
    if (this._isAutoClosingPairDelete(config2, model, selections)) {
      return this._runAutoClosingPairDelete(config2, model, selections);
    }
    let commands = [];
    let shouldPushStackElementBefore = prevEditOperationType !== 2;
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      let deleteSelection = selection2;
      if (deleteSelection.isEmpty()) {
        let position2 = selection2.getPosition();
        if (config2.useTabStops && position2.column > 1) {
          let lineContent = model.getLineContent(position2.lineNumber);
          let firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
          let lastIndentationColumn = firstNonWhitespaceIndex$1 === -1 ? lineContent.length + 1 : firstNonWhitespaceIndex$1 + 1;
          if (position2.column <= lastIndentationColumn) {
            let fromVisibleColumn = CursorColumns.visibleColumnFromColumn2(config2, model, position2);
            let toVisibleColumn = CursorColumns.prevIndentTabStop(fromVisibleColumn, config2.indentSize);
            let toColumn = CursorColumns.columnFromVisibleColumn2(config2, model, position2.lineNumber, toVisibleColumn);
            deleteSelection = new Range(position2.lineNumber, toColumn, position2.lineNumber, position2.column);
          } else {
            deleteSelection = new Range(position2.lineNumber, position2.column - 1, position2.lineNumber, position2.column);
          }
        } else {
          let leftOfPosition = MoveOperations.left(config2, model, position2.lineNumber, position2.column);
          deleteSelection = new Range(leftOfPosition.lineNumber, leftOfPosition.column, position2.lineNumber, position2.column);
        }
      }
      if (deleteSelection.isEmpty()) {
        commands[i3] = null;
        continue;
      }
      if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) {
        shouldPushStackElementBefore = true;
      }
      commands[i3] = new ReplaceCommand(deleteSelection, "");
    }
    return [shouldPushStackElementBefore, commands];
  }
  static cut(config2, model, selections) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      if (selection2.isEmpty()) {
        if (config2.emptySelectionClipboard) {
          let position2 = selection2.getPosition();
          let startLineNumber, startColumn, endLineNumber, endColumn;
          if (position2.lineNumber < model.getLineCount()) {
            startLineNumber = position2.lineNumber;
            startColumn = 1;
            endLineNumber = position2.lineNumber + 1;
            endColumn = 1;
          } else if (position2.lineNumber > 1) {
            startLineNumber = position2.lineNumber - 1;
            startColumn = model.getLineMaxColumn(position2.lineNumber - 1);
            endLineNumber = position2.lineNumber;
            endColumn = model.getLineMaxColumn(position2.lineNumber);
          } else {
            startLineNumber = position2.lineNumber;
            startColumn = 1;
            endLineNumber = position2.lineNumber;
            endColumn = model.getLineMaxColumn(position2.lineNumber);
          }
          let deleteSelection = new Range(startLineNumber, startColumn, endLineNumber, endColumn);
          if (!deleteSelection.isEmpty()) {
            commands[i3] = new ReplaceCommand(deleteSelection, "");
          } else {
            commands[i3] = null;
          }
        } else {
          commands[i3] = null;
        }
      } else {
        commands[i3] = new ReplaceCommand(selection2, "");
      }
    }
    return new EditOperationResult(0, commands, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
};
var WordOperations = class {
  static _createWord(lineContent, wordType, nextCharClass, start3, end2) {
    return {start: start3, end: end2, wordType, nextCharClass};
  }
  static _findPreviousWordOnLine(wordSeparators2, model, position2) {
    let lineContent = model.getLineContent(position2.lineNumber);
    return this._doFindPreviousWordOnLine(lineContent, wordSeparators2, position2);
  }
  static _doFindPreviousWordOnLine(lineContent, wordSeparators2, position2) {
    let wordType = 0;
    for (let chIndex = position2.column - 2; chIndex >= 0; chIndex--) {
      let chCode = lineContent.charCodeAt(chIndex);
      let chClass = wordSeparators2.get(chCode);
      if (chClass === 0) {
        if (wordType === 2) {
          return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators2, wordType, chIndex + 1));
        }
        wordType = 1;
      } else if (chClass === 2) {
        if (wordType === 1) {
          return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators2, wordType, chIndex + 1));
        }
        wordType = 2;
      } else if (chClass === 1) {
        if (wordType !== 0) {
          return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators2, wordType, chIndex + 1));
        }
      }
    }
    if (wordType !== 0) {
      return this._createWord(lineContent, wordType, 1, 0, this._findEndOfWord(lineContent, wordSeparators2, wordType, 0));
    }
    return null;
  }
  static _findEndOfWord(lineContent, wordSeparators2, wordType, startIndex) {
    let len2 = lineContent.length;
    for (let chIndex = startIndex; chIndex < len2; chIndex++) {
      let chCode = lineContent.charCodeAt(chIndex);
      let chClass = wordSeparators2.get(chCode);
      if (chClass === 1) {
        return chIndex;
      }
      if (wordType === 1 && chClass === 2) {
        return chIndex;
      }
      if (wordType === 2 && chClass === 0) {
        return chIndex;
      }
    }
    return len2;
  }
  static _findNextWordOnLine(wordSeparators2, model, position2) {
    let lineContent = model.getLineContent(position2.lineNumber);
    return this._doFindNextWordOnLine(lineContent, wordSeparators2, position2);
  }
  static _doFindNextWordOnLine(lineContent, wordSeparators2, position2) {
    let wordType = 0;
    let len2 = lineContent.length;
    for (let chIndex = position2.column - 1; chIndex < len2; chIndex++) {
      let chCode = lineContent.charCodeAt(chIndex);
      let chClass = wordSeparators2.get(chCode);
      if (chClass === 0) {
        if (wordType === 2) {
          return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex);
        }
        wordType = 1;
      } else if (chClass === 2) {
        if (wordType === 1) {
          return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex);
        }
        wordType = 2;
      } else if (chClass === 1) {
        if (wordType !== 0) {
          return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex);
        }
      }
    }
    if (wordType !== 0) {
      return this._createWord(lineContent, wordType, 1, this._findStartOfWord(lineContent, wordSeparators2, wordType, len2 - 1), len2);
    }
    return null;
  }
  static _findStartOfWord(lineContent, wordSeparators2, wordType, startIndex) {
    for (let chIndex = startIndex; chIndex >= 0; chIndex--) {
      let chCode = lineContent.charCodeAt(chIndex);
      let chClass = wordSeparators2.get(chCode);
      if (chClass === 1) {
        return chIndex + 1;
      }
      if (wordType === 1 && chClass === 2) {
        return chIndex + 1;
      }
      if (wordType === 2 && chClass === 0) {
        return chIndex + 1;
      }
    }
    return 0;
  }
  static moveWordLeft(wordSeparators2, model, position2, wordNavigationType) {
    let lineNumber = position2.lineNumber;
    let column = position2.column;
    if (column === 1) {
      if (lineNumber > 1) {
        lineNumber = lineNumber - 1;
        column = model.getLineMaxColumn(lineNumber);
      }
    }
    let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position(lineNumber, column));
    if (wordNavigationType === 0) {
      return new Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
    }
    if (wordNavigationType === 1) {
      if (prevWordOnLine && prevWordOnLine.wordType === 2 && prevWordOnLine.end - prevWordOnLine.start === 1 && prevWordOnLine.nextCharClass === 0) {
        prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position(lineNumber, prevWordOnLine.start + 1));
      }
      return new Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
    }
    if (wordNavigationType === 3) {
      while (prevWordOnLine && prevWordOnLine.wordType === 2) {
        prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position(lineNumber, prevWordOnLine.start + 1));
      }
      return new Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
    }
    if (prevWordOnLine && column <= prevWordOnLine.end + 1) {
      prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position(lineNumber, prevWordOnLine.start + 1));
    }
    return new Position(lineNumber, prevWordOnLine ? prevWordOnLine.end + 1 : 1);
  }
  static _moveWordPartLeft(model, position2) {
    const lineNumber = position2.lineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    if (position2.column === 1) {
      return lineNumber > 1 ? new Position(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)) : position2;
    }
    const lineContent = model.getLineContent(lineNumber);
    for (let column = position2.column - 1; column > 1; column--) {
      const left2 = lineContent.charCodeAt(column - 2);
      const right2 = lineContent.charCodeAt(column - 1);
      if (left2 === 95 && right2 !== 95) {
        return new Position(lineNumber, column);
      }
      if (isLowerAsciiLetter(left2) && isUpperAsciiLetter(right2)) {
        return new Position(lineNumber, column);
      }
      if (isUpperAsciiLetter(left2) && isUpperAsciiLetter(right2)) {
        if (column + 1 < maxColumn) {
          const rightRight = lineContent.charCodeAt(column);
          if (isLowerAsciiLetter(rightRight)) {
            return new Position(lineNumber, column);
          }
        }
      }
    }
    return new Position(lineNumber, 1);
  }
  static moveWordRight(wordSeparators2, model, position2, wordNavigationType) {
    let lineNumber = position2.lineNumber;
    let column = position2.column;
    let movedDown = false;
    if (column === model.getLineMaxColumn(lineNumber)) {
      if (lineNumber < model.getLineCount()) {
        movedDown = true;
        lineNumber = lineNumber + 1;
        column = 1;
      }
    }
    let nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position(lineNumber, column));
    if (wordNavigationType === 2) {
      if (nextWordOnLine && nextWordOnLine.wordType === 2) {
        if (nextWordOnLine.end - nextWordOnLine.start === 1 && nextWordOnLine.nextCharClass === 0) {
          nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position(lineNumber, nextWordOnLine.end + 1));
        }
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.end + 1;
      } else {
        column = model.getLineMaxColumn(lineNumber);
      }
    } else if (wordNavigationType === 3) {
      if (movedDown) {
        column = 0;
      }
      while (nextWordOnLine && (nextWordOnLine.wordType === 2 || nextWordOnLine.start + 1 <= column)) {
        nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position(lineNumber, nextWordOnLine.end + 1));
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.start + 1;
      } else {
        column = model.getLineMaxColumn(lineNumber);
      }
    } else {
      if (nextWordOnLine && !movedDown && column >= nextWordOnLine.start + 1) {
        nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position(lineNumber, nextWordOnLine.end + 1));
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.start + 1;
      } else {
        column = model.getLineMaxColumn(lineNumber);
      }
    }
    return new Position(lineNumber, column);
  }
  static _moveWordPartRight(model, position2) {
    const lineNumber = position2.lineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    if (position2.column === maxColumn) {
      return lineNumber < model.getLineCount() ? new Position(lineNumber + 1, 1) : position2;
    }
    const lineContent = model.getLineContent(lineNumber);
    for (let column = position2.column + 1; column < maxColumn; column++) {
      const left2 = lineContent.charCodeAt(column - 2);
      const right2 = lineContent.charCodeAt(column - 1);
      if (left2 !== 95 && right2 === 95) {
        return new Position(lineNumber, column);
      }
      if (isLowerAsciiLetter(left2) && isUpperAsciiLetter(right2)) {
        return new Position(lineNumber, column);
      }
      if (isUpperAsciiLetter(left2) && isUpperAsciiLetter(right2)) {
        if (column + 1 < maxColumn) {
          const rightRight = lineContent.charCodeAt(column);
          if (isLowerAsciiLetter(rightRight)) {
            return new Position(lineNumber, column);
          }
        }
      }
    }
    return new Position(lineNumber, maxColumn);
  }
  static _deleteWordLeftWhitespace(model, position2) {
    const lineContent = model.getLineContent(position2.lineNumber);
    const startIndex = position2.column - 2;
    const lastNonWhitespace = lastNonWhitespaceIndex(lineContent, startIndex);
    if (lastNonWhitespace + 1 < startIndex) {
      return new Range(position2.lineNumber, lastNonWhitespace + 2, position2.lineNumber, position2.column);
    }
    return null;
  }
  static deleteWordLeft(wordSeparators2, model, selection2, whitespaceHeuristics, wordNavigationType) {
    if (!selection2.isEmpty()) {
      return selection2;
    }
    const position2 = new Position(selection2.positionLineNumber, selection2.positionColumn);
    let lineNumber = position2.lineNumber;
    let column = position2.column;
    if (lineNumber === 1 && column === 1) {
      return null;
    }
    if (whitespaceHeuristics) {
      let r3 = this._deleteWordLeftWhitespace(model, position2);
      if (r3) {
        return r3;
      }
    }
    let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, position2);
    if (wordNavigationType === 0) {
      if (prevWordOnLine) {
        column = prevWordOnLine.start + 1;
      } else {
        if (column > 1) {
          column = 1;
        } else {
          lineNumber--;
          column = model.getLineMaxColumn(lineNumber);
        }
      }
    } else {
      if (prevWordOnLine && column <= prevWordOnLine.end + 1) {
        prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position(lineNumber, prevWordOnLine.start + 1));
      }
      if (prevWordOnLine) {
        column = prevWordOnLine.end + 1;
      } else {
        if (column > 1) {
          column = 1;
        } else {
          lineNumber--;
          column = model.getLineMaxColumn(lineNumber);
        }
      }
    }
    return new Range(lineNumber, column, position2.lineNumber, position2.column);
  }
  static _deleteWordPartLeft(model, selection2) {
    if (!selection2.isEmpty()) {
      return selection2;
    }
    const pos = selection2.getPosition();
    const toPosition = WordOperations._moveWordPartLeft(model, pos);
    return new Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
  }
  static _findFirstNonWhitespaceChar(str, startIndex) {
    let len2 = str.length;
    for (let chIndex = startIndex; chIndex < len2; chIndex++) {
      let ch2 = str.charAt(chIndex);
      if (ch2 !== " " && ch2 !== "	") {
        return chIndex;
      }
    }
    return len2;
  }
  static _deleteWordRightWhitespace(model, position2) {
    const lineContent = model.getLineContent(position2.lineNumber);
    const startIndex = position2.column - 1;
    const firstNonWhitespace = this._findFirstNonWhitespaceChar(lineContent, startIndex);
    if (startIndex + 1 < firstNonWhitespace) {
      return new Range(position2.lineNumber, position2.column, position2.lineNumber, firstNonWhitespace + 1);
    }
    return null;
  }
  static deleteWordRight(wordSeparators2, model, selection2, whitespaceHeuristics, wordNavigationType) {
    if (!selection2.isEmpty()) {
      return selection2;
    }
    const position2 = new Position(selection2.positionLineNumber, selection2.positionColumn);
    let lineNumber = position2.lineNumber;
    let column = position2.column;
    const lineCount = model.getLineCount();
    const maxColumn = model.getLineMaxColumn(lineNumber);
    if (lineNumber === lineCount && column === maxColumn) {
      return null;
    }
    if (whitespaceHeuristics) {
      let r3 = this._deleteWordRightWhitespace(model, position2);
      if (r3) {
        return r3;
      }
    }
    let nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, position2);
    if (wordNavigationType === 2) {
      if (nextWordOnLine) {
        column = nextWordOnLine.end + 1;
      } else {
        if (column < maxColumn || lineNumber === lineCount) {
          column = maxColumn;
        } else {
          lineNumber++;
          nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position(lineNumber, 1));
          if (nextWordOnLine) {
            column = nextWordOnLine.start + 1;
          } else {
            column = model.getLineMaxColumn(lineNumber);
          }
        }
      }
    } else {
      if (nextWordOnLine && column >= nextWordOnLine.start + 1) {
        nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position(lineNumber, nextWordOnLine.end + 1));
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.start + 1;
      } else {
        if (column < maxColumn || lineNumber === lineCount) {
          column = maxColumn;
        } else {
          lineNumber++;
          nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position(lineNumber, 1));
          if (nextWordOnLine) {
            column = nextWordOnLine.start + 1;
          } else {
            column = model.getLineMaxColumn(lineNumber);
          }
        }
      }
    }
    return new Range(lineNumber, column, position2.lineNumber, position2.column);
  }
  static _deleteWordPartRight(model, selection2) {
    if (!selection2.isEmpty()) {
      return selection2;
    }
    const pos = selection2.getPosition();
    const toPosition = WordOperations._moveWordPartRight(model, pos);
    return new Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
  }
  static _createWordAtPosition(model, lineNumber, word) {
    const range3 = new Range(lineNumber, word.start + 1, lineNumber, word.end + 1);
    return {
      word: model.getValueInRange(range3),
      startColumn: range3.startColumn,
      endColumn: range3.endColumn
    };
  }
  static getWordAtPosition(model, _wordSeparators, position2) {
    const wordSeparators2 = getMapForWordSeparators(_wordSeparators);
    const prevWord = WordOperations._findPreviousWordOnLine(wordSeparators2, model, position2);
    if (prevWord && prevWord.wordType === 1 && prevWord.start <= position2.column - 1 && position2.column - 1 <= prevWord.end) {
      return WordOperations._createWordAtPosition(model, position2.lineNumber, prevWord);
    }
    const nextWord = WordOperations._findNextWordOnLine(wordSeparators2, model, position2);
    if (nextWord && nextWord.wordType === 1 && nextWord.start <= position2.column - 1 && position2.column - 1 <= nextWord.end) {
      return WordOperations._createWordAtPosition(model, position2.lineNumber, nextWord);
    }
    return null;
  }
  static word(config2, model, cursor, inSelectionMode, position2) {
    const wordSeparators2 = getMapForWordSeparators(config2.wordSeparators);
    let prevWord = WordOperations._findPreviousWordOnLine(wordSeparators2, model, position2);
    let nextWord = WordOperations._findNextWordOnLine(wordSeparators2, model, position2);
    if (!inSelectionMode) {
      let startColumn2;
      let endColumn2;
      if (prevWord && prevWord.wordType === 1 && prevWord.start <= position2.column - 1 && position2.column - 1 <= prevWord.end) {
        startColumn2 = prevWord.start + 1;
        endColumn2 = prevWord.end + 1;
      } else if (nextWord && nextWord.wordType === 1 && nextWord.start <= position2.column - 1 && position2.column - 1 <= nextWord.end) {
        startColumn2 = nextWord.start + 1;
        endColumn2 = nextWord.end + 1;
      } else {
        if (prevWord) {
          startColumn2 = prevWord.end + 1;
        } else {
          startColumn2 = 1;
        }
        if (nextWord) {
          endColumn2 = nextWord.start + 1;
        } else {
          endColumn2 = model.getLineMaxColumn(position2.lineNumber);
        }
      }
      return new SingleCursorState(new Range(position2.lineNumber, startColumn2, position2.lineNumber, endColumn2), 0, new Position(position2.lineNumber, endColumn2), 0);
    }
    let startColumn;
    let endColumn;
    if (prevWord && prevWord.wordType === 1 && prevWord.start < position2.column - 1 && position2.column - 1 < prevWord.end) {
      startColumn = prevWord.start + 1;
      endColumn = prevWord.end + 1;
    } else if (nextWord && nextWord.wordType === 1 && nextWord.start < position2.column - 1 && position2.column - 1 < nextWord.end) {
      startColumn = nextWord.start + 1;
      endColumn = nextWord.end + 1;
    } else {
      startColumn = position2.column;
      endColumn = position2.column;
    }
    let lineNumber = position2.lineNumber;
    let column;
    if (cursor.selectionStart.containsPosition(position2)) {
      column = cursor.selectionStart.endColumn;
    } else if (position2.isBeforeOrEqual(cursor.selectionStart.getStartPosition())) {
      column = startColumn;
      let possiblePosition = new Position(lineNumber, column);
      if (cursor.selectionStart.containsPosition(possiblePosition)) {
        column = cursor.selectionStart.endColumn;
      }
    } else {
      column = endColumn;
      let possiblePosition = new Position(lineNumber, column);
      if (cursor.selectionStart.containsPosition(possiblePosition)) {
        column = cursor.selectionStart.startColumn;
      }
    }
    return cursor.move(true, lineNumber, column, 0);
  }
};
var CursorMoveCommands = class {
  static addCursorDown(viewModel, cursors, useLogicalLine) {
    let result = [], resultLen = 0;
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      result[resultLen++] = new CursorState(cursor.modelState, cursor.viewState);
      if (useLogicalLine) {
        result[resultLen++] = CursorState.fromModelState(MoveOperations.translateDown(viewModel.cursorConfig, viewModel.model, cursor.modelState));
      } else {
        result[resultLen++] = CursorState.fromViewState(MoveOperations.translateDown(viewModel.cursorConfig, viewModel, cursor.viewState));
      }
    }
    return result;
  }
  static addCursorUp(viewModel, cursors, useLogicalLine) {
    let result = [], resultLen = 0;
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      result[resultLen++] = new CursorState(cursor.modelState, cursor.viewState);
      if (useLogicalLine) {
        result[resultLen++] = CursorState.fromModelState(MoveOperations.translateUp(viewModel.cursorConfig, viewModel.model, cursor.modelState));
      } else {
        result[resultLen++] = CursorState.fromViewState(MoveOperations.translateUp(viewModel.cursorConfig, viewModel, cursor.viewState));
      }
    }
    return result;
  }
  static moveToBeginningOfLine(viewModel, cursors, inSelectionMode) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      result[i3] = this._moveToLineStart(viewModel, cursor, inSelectionMode);
    }
    return result;
  }
  static _moveToLineStart(viewModel, cursor, inSelectionMode) {
    const currentViewStateColumn = cursor.viewState.position.column;
    const currentModelStateColumn = cursor.modelState.position.column;
    const isFirstLineOfWrappedLine = currentViewStateColumn === currentModelStateColumn;
    const currentViewStatelineNumber = cursor.viewState.position.lineNumber;
    const firstNonBlankColumn = viewModel.getLineFirstNonWhitespaceColumn(currentViewStatelineNumber);
    const isBeginningOfViewLine = currentViewStateColumn === firstNonBlankColumn;
    if (!isFirstLineOfWrappedLine && !isBeginningOfViewLine) {
      return this._moveToLineStartByView(viewModel, cursor, inSelectionMode);
    } else {
      return this._moveToLineStartByModel(viewModel, cursor, inSelectionMode);
    }
  }
  static _moveToLineStartByView(viewModel, cursor, inSelectionMode) {
    return CursorState.fromViewState(MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode));
  }
  static _moveToLineStartByModel(viewModel, cursor, inSelectionMode) {
    return CursorState.fromModelState(MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
  }
  static moveToEndOfLine(viewModel, cursors, inSelectionMode, sticky) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      result[i3] = this._moveToLineEnd(viewModel, cursor, inSelectionMode, sticky);
    }
    return result;
  }
  static _moveToLineEnd(viewModel, cursor, inSelectionMode, sticky) {
    const viewStatePosition = cursor.viewState.position;
    const viewModelMaxColumn = viewModel.getLineMaxColumn(viewStatePosition.lineNumber);
    const isEndOfViewLine = viewStatePosition.column === viewModelMaxColumn;
    const modelStatePosition = cursor.modelState.position;
    const modelMaxColumn = viewModel.model.getLineMaxColumn(modelStatePosition.lineNumber);
    const isEndLineOfWrappedLine = viewModelMaxColumn - viewStatePosition.column === modelMaxColumn - modelStatePosition.column;
    if (isEndOfViewLine || isEndLineOfWrappedLine) {
      return this._moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky);
    } else {
      return this._moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky);
    }
  }
  static _moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky) {
    return CursorState.fromViewState(MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, sticky));
  }
  static _moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky) {
    return CursorState.fromModelState(MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, sticky));
  }
  static expandLineSelection(viewModel, cursors) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      const startLineNumber = cursor.modelState.selection.startLineNumber;
      const lineCount = viewModel.model.getLineCount();
      let endLineNumber = cursor.modelState.selection.endLineNumber;
      let endColumn;
      if (endLineNumber === lineCount) {
        endColumn = viewModel.model.getLineMaxColumn(lineCount);
      } else {
        endLineNumber++;
        endColumn = 1;
      }
      result[i3] = CursorState.fromModelState(new SingleCursorState(new Range(startLineNumber, 1, startLineNumber, 1), 0, new Position(endLineNumber, endColumn), 0));
    }
    return result;
  }
  static moveToBeginningOfBuffer(viewModel, cursors, inSelectionMode) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      result[i3] = CursorState.fromModelState(MoveOperations.moveToBeginningOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
    }
    return result;
  }
  static moveToEndOfBuffer(viewModel, cursors, inSelectionMode) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      result[i3] = CursorState.fromModelState(MoveOperations.moveToEndOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
    }
    return result;
  }
  static selectAll(viewModel, cursor) {
    const lineCount = viewModel.model.getLineCount();
    const maxColumn = viewModel.model.getLineMaxColumn(lineCount);
    return CursorState.fromModelState(new SingleCursorState(new Range(1, 1, 1, 1), 0, new Position(lineCount, maxColumn), 0));
  }
  static line(viewModel, cursor, inSelectionMode, _position, _viewPosition) {
    const position2 = viewModel.model.validatePosition(_position);
    const viewPosition = _viewPosition ? viewModel.coordinatesConverter.validateViewPosition(new Position(_viewPosition.lineNumber, _viewPosition.column), position2) : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position2);
    if (!inSelectionMode || !cursor.modelState.hasSelection()) {
      const lineCount = viewModel.model.getLineCount();
      let selectToLineNumber = position2.lineNumber + 1;
      let selectToColumn = 1;
      if (selectToLineNumber > lineCount) {
        selectToLineNumber = lineCount;
        selectToColumn = viewModel.model.getLineMaxColumn(selectToLineNumber);
      }
      return CursorState.fromModelState(new SingleCursorState(new Range(position2.lineNumber, 1, selectToLineNumber, selectToColumn), 0, new Position(selectToLineNumber, selectToColumn), 0));
    }
    const enteringLineNumber = cursor.modelState.selectionStart.getStartPosition().lineNumber;
    if (position2.lineNumber < enteringLineNumber) {
      return CursorState.fromViewState(cursor.viewState.move(cursor.modelState.hasSelection(), viewPosition.lineNumber, 1, 0));
    } else if (position2.lineNumber > enteringLineNumber) {
      const lineCount = viewModel.getLineCount();
      let selectToViewLineNumber = viewPosition.lineNumber + 1;
      let selectToViewColumn = 1;
      if (selectToViewLineNumber > lineCount) {
        selectToViewLineNumber = lineCount;
        selectToViewColumn = viewModel.getLineMaxColumn(selectToViewLineNumber);
      }
      return CursorState.fromViewState(cursor.viewState.move(cursor.modelState.hasSelection(), selectToViewLineNumber, selectToViewColumn, 0));
    } else {
      const endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition();
      return CursorState.fromModelState(cursor.modelState.move(cursor.modelState.hasSelection(), endPositionOfSelectionStart.lineNumber, endPositionOfSelectionStart.column, 0));
    }
  }
  static word(viewModel, cursor, inSelectionMode, _position) {
    const position2 = viewModel.model.validatePosition(_position);
    return CursorState.fromModelState(WordOperations.word(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, position2));
  }
  static cancelSelection(viewModel, cursor) {
    if (!cursor.modelState.hasSelection()) {
      return new CursorState(cursor.modelState, cursor.viewState);
    }
    const lineNumber = cursor.viewState.position.lineNumber;
    const column = cursor.viewState.position.column;
    return CursorState.fromViewState(new SingleCursorState(new Range(lineNumber, column, lineNumber, column), 0, new Position(lineNumber, column), 0));
  }
  static moveTo(viewModel, cursor, inSelectionMode, _position, _viewPosition) {
    const position2 = viewModel.model.validatePosition(_position);
    const viewPosition = _viewPosition ? viewModel.coordinatesConverter.validateViewPosition(new Position(_viewPosition.lineNumber, _viewPosition.column), position2) : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position2);
    return CursorState.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0));
  }
  static simpleMove(viewModel, cursors, direction, inSelectionMode, value, unit) {
    switch (direction) {
      case 0: {
        if (unit === 4) {
          return this._moveHalfLineLeft(viewModel, cursors, inSelectionMode);
        } else {
          return this._moveLeft(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 1: {
        if (unit === 4) {
          return this._moveHalfLineRight(viewModel, cursors, inSelectionMode);
        } else {
          return this._moveRight(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 2: {
        if (unit === 2) {
          return this._moveUpByViewLines(viewModel, cursors, inSelectionMode, value);
        } else {
          return this._moveUpByModelLines(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 3: {
        if (unit === 2) {
          return this._moveDownByViewLines(viewModel, cursors, inSelectionMode, value);
        } else {
          return this._moveDownByModelLines(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 4: {
        return this._moveToViewMinColumn(viewModel, cursors, inSelectionMode);
      }
      case 5: {
        return this._moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode);
      }
      case 6: {
        return this._moveToViewCenterColumn(viewModel, cursors, inSelectionMode);
      }
      case 7: {
        return this._moveToViewMaxColumn(viewModel, cursors, inSelectionMode);
      }
      case 8: {
        return this._moveToViewLastNonWhitespaceColumn(viewModel, cursors, inSelectionMode);
      }
      default:
        return null;
    }
  }
  static viewportMove(viewModel, cursors, direction, inSelectionMode, value) {
    const visibleViewRange = viewModel.getCompletelyVisibleViewRange();
    const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
    switch (direction) {
      case 9: {
        const modelLineNumber = this._firstLineNumberInRange(viewModel.model, visibleModelRange, value);
        const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
        return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
      }
      case 11: {
        const modelLineNumber = this._lastLineNumberInRange(viewModel.model, visibleModelRange, value);
        const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
        return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
      }
      case 10: {
        const modelLineNumber = Math.round((visibleModelRange.startLineNumber + visibleModelRange.endLineNumber) / 2);
        const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
        return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
      }
      case 12: {
        let result = [];
        for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
          const cursor = cursors[i3];
          result[i3] = this.findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode);
        }
        return result;
      }
      default:
        return null;
    }
  }
  static findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode) {
    let viewLineNumber = cursor.viewState.position.lineNumber;
    if (visibleViewRange.startLineNumber <= viewLineNumber && viewLineNumber <= visibleViewRange.endLineNumber - 1) {
      return new CursorState(cursor.modelState, cursor.viewState);
    } else {
      if (viewLineNumber > visibleViewRange.endLineNumber - 1) {
        viewLineNumber = visibleViewRange.endLineNumber - 1;
      }
      if (viewLineNumber < visibleViewRange.startLineNumber) {
        viewLineNumber = visibleViewRange.startLineNumber;
      }
      const viewColumn = viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber);
      return this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
  }
  static _firstLineNumberInRange(model, range3, count) {
    let startLineNumber = range3.startLineNumber;
    if (range3.startColumn !== model.getLineMinColumn(startLineNumber)) {
      startLineNumber++;
    }
    return Math.min(range3.endLineNumber, startLineNumber + count - 1);
  }
  static _lastLineNumberInRange(model, range3, count) {
    let startLineNumber = range3.startLineNumber;
    if (range3.startColumn !== model.getLineMinColumn(startLineNumber)) {
      startLineNumber++;
    }
    return Math.max(startLineNumber, range3.endLineNumber - count + 1);
  }
  static _moveLeft(viewModel, cursors, inSelectionMode, noOfColumns) {
    const hasMultipleCursors = cursors.length > 1;
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      const skipWrappingPointStop = hasMultipleCursors || !cursor.viewState.hasSelection();
      let newViewState = MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns);
      if (skipWrappingPointStop && noOfColumns === 1 && newViewState.position.lineNumber !== cursor.viewState.position.lineNumber) {
        const newViewModelPosition = viewModel.coordinatesConverter.convertViewPositionToModelPosition(newViewState.position);
        if (newViewModelPosition.lineNumber === cursor.modelState.position.lineNumber) {
          newViewState = MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, newViewState, inSelectionMode, 1);
        }
      }
      result[i3] = CursorState.fromViewState(newViewState);
    }
    return result;
  }
  static _moveHalfLineLeft(viewModel, cursors, inSelectionMode) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const halfLine = Math.round(viewModel.getLineContent(viewLineNumber).length / 2);
      result[i3] = CursorState.fromViewState(MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine));
    }
    return result;
  }
  static _moveRight(viewModel, cursors, inSelectionMode, noOfColumns) {
    const hasMultipleCursors = cursors.length > 1;
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      const skipWrappingPointStop = hasMultipleCursors || !cursor.viewState.hasSelection();
      let newViewState = MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns);
      if (skipWrappingPointStop && noOfColumns === 1 && newViewState.position.lineNumber !== cursor.viewState.position.lineNumber) {
        const newViewModelPosition = viewModel.coordinatesConverter.convertViewPositionToModelPosition(newViewState.position);
        if (newViewModelPosition.lineNumber === cursor.modelState.position.lineNumber) {
          newViewState = MoveOperations.moveRight(viewModel.cursorConfig, viewModel, newViewState, inSelectionMode, 1);
        }
      }
      result[i3] = CursorState.fromViewState(newViewState);
    }
    return result;
  }
  static _moveHalfLineRight(viewModel, cursors, inSelectionMode) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const halfLine = Math.round(viewModel.getLineContent(viewLineNumber).length / 2);
      result[i3] = CursorState.fromViewState(MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine));
    }
    return result;
  }
  static _moveDownByViewLines(viewModel, cursors, inSelectionMode, linesCount) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      result[i3] = CursorState.fromViewState(MoveOperations.moveDown(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount));
    }
    return result;
  }
  static _moveDownByModelLines(viewModel, cursors, inSelectionMode, linesCount) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      result[i3] = CursorState.fromModelState(MoveOperations.moveDown(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount));
    }
    return result;
  }
  static _moveUpByViewLines(viewModel, cursors, inSelectionMode, linesCount) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      result[i3] = CursorState.fromViewState(MoveOperations.moveUp(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount));
    }
    return result;
  }
  static _moveUpByModelLines(viewModel, cursors, inSelectionMode, linesCount) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      result[i3] = CursorState.fromModelState(MoveOperations.moveUp(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount));
    }
    return result;
  }
  static _moveToViewPosition(viewModel, cursor, inSelectionMode, toViewLineNumber, toViewColumn) {
    return CursorState.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0));
  }
  static _moveToModelPosition(viewModel, cursor, inSelectionMode, toModelLineNumber, toModelColumn) {
    return CursorState.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0));
  }
  static _moveToViewMinColumn(viewModel, cursors, inSelectionMode) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineMinColumn(viewLineNumber);
      result[i3] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result;
  }
  static _moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber);
      result[i3] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result;
  }
  static _moveToViewCenterColumn(viewModel, cursors, inSelectionMode) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = Math.round((viewModel.getLineMaxColumn(viewLineNumber) + viewModel.getLineMinColumn(viewLineNumber)) / 2);
      result[i3] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result;
  }
  static _moveToViewMaxColumn(viewModel, cursors, inSelectionMode) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineMaxColumn(viewLineNumber);
      result[i3] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result;
  }
  static _moveToViewLastNonWhitespaceColumn(viewModel, cursors, inSelectionMode) {
    let result = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      const cursor = cursors[i3];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineLastNonWhitespaceColumn(viewLineNumber);
      result[i3] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result;
  }
};
var CursorMove;
(function(CursorMove2) {
  const isCursorMoveArgs = function(arg) {
    if (!isObject3(arg)) {
      return false;
    }
    let cursorMoveArg = arg;
    if (!isString3(cursorMoveArg.to)) {
      return false;
    }
    if (!isUndefined3(cursorMoveArg.select) && !isBoolean2(cursorMoveArg.select)) {
      return false;
    }
    if (!isUndefined3(cursorMoveArg.by) && !isString3(cursorMoveArg.by)) {
      return false;
    }
    if (!isUndefined3(cursorMoveArg.value) && !isNumber2(cursorMoveArg.value)) {
      return false;
    }
    return true;
  };
  CursorMove2.description = {
    description: "Move cursor to a logical position in the view",
    args: [
      {
        name: "Cursor move argument object",
        description: `Property-value pairs that can be passed through this argument:
					* 'to': A mandatory logical position value providing where to move the cursor.
						\`\`\`
						'left', 'right', 'up', 'down'
						'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter'
						'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter'
						'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside'
						\`\`\`
					* 'by': Unit to move. Default is computed based on 'to' value.
						\`\`\`
						'line', 'wrappedLine', 'character', 'halfLine'
						\`\`\`
					* 'value': Number of units to move. Default is '1'.
					* 'select': If 'true' makes the selection. Default is 'false'.
				`,
        constraint: isCursorMoveArgs,
        schema: {
          type: "object",
          required: ["to"],
          properties: {
            to: {
              type: "string",
              enum: ["left", "right", "up", "down", "wrappedLineStart", "wrappedLineEnd", "wrappedLineColumnCenter", "wrappedLineFirstNonWhitespaceCharacter", "wrappedLineLastNonWhitespaceCharacter", "viewPortTop", "viewPortCenter", "viewPortBottom", "viewPortIfOutside"]
            },
            by: {
              type: "string",
              enum: ["line", "wrappedLine", "character", "halfLine"]
            },
            value: {
              type: "number",
              default: 1
            },
            select: {
              type: "boolean",
              default: false
            }
          }
        }
      }
    ]
  };
  CursorMove2.RawDirection = {
    Left: "left",
    Right: "right",
    Up: "up",
    Down: "down",
    WrappedLineStart: "wrappedLineStart",
    WrappedLineFirstNonWhitespaceCharacter: "wrappedLineFirstNonWhitespaceCharacter",
    WrappedLineColumnCenter: "wrappedLineColumnCenter",
    WrappedLineEnd: "wrappedLineEnd",
    WrappedLineLastNonWhitespaceCharacter: "wrappedLineLastNonWhitespaceCharacter",
    ViewPortTop: "viewPortTop",
    ViewPortCenter: "viewPortCenter",
    ViewPortBottom: "viewPortBottom",
    ViewPortIfOutside: "viewPortIfOutside"
  };
  CursorMove2.RawUnit = {
    Line: "line",
    WrappedLine: "wrappedLine",
    Character: "character",
    HalfLine: "halfLine"
  };
  function parse3(args) {
    if (!args.to) {
      return null;
    }
    let direction;
    switch (args.to) {
      case CursorMove2.RawDirection.Left:
        direction = 0;
        break;
      case CursorMove2.RawDirection.Right:
        direction = 1;
        break;
      case CursorMove2.RawDirection.Up:
        direction = 2;
        break;
      case CursorMove2.RawDirection.Down:
        direction = 3;
        break;
      case CursorMove2.RawDirection.WrappedLineStart:
        direction = 4;
        break;
      case CursorMove2.RawDirection.WrappedLineFirstNonWhitespaceCharacter:
        direction = 5;
        break;
      case CursorMove2.RawDirection.WrappedLineColumnCenter:
        direction = 6;
        break;
      case CursorMove2.RawDirection.WrappedLineEnd:
        direction = 7;
        break;
      case CursorMove2.RawDirection.WrappedLineLastNonWhitespaceCharacter:
        direction = 8;
        break;
      case CursorMove2.RawDirection.ViewPortTop:
        direction = 9;
        break;
      case CursorMove2.RawDirection.ViewPortBottom:
        direction = 11;
        break;
      case CursorMove2.RawDirection.ViewPortCenter:
        direction = 10;
        break;
      case CursorMove2.RawDirection.ViewPortIfOutside:
        direction = 12;
        break;
      default:
        return null;
    }
    let unit = 0;
    switch (args.by) {
      case CursorMove2.RawUnit.Line:
        unit = 1;
        break;
      case CursorMove2.RawUnit.WrappedLine:
        unit = 2;
        break;
      case CursorMove2.RawUnit.Character:
        unit = 3;
        break;
      case CursorMove2.RawUnit.HalfLine:
        unit = 4;
        break;
    }
    return {
      direction,
      unit,
      select: !!args.select,
      value: args.value || 1
    };
  }
  CursorMove2.parse = parse3;
})(CursorMove || (CursorMove = {}));
var repeatCache = Object.create(null);
function cachedStringRepeat(str, count) {
  if (!repeatCache[str]) {
    repeatCache[str] = ["", str];
  }
  const cache3 = repeatCache[str];
  for (let i3 = cache3.length; i3 <= count; i3++) {
    cache3[i3] = cache3[i3 - 1] + str;
  }
  return cache3[count];
}
var ShiftCommand = class {
  constructor(range3, opts) {
    this._opts = opts;
    this._selection = range3;
    this._selectionId = null;
    this._useLastEditRangeForCursorEndPosition = false;
    this._selectionStartColumnStaysPut = false;
  }
  static unshiftIndent(line, column, tabSize, indentSize, insertSpaces) {
    const contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(line, column, tabSize);
    if (insertSpaces) {
      const indent = cachedStringRepeat(" ", indentSize);
      const desiredTabStop = CursorColumns.prevIndentTabStop(contentStartVisibleColumn, indentSize);
      const indentCount = desiredTabStop / indentSize;
      return cachedStringRepeat(indent, indentCount);
    } else {
      const indent = "	";
      const desiredTabStop = CursorColumns.prevRenderTabStop(contentStartVisibleColumn, tabSize);
      const indentCount = desiredTabStop / tabSize;
      return cachedStringRepeat(indent, indentCount);
    }
  }
  static shiftIndent(line, column, tabSize, indentSize, insertSpaces) {
    const contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(line, column, tabSize);
    if (insertSpaces) {
      const indent = cachedStringRepeat(" ", indentSize);
      const desiredTabStop = CursorColumns.nextIndentTabStop(contentStartVisibleColumn, indentSize);
      const indentCount = desiredTabStop / indentSize;
      return cachedStringRepeat(indent, indentCount);
    } else {
      const indent = "	";
      const desiredTabStop = CursorColumns.nextRenderTabStop(contentStartVisibleColumn, tabSize);
      const indentCount = desiredTabStop / tabSize;
      return cachedStringRepeat(indent, indentCount);
    }
  }
  _addEditOperation(builder, range3, text) {
    if (this._useLastEditRangeForCursorEndPosition) {
      builder.addTrackedEditOperation(range3, text);
    } else {
      builder.addEditOperation(range3, text);
    }
  }
  getEditOperations(model, builder) {
    const startLine = this._selection.startLineNumber;
    let endLine = this._selection.endLineNumber;
    if (this._selection.endColumn === 1 && startLine !== endLine) {
      endLine = endLine - 1;
    }
    const {tabSize, indentSize, insertSpaces} = this._opts;
    const shouldIndentEmptyLines = startLine === endLine;
    if (this._opts.useTabStops) {
      if (this._selection.isEmpty()) {
        if (/^\s*$/.test(model.getLineContent(startLine))) {
          this._useLastEditRangeForCursorEndPosition = true;
        }
      }
      let previousLineExtraSpaces = 0, extraSpaces = 0;
      for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) {
        extraSpaces = 0;
        let lineText = model.getLineContent(lineNumber);
        let indentationEndIndex = firstNonWhitespaceIndex(lineText);
        if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
          continue;
        }
        if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {
          continue;
        }
        if (indentationEndIndex === -1) {
          indentationEndIndex = lineText.length;
        }
        if (lineNumber > 1) {
          let contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(lineText, indentationEndIndex + 1, tabSize);
          if (contentStartVisibleColumn % indentSize !== 0) {
            if (model.isCheapToTokenize(lineNumber - 1)) {
              let enterAction = LanguageConfigurationRegistry.getEnterAction(this._opts.autoIndent, model, new Range(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1), lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)));
              if (enterAction) {
                extraSpaces = previousLineExtraSpaces;
                if (enterAction.appendText) {
                  for (let j = 0, lenJ = enterAction.appendText.length; j < lenJ && extraSpaces < indentSize; j++) {
                    if (enterAction.appendText.charCodeAt(j) === 32) {
                      extraSpaces++;
                    } else {
                      break;
                    }
                  }
                }
                if (enterAction.removeText) {
                  extraSpaces = Math.max(0, extraSpaces - enterAction.removeText);
                }
                for (let j = 0; j < extraSpaces; j++) {
                  if (indentationEndIndex === 0 || lineText.charCodeAt(indentationEndIndex - 1) !== 32) {
                    break;
                  }
                  indentationEndIndex--;
                }
              }
            }
          }
        }
        if (this._opts.isUnshift && indentationEndIndex === 0) {
          continue;
        }
        let desiredIndent;
        if (this._opts.isUnshift) {
          desiredIndent = ShiftCommand.unshiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
        } else {
          desiredIndent = ShiftCommand.shiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
        }
        this._addEditOperation(builder, new Range(lineNumber, 1, lineNumber, indentationEndIndex + 1), desiredIndent);
        if (lineNumber === startLine && !this._selection.isEmpty()) {
          this._selectionStartColumnStaysPut = this._selection.startColumn <= indentationEndIndex + 1;
        }
      }
    } else {
      if (!this._opts.isUnshift && this._selection.isEmpty() && model.getLineLength(startLine) === 0) {
        this._useLastEditRangeForCursorEndPosition = true;
      }
      const oneIndent = insertSpaces ? cachedStringRepeat(" ", indentSize) : "	";
      for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++) {
        const lineText = model.getLineContent(lineNumber);
        let indentationEndIndex = firstNonWhitespaceIndex(lineText);
        if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
          continue;
        }
        if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {
          continue;
        }
        if (indentationEndIndex === -1) {
          indentationEndIndex = lineText.length;
        }
        if (this._opts.isUnshift && indentationEndIndex === 0) {
          continue;
        }
        if (this._opts.isUnshift) {
          indentationEndIndex = Math.min(indentationEndIndex, indentSize);
          for (let i3 = 0; i3 < indentationEndIndex; i3++) {
            const chr = lineText.charCodeAt(i3);
            if (chr === 9) {
              indentationEndIndex = i3 + 1;
              break;
            }
          }
          this._addEditOperation(builder, new Range(lineNumber, 1, lineNumber, indentationEndIndex + 1), "");
        } else {
          this._addEditOperation(builder, new Range(lineNumber, 1, lineNumber, 1), oneIndent);
          if (lineNumber === startLine && !this._selection.isEmpty()) {
            this._selectionStartColumnStaysPut = this._selection.startColumn === 1;
          }
        }
      }
    }
    this._selectionId = builder.trackSelection(this._selection);
  }
  computeCursorState(model, helper) {
    if (this._useLastEditRangeForCursorEndPosition) {
      let lastOp = helper.getInverseEditOperations()[0];
      return new Selection(lastOp.range.endLineNumber, lastOp.range.endColumn, lastOp.range.endLineNumber, lastOp.range.endColumn);
    }
    const result = helper.getTrackedSelection(this._selectionId);
    if (this._selectionStartColumnStaysPut) {
      let initialStartColumn = this._selection.startColumn;
      let resultStartColumn = result.startColumn;
      if (resultStartColumn <= initialStartColumn) {
        return result;
      }
      if (result.getDirection() === 0) {
        return new Selection(result.startLineNumber, initialStartColumn, result.endLineNumber, result.endColumn);
      }
      return new Selection(result.endLineNumber, result.endColumn, result.startLineNumber, initialStartColumn);
    }
    return result;
  }
};
var SurroundSelectionCommand = class {
  constructor(range3, charBeforeSelection, charAfterSelection) {
    this._range = range3;
    this._charBeforeSelection = charBeforeSelection;
    this._charAfterSelection = charAfterSelection;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(new Range(this._range.startLineNumber, this._range.startColumn, this._range.startLineNumber, this._range.startColumn), this._charBeforeSelection);
    builder.addTrackedEditOperation(new Range(this._range.endLineNumber, this._range.endColumn, this._range.endLineNumber, this._range.endColumn), this._charAfterSelection);
  }
  computeCursorState(model, helper) {
    let inverseEditOperations = helper.getInverseEditOperations();
    let firstOperationRange = inverseEditOperations[0].range;
    let secondOperationRange = inverseEditOperations[1].range;
    return new Selection(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this._charAfterSelection.length);
  }
};
var TypeOperations = class {
  static indent(config2, model, selections) {
    if (model === null || selections === null) {
      return [];
    }
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      commands[i3] = new ShiftCommand(selections[i3], {
        isUnshift: false,
        tabSize: config2.tabSize,
        indentSize: config2.indentSize,
        insertSpaces: config2.insertSpaces,
        useTabStops: config2.useTabStops,
        autoIndent: config2.autoIndent
      });
    }
    return commands;
  }
  static outdent(config2, model, selections) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      commands[i3] = new ShiftCommand(selections[i3], {
        isUnshift: true,
        tabSize: config2.tabSize,
        indentSize: config2.indentSize,
        insertSpaces: config2.insertSpaces,
        useTabStops: config2.useTabStops,
        autoIndent: config2.autoIndent
      });
    }
    return commands;
  }
  static shiftIndent(config2, indentation, count) {
    count = count || 1;
    return ShiftCommand.shiftIndent(indentation, indentation.length + count, config2.tabSize, config2.indentSize, config2.insertSpaces);
  }
  static unshiftIndent(config2, indentation, count) {
    count = count || 1;
    return ShiftCommand.unshiftIndent(indentation, indentation.length + count, config2.tabSize, config2.indentSize, config2.insertSpaces);
  }
  static _distributedPaste(config2, model, selections, text) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      commands[i3] = new ReplaceCommand(selections[i3], text[i3]);
    }
    return new EditOperationResult(0, commands, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
  static _simplePaste(config2, model, selections, text, pasteOnNewLine) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      let position2 = selection2.getPosition();
      if (pasteOnNewLine && !selection2.isEmpty()) {
        pasteOnNewLine = false;
      }
      if (pasteOnNewLine && text.indexOf("\n") !== text.length - 1) {
        pasteOnNewLine = false;
      }
      if (pasteOnNewLine) {
        let typeSelection = new Range(position2.lineNumber, 1, position2.lineNumber, 1);
        commands[i3] = new ReplaceCommandThatPreservesSelection(typeSelection, text, selection2, true);
      } else {
        commands[i3] = new ReplaceCommand(selection2, text);
      }
    }
    return new EditOperationResult(0, commands, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
  static _distributePasteToCursors(config2, selections, text, pasteOnNewLine, multicursorText) {
    if (pasteOnNewLine) {
      return null;
    }
    if (selections.length === 1) {
      return null;
    }
    if (multicursorText && multicursorText.length === selections.length) {
      return multicursorText;
    }
    if (config2.multiCursorPaste === "spread") {
      if (text.charCodeAt(text.length - 1) === 10) {
        text = text.substr(0, text.length - 1);
      }
      if (text.charCodeAt(text.length - 1) === 13) {
        text = text.substr(0, text.length - 1);
      }
      let lines = text.split(/\r\n|\r|\n/);
      if (lines.length === selections.length) {
        return lines;
      }
    }
    return null;
  }
  static paste(config2, model, selections, text, pasteOnNewLine, multicursorText) {
    const distributedPaste = this._distributePasteToCursors(config2, selections, text, pasteOnNewLine, multicursorText);
    if (distributedPaste) {
      selections = selections.sort(Range.compareRangesUsingStarts);
      return this._distributedPaste(config2, model, selections, distributedPaste);
    } else {
      return this._simplePaste(config2, model, selections, text, pasteOnNewLine);
    }
  }
  static _goodIndentForLine(config2, model, lineNumber) {
    let action = null;
    let indentation = "";
    const expectedIndentAction = LanguageConfigurationRegistry.getInheritIndentForLine(config2.autoIndent, model, lineNumber, false);
    if (expectedIndentAction) {
      action = expectedIndentAction.action;
      indentation = expectedIndentAction.indentation;
    } else if (lineNumber > 1) {
      let lastLineNumber;
      for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
        const lineText = model.getLineContent(lastLineNumber);
        const nonWhitespaceIdx = lastNonWhitespaceIndex(lineText);
        if (nonWhitespaceIdx >= 0) {
          break;
        }
      }
      if (lastLineNumber < 1) {
        return null;
      }
      const maxColumn = model.getLineMaxColumn(lastLineNumber);
      const expectedEnterAction = LanguageConfigurationRegistry.getEnterAction(config2.autoIndent, model, new Range(lastLineNumber, maxColumn, lastLineNumber, maxColumn));
      if (expectedEnterAction) {
        indentation = expectedEnterAction.indentation + expectedEnterAction.appendText;
      }
    }
    if (action) {
      if (action === IndentAction$1.Indent) {
        indentation = TypeOperations.shiftIndent(config2, indentation);
      }
      if (action === IndentAction$1.Outdent) {
        indentation = TypeOperations.unshiftIndent(config2, indentation);
      }
      indentation = config2.normalizeIndentation(indentation);
    }
    if (!indentation) {
      return null;
    }
    return indentation;
  }
  static _replaceJumpToNextIndent(config2, model, selection2, insertsAutoWhitespace) {
    let typeText = "";
    let position2 = selection2.getStartPosition();
    if (config2.insertSpaces) {
      let visibleColumnFromColumn = CursorColumns.visibleColumnFromColumn2(config2, model, position2);
      let indentSize = config2.indentSize;
      let spacesCnt = indentSize - visibleColumnFromColumn % indentSize;
      for (let i3 = 0; i3 < spacesCnt; i3++) {
        typeText += " ";
      }
    } else {
      typeText = "	";
    }
    return new ReplaceCommand(selection2, typeText, insertsAutoWhitespace);
  }
  static tab(config2, model, selections) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      if (selection2.isEmpty()) {
        let lineText = model.getLineContent(selection2.startLineNumber);
        if (/^\s*$/.test(lineText) && model.isCheapToTokenize(selection2.startLineNumber)) {
          let goodIndent = this._goodIndentForLine(config2, model, selection2.startLineNumber);
          goodIndent = goodIndent || "	";
          let possibleTypeText = config2.normalizeIndentation(goodIndent);
          if (!startsWith(lineText, possibleTypeText)) {
            commands[i3] = new ReplaceCommand(new Range(selection2.startLineNumber, 1, selection2.startLineNumber, lineText.length + 1), possibleTypeText, true);
            continue;
          }
        }
        commands[i3] = this._replaceJumpToNextIndent(config2, model, selection2, true);
      } else {
        if (selection2.startLineNumber === selection2.endLineNumber) {
          let lineMaxColumn = model.getLineMaxColumn(selection2.startLineNumber);
          if (selection2.startColumn !== 1 || selection2.endColumn !== lineMaxColumn) {
            commands[i3] = this._replaceJumpToNextIndent(config2, model, selection2, false);
            continue;
          }
        }
        commands[i3] = new ShiftCommand(selection2, {
          isUnshift: false,
          tabSize: config2.tabSize,
          indentSize: config2.indentSize,
          insertSpaces: config2.insertSpaces,
          useTabStops: config2.useTabStops,
          autoIndent: config2.autoIndent
        });
      }
    }
    return commands;
  }
  static replacePreviousChar(prevEditOperationType, config2, model, selections, txt, replaceCharCnt) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      if (!selection2.isEmpty()) {
        commands[i3] = null;
        continue;
      }
      const pos = selection2.getPosition();
      const startColumn = Math.max(1, pos.column - replaceCharCnt);
      const range3 = new Range(pos.lineNumber, startColumn, pos.lineNumber, pos.column);
      const oldText = model.getValueInRange(range3);
      if (oldText === txt) {
        commands[i3] = null;
        continue;
      }
      commands[i3] = new ReplaceCommand(range3, txt);
    }
    return new EditOperationResult(1, commands, {
      shouldPushStackElementBefore: prevEditOperationType !== 1,
      shouldPushStackElementAfter: false
    });
  }
  static _typeCommand(range3, text, keepPosition) {
    if (keepPosition) {
      return new ReplaceCommandWithoutChangingPosition(range3, text, true);
    } else {
      return new ReplaceCommand(range3, text, true);
    }
  }
  static _enter(config2, model, keepPosition, range3) {
    if (config2.autoIndent === 0) {
      return TypeOperations._typeCommand(range3, "\n", keepPosition);
    }
    if (!model.isCheapToTokenize(range3.getStartPosition().lineNumber) || config2.autoIndent === 1) {
      let lineText2 = model.getLineContent(range3.startLineNumber);
      let indentation2 = getLeadingWhitespace(lineText2).substring(0, range3.startColumn - 1);
      return TypeOperations._typeCommand(range3, "\n" + config2.normalizeIndentation(indentation2), keepPosition);
    }
    const r3 = LanguageConfigurationRegistry.getEnterAction(config2.autoIndent, model, range3);
    if (r3) {
      if (r3.indentAction === IndentAction$1.None) {
        return TypeOperations._typeCommand(range3, "\n" + config2.normalizeIndentation(r3.indentation + r3.appendText), keepPosition);
      } else if (r3.indentAction === IndentAction$1.Indent) {
        return TypeOperations._typeCommand(range3, "\n" + config2.normalizeIndentation(r3.indentation + r3.appendText), keepPosition);
      } else if (r3.indentAction === IndentAction$1.IndentOutdent) {
        const normalIndent = config2.normalizeIndentation(r3.indentation);
        const increasedIndent = config2.normalizeIndentation(r3.indentation + r3.appendText);
        const typeText = "\n" + increasedIndent + "\n" + normalIndent;
        if (keepPosition) {
          return new ReplaceCommandWithoutChangingPosition(range3, typeText, true);
        } else {
          return new ReplaceCommandWithOffsetCursorState(range3, typeText, -1, increasedIndent.length - normalIndent.length, true);
        }
      } else if (r3.indentAction === IndentAction$1.Outdent) {
        const actualIndentation = TypeOperations.unshiftIndent(config2, r3.indentation);
        return TypeOperations._typeCommand(range3, "\n" + config2.normalizeIndentation(actualIndentation + r3.appendText), keepPosition);
      }
    }
    const lineText = model.getLineContent(range3.startLineNumber);
    const indentation = getLeadingWhitespace(lineText).substring(0, range3.startColumn - 1);
    if (config2.autoIndent >= 4) {
      const ir = LanguageConfigurationRegistry.getIndentForEnter(config2.autoIndent, model, range3, {
        unshiftIndent: (indent) => {
          return TypeOperations.unshiftIndent(config2, indent);
        },
        shiftIndent: (indent) => {
          return TypeOperations.shiftIndent(config2, indent);
        },
        normalizeIndentation: (indent) => {
          return config2.normalizeIndentation(indent);
        }
      });
      if (ir) {
        let oldEndViewColumn = CursorColumns.visibleColumnFromColumn2(config2, model, range3.getEndPosition());
        const oldEndColumn = range3.endColumn;
        let beforeText = "\n";
        if (indentation !== config2.normalizeIndentation(ir.beforeEnter)) {
          beforeText = config2.normalizeIndentation(ir.beforeEnter) + lineText.substring(indentation.length, range3.startColumn - 1) + "\n";
          range3 = new Range(range3.startLineNumber, 1, range3.endLineNumber, range3.endColumn);
        }
        const newLineContent = model.getLineContent(range3.endLineNumber);
        const firstNonWhitespace = firstNonWhitespaceIndex(newLineContent);
        if (firstNonWhitespace >= 0) {
          range3 = range3.setEndPosition(range3.endLineNumber, Math.max(range3.endColumn, firstNonWhitespace + 1));
        } else {
          range3 = range3.setEndPosition(range3.endLineNumber, model.getLineMaxColumn(range3.endLineNumber));
        }
        if (keepPosition) {
          return new ReplaceCommandWithoutChangingPosition(range3, beforeText + config2.normalizeIndentation(ir.afterEnter), true);
        } else {
          let offset2 = 0;
          if (oldEndColumn <= firstNonWhitespace + 1) {
            if (!config2.insertSpaces) {
              oldEndViewColumn = Math.ceil(oldEndViewColumn / config2.indentSize);
            }
            offset2 = Math.min(oldEndViewColumn + 1 - config2.normalizeIndentation(ir.afterEnter).length - 1, 0);
          }
          return new ReplaceCommandWithOffsetCursorState(range3, beforeText + config2.normalizeIndentation(ir.afterEnter), 0, offset2, true);
        }
      }
    }
    return TypeOperations._typeCommand(range3, "\n" + config2.normalizeIndentation(indentation), keepPosition);
  }
  static _isAutoIndentType(config2, model, selections) {
    if (config2.autoIndent < 4) {
      return false;
    }
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      if (!model.isCheapToTokenize(selections[i3].getEndPosition().lineNumber)) {
        return false;
      }
    }
    return true;
  }
  static _runAutoIndentType(config2, model, range3, ch2) {
    const currentIndentation = LanguageConfigurationRegistry.getIndentationAtPosition(model, range3.startLineNumber, range3.startColumn);
    const actualIndentation = LanguageConfigurationRegistry.getIndentActionForType(config2.autoIndent, model, range3, ch2, {
      shiftIndent: (indentation) => {
        return TypeOperations.shiftIndent(config2, indentation);
      },
      unshiftIndent: (indentation) => {
        return TypeOperations.unshiftIndent(config2, indentation);
      }
    });
    if (actualIndentation === null) {
      return null;
    }
    if (actualIndentation !== config2.normalizeIndentation(currentIndentation)) {
      const firstNonWhitespace = model.getLineFirstNonWhitespaceColumn(range3.startLineNumber);
      if (firstNonWhitespace === 0) {
        return TypeOperations._typeCommand(new Range(range3.startLineNumber, 0, range3.endLineNumber, range3.endColumn), config2.normalizeIndentation(actualIndentation) + ch2, false);
      } else {
        return TypeOperations._typeCommand(new Range(range3.startLineNumber, 0, range3.endLineNumber, range3.endColumn), config2.normalizeIndentation(actualIndentation) + model.getLineContent(range3.startLineNumber).substring(firstNonWhitespace - 1, range3.startColumn - 1) + ch2, false);
      }
    }
    return null;
  }
  static _isAutoClosingOvertype(config2, model, selections, autoClosedCharacters, ch2) {
    if (config2.autoClosingOvertype === "never") {
      return false;
    }
    if (!config2.autoClosingPairsClose2.has(ch2)) {
      return false;
    }
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      if (!selection2.isEmpty()) {
        return false;
      }
      const position2 = selection2.getPosition();
      const lineText = model.getLineContent(position2.lineNumber);
      const afterCharacter = lineText.charAt(position2.column - 1);
      if (afterCharacter !== ch2) {
        return false;
      }
      const chIsQuote = isQuote(ch2);
      const beforeCharacter = position2.column > 2 ? lineText.charCodeAt(position2.column - 2) : 0;
      if (beforeCharacter === 92 && chIsQuote) {
        return false;
      }
      if (config2.autoClosingOvertype === "auto") {
        let found = false;
        for (let j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) {
          const autoClosedCharacter = autoClosedCharacters[j];
          if (position2.lineNumber === autoClosedCharacter.startLineNumber && position2.column === autoClosedCharacter.startColumn) {
            found = true;
            break;
          }
        }
        if (!found) {
          return false;
        }
      }
    }
    return true;
  }
  static _runAutoClosingOvertype(prevEditOperationType, config2, model, selections, ch2) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      const position2 = selection2.getPosition();
      const typeSelection = new Range(position2.lineNumber, position2.column, position2.lineNumber, position2.column + 1);
      commands[i3] = new ReplaceCommand(typeSelection, ch2);
    }
    return new EditOperationResult(1, commands, {
      shouldPushStackElementBefore: prevEditOperationType !== 1,
      shouldPushStackElementAfter: false
    });
  }
  static _autoClosingPairIsSymmetric(autoClosingPair) {
    const {open: open2, close} = autoClosingPair;
    return open2.indexOf(close) >= 0 || close.indexOf(open2) >= 0;
  }
  static _isBeforeClosingBrace(config2, autoClosingPair, characterAfter) {
    const otherAutoClosingPairs = config2.autoClosingPairsClose2.get(characterAfter);
    if (!otherAutoClosingPairs) {
      return false;
    }
    const thisBraceIsSymmetric = TypeOperations._autoClosingPairIsSymmetric(autoClosingPair);
    for (const otherAutoClosingPair of otherAutoClosingPairs) {
      const otherBraceIsSymmetric = TypeOperations._autoClosingPairIsSymmetric(otherAutoClosingPair);
      if (!thisBraceIsSymmetric && otherBraceIsSymmetric) {
        continue;
      }
      return true;
    }
    return false;
  }
  static _findAutoClosingPairOpen(config2, model, positions, ch2) {
    const autoClosingPairCandidates = config2.autoClosingPairsOpen2.get(ch2);
    if (!autoClosingPairCandidates) {
      return null;
    }
    let autoClosingPair = null;
    for (const autoClosingPairCandidate of autoClosingPairCandidates) {
      if (autoClosingPair === null || autoClosingPairCandidate.open.length > autoClosingPair.open.length) {
        let candidateIsMatch = true;
        for (const position2 of positions) {
          const relevantText = model.getValueInRange(new Range(position2.lineNumber, position2.column - autoClosingPairCandidate.open.length + 1, position2.lineNumber, position2.column));
          if (relevantText + ch2 !== autoClosingPairCandidate.open) {
            candidateIsMatch = false;
            break;
          }
        }
        if (candidateIsMatch) {
          autoClosingPair = autoClosingPairCandidate;
        }
      }
    }
    return autoClosingPair;
  }
  static _isAutoClosingOpenCharType(config2, model, selections, ch2, insertOpenCharacter) {
    const chIsQuote = isQuote(ch2);
    const autoCloseConfig = chIsQuote ? config2.autoClosingQuotes : config2.autoClosingBrackets;
    if (autoCloseConfig === "never") {
      return null;
    }
    const autoClosingPair = this._findAutoClosingPairOpen(config2, model, selections.map((s2) => s2.getPosition()), ch2);
    if (!autoClosingPair) {
      return null;
    }
    const shouldAutoCloseBefore = chIsQuote ? config2.shouldAutoCloseBefore.quote : config2.shouldAutoCloseBefore.bracket;
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      if (!selection2.isEmpty()) {
        return null;
      }
      const position2 = selection2.getPosition();
      const lineText = model.getLineContent(position2.lineNumber);
      if (lineText.length > position2.column - 1) {
        const characterAfter = lineText.charAt(position2.column - 1);
        const isBeforeCloseBrace = TypeOperations._isBeforeClosingBrace(config2, autoClosingPair, characterAfter);
        if (!isBeforeCloseBrace && !shouldAutoCloseBefore(characterAfter)) {
          return null;
        }
      }
      if (!model.isCheapToTokenize(position2.lineNumber)) {
        return null;
      }
      if (autoClosingPair.open.length === 1 && chIsQuote && autoCloseConfig !== "always") {
        const wordSeparators2 = getMapForWordSeparators(config2.wordSeparators);
        if (insertOpenCharacter && position2.column > 1 && wordSeparators2.get(lineText.charCodeAt(position2.column - 2)) === 0) {
          return null;
        }
        if (!insertOpenCharacter && position2.column > 2 && wordSeparators2.get(lineText.charCodeAt(position2.column - 3)) === 0) {
          return null;
        }
      }
      model.forceTokenization(position2.lineNumber);
      const lineTokens = model.getLineTokens(position2.lineNumber);
      let shouldAutoClosePair = false;
      try {
        shouldAutoClosePair = LanguageConfigurationRegistry.shouldAutoClosePair(autoClosingPair, lineTokens, insertOpenCharacter ? position2.column : position2.column - 1);
      } catch (e2) {
        onUnexpectedError(e2);
      }
      if (!shouldAutoClosePair) {
        return null;
      }
    }
    return autoClosingPair;
  }
  static _runAutoClosingOpenCharType(prevEditOperationType, config2, model, selections, ch2, insertOpenCharacter, autoClosingPair) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      commands[i3] = new TypeWithAutoClosingCommand(selection2, ch2, insertOpenCharacter, autoClosingPair.close);
    }
    return new EditOperationResult(1, commands, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: false
    });
  }
  static _shouldSurroundChar(config2, ch2) {
    if (isQuote(ch2)) {
      return config2.autoSurround === "quotes" || config2.autoSurround === "languageDefined";
    } else {
      return config2.autoSurround === "brackets" || config2.autoSurround === "languageDefined";
    }
  }
  static _isSurroundSelectionType(config2, model, selections, ch2) {
    if (!TypeOperations._shouldSurroundChar(config2, ch2) || !config2.surroundingPairs.hasOwnProperty(ch2)) {
      return false;
    }
    const isTypingAQuoteCharacter = isQuote(ch2);
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      if (selection2.isEmpty()) {
        return false;
      }
      let selectionContainsOnlyWhitespace = true;
      for (let lineNumber = selection2.startLineNumber; lineNumber <= selection2.endLineNumber; lineNumber++) {
        const lineText = model.getLineContent(lineNumber);
        const startIndex = lineNumber === selection2.startLineNumber ? selection2.startColumn - 1 : 0;
        const endIndex = lineNumber === selection2.endLineNumber ? selection2.endColumn - 1 : lineText.length;
        const selectedText = lineText.substring(startIndex, endIndex);
        if (/[^ \t]/.test(selectedText)) {
          selectionContainsOnlyWhitespace = false;
          break;
        }
      }
      if (selectionContainsOnlyWhitespace) {
        return false;
      }
      if (isTypingAQuoteCharacter && selection2.startLineNumber === selection2.endLineNumber && selection2.startColumn + 1 === selection2.endColumn) {
        const selectionText = model.getValueInRange(selection2);
        if (isQuote(selectionText)) {
          return false;
        }
      }
    }
    return true;
  }
  static _runSurroundSelectionType(prevEditOperationType, config2, model, selections, ch2) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      const closeCharacter = config2.surroundingPairs[ch2];
      commands[i3] = new SurroundSelectionCommand(selection2, ch2, closeCharacter);
    }
    return new EditOperationResult(0, commands, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
  static _isTypeInterceptorElectricChar(config2, model, selections) {
    if (selections.length === 1 && model.isCheapToTokenize(selections[0].getEndPosition().lineNumber)) {
      return true;
    }
    return false;
  }
  static _typeInterceptorElectricChar(prevEditOperationType, config2, model, selection2, ch2) {
    if (!config2.electricChars.hasOwnProperty(ch2) || !selection2.isEmpty()) {
      return null;
    }
    let position2 = selection2.getPosition();
    model.forceTokenization(position2.lineNumber);
    let lineTokens = model.getLineTokens(position2.lineNumber);
    let electricAction;
    try {
      electricAction = LanguageConfigurationRegistry.onElectricCharacter(ch2, lineTokens, position2.column);
    } catch (e2) {
      onUnexpectedError(e2);
      return null;
    }
    if (!electricAction) {
      return null;
    }
    if (electricAction.matchOpenBracket) {
      let endColumn = (lineTokens.getLineContent() + ch2).lastIndexOf(electricAction.matchOpenBracket) + 1;
      let match2 = model.findMatchingBracketUp(electricAction.matchOpenBracket, {
        lineNumber: position2.lineNumber,
        column: endColumn
      });
      if (match2) {
        if (match2.startLineNumber === position2.lineNumber) {
          return null;
        }
        let matchLine = model.getLineContent(match2.startLineNumber);
        let matchLineIndentation = getLeadingWhitespace(matchLine);
        let newIndentation = config2.normalizeIndentation(matchLineIndentation);
        let lineText = model.getLineContent(position2.lineNumber);
        let lineFirstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(position2.lineNumber) || position2.column;
        let prefix2 = lineText.substring(lineFirstNonBlankColumn - 1, position2.column - 1);
        let typeText = newIndentation + prefix2 + ch2;
        let typeSelection = new Range(position2.lineNumber, 1, position2.lineNumber, position2.column);
        const command = new ReplaceCommand(typeSelection, typeText);
        return new EditOperationResult(1, [command], {
          shouldPushStackElementBefore: false,
          shouldPushStackElementAfter: true
        });
      }
    }
    return null;
  }
  static compositionEndWithInterceptors(prevEditOperationType, config2, model, selectionsWhenCompositionStarted, selections, autoClosedCharacters) {
    if (!selectionsWhenCompositionStarted || Selection.selectionsArrEqual(selectionsWhenCompositionStarted, selections)) {
      return null;
    }
    let ch2 = null;
    for (const selection2 of selections) {
      if (!selection2.isEmpty()) {
        return null;
      }
      const position2 = selection2.getPosition();
      const currentChar = model.getValueInRange(new Range(position2.lineNumber, position2.column - 1, position2.lineNumber, position2.column));
      if (ch2 === null) {
        ch2 = currentChar;
      } else if (ch2 !== currentChar) {
        return null;
      }
    }
    if (!ch2) {
      return null;
    }
    if (this._isAutoClosingOvertype(config2, model, selections, autoClosedCharacters, ch2)) {
      const commands = selections.map((s2) => new ReplaceCommand(new Range(s2.positionLineNumber, s2.positionColumn, s2.positionLineNumber, s2.positionColumn + 1), "", false));
      return new EditOperationResult(1, commands, {
        shouldPushStackElementBefore: true,
        shouldPushStackElementAfter: false
      });
    }
    const autoClosingPairOpenCharType = this._isAutoClosingOpenCharType(config2, model, selections, ch2, false);
    if (autoClosingPairOpenCharType) {
      return this._runAutoClosingOpenCharType(prevEditOperationType, config2, model, selections, ch2, false, autoClosingPairOpenCharType);
    }
    return null;
  }
  static typeWithInterceptors(isDoingComposition, prevEditOperationType, config2, model, selections, autoClosedCharacters, ch2) {
    if (!isDoingComposition && ch2 === "\n") {
      let commands2 = [];
      for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
        commands2[i3] = TypeOperations._enter(config2, model, false, selections[i3]);
      }
      return new EditOperationResult(1, commands2, {
        shouldPushStackElementBefore: true,
        shouldPushStackElementAfter: false
      });
    }
    if (!isDoingComposition && this._isAutoIndentType(config2, model, selections)) {
      let commands2 = [];
      let autoIndentFails = false;
      for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
        commands2[i3] = this._runAutoIndentType(config2, model, selections[i3], ch2);
        if (!commands2[i3]) {
          autoIndentFails = true;
          break;
        }
      }
      if (!autoIndentFails) {
        return new EditOperationResult(1, commands2, {
          shouldPushStackElementBefore: true,
          shouldPushStackElementAfter: false
        });
      }
    }
    if (!isDoingComposition && this._isAutoClosingOvertype(config2, model, selections, autoClosedCharacters, ch2)) {
      return this._runAutoClosingOvertype(prevEditOperationType, config2, model, selections, ch2);
    }
    if (!isDoingComposition) {
      const autoClosingPairOpenCharType = this._isAutoClosingOpenCharType(config2, model, selections, ch2, true);
      if (autoClosingPairOpenCharType) {
        return this._runAutoClosingOpenCharType(prevEditOperationType, config2, model, selections, ch2, true, autoClosingPairOpenCharType);
      }
    }
    if (this._isSurroundSelectionType(config2, model, selections, ch2)) {
      return this._runSurroundSelectionType(prevEditOperationType, config2, model, selections, ch2);
    }
    if (!isDoingComposition && this._isTypeInterceptorElectricChar(config2, model, selections)) {
      const r3 = this._typeInterceptorElectricChar(prevEditOperationType, config2, model, selections[0], ch2);
      if (r3) {
        return r3;
      }
    }
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      commands[i3] = new ReplaceCommand(selections[i3], ch2);
    }
    let shouldPushStackElementBefore = prevEditOperationType !== 1;
    if (ch2 === " ") {
      shouldPushStackElementBefore = true;
    }
    return new EditOperationResult(1, commands, {
      shouldPushStackElementBefore,
      shouldPushStackElementAfter: false
    });
  }
  static typeWithoutInterceptors(prevEditOperationType, config2, model, selections, str) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      commands[i3] = new ReplaceCommand(selections[i3], str);
    }
    return new EditOperationResult(1, commands, {
      shouldPushStackElementBefore: prevEditOperationType !== 1,
      shouldPushStackElementAfter: false
    });
  }
  static lineInsertBefore(config2, model, selections) {
    if (model === null || selections === null) {
      return [];
    }
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      let lineNumber = selections[i3].positionLineNumber;
      if (lineNumber === 1) {
        commands[i3] = new ReplaceCommandWithoutChangingPosition(new Range(1, 1, 1, 1), "\n");
      } else {
        lineNumber--;
        let column = model.getLineMaxColumn(lineNumber);
        commands[i3] = this._enter(config2, model, false, new Range(lineNumber, column, lineNumber, column));
      }
    }
    return commands;
  }
  static lineInsertAfter(config2, model, selections) {
    if (model === null || selections === null) {
      return [];
    }
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const lineNumber = selections[i3].positionLineNumber;
      let column = model.getLineMaxColumn(lineNumber);
      commands[i3] = this._enter(config2, model, false, new Range(lineNumber, column, lineNumber, column));
    }
    return commands;
  }
  static lineBreakInsert(config2, model, selections) {
    let commands = [];
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      commands[i3] = this._enter(config2, model, true, selections[i3]);
    }
    return commands;
  }
};
var TypeWithAutoClosingCommand = class extends ReplaceCommandWithOffsetCursorState {
  constructor(selection2, openCharacter, insertOpenCharacter, closeCharacter) {
    super(selection2, (insertOpenCharacter ? openCharacter : "") + closeCharacter, 0, -closeCharacter.length);
    this._openCharacter = openCharacter;
    this._closeCharacter = closeCharacter;
    this.closeCharacterRange = null;
    this.enclosingRange = null;
  }
  computeCursorState(model, helper) {
    let inverseEditOperations = helper.getInverseEditOperations();
    let range3 = inverseEditOperations[0].range;
    this.closeCharacterRange = new Range(range3.startLineNumber, range3.endColumn - this._closeCharacter.length, range3.endLineNumber, range3.endColumn);
    this.enclosingRange = new Range(range3.startLineNumber, range3.endColumn - this._openCharacter.length - this._closeCharacter.length, range3.endLineNumber, range3.endColumn);
    return super.computeCursorState(model, helper);
  }
};
var EditorContextKeys;
(function(EditorContextKeys2) {
  EditorContextKeys2.editorSimpleInput = new RawContextKey("editorSimpleInput", false);
  EditorContextKeys2.editorTextFocus = new RawContextKey("editorTextFocus", false);
  EditorContextKeys2.focus = new RawContextKey("editorFocus", false);
  EditorContextKeys2.textInputFocus = new RawContextKey("textInputFocus", false);
  EditorContextKeys2.readOnly = new RawContextKey("editorReadonly", false);
  EditorContextKeys2.columnSelection = new RawContextKey("editorColumnSelection", false);
  EditorContextKeys2.writable = EditorContextKeys2.readOnly.toNegated();
  EditorContextKeys2.hasNonEmptySelection = new RawContextKey("editorHasSelection", false);
  EditorContextKeys2.hasOnlyEmptySelection = EditorContextKeys2.hasNonEmptySelection.toNegated();
  EditorContextKeys2.hasMultipleSelections = new RawContextKey("editorHasMultipleSelections", false);
  EditorContextKeys2.hasSingleSelection = EditorContextKeys2.hasMultipleSelections.toNegated();
  EditorContextKeys2.tabMovesFocus = new RawContextKey("editorTabMovesFocus", false);
  EditorContextKeys2.tabDoesNotMoveFocus = EditorContextKeys2.tabMovesFocus.toNegated();
  EditorContextKeys2.isInWalkThroughSnippet = new RawContextKey("isInEmbeddedEditor", false);
  EditorContextKeys2.canUndo = new RawContextKey("canUndo", false);
  EditorContextKeys2.canRedo = new RawContextKey("canRedo", false);
  EditorContextKeys2.hoverVisible = new RawContextKey("editorHoverVisible", false);
  EditorContextKeys2.inCompositeEditor = new RawContextKey("inCompositeEditor", void 0);
  EditorContextKeys2.notInCompositeEditor = EditorContextKeys2.inCompositeEditor.toNegated();
  EditorContextKeys2.languageId = new RawContextKey("editorLangId", "");
  EditorContextKeys2.hasCompletionItemProvider = new RawContextKey("editorHasCompletionItemProvider", false);
  EditorContextKeys2.hasCodeActionsProvider = new RawContextKey("editorHasCodeActionsProvider", false);
  EditorContextKeys2.hasCodeLensProvider = new RawContextKey("editorHasCodeLensProvider", false);
  EditorContextKeys2.hasDefinitionProvider = new RawContextKey("editorHasDefinitionProvider", false);
  EditorContextKeys2.hasDeclarationProvider = new RawContextKey("editorHasDeclarationProvider", false);
  EditorContextKeys2.hasImplementationProvider = new RawContextKey("editorHasImplementationProvider", false);
  EditorContextKeys2.hasTypeDefinitionProvider = new RawContextKey("editorHasTypeDefinitionProvider", false);
  EditorContextKeys2.hasHoverProvider = new RawContextKey("editorHasHoverProvider", false);
  EditorContextKeys2.hasDocumentHighlightProvider = new RawContextKey("editorHasDocumentHighlightProvider", false);
  EditorContextKeys2.hasDocumentSymbolProvider = new RawContextKey("editorHasDocumentSymbolProvider", false);
  EditorContextKeys2.hasReferenceProvider = new RawContextKey("editorHasReferenceProvider", false);
  EditorContextKeys2.hasRenameProvider = new RawContextKey("editorHasRenameProvider", false);
  EditorContextKeys2.hasSignatureHelpProvider = new RawContextKey("editorHasSignatureHelpProvider", false);
  EditorContextKeys2.hasDocumentFormattingProvider = new RawContextKey("editorHasDocumentFormattingProvider", false);
  EditorContextKeys2.hasDocumentSelectionFormattingProvider = new RawContextKey("editorHasDocumentSelectionFormattingProvider", false);
  EditorContextKeys2.hasMultipleDocumentFormattingProvider = new RawContextKey("editorHasMultipleDocumentFormattingProvider", false);
  EditorContextKeys2.hasMultipleDocumentSelectionFormattingProvider = new RawContextKey("editorHasMultipleDocumentSelectionFormattingProvider", false);
})(EditorContextKeys || (EditorContextKeys = {}));
var CORE_WEIGHT = 0;
var CoreEditorCommand = class extends EditorCommand {
  runEditorCommand(accessor, editor2, args) {
    const viewModel = editor2._getViewModel();
    if (!viewModel) {
      return;
    }
    this.runCoreEditorCommand(viewModel, args || {});
  }
};
var EditorScroll_;
(function(EditorScroll_2) {
  const isEditorScrollArgs = function(arg) {
    if (!isObject3(arg)) {
      return false;
    }
    const scrollArg = arg;
    if (!isString3(scrollArg.to)) {
      return false;
    }
    if (!isUndefined3(scrollArg.by) && !isString3(scrollArg.by)) {
      return false;
    }
    if (!isUndefined3(scrollArg.value) && !isNumber2(scrollArg.value)) {
      return false;
    }
    if (!isUndefined3(scrollArg.revealCursor) && !isBoolean2(scrollArg.revealCursor)) {
      return false;
    }
    return true;
  };
  EditorScroll_2.description = {
    description: "Scroll editor in the given direction",
    args: [
      {
        name: "Editor scroll argument object",
        description: `Property-value pairs that can be passed through this argument:
					* 'to': A mandatory direction value.
						\`\`\`
						'up', 'down'
						\`\`\`
					* 'by': Unit to move. Default is computed based on 'to' value.
						\`\`\`
						'line', 'wrappedLine', 'page', 'halfPage'
						\`\`\`
					* 'value': Number of units to move. Default is '1'.
					* 'revealCursor': If 'true' reveals the cursor if it is outside view port.
				`,
        constraint: isEditorScrollArgs,
        schema: {
          type: "object",
          required: ["to"],
          properties: {
            to: {
              type: "string",
              enum: ["up", "down"]
            },
            by: {
              type: "string",
              enum: ["line", "wrappedLine", "page", "halfPage"]
            },
            value: {
              type: "number",
              default: 1
            },
            revealCursor: {
              type: "boolean"
            }
          }
        }
      }
    ]
  };
  EditorScroll_2.RawDirection = {
    Up: "up",
    Down: "down"
  };
  EditorScroll_2.RawUnit = {
    Line: "line",
    WrappedLine: "wrappedLine",
    Page: "page",
    HalfPage: "halfPage"
  };
  function parse3(args) {
    let direction;
    switch (args.to) {
      case EditorScroll_2.RawDirection.Up:
        direction = 1;
        break;
      case EditorScroll_2.RawDirection.Down:
        direction = 2;
        break;
      default:
        return null;
    }
    let unit;
    switch (args.by) {
      case EditorScroll_2.RawUnit.Line:
        unit = 1;
        break;
      case EditorScroll_2.RawUnit.WrappedLine:
        unit = 2;
        break;
      case EditorScroll_2.RawUnit.Page:
        unit = 3;
        break;
      case EditorScroll_2.RawUnit.HalfPage:
        unit = 4;
        break;
      default:
        unit = 2;
    }
    const value = Math.floor(args.value || 1);
    const revealCursor = !!args.revealCursor;
    return {
      direction,
      unit,
      value,
      revealCursor,
      select: !!args.select
    };
  }
  EditorScroll_2.parse = parse3;
})(EditorScroll_ || (EditorScroll_ = {}));
var RevealLine_;
(function(RevealLine_2) {
  const isRevealLineArgs = function(arg) {
    if (!isObject3(arg)) {
      return false;
    }
    const reveaLineArg = arg;
    if (!isNumber2(reveaLineArg.lineNumber)) {
      return false;
    }
    if (!isUndefined3(reveaLineArg.at) && !isString3(reveaLineArg.at)) {
      return false;
    }
    return true;
  };
  RevealLine_2.description = {
    description: "Reveal the given line at the given logical position",
    args: [
      {
        name: "Reveal line argument object",
        description: `Property-value pairs that can be passed through this argument:
					* 'lineNumber': A mandatory line number value.
					* 'at': Logical position at which line has to be revealed .
						\`\`\`
						'top', 'center', 'bottom'
						\`\`\`
				`,
        constraint: isRevealLineArgs,
        schema: {
          type: "object",
          required: ["lineNumber"],
          properties: {
            lineNumber: {
              type: "number"
            },
            at: {
              type: "string",
              enum: ["top", "center", "bottom"]
            }
          }
        }
      }
    ]
  };
  RevealLine_2.RawAtArgument = {
    Top: "top",
    Center: "center",
    Bottom: "bottom"
  };
})(RevealLine_ || (RevealLine_ = {}));
var EditorOrNativeTextInputCommand = class {
  constructor(target) {
    target.addImplementation(1e4, (accessor, args) => {
      const focusedEditor = accessor.get(ICodeEditorService).getFocusedCodeEditor();
      if (focusedEditor && focusedEditor.hasTextFocus()) {
        this.runEditorCommand(accessor, focusedEditor, args);
        return true;
      }
      return false;
    });
    target.addImplementation(1e3, (accessor, args) => {
      const activeElement = document.activeElement;
      if (activeElement && ["input", "textarea"].indexOf(activeElement.tagName.toLowerCase()) >= 0) {
        this.runDOMCommand();
        return true;
      }
      return false;
    });
    target.addImplementation(0, (accessor, args) => {
      const activeEditor = accessor.get(ICodeEditorService).getActiveCodeEditor();
      if (activeEditor) {
        activeEditor.focus();
        this.runEditorCommand(accessor, activeEditor, args);
        return true;
      }
      return false;
    });
  }
};
var CoreNavigationCommands;
(function(CoreNavigationCommands2) {
  class BaseMoveToCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, [
        CursorMoveCommands.moveTo(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition)
      ]);
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }
  CoreNavigationCommands2.MoveTo = registerEditorCommand(new BaseMoveToCommand({
    id: "_moveTo",
    inSelectionMode: false,
    precondition: void 0
  }));
  CoreNavigationCommands2.MoveToSelect = registerEditorCommand(new BaseMoveToCommand({
    id: "_moveToSelect",
    inSelectionMode: true,
    precondition: void 0
  }));
  class ColumnSelectCommand extends CoreEditorCommand {
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      const result = this._getColumnSelectResult(viewModel, viewModel.getPrimaryCursorState(), viewModel.getCursorColumnSelectData(), args);
      viewModel.setCursorStates(args.source, 3, result.viewStates.map((viewState) => CursorState.fromViewState(viewState)));
      viewModel.setCursorColumnSelectData({
        isReal: true,
        fromViewLineNumber: result.fromLineNumber,
        fromViewVisualColumn: result.fromVisualColumn,
        toViewLineNumber: result.toLineNumber,
        toViewVisualColumn: result.toVisualColumn
      });
      if (result.reversed) {
        viewModel.revealTopMostCursor(args.source);
      } else {
        viewModel.revealBottomMostCursor(args.source);
      }
    }
  }
  CoreNavigationCommands2.ColumnSelect = registerEditorCommand(new class extends ColumnSelectCommand {
    constructor() {
      super({
        id: "columnSelect",
        precondition: void 0
      });
    }
    _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
      const validatedPosition = viewModel.model.validatePosition(args.position);
      const validatedViewPosition = viewModel.coordinatesConverter.validateViewPosition(new Position(args.viewPosition.lineNumber, args.viewPosition.column), validatedPosition);
      let fromViewLineNumber = args.doColumnSelect ? prevColumnSelectData.fromViewLineNumber : validatedViewPosition.lineNumber;
      let fromViewVisualColumn = args.doColumnSelect ? prevColumnSelectData.fromViewVisualColumn : args.mouseColumn - 1;
      return ColumnSelection.columnSelect(viewModel.cursorConfig, viewModel, fromViewLineNumber, fromViewVisualColumn, validatedViewPosition.lineNumber, args.mouseColumn - 1);
    }
  }());
  CoreNavigationCommands2.CursorColumnSelectLeft = registerEditorCommand(new class extends ColumnSelectCommand {
    constructor() {
      super({
        id: "cursorColumnSelectLeft",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 1024 | 512 | 15,
          linux: {primary: 0}
        }
      });
    }
    _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
      return ColumnSelection.columnSelectLeft(viewModel.cursorConfig, viewModel, prevColumnSelectData);
    }
  }());
  CoreNavigationCommands2.CursorColumnSelectRight = registerEditorCommand(new class extends ColumnSelectCommand {
    constructor() {
      super({
        id: "cursorColumnSelectRight",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 1024 | 512 | 17,
          linux: {primary: 0}
        }
      });
    }
    _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
      return ColumnSelection.columnSelectRight(viewModel.cursorConfig, viewModel, prevColumnSelectData);
    }
  }());
  class ColumnSelectUpCommand extends ColumnSelectCommand {
    constructor(opts) {
      super(opts);
      this._isPaged = opts.isPaged;
    }
    _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
      return ColumnSelection.columnSelectUp(viewModel.cursorConfig, viewModel, prevColumnSelectData, this._isPaged);
    }
  }
  CoreNavigationCommands2.CursorColumnSelectUp = registerEditorCommand(new ColumnSelectUpCommand({
    isPaged: false,
    id: "cursorColumnSelectUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 16,
      linux: {primary: 0}
    }
  }));
  CoreNavigationCommands2.CursorColumnSelectPageUp = registerEditorCommand(new ColumnSelectUpCommand({
    isPaged: true,
    id: "cursorColumnSelectPageUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 11,
      linux: {primary: 0}
    }
  }));
  class ColumnSelectDownCommand extends ColumnSelectCommand {
    constructor(opts) {
      super(opts);
      this._isPaged = opts.isPaged;
    }
    _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
      return ColumnSelection.columnSelectDown(viewModel.cursorConfig, viewModel, prevColumnSelectData, this._isPaged);
    }
  }
  CoreNavigationCommands2.CursorColumnSelectDown = registerEditorCommand(new ColumnSelectDownCommand({
    isPaged: false,
    id: "cursorColumnSelectDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 18,
      linux: {primary: 0}
    }
  }));
  CoreNavigationCommands2.CursorColumnSelectPageDown = registerEditorCommand(new ColumnSelectDownCommand({
    isPaged: true,
    id: "cursorColumnSelectPageDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 12,
      linux: {primary: 0}
    }
  }));
  class CursorMoveImpl extends CoreEditorCommand {
    constructor() {
      super({
        id: "cursorMove",
        precondition: void 0,
        description: CursorMove.description
      });
    }
    runCoreEditorCommand(viewModel, args) {
      const parsed = CursorMove.parse(args);
      if (!parsed) {
        return;
      }
      this._runCursorMove(viewModel, args.source, parsed);
    }
    _runCursorMove(viewModel, source2, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(source2, 3, CursorMoveImpl._move(viewModel, viewModel.getCursorStates(), args));
      viewModel.revealPrimaryCursor(source2, true);
    }
    static _move(viewModel, cursors, args) {
      const inSelectionMode = args.select;
      const value = args.value;
      switch (args.direction) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
          return CursorMoveCommands.simpleMove(viewModel, cursors, args.direction, inSelectionMode, value, args.unit);
        case 9:
        case 11:
        case 10:
        case 12:
          return CursorMoveCommands.viewportMove(viewModel, cursors, args.direction, inSelectionMode, value);
        default:
          return null;
      }
    }
  }
  CoreNavigationCommands2.CursorMoveImpl = CursorMoveImpl;
  CoreNavigationCommands2.CursorMove = registerEditorCommand(new CursorMoveImpl());
  class CursorMoveBasedCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._staticArgs = opts.args;
    }
    runCoreEditorCommand(viewModel, dynamicArgs) {
      let args = this._staticArgs;
      if (this._staticArgs.value === -1) {
        args = {
          direction: this._staticArgs.direction,
          unit: this._staticArgs.unit,
          select: this._staticArgs.select,
          value: viewModel.cursorConfig.pageSize
        };
      }
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(dynamicArgs.source, 3, CursorMoveCommands.simpleMove(viewModel, viewModel.getCursorStates(), args.direction, args.select, args.value, args.unit));
      viewModel.revealPrimaryCursor(dynamicArgs.source, true);
    }
  }
  CoreNavigationCommands2.CursorLeft = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 0,
      unit: 0,
      select: false,
      value: 1
    },
    id: "cursorLeft",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 15,
      mac: {primary: 15, secondary: [256 | 32]}
    }
  }));
  CoreNavigationCommands2.CursorLeftSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 0,
      unit: 0,
      select: true,
      value: 1
    },
    id: "cursorLeftSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 15
    }
  }));
  CoreNavigationCommands2.CursorRight = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 1,
      unit: 0,
      select: false,
      value: 1
    },
    id: "cursorRight",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 17,
      mac: {primary: 17, secondary: [256 | 36]}
    }
  }));
  CoreNavigationCommands2.CursorRightSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 1,
      unit: 0,
      select: true,
      value: 1
    },
    id: "cursorRightSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 17
    }
  }));
  CoreNavigationCommands2.CursorUp = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: false,
      value: 1
    },
    id: "cursorUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 16,
      mac: {primary: 16, secondary: [256 | 46]}
    }
  }));
  CoreNavigationCommands2.CursorUpSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: true,
      value: 1
    },
    id: "cursorUpSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 16,
      secondary: [2048 | 1024 | 16],
      mac: {primary: 1024 | 16},
      linux: {primary: 1024 | 16}
    }
  }));
  CoreNavigationCommands2.CursorPageUp = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: false,
      value: -1
    },
    id: "cursorPageUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 11
    }
  }));
  CoreNavigationCommands2.CursorPageUpSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: true,
      value: -1
    },
    id: "cursorPageUpSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 11
    }
  }));
  CoreNavigationCommands2.CursorDown = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: false,
      value: 1
    },
    id: "cursorDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 18,
      mac: {primary: 18, secondary: [256 | 44]}
    }
  }));
  CoreNavigationCommands2.CursorDownSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: true,
      value: 1
    },
    id: "cursorDownSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 18,
      secondary: [2048 | 1024 | 18],
      mac: {primary: 1024 | 18},
      linux: {primary: 1024 | 18}
    }
  }));
  CoreNavigationCommands2.CursorPageDown = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: false,
      value: -1
    },
    id: "cursorPageDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 12
    }
  }));
  CoreNavigationCommands2.CursorPageDownSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: true,
      value: -1
    },
    id: "cursorPageDownSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 12
    }
  }));
  CoreNavigationCommands2.CreateCursor = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "createCursor",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args) {
      let newState;
      if (args.wholeLine) {
        newState = CursorMoveCommands.line(viewModel, viewModel.getPrimaryCursorState(), false, args.position, args.viewPosition);
      } else {
        newState = CursorMoveCommands.moveTo(viewModel, viewModel.getPrimaryCursorState(), false, args.position, args.viewPosition);
      }
      const states = viewModel.getCursorStates();
      if (states.length > 1) {
        const newModelPosition = newState.modelState ? newState.modelState.position : null;
        const newViewPosition = newState.viewState ? newState.viewState.position : null;
        for (let i3 = 0, len2 = states.length; i3 < len2; i3++) {
          const state = states[i3];
          if (newModelPosition && !state.modelState.selection.containsPosition(newModelPosition)) {
            continue;
          }
          if (newViewPosition && !state.viewState.selection.containsPosition(newViewPosition)) {
            continue;
          }
          states.splice(i3, 1);
          viewModel.model.pushStackElement();
          viewModel.setCursorStates(args.source, 3, states);
          return;
        }
      }
      states.push(newState);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, states);
    }
  }());
  CoreNavigationCommands2.LastCursorMoveToSelect = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "_lastCursorMoveToSelect",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args) {
      const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
      const states = viewModel.getCursorStates();
      const newStates = states.slice(0);
      newStates[lastAddedCursorIndex] = CursorMoveCommands.moveTo(viewModel, states[lastAddedCursorIndex], true, args.position, args.viewPosition);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, newStates);
    }
  }());
  class HomeCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToBeginningOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }
  CoreNavigationCommands2.CursorHome = registerEditorCommand(new HomeCommand({
    inSelectionMode: false,
    id: "cursorHome",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 14,
      mac: {primary: 14, secondary: [2048 | 15]}
    }
  }));
  CoreNavigationCommands2.CursorHomeSelect = registerEditorCommand(new HomeCommand({
    inSelectionMode: true,
    id: "cursorHomeSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 14,
      mac: {primary: 1024 | 14, secondary: [2048 | 1024 | 15]}
    }
  }));
  class LineStartCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, this._exec(viewModel.getCursorStates()));
      viewModel.revealPrimaryCursor(args.source, true);
    }
    _exec(cursors) {
      const result = [];
      for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
        const cursor = cursors[i3];
        const lineNumber = cursor.modelState.position.lineNumber;
        result[i3] = CursorState.fromModelState(cursor.modelState.move(this._inSelectionMode, lineNumber, 1, 0));
      }
      return result;
    }
  }
  CoreNavigationCommands2.CursorLineStart = registerEditorCommand(new LineStartCommand({
    inSelectionMode: false,
    id: "cursorLineStart",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {primary: 256 | 31}
    }
  }));
  CoreNavigationCommands2.CursorLineStartSelect = registerEditorCommand(new LineStartCommand({
    inSelectionMode: true,
    id: "cursorLineStartSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {primary: 256 | 1024 | 31}
    }
  }));
  class EndCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToEndOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode, args.sticky || false));
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }
  CoreNavigationCommands2.CursorEnd = registerEditorCommand(new EndCommand({
    inSelectionMode: false,
    id: "cursorEnd",
    precondition: void 0,
    kbOpts: {
      args: {sticky: false},
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 13,
      mac: {primary: 13, secondary: [2048 | 17]}
    },
    description: {
      description: `Go to End`,
      args: [{
        name: "args",
        schema: {
          type: "object",
          properties: {
            sticky: {
              description: localize("stickydesc", "Stick to the end even when going to longer lines"),
              type: "boolean",
              default: false
            }
          }
        }
      }]
    }
  }));
  CoreNavigationCommands2.CursorEndSelect = registerEditorCommand(new EndCommand({
    inSelectionMode: true,
    id: "cursorEndSelect",
    precondition: void 0,
    kbOpts: {
      args: {sticky: false},
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 13,
      mac: {primary: 1024 | 13, secondary: [2048 | 1024 | 17]}
    },
    description: {
      description: `Select to End`,
      args: [{
        name: "args",
        schema: {
          type: "object",
          properties: {
            sticky: {
              description: localize("stickydesc", "Stick to the end even when going to longer lines"),
              type: "boolean",
              default: false
            }
          }
        }
      }]
    }
  }));
  class LineEndCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, this._exec(viewModel, viewModel.getCursorStates()));
      viewModel.revealPrimaryCursor(args.source, true);
    }
    _exec(viewModel, cursors) {
      const result = [];
      for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
        const cursor = cursors[i3];
        const lineNumber = cursor.modelState.position.lineNumber;
        const maxColumn = viewModel.model.getLineMaxColumn(lineNumber);
        result[i3] = CursorState.fromModelState(cursor.modelState.move(this._inSelectionMode, lineNumber, maxColumn, 0));
      }
      return result;
    }
  }
  CoreNavigationCommands2.CursorLineEnd = registerEditorCommand(new LineEndCommand({
    inSelectionMode: false,
    id: "cursorLineEnd",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {primary: 256 | 35}
    }
  }));
  CoreNavigationCommands2.CursorLineEndSelect = registerEditorCommand(new LineEndCommand({
    inSelectionMode: true,
    id: "cursorLineEndSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {primary: 256 | 1024 | 35}
    }
  }));
  class TopCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToBeginningOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }
  CoreNavigationCommands2.CursorTop = registerEditorCommand(new TopCommand({
    inSelectionMode: false,
    id: "cursorTop",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 14,
      mac: {primary: 2048 | 16}
    }
  }));
  CoreNavigationCommands2.CursorTopSelect = registerEditorCommand(new TopCommand({
    inSelectionMode: true,
    id: "cursorTopSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 14,
      mac: {primary: 2048 | 1024 | 16}
    }
  }));
  class BottomCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToEndOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }
  CoreNavigationCommands2.CursorBottom = registerEditorCommand(new BottomCommand({
    inSelectionMode: false,
    id: "cursorBottom",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 13,
      mac: {primary: 2048 | 18}
    }
  }));
  CoreNavigationCommands2.CursorBottomSelect = registerEditorCommand(new BottomCommand({
    inSelectionMode: true,
    id: "cursorBottomSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 13,
      mac: {primary: 2048 | 1024 | 18}
    }
  }));
  class EditorScrollImpl extends CoreEditorCommand {
    constructor() {
      super({
        id: "editorScroll",
        precondition: void 0,
        description: EditorScroll_.description
      });
    }
    runCoreEditorCommand(viewModel, args) {
      const parsed = EditorScroll_.parse(args);
      if (!parsed) {
        return;
      }
      this._runEditorScroll(viewModel, args.source, parsed);
    }
    _runEditorScroll(viewModel, source2, args) {
      const desiredScrollTop = this._computeDesiredScrollTop(viewModel, args);
      if (args.revealCursor) {
        const desiredVisibleViewRange = viewModel.getCompletelyVisibleViewRangeAtScrollTop(desiredScrollTop);
        viewModel.setCursorStates(source2, 3, [
          CursorMoveCommands.findPositionInViewportIfOutside(viewModel, viewModel.getPrimaryCursorState(), desiredVisibleViewRange, args.select)
        ]);
      }
      viewModel.setScrollTop(desiredScrollTop, 0);
    }
    _computeDesiredScrollTop(viewModel, args) {
      if (args.unit === 1) {
        const visibleViewRange = viewModel.getCompletelyVisibleViewRange();
        const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
        let desiredTopModelLineNumber;
        if (args.direction === 1) {
          desiredTopModelLineNumber = Math.max(1, visibleModelRange.startLineNumber - args.value);
        } else {
          desiredTopModelLineNumber = Math.min(viewModel.model.getLineCount(), visibleModelRange.startLineNumber + args.value);
        }
        const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(new Position(desiredTopModelLineNumber, 1));
        return viewModel.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
      }
      let noOfLines;
      if (args.unit === 3) {
        noOfLines = viewModel.cursorConfig.pageSize * args.value;
      } else if (args.unit === 4) {
        noOfLines = Math.round(viewModel.cursorConfig.pageSize / 2) * args.value;
      } else {
        noOfLines = args.value;
      }
      const deltaLines = (args.direction === 1 ? -1 : 1) * noOfLines;
      return viewModel.getScrollTop() + deltaLines * viewModel.cursorConfig.lineHeight;
    }
  }
  CoreNavigationCommands2.EditorScrollImpl = EditorScrollImpl;
  CoreNavigationCommands2.EditorScroll = registerEditorCommand(new EditorScrollImpl());
  CoreNavigationCommands2.ScrollLineUp = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollLineUp",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 16,
          mac: {primary: 256 | 11}
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll._runEditorScroll(viewModel, args.source, {
        direction: 1,
        unit: 2,
        value: 1,
        revealCursor: false,
        select: false
      });
    }
  }());
  CoreNavigationCommands2.ScrollPageUp = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollPageUp",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 11,
          win: {primary: 512 | 11},
          linux: {primary: 512 | 11}
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll._runEditorScroll(viewModel, args.source, {
        direction: 1,
        unit: 3,
        value: 1,
        revealCursor: false,
        select: false
      });
    }
  }());
  CoreNavigationCommands2.ScrollLineDown = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollLineDown",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 18,
          mac: {primary: 256 | 12}
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll._runEditorScroll(viewModel, args.source, {
        direction: 2,
        unit: 2,
        value: 1,
        revealCursor: false,
        select: false
      });
    }
  }());
  CoreNavigationCommands2.ScrollPageDown = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollPageDown",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 12,
          win: {primary: 512 | 12},
          linux: {primary: 512 | 12}
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll._runEditorScroll(viewModel, args.source, {
        direction: 2,
        unit: 3,
        value: 1,
        revealCursor: false,
        select: false
      });
    }
  }());
  class WordCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, [
        CursorMoveCommands.word(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position)
      ]);
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }
  CoreNavigationCommands2.WordSelect = registerEditorCommand(new WordCommand({
    inSelectionMode: false,
    id: "_wordSelect",
    precondition: void 0
  }));
  CoreNavigationCommands2.WordSelectDrag = registerEditorCommand(new WordCommand({
    inSelectionMode: true,
    id: "_wordSelectDrag",
    precondition: void 0
  }));
  CoreNavigationCommands2.LastCursorWordSelect = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "lastCursorWordSelect",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args) {
      const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
      const states = viewModel.getCursorStates();
      const newStates = states.slice(0);
      const lastAddedState = states[lastAddedCursorIndex];
      newStates[lastAddedCursorIndex] = CursorMoveCommands.word(viewModel, lastAddedState, lastAddedState.modelState.hasSelection(), args.position);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, newStates);
    }
  }());
  class LineCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, [
        CursorMoveCommands.line(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition)
      ]);
      viewModel.revealPrimaryCursor(args.source, false);
    }
  }
  CoreNavigationCommands2.LineSelect = registerEditorCommand(new LineCommand({
    inSelectionMode: false,
    id: "_lineSelect",
    precondition: void 0
  }));
  CoreNavigationCommands2.LineSelectDrag = registerEditorCommand(new LineCommand({
    inSelectionMode: true,
    id: "_lineSelectDrag",
    precondition: void 0
  }));
  class LastCursorLineCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
      const states = viewModel.getCursorStates();
      const newStates = states.slice(0);
      newStates[lastAddedCursorIndex] = CursorMoveCommands.line(viewModel, states[lastAddedCursorIndex], this._inSelectionMode, args.position, args.viewPosition);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, newStates);
    }
  }
  CoreNavigationCommands2.LastCursorLineSelect = registerEditorCommand(new LastCursorLineCommand({
    inSelectionMode: false,
    id: "lastCursorLineSelect",
    precondition: void 0
  }));
  CoreNavigationCommands2.LastCursorLineSelectDrag = registerEditorCommand(new LastCursorLineCommand({
    inSelectionMode: true,
    id: "lastCursorLineSelectDrag",
    precondition: void 0
  }));
  CoreNavigationCommands2.ExpandLineSelection = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "expandLineSelection",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 42
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.expandLineSelection(viewModel, viewModel.getCursorStates()));
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }());
  CoreNavigationCommands2.CancelSelection = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "cancelSelection",
        precondition: EditorContextKeys.hasNonEmptySelection,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 9,
          secondary: [1024 | 9]
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, [
        CursorMoveCommands.cancelSelection(viewModel, viewModel.getPrimaryCursorState())
      ]);
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }());
  CoreNavigationCommands2.RemoveSecondaryCursors = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "removeSecondaryCursors",
        precondition: EditorContextKeys.hasMultipleSelections,
        kbOpts: {
          weight: CORE_WEIGHT + 1,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 9,
          secondary: [1024 | 9]
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, [
        viewModel.getPrimaryCursorState()
      ]);
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }());
  CoreNavigationCommands2.RevealLine = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "revealLine",
        precondition: void 0,
        description: RevealLine_.description
      });
    }
    runCoreEditorCommand(viewModel, args) {
      const revealLineArg = args;
      let lineNumber = (revealLineArg.lineNumber || 0) + 1;
      if (lineNumber < 1) {
        lineNumber = 1;
      }
      const lineCount = viewModel.model.getLineCount();
      if (lineNumber > lineCount) {
        lineNumber = lineCount;
      }
      const range3 = new Range(lineNumber, 1, lineNumber, viewModel.model.getLineMaxColumn(lineNumber));
      let revealAt = 0;
      if (revealLineArg.at) {
        switch (revealLineArg.at) {
          case RevealLine_.RawAtArgument.Top:
            revealAt = 3;
            break;
          case RevealLine_.RawAtArgument.Center:
            revealAt = 1;
            break;
          case RevealLine_.RawAtArgument.Bottom:
            revealAt = 4;
            break;
        }
      }
      const viewRange = viewModel.coordinatesConverter.convertModelRangeToViewRange(range3);
      viewModel.revealRange(args.source, false, viewRange, revealAt, 0);
    }
  }());
  CoreNavigationCommands2.SelectAll = new class extends EditorOrNativeTextInputCommand {
    constructor() {
      super(SelectAllCommand);
    }
    runDOMCommand() {
      document.execCommand("selectAll");
    }
    runEditorCommand(accessor, editor2, args) {
      const viewModel = editor2._getViewModel();
      if (!viewModel) {
        return;
      }
      this.runCoreEditorCommand(viewModel, args);
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates("keyboard", 3, [
        CursorMoveCommands.selectAll(viewModel, viewModel.getPrimaryCursorState())
      ]);
    }
  }();
  CoreNavigationCommands2.SetSelection = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "setSelection",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, [
        CursorState.fromModelSelection(args.selection)
      ]);
    }
  }());
})(CoreNavigationCommands || (CoreNavigationCommands = {}));
var columnSelectionCondition = ContextKeyExpr.and(EditorContextKeys.textInputFocus, EditorContextKeys.columnSelection);
function registerColumnSelection(id3, keybinding) {
  KeybindingsRegistry.registerKeybindingRule({
    id: id3,
    primary: keybinding,
    when: columnSelectionCondition,
    weight: CORE_WEIGHT + 1
  });
}
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectLeft.id, 1024 | 15);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectRight.id, 1024 | 17);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectUp.id, 1024 | 16);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectPageUp.id, 1024 | 11);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectDown.id, 1024 | 18);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectPageDown.id, 1024 | 12);
function registerCommand$1(command) {
  command.register();
  return command;
}
var CoreEditingCommands;
(function(CoreEditingCommands2) {
  class CoreEditingCommand extends EditorCommand {
    runEditorCommand(accessor, editor2, args) {
      const viewModel = editor2._getViewModel();
      if (!viewModel) {
        return;
      }
      this.runCoreEditingCommand(editor2, viewModel, args || {});
    }
  }
  CoreEditingCommands2.CoreEditingCommand = CoreEditingCommand;
  CoreEditingCommands2.LineBreakInsert = registerEditorCommand(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "lineBreakInsert",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: {primary: 256 | 45}
        }
      });
    }
    runCoreEditingCommand(editor2, viewModel, args) {
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, TypeOperations.lineBreakInsert(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s2) => s2.modelState.selection)));
    }
  }());
  CoreEditingCommands2.Outdent = registerEditorCommand(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "outdent",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus),
          primary: 1024 | 2
        }
      });
    }
    runCoreEditingCommand(editor2, viewModel, args) {
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, TypeOperations.outdent(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s2) => s2.modelState.selection)));
      editor2.pushUndoStop();
    }
  }());
  CoreEditingCommands2.Tab = registerEditorCommand(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "tab",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus),
          primary: 2
        }
      });
    }
    runCoreEditingCommand(editor2, viewModel, args) {
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, TypeOperations.tab(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s2) => s2.modelState.selection)));
      editor2.pushUndoStop();
    }
  }());
  CoreEditingCommands2.DeleteLeft = registerEditorCommand(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "deleteLeft",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 1,
          secondary: [1024 | 1],
          mac: {primary: 1, secondary: [1024 | 1, 256 | 38, 256 | 1]}
        }
      });
    }
    runCoreEditingCommand(editor2, viewModel, args) {
      const [shouldPushStackElementBefore, commands] = DeleteOperations.deleteLeft(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s2) => s2.modelState.selection));
      if (shouldPushStackElementBefore) {
        editor2.pushUndoStop();
      }
      editor2.executeCommands(this.id, commands);
      viewModel.setPrevEditOperationType(2);
    }
  }());
  CoreEditingCommands2.DeleteRight = registerEditorCommand(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "deleteRight",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 20,
          mac: {primary: 20, secondary: [256 | 34, 256 | 20]}
        }
      });
    }
    runCoreEditingCommand(editor2, viewModel, args) {
      const [shouldPushStackElementBefore, commands] = DeleteOperations.deleteRight(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s2) => s2.modelState.selection));
      if (shouldPushStackElementBefore) {
        editor2.pushUndoStop();
      }
      editor2.executeCommands(this.id, commands);
      viewModel.setPrevEditOperationType(3);
    }
  }());
  CoreEditingCommands2.Undo = new class extends EditorOrNativeTextInputCommand {
    constructor() {
      super(UndoCommand);
    }
    runDOMCommand() {
      document.execCommand("undo");
    }
    runEditorCommand(accessor, editor2, args) {
      if (!editor2.hasModel() || editor2.getOption(72) === true) {
        return;
      }
      editor2.getModel().undo();
    }
  }();
  CoreEditingCommands2.Redo = new class extends EditorOrNativeTextInputCommand {
    constructor() {
      super(RedoCommand);
    }
    runDOMCommand() {
      document.execCommand("redo");
    }
    runEditorCommand(accessor, editor2, args) {
      if (!editor2.hasModel() || editor2.getOption(72) === true) {
        return;
      }
      editor2.getModel().redo();
    }
  }();
})(CoreEditingCommands || (CoreEditingCommands = {}));
var EditorHandlerCommand = class extends Command {
  constructor(id3, handlerId, description) {
    super({
      id: id3,
      precondition: void 0,
      description
    });
    this._handlerId = handlerId;
  }
  runCommand(accessor, args) {
    const editor2 = accessor.get(ICodeEditorService).getFocusedCodeEditor();
    if (!editor2) {
      return;
    }
    editor2.trigger("keyboard", this._handlerId, args);
  }
};
function registerOverwritableCommand(handlerId, description) {
  registerCommand$1(new EditorHandlerCommand("default:" + handlerId, handlerId));
  registerCommand$1(new EditorHandlerCommand(handlerId, handlerId, description));
}
registerOverwritableCommand("type", {
  description: `Type`,
  args: [{
    name: "args",
    schema: {
      type: "object",
      required: ["text"],
      properties: {
        text: {
          type: "string"
        }
      }
    }
  }]
});
registerOverwritableCommand("replacePreviousChar");
registerOverwritableCommand("compositionStart");
registerOverwritableCommand("compositionEnd");
registerOverwritableCommand("paste");
registerOverwritableCommand("cut");
var ViewController = class {
  constructor(configuration, viewModel, userInputEvents, commandDelegate) {
    this.configuration = configuration;
    this.viewModel = viewModel;
    this.userInputEvents = userInputEvents;
    this.commandDelegate = commandDelegate;
  }
  paste(text, pasteOnNewLine, multicursorText, mode) {
    this.commandDelegate.paste(text, pasteOnNewLine, multicursorText, mode);
  }
  type(text) {
    this.commandDelegate.type(text);
  }
  replacePreviousChar(text, replaceCharCnt) {
    this.commandDelegate.replacePreviousChar(text, replaceCharCnt);
  }
  compositionStart() {
    this.commandDelegate.startComposition();
  }
  compositionEnd() {
    this.commandDelegate.endComposition();
  }
  cut() {
    this.commandDelegate.cut();
  }
  setSelection(modelSelection) {
    CoreNavigationCommands.SetSelection.runCoreEditorCommand(this.viewModel, {
      source: "keyboard",
      selection: modelSelection
    });
  }
  _validateViewColumn(viewPosition) {
    const minColumn = this.viewModel.getLineMinColumn(viewPosition.lineNumber);
    if (viewPosition.column < minColumn) {
      return new Position(viewPosition.lineNumber, minColumn);
    }
    return viewPosition;
  }
  _hasMulticursorModifier(data2) {
    switch (this.configuration.options.get(61)) {
      case "altKey":
        return data2.altKey;
      case "ctrlKey":
        return data2.ctrlKey;
      case "metaKey":
        return data2.metaKey;
      default:
        return false;
    }
  }
  _hasNonMulticursorModifier(data2) {
    switch (this.configuration.options.get(61)) {
      case "altKey":
        return data2.ctrlKey || data2.metaKey;
      case "ctrlKey":
        return data2.altKey || data2.metaKey;
      case "metaKey":
        return data2.ctrlKey || data2.altKey;
      default:
        return false;
    }
  }
  dispatchMouse(data2) {
    const options = this.configuration.options;
    const selectionClipboardIsOn = isLinux && options.get(88);
    const columnSelection = options.get(13);
    if (data2.middleButton && !selectionClipboardIsOn) {
      this._columnSelect(data2.position, data2.mouseColumn, data2.inSelectionMode);
    } else if (data2.startedOnLineNumbers) {
      if (this._hasMulticursorModifier(data2)) {
        if (data2.inSelectionMode) {
          this._lastCursorLineSelect(data2.position);
        } else {
          this._createCursor(data2.position, true);
        }
      } else {
        if (data2.inSelectionMode) {
          this._lineSelectDrag(data2.position);
        } else {
          this._lineSelect(data2.position);
        }
      }
    } else if (data2.mouseDownCount >= 4) {
      this._selectAll();
    } else if (data2.mouseDownCount === 3) {
      if (this._hasMulticursorModifier(data2)) {
        if (data2.inSelectionMode) {
          this._lastCursorLineSelectDrag(data2.position);
        } else {
          this._lastCursorLineSelect(data2.position);
        }
      } else {
        if (data2.inSelectionMode) {
          this._lineSelectDrag(data2.position);
        } else {
          this._lineSelect(data2.position);
        }
      }
    } else if (data2.mouseDownCount === 2) {
      if (this._hasMulticursorModifier(data2)) {
        this._lastCursorWordSelect(data2.position);
      } else {
        if (data2.inSelectionMode) {
          this._wordSelectDrag(data2.position);
        } else {
          this._wordSelect(data2.position);
        }
      }
    } else {
      if (this._hasMulticursorModifier(data2)) {
        if (!this._hasNonMulticursorModifier(data2)) {
          if (data2.shiftKey) {
            this._columnSelect(data2.position, data2.mouseColumn, true);
          } else {
            if (data2.inSelectionMode) {
              this._lastCursorMoveToSelect(data2.position);
            } else {
              this._createCursor(data2.position, false);
            }
          }
        }
      } else {
        if (data2.inSelectionMode) {
          if (data2.altKey) {
            this._columnSelect(data2.position, data2.mouseColumn, true);
          } else {
            if (columnSelection) {
              this._columnSelect(data2.position, data2.mouseColumn, true);
            } else {
              this._moveToSelect(data2.position);
            }
          }
        } else {
          this.moveTo(data2.position);
        }
      }
    }
  }
  _usualArgs(viewPosition) {
    viewPosition = this._validateViewColumn(viewPosition);
    return {
      source: "mouse",
      position: this._convertViewToModelPosition(viewPosition),
      viewPosition
    };
  }
  moveTo(viewPosition) {
    CoreNavigationCommands.MoveTo.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
  }
  _moveToSelect(viewPosition) {
    CoreNavigationCommands.MoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
  }
  _columnSelect(viewPosition, mouseColumn, doColumnSelect) {
    viewPosition = this._validateViewColumn(viewPosition);
    CoreNavigationCommands.ColumnSelect.runCoreEditorCommand(this.viewModel, {
      source: "mouse",
      position: this._convertViewToModelPosition(viewPosition),
      viewPosition,
      mouseColumn,
      doColumnSelect
    });
  }
  _createCursor(viewPosition, wholeLine) {
    viewPosition = this._validateViewColumn(viewPosition);
    CoreNavigationCommands.CreateCursor.runCoreEditorCommand(this.viewModel, {
      source: "mouse",
      position: this._convertViewToModelPosition(viewPosition),
      viewPosition,
      wholeLine
    });
  }
  _lastCursorMoveToSelect(viewPosition) {
    CoreNavigationCommands.LastCursorMoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
  }
  _wordSelect(viewPosition) {
    CoreNavigationCommands.WordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
  }
  _wordSelectDrag(viewPosition) {
    CoreNavigationCommands.WordSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
  }
  _lastCursorWordSelect(viewPosition) {
    CoreNavigationCommands.LastCursorWordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
  }
  _lineSelect(viewPosition) {
    CoreNavigationCommands.LineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
  }
  _lineSelectDrag(viewPosition) {
    CoreNavigationCommands.LineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
  }
  _lastCursorLineSelect(viewPosition) {
    CoreNavigationCommands.LastCursorLineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
  }
  _lastCursorLineSelectDrag(viewPosition) {
    CoreNavigationCommands.LastCursorLineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
  }
  _selectAll() {
    CoreNavigationCommands.SelectAll.runCoreEditorCommand(this.viewModel, {source: "mouse"});
  }
  _convertViewToModelPosition(viewPosition) {
    return this.viewModel.coordinatesConverter.convertViewPositionToModelPosition(viewPosition);
  }
  emitKeyDown(e2) {
    this.userInputEvents.emitKeyDown(e2);
  }
  emitKeyUp(e2) {
    this.userInputEvents.emitKeyUp(e2);
  }
  emitContextMenu(e2) {
    this.userInputEvents.emitContextMenu(e2);
  }
  emitMouseMove(e2) {
    this.userInputEvents.emitMouseMove(e2);
  }
  emitMouseLeave(e2) {
    this.userInputEvents.emitMouseLeave(e2);
  }
  emitMouseUp(e2) {
    this.userInputEvents.emitMouseUp(e2);
  }
  emitMouseDown(e2) {
    this.userInputEvents.emitMouseDown(e2);
  }
  emitMouseDrag(e2) {
    this.userInputEvents.emitMouseDrag(e2);
  }
  emitMouseDrop(e2) {
    this.userInputEvents.emitMouseDrop(e2);
  }
  emitMouseWheel(e2) {
    this.userInputEvents.emitMouseWheel(e2);
  }
};
var ViewUserInputEvents = class {
  constructor(coordinatesConverter) {
    this.onKeyDown = null;
    this.onKeyUp = null;
    this.onContextMenu = null;
    this.onMouseMove = null;
    this.onMouseLeave = null;
    this.onMouseDown = null;
    this.onMouseUp = null;
    this.onMouseDrag = null;
    this.onMouseDrop = null;
    this.onMouseWheel = null;
    this._coordinatesConverter = coordinatesConverter;
  }
  emitKeyDown(e2) {
    if (this.onKeyDown) {
      this.onKeyDown(e2);
    }
  }
  emitKeyUp(e2) {
    if (this.onKeyUp) {
      this.onKeyUp(e2);
    }
  }
  emitContextMenu(e2) {
    if (this.onContextMenu) {
      this.onContextMenu(this._convertViewToModelMouseEvent(e2));
    }
  }
  emitMouseMove(e2) {
    if (this.onMouseMove) {
      this.onMouseMove(this._convertViewToModelMouseEvent(e2));
    }
  }
  emitMouseLeave(e2) {
    if (this.onMouseLeave) {
      this.onMouseLeave(this._convertViewToModelMouseEvent(e2));
    }
  }
  emitMouseDown(e2) {
    if (this.onMouseDown) {
      this.onMouseDown(this._convertViewToModelMouseEvent(e2));
    }
  }
  emitMouseUp(e2) {
    if (this.onMouseUp) {
      this.onMouseUp(this._convertViewToModelMouseEvent(e2));
    }
  }
  emitMouseDrag(e2) {
    if (this.onMouseDrag) {
      this.onMouseDrag(this._convertViewToModelMouseEvent(e2));
    }
  }
  emitMouseDrop(e2) {
    if (this.onMouseDrop) {
      this.onMouseDrop(this._convertViewToModelMouseEvent(e2));
    }
  }
  emitMouseWheel(e2) {
    if (this.onMouseWheel) {
      this.onMouseWheel(e2);
    }
  }
  _convertViewToModelMouseEvent(e2) {
    if (e2.target) {
      return {
        event: e2.event,
        target: this._convertViewToModelMouseTarget(e2.target)
      };
    }
    return e2;
  }
  _convertViewToModelMouseTarget(target) {
    return ViewUserInputEvents.convertViewToModelMouseTarget(target, this._coordinatesConverter);
  }
  static convertViewToModelMouseTarget(target, coordinatesConverter) {
    return new ExternalMouseTarget(target.element, target.type, target.mouseColumn, target.position ? coordinatesConverter.convertViewPositionToModelPosition(target.position) : null, target.range ? coordinatesConverter.convertViewRangeToModelRange(target.range) : null, target.detail);
  }
};
var ExternalMouseTarget = class {
  constructor(element, type, mouseColumn, position2, range3, detail) {
    this.element = element;
    this.type = type;
    this.mouseColumn = mouseColumn;
    this.position = position2;
    this.range = range3;
    this.detail = detail;
  }
  toString() {
    return MouseTarget.toString(this);
  }
};
var RenderedLinesCollection = class {
  constructor(createLine) {
    this._createLine = createLine;
    this._set(1, []);
  }
  flush() {
    this._set(1, []);
  }
  _set(rendLineNumberStart, lines) {
    this._lines = lines;
    this._rendLineNumberStart = rendLineNumberStart;
  }
  _get() {
    return {
      rendLineNumberStart: this._rendLineNumberStart,
      lines: this._lines
    };
  }
  getStartLineNumber() {
    return this._rendLineNumberStart;
  }
  getEndLineNumber() {
    return this._rendLineNumberStart + this._lines.length - 1;
  }
  getCount() {
    return this._lines.length;
  }
  getLine(lineNumber) {
    const lineIndex = lineNumber - this._rendLineNumberStart;
    if (lineIndex < 0 || lineIndex >= this._lines.length) {
      throw new Error("Illegal value for lineNumber");
    }
    return this._lines[lineIndex];
  }
  onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
    if (this.getCount() === 0) {
      return null;
    }
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    if (deleteToLineNumber < startLineNumber) {
      const deleteCnt = deleteToLineNumber - deleteFromLineNumber + 1;
      this._rendLineNumberStart -= deleteCnt;
      return null;
    }
    if (deleteFromLineNumber > endLineNumber) {
      return null;
    }
    let deleteStartIndex = 0;
    let deleteCount = 0;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const lineIndex = lineNumber - this._rendLineNumberStart;
      if (deleteFromLineNumber <= lineNumber && lineNumber <= deleteToLineNumber) {
        if (deleteCount === 0) {
          deleteStartIndex = lineIndex;
          deleteCount = 1;
        } else {
          deleteCount++;
        }
      }
    }
    if (deleteFromLineNumber < startLineNumber) {
      let deleteAboveCount = 0;
      if (deleteToLineNumber < startLineNumber) {
        deleteAboveCount = deleteToLineNumber - deleteFromLineNumber + 1;
      } else {
        deleteAboveCount = startLineNumber - deleteFromLineNumber;
      }
      this._rendLineNumberStart -= deleteAboveCount;
    }
    const deleted = this._lines.splice(deleteStartIndex, deleteCount);
    return deleted;
  }
  onLinesChanged(changeFromLineNumber, changeToLineNumber) {
    if (this.getCount() === 0) {
      return false;
    }
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    let someoneNotified = false;
    for (let changedLineNumber = changeFromLineNumber; changedLineNumber <= changeToLineNumber; changedLineNumber++) {
      if (changedLineNumber >= startLineNumber && changedLineNumber <= endLineNumber) {
        this._lines[changedLineNumber - this._rendLineNumberStart].onContentChanged();
        someoneNotified = true;
      }
    }
    return someoneNotified;
  }
  onLinesInserted(insertFromLineNumber, insertToLineNumber) {
    if (this.getCount() === 0) {
      return null;
    }
    const insertCnt = insertToLineNumber - insertFromLineNumber + 1;
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    if (insertFromLineNumber <= startLineNumber) {
      this._rendLineNumberStart += insertCnt;
      return null;
    }
    if (insertFromLineNumber > endLineNumber) {
      return null;
    }
    if (insertCnt + insertFromLineNumber > endLineNumber) {
      const deleted = this._lines.splice(insertFromLineNumber - this._rendLineNumberStart, endLineNumber - insertFromLineNumber + 1);
      return deleted;
    }
    const newLines = [];
    for (let i3 = 0; i3 < insertCnt; i3++) {
      newLines[i3] = this._createLine();
    }
    const insertIndex = insertFromLineNumber - this._rendLineNumberStart;
    const beforeLines = this._lines.slice(0, insertIndex);
    const afterLines = this._lines.slice(insertIndex, this._lines.length - insertCnt);
    const deletedLines = this._lines.slice(this._lines.length - insertCnt, this._lines.length);
    this._lines = beforeLines.concat(newLines).concat(afterLines);
    return deletedLines;
  }
  onTokensChanged(ranges) {
    if (this.getCount() === 0) {
      return false;
    }
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    let notifiedSomeone = false;
    for (let i3 = 0, len2 = ranges.length; i3 < len2; i3++) {
      const rng = ranges[i3];
      if (rng.toLineNumber < startLineNumber || rng.fromLineNumber > endLineNumber) {
        continue;
      }
      const from = Math.max(startLineNumber, rng.fromLineNumber);
      const to = Math.min(endLineNumber, rng.toLineNumber);
      for (let lineNumber = from; lineNumber <= to; lineNumber++) {
        const lineIndex = lineNumber - this._rendLineNumberStart;
        this._lines[lineIndex].onTokensChanged();
        notifiedSomeone = true;
      }
    }
    return notifiedSomeone;
  }
};
var VisibleLinesCollection = class {
  constructor(host) {
    this._host = host;
    this.domNode = this._createDomNode();
    this._linesCollection = new RenderedLinesCollection(() => this._host.createVisibleLine());
  }
  _createDomNode() {
    const domNode = createFastDomNode(document.createElement("div"));
    domNode.setClassName("view-layer");
    domNode.setPosition("absolute");
    domNode.domNode.setAttribute("role", "presentation");
    domNode.domNode.setAttribute("aria-hidden", "true");
    return domNode;
  }
  onConfigurationChanged(e2) {
    if (e2.hasChanged(117)) {
      return true;
    }
    return false;
  }
  onFlushed(e2) {
    this._linesCollection.flush();
    return true;
  }
  onLinesChanged(e2) {
    return this._linesCollection.onLinesChanged(e2.fromLineNumber, e2.toLineNumber);
  }
  onLinesDeleted(e2) {
    const deleted = this._linesCollection.onLinesDeleted(e2.fromLineNumber, e2.toLineNumber);
    if (deleted) {
      for (let i3 = 0, len2 = deleted.length; i3 < len2; i3++) {
        const lineDomNode = deleted[i3].getDomNode();
        if (lineDomNode) {
          this.domNode.domNode.removeChild(lineDomNode);
        }
      }
    }
    return true;
  }
  onLinesInserted(e2) {
    const deleted = this._linesCollection.onLinesInserted(e2.fromLineNumber, e2.toLineNumber);
    if (deleted) {
      for (let i3 = 0, len2 = deleted.length; i3 < len2; i3++) {
        const lineDomNode = deleted[i3].getDomNode();
        if (lineDomNode) {
          this.domNode.domNode.removeChild(lineDomNode);
        }
      }
    }
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollTopChanged;
  }
  onTokensChanged(e2) {
    return this._linesCollection.onTokensChanged(e2.ranges);
  }
  onZonesChanged(e2) {
    return true;
  }
  getStartLineNumber() {
    return this._linesCollection.getStartLineNumber();
  }
  getEndLineNumber() {
    return this._linesCollection.getEndLineNumber();
  }
  getVisibleLine(lineNumber) {
    return this._linesCollection.getLine(lineNumber);
  }
  renderLines(viewportData) {
    const inp = this._linesCollection._get();
    const renderer = new ViewLayerRenderer(this.domNode.domNode, this._host, viewportData);
    const ctx = {
      rendLineNumberStart: inp.rendLineNumberStart,
      lines: inp.lines,
      linesLength: inp.lines.length
    };
    const resCtx = renderer.render(ctx, viewportData.startLineNumber, viewportData.endLineNumber, viewportData.relativeVerticalOffset);
    this._linesCollection._set(resCtx.rendLineNumberStart, resCtx.lines);
  }
};
var ViewLayerRenderer = class {
  constructor(domNode, host, viewportData) {
    this.domNode = domNode;
    this.host = host;
    this.viewportData = viewportData;
  }
  render(inContext, startLineNumber, stopLineNumber, deltaTop) {
    const ctx = {
      rendLineNumberStart: inContext.rendLineNumberStart,
      lines: inContext.lines.slice(0),
      linesLength: inContext.linesLength
    };
    if (ctx.rendLineNumberStart + ctx.linesLength - 1 < startLineNumber || stopLineNumber < ctx.rendLineNumberStart) {
      ctx.rendLineNumberStart = startLineNumber;
      ctx.linesLength = stopLineNumber - startLineNumber + 1;
      ctx.lines = [];
      for (let x2 = startLineNumber; x2 <= stopLineNumber; x2++) {
        ctx.lines[x2 - startLineNumber] = this.host.createVisibleLine();
      }
      this._finishRendering(ctx, true, deltaTop);
      return ctx;
    }
    this._renderUntouchedLines(ctx, Math.max(startLineNumber - ctx.rendLineNumberStart, 0), Math.min(stopLineNumber - ctx.rendLineNumberStart, ctx.linesLength - 1), deltaTop, startLineNumber);
    if (ctx.rendLineNumberStart > startLineNumber) {
      const fromLineNumber = startLineNumber;
      const toLineNumber = Math.min(stopLineNumber, ctx.rendLineNumberStart - 1);
      if (fromLineNumber <= toLineNumber) {
        this._insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
        ctx.linesLength += toLineNumber - fromLineNumber + 1;
      }
    } else if (ctx.rendLineNumberStart < startLineNumber) {
      const removeCnt = Math.min(ctx.linesLength, startLineNumber - ctx.rendLineNumberStart);
      if (removeCnt > 0) {
        this._removeLinesBefore(ctx, removeCnt);
        ctx.linesLength -= removeCnt;
      }
    }
    ctx.rendLineNumberStart = startLineNumber;
    if (ctx.rendLineNumberStart + ctx.linesLength - 1 < stopLineNumber) {
      const fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength;
      const toLineNumber = stopLineNumber;
      if (fromLineNumber <= toLineNumber) {
        this._insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
        ctx.linesLength += toLineNumber - fromLineNumber + 1;
      }
    } else if (ctx.rendLineNumberStart + ctx.linesLength - 1 > stopLineNumber) {
      const fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1);
      const toLineNumber = ctx.linesLength - 1;
      const removeCnt = toLineNumber - fromLineNumber + 1;
      if (removeCnt > 0) {
        this._removeLinesAfter(ctx, removeCnt);
        ctx.linesLength -= removeCnt;
      }
    }
    this._finishRendering(ctx, false, deltaTop);
    return ctx;
  }
  _renderUntouchedLines(ctx, startIndex, endIndex, deltaTop, deltaLN) {
    const rendLineNumberStart = ctx.rendLineNumberStart;
    const lines = ctx.lines;
    for (let i3 = startIndex; i3 <= endIndex; i3++) {
      const lineNumber = rendLineNumberStart + i3;
      lines[i3].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN]);
    }
  }
  _insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
    const newLines = [];
    let newLinesLen = 0;
    for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
      newLines[newLinesLen++] = this.host.createVisibleLine();
    }
    ctx.lines = newLines.concat(ctx.lines);
  }
  _removeLinesBefore(ctx, removeCount) {
    for (let i3 = 0; i3 < removeCount; i3++) {
      const lineDomNode = ctx.lines[i3].getDomNode();
      if (lineDomNode) {
        this.domNode.removeChild(lineDomNode);
      }
    }
    ctx.lines.splice(0, removeCount);
  }
  _insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
    const newLines = [];
    let newLinesLen = 0;
    for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
      newLines[newLinesLen++] = this.host.createVisibleLine();
    }
    ctx.lines = ctx.lines.concat(newLines);
  }
  _removeLinesAfter(ctx, removeCount) {
    const removeIndex = ctx.linesLength - removeCount;
    for (let i3 = 0; i3 < removeCount; i3++) {
      const lineDomNode = ctx.lines[removeIndex + i3].getDomNode();
      if (lineDomNode) {
        this.domNode.removeChild(lineDomNode);
      }
    }
    ctx.lines.splice(removeIndex, removeCount);
  }
  _finishRenderingNewLines(ctx, domNodeIsEmpty, newLinesHTML, wasNew) {
    const lastChild = this.domNode.lastChild;
    if (domNodeIsEmpty || !lastChild) {
      this.domNode.innerHTML = newLinesHTML;
    } else {
      lastChild.insertAdjacentHTML("afterend", newLinesHTML);
    }
    let currChild = this.domNode.lastChild;
    for (let i3 = ctx.linesLength - 1; i3 >= 0; i3--) {
      const line = ctx.lines[i3];
      if (wasNew[i3]) {
        line.setDomNode(currChild);
        currChild = currChild.previousSibling;
      }
    }
  }
  _finishRenderingInvalidLines(ctx, invalidLinesHTML, wasInvalid) {
    const hugeDomNode = document.createElement("div");
    hugeDomNode.innerHTML = invalidLinesHTML;
    for (let i3 = 0; i3 < ctx.linesLength; i3++) {
      const line = ctx.lines[i3];
      if (wasInvalid[i3]) {
        const source2 = hugeDomNode.firstChild;
        const lineDomNode = line.getDomNode();
        lineDomNode.parentNode.replaceChild(source2, lineDomNode);
        line.setDomNode(source2);
      }
    }
  }
  _finishRendering(ctx, domNodeIsEmpty, deltaTop) {
    const sb2 = ViewLayerRenderer._sb;
    const linesLength = ctx.linesLength;
    const lines = ctx.lines;
    const rendLineNumberStart = ctx.rendLineNumberStart;
    const wasNew = [];
    {
      sb2.reset();
      let hadNewLine = false;
      for (let i3 = 0; i3 < linesLength; i3++) {
        const line = lines[i3];
        wasNew[i3] = false;
        const lineDomNode = line.getDomNode();
        if (lineDomNode) {
          continue;
        }
        const renderResult = line.renderLine(i3 + rendLineNumberStart, deltaTop[i3], this.viewportData, sb2);
        if (!renderResult) {
          continue;
        }
        wasNew[i3] = true;
        hadNewLine = true;
      }
      if (hadNewLine) {
        this._finishRenderingNewLines(ctx, domNodeIsEmpty, sb2.build(), wasNew);
      }
    }
    {
      sb2.reset();
      let hadInvalidLine = false;
      const wasInvalid = [];
      for (let i3 = 0; i3 < linesLength; i3++) {
        const line = lines[i3];
        wasInvalid[i3] = false;
        if (wasNew[i3]) {
          continue;
        }
        const renderResult = line.renderLine(i3 + rendLineNumberStart, deltaTop[i3], this.viewportData, sb2);
        if (!renderResult) {
          continue;
        }
        wasInvalid[i3] = true;
        hadInvalidLine = true;
      }
      if (hadInvalidLine) {
        this._finishRenderingInvalidLines(ctx, sb2.build(), wasInvalid);
      }
    }
  }
};
ViewLayerRenderer._sb = createStringBuilder(1e5);
var ViewOverlays = class extends ViewPart {
  constructor(context2) {
    super(context2);
    this._visibleLines = new VisibleLinesCollection(this);
    this.domNode = this._visibleLines.domNode;
    this._dynamicOverlays = [];
    this._isFocused = false;
    this.domNode.setClassName("view-overlays");
  }
  shouldRender() {
    if (super.shouldRender()) {
      return true;
    }
    for (let i3 = 0, len2 = this._dynamicOverlays.length; i3 < len2; i3++) {
      const dynamicOverlay = this._dynamicOverlays[i3];
      if (dynamicOverlay.shouldRender()) {
        return true;
      }
    }
    return false;
  }
  dispose() {
    super.dispose();
    for (let i3 = 0, len2 = this._dynamicOverlays.length; i3 < len2; i3++) {
      const dynamicOverlay = this._dynamicOverlays[i3];
      dynamicOverlay.dispose();
    }
    this._dynamicOverlays = [];
  }
  getDomNode() {
    return this.domNode;
  }
  createVisibleLine() {
    return new ViewOverlayLine(this._context.configuration, this._dynamicOverlays);
  }
  addDynamicOverlay(overlay) {
    this._dynamicOverlays.push(overlay);
  }
  onConfigurationChanged(e2) {
    this._visibleLines.onConfigurationChanged(e2);
    const startLineNumber = this._visibleLines.getStartLineNumber();
    const endLineNumber = this._visibleLines.getEndLineNumber();
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const line = this._visibleLines.getVisibleLine(lineNumber);
      line.onConfigurationChanged(e2);
    }
    return true;
  }
  onFlushed(e2) {
    return this._visibleLines.onFlushed(e2);
  }
  onFocusChanged(e2) {
    this._isFocused = e2.isFocused;
    return true;
  }
  onLinesChanged(e2) {
    return this._visibleLines.onLinesChanged(e2);
  }
  onLinesDeleted(e2) {
    return this._visibleLines.onLinesDeleted(e2);
  }
  onLinesInserted(e2) {
    return this._visibleLines.onLinesInserted(e2);
  }
  onScrollChanged(e2) {
    return this._visibleLines.onScrollChanged(e2) || true;
  }
  onTokensChanged(e2) {
    return this._visibleLines.onTokensChanged(e2);
  }
  onZonesChanged(e2) {
    return this._visibleLines.onZonesChanged(e2);
  }
  prepareRender(ctx) {
    const toRender = this._dynamicOverlays.filter((overlay) => overlay.shouldRender());
    for (let i3 = 0, len2 = toRender.length; i3 < len2; i3++) {
      const dynamicOverlay = toRender[i3];
      dynamicOverlay.prepareRender(ctx);
      dynamicOverlay.onDidRender();
    }
  }
  render(ctx) {
    this._viewOverlaysRender(ctx);
    this.domNode.toggleClassName("focused", this._isFocused);
  }
  _viewOverlaysRender(ctx) {
    this._visibleLines.renderLines(ctx.viewportData);
  }
};
var ViewOverlayLine = class {
  constructor(configuration, dynamicOverlays) {
    this._configuration = configuration;
    this._lineHeight = this._configuration.options.get(51);
    this._dynamicOverlays = dynamicOverlays;
    this._domNode = null;
    this._renderedContent = null;
  }
  getDomNode() {
    if (!this._domNode) {
      return null;
    }
    return this._domNode.domNode;
  }
  setDomNode(domNode) {
    this._domNode = createFastDomNode(domNode);
  }
  onContentChanged() {
  }
  onTokensChanged() {
  }
  onConfigurationChanged(e2) {
    this._lineHeight = this._configuration.options.get(51);
  }
  renderLine(lineNumber, deltaTop, viewportData, sb2) {
    let result = "";
    for (let i3 = 0, len2 = this._dynamicOverlays.length; i3 < len2; i3++) {
      const dynamicOverlay = this._dynamicOverlays[i3];
      result += dynamicOverlay.render(viewportData.startLineNumber, lineNumber);
    }
    if (this._renderedContent === result) {
      return false;
    }
    this._renderedContent = result;
    sb2.appendASCIIString('<div style="position:absolute;top:');
    sb2.appendASCIIString(String(deltaTop));
    sb2.appendASCIIString("px;width:100%;height:");
    sb2.appendASCIIString(String(this._lineHeight));
    sb2.appendASCIIString('px;">');
    sb2.appendASCIIString(result);
    sb2.appendASCIIString("</div>");
    return true;
  }
  layoutLine(lineNumber, deltaTop) {
    if (this._domNode) {
      this._domNode.setTop(deltaTop);
      this._domNode.setHeight(this._lineHeight);
    }
  }
};
var ContentViewOverlays = class extends ViewOverlays {
  constructor(context2) {
    super(context2);
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._contentWidth = layoutInfo.contentWidth;
    this.domNode.setHeight(0);
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._contentWidth = layoutInfo.contentWidth;
    return super.onConfigurationChanged(e2) || true;
  }
  onScrollChanged(e2) {
    return super.onScrollChanged(e2) || e2.scrollWidthChanged;
  }
  _viewOverlaysRender(ctx) {
    super._viewOverlaysRender(ctx);
    this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth));
  }
};
var MarginViewOverlays = class extends ViewOverlays {
  constructor(context2) {
    super(context2);
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._contentLeft = layoutInfo.contentLeft;
    this.domNode.setClassName("margin-view-overlays");
    this.domNode.setWidth(1);
    Configuration$1.applyFontInfo(this.domNode, options.get(36));
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    Configuration$1.applyFontInfo(this.domNode, options.get(36));
    const layoutInfo = options.get(117);
    this._contentLeft = layoutInfo.contentLeft;
    return super.onConfigurationChanged(e2) || true;
  }
  onScrollChanged(e2) {
    return super.onScrollChanged(e2) || e2.scrollHeightChanged;
  }
  _viewOverlaysRender(ctx) {
    super._viewOverlaysRender(ctx);
    const height = Math.min(ctx.scrollHeight, 1e6);
    this.domNode.setHeight(height);
    this.domNode.setWidth(this._contentLeft);
  }
};
var Coordinate = class {
  constructor(top2, left2) {
    this.top = top2;
    this.left = left2;
  }
};
var ViewContentWidgets = class extends ViewPart {
  constructor(context2, viewDomNode) {
    super(context2);
    this._viewDomNode = viewDomNode;
    this._widgets = {};
    this.domNode = createFastDomNode(document.createElement("div"));
    PartFingerprints.write(this.domNode, 1);
    this.domNode.setClassName("contentWidgets");
    this.domNode.setPosition("absolute");
    this.domNode.setTop(0);
    this.overflowingContentWidgetsDomNode = createFastDomNode(document.createElement("div"));
    PartFingerprints.write(this.overflowingContentWidgetsDomNode, 2);
    this.overflowingContentWidgetsDomNode.setClassName("overflowingContentWidgets");
  }
  dispose() {
    super.dispose();
    this._widgets = {};
  }
  onConfigurationChanged(e2) {
    const keys2 = Object.keys(this._widgets);
    for (const widgetId of keys2) {
      this._widgets[widgetId].onConfigurationChanged(e2);
    }
    return true;
  }
  onDecorationsChanged(e2) {
    return true;
  }
  onFlushed(e2) {
    return true;
  }
  onLineMappingChanged(e2) {
    const keys2 = Object.keys(this._widgets);
    for (const widgetId of keys2) {
      this._widgets[widgetId].onLineMappingChanged(e2);
    }
    return true;
  }
  onLinesChanged(e2) {
    return true;
  }
  onLinesDeleted(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return true;
  }
  onZonesChanged(e2) {
    return true;
  }
  addWidget(_widget) {
    const myWidget = new Widget(this._context, this._viewDomNode, _widget);
    this._widgets[myWidget.id] = myWidget;
    if (myWidget.allowEditorOverflow) {
      this.overflowingContentWidgetsDomNode.appendChild(myWidget.domNode);
    } else {
      this.domNode.appendChild(myWidget.domNode);
    }
    this.setShouldRender();
  }
  setWidgetPosition(widget, range3, preference) {
    const myWidget = this._widgets[widget.getId()];
    myWidget.setPosition(range3, preference);
    this.setShouldRender();
  }
  removeWidget(widget) {
    const widgetId = widget.getId();
    if (this._widgets.hasOwnProperty(widgetId)) {
      const myWidget = this._widgets[widgetId];
      delete this._widgets[widgetId];
      const domNode = myWidget.domNode.domNode;
      domNode.parentNode.removeChild(domNode);
      domNode.removeAttribute("monaco-visible-content-widget");
      this.setShouldRender();
    }
  }
  shouldSuppressMouseDownOnWidget(widgetId) {
    if (this._widgets.hasOwnProperty(widgetId)) {
      return this._widgets[widgetId].suppressMouseDown;
    }
    return false;
  }
  onBeforeRender(viewportData) {
    const keys2 = Object.keys(this._widgets);
    for (const widgetId of keys2) {
      this._widgets[widgetId].onBeforeRender(viewportData);
    }
  }
  prepareRender(ctx) {
    const keys2 = Object.keys(this._widgets);
    for (const widgetId of keys2) {
      this._widgets[widgetId].prepareRender(ctx);
    }
  }
  render(ctx) {
    const keys2 = Object.keys(this._widgets);
    for (const widgetId of keys2) {
      this._widgets[widgetId].render(ctx);
    }
  }
};
var Widget = class {
  constructor(context2, viewDomNode, actual) {
    this._context = context2;
    this._viewDomNode = viewDomNode;
    this._actual = actual;
    this.domNode = createFastDomNode(this._actual.getDomNode());
    this.id = this._actual.getId();
    this.allowEditorOverflow = this._actual.allowEditorOverflow || false;
    this.suppressMouseDown = this._actual.suppressMouseDown || false;
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._fixedOverflowWidgets = options.get(30);
    this._contentWidth = layoutInfo.contentWidth;
    this._contentLeft = layoutInfo.contentLeft;
    this._lineHeight = options.get(51);
    this._range = null;
    this._viewRange = null;
    this._preference = [];
    this._cachedDomNodeClientWidth = -1;
    this._cachedDomNodeClientHeight = -1;
    this._maxWidth = this._getMaxWidth();
    this._isVisible = false;
    this._renderData = null;
    this.domNode.setPosition(this._fixedOverflowWidgets && this.allowEditorOverflow ? "fixed" : "absolute");
    this.domNode.setVisibility("hidden");
    this.domNode.setAttribute("widgetId", this.id);
    this.domNode.setMaxWidth(this._maxWidth);
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    this._lineHeight = options.get(51);
    if (e2.hasChanged(117)) {
      const layoutInfo = options.get(117);
      this._contentLeft = layoutInfo.contentLeft;
      this._contentWidth = layoutInfo.contentWidth;
      this._maxWidth = this._getMaxWidth();
    }
  }
  onLineMappingChanged(e2) {
    this._setPosition(this._range);
  }
  _setPosition(range3) {
    this._range = range3;
    this._viewRange = null;
    if (this._range) {
      const validModelRange = this._context.model.validateModelRange(this._range);
      if (this._context.model.coordinatesConverter.modelPositionIsVisible(validModelRange.getStartPosition()) || this._context.model.coordinatesConverter.modelPositionIsVisible(validModelRange.getEndPosition())) {
        this._viewRange = this._context.model.coordinatesConverter.convertModelRangeToViewRange(validModelRange);
      }
    }
  }
  _getMaxWidth() {
    return this.allowEditorOverflow ? window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth : this._contentWidth;
  }
  setPosition(range3, preference) {
    this._setPosition(range3);
    this._preference = preference;
    this._cachedDomNodeClientWidth = -1;
    this._cachedDomNodeClientHeight = -1;
  }
  _layoutBoxInViewport(topLeft, bottomLeft, width2, height, ctx) {
    const aboveLineTop = topLeft.top;
    const heightAboveLine = aboveLineTop;
    const underLineTop = bottomLeft.top + this._lineHeight;
    const heightUnderLine = ctx.viewportHeight - underLineTop;
    const aboveTop = aboveLineTop - height;
    const fitsAbove = heightAboveLine >= height;
    const belowTop = underLineTop;
    const fitsBelow = heightUnderLine >= height;
    let actualAboveLeft = topLeft.left;
    let actualBelowLeft = bottomLeft.left;
    if (actualAboveLeft + width2 > ctx.scrollLeft + ctx.viewportWidth) {
      actualAboveLeft = ctx.scrollLeft + ctx.viewportWidth - width2;
    }
    if (actualBelowLeft + width2 > ctx.scrollLeft + ctx.viewportWidth) {
      actualBelowLeft = ctx.scrollLeft + ctx.viewportWidth - width2;
    }
    if (actualAboveLeft < ctx.scrollLeft) {
      actualAboveLeft = ctx.scrollLeft;
    }
    if (actualBelowLeft < ctx.scrollLeft) {
      actualBelowLeft = ctx.scrollLeft;
    }
    return {
      fitsAbove,
      aboveTop,
      aboveLeft: actualAboveLeft,
      fitsBelow,
      belowTop,
      belowLeft: actualBelowLeft
    };
  }
  _layoutHorizontalSegmentInPage(windowSize, domNodePosition, left2, width2) {
    const MIN_LIMIT = Math.max(0, domNodePosition.left - width2);
    const MAX_LIMIT = Math.min(domNodePosition.left + domNodePosition.width + width2, windowSize.width);
    let absoluteLeft = domNodePosition.left + left2 - StandardWindow.scrollX;
    if (absoluteLeft + width2 > MAX_LIMIT) {
      const delta = absoluteLeft - (MAX_LIMIT - width2);
      absoluteLeft -= delta;
      left2 -= delta;
    }
    if (absoluteLeft < MIN_LIMIT) {
      const delta = absoluteLeft - MIN_LIMIT;
      absoluteLeft -= delta;
      left2 -= delta;
    }
    return [left2, absoluteLeft];
  }
  _layoutBoxInPage(topLeft, bottomLeft, width2, height, ctx) {
    const aboveTop = topLeft.top - height;
    const belowTop = bottomLeft.top + this._lineHeight;
    const domNodePosition = getDomNodePagePosition(this._viewDomNode.domNode);
    const absoluteAboveTop = domNodePosition.top + aboveTop - StandardWindow.scrollY;
    const absoluteBelowTop = domNodePosition.top + belowTop - StandardWindow.scrollY;
    const windowSize = getClientArea(document.body);
    const [aboveLeft, absoluteAboveLeft] = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, topLeft.left - ctx.scrollLeft + this._contentLeft, width2);
    const [belowLeft, absoluteBelowLeft] = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, bottomLeft.left - ctx.scrollLeft + this._contentLeft, width2);
    const TOP_PADDING = 22;
    const BOTTOM_PADDING = 22;
    const fitsAbove = absoluteAboveTop >= TOP_PADDING;
    const fitsBelow = absoluteBelowTop + height <= windowSize.height - BOTTOM_PADDING;
    if (this._fixedOverflowWidgets) {
      return {
        fitsAbove,
        aboveTop: Math.max(absoluteAboveTop, TOP_PADDING),
        aboveLeft: absoluteAboveLeft,
        fitsBelow,
        belowTop: absoluteBelowTop,
        belowLeft: absoluteBelowLeft
      };
    }
    return {
      fitsAbove,
      aboveTop,
      aboveLeft,
      fitsBelow,
      belowTop,
      belowLeft
    };
  }
  _prepareRenderWidgetAtExactPositionOverflowing(topLeft) {
    return new Coordinate(topLeft.top, topLeft.left + this._contentLeft);
  }
  _getTopAndBottomLeft(ctx) {
    if (!this._viewRange) {
      return [null, null];
    }
    const visibleRangesForRange = ctx.linesVisibleRangesForRange(this._viewRange, false);
    if (!visibleRangesForRange || visibleRangesForRange.length === 0) {
      return [null, null];
    }
    let firstLine = visibleRangesForRange[0];
    let lastLine = visibleRangesForRange[0];
    for (const visibleRangesForLine of visibleRangesForRange) {
      if (visibleRangesForLine.lineNumber < firstLine.lineNumber) {
        firstLine = visibleRangesForLine;
      }
      if (visibleRangesForLine.lineNumber > lastLine.lineNumber) {
        lastLine = visibleRangesForLine;
      }
    }
    let firstLineMinLeft = 1073741824;
    for (const visibleRange of firstLine.ranges) {
      if (visibleRange.left < firstLineMinLeft) {
        firstLineMinLeft = visibleRange.left;
      }
    }
    let lastLineMinLeft = 1073741824;
    for (const visibleRange of lastLine.ranges) {
      if (visibleRange.left < lastLineMinLeft) {
        lastLineMinLeft = visibleRange.left;
      }
    }
    const topForPosition = ctx.getVerticalOffsetForLineNumber(firstLine.lineNumber) - ctx.scrollTop;
    const topLeft = new Coordinate(topForPosition, firstLineMinLeft);
    const topForBottomLine = ctx.getVerticalOffsetForLineNumber(lastLine.lineNumber) - ctx.scrollTop;
    const bottomLeft = new Coordinate(topForBottomLine, lastLineMinLeft);
    return [topLeft, bottomLeft];
  }
  _prepareRenderWidget(ctx) {
    const [topLeft, bottomLeft] = this._getTopAndBottomLeft(ctx);
    if (!topLeft || !bottomLeft) {
      return null;
    }
    if (this._cachedDomNodeClientWidth === -1 || this._cachedDomNodeClientHeight === -1) {
      const domNode = this.domNode.domNode;
      this._cachedDomNodeClientWidth = domNode.clientWidth;
      this._cachedDomNodeClientHeight = domNode.clientHeight;
    }
    let placement;
    if (this.allowEditorOverflow) {
      placement = this._layoutBoxInPage(topLeft, bottomLeft, this._cachedDomNodeClientWidth, this._cachedDomNodeClientHeight, ctx);
    } else {
      placement = this._layoutBoxInViewport(topLeft, bottomLeft, this._cachedDomNodeClientWidth, this._cachedDomNodeClientHeight, ctx);
    }
    if (this._preference) {
      for (let pass = 1; pass <= 2; pass++) {
        for (const pref of this._preference) {
          if (pref === 1) {
            if (!placement) {
              return null;
            }
            if (pass === 2 || placement.fitsAbove) {
              return new Coordinate(placement.aboveTop, placement.aboveLeft);
            }
          } else if (pref === 2) {
            if (!placement) {
              return null;
            }
            if (pass === 2 || placement.fitsBelow) {
              return new Coordinate(placement.belowTop, placement.belowLeft);
            }
          } else {
            if (this.allowEditorOverflow) {
              return this._prepareRenderWidgetAtExactPositionOverflowing(topLeft);
            } else {
              return topLeft;
            }
          }
        }
      }
    }
    return null;
  }
  onBeforeRender(viewportData) {
    if (!this._viewRange || !this._preference) {
      return;
    }
    if (this._viewRange.endLineNumber < viewportData.startLineNumber || this._viewRange.startLineNumber > viewportData.endLineNumber) {
      return;
    }
    this.domNode.setMaxWidth(this._maxWidth);
  }
  prepareRender(ctx) {
    this._renderData = this._prepareRenderWidget(ctx);
  }
  render(ctx) {
    if (!this._renderData) {
      if (this._isVisible) {
        this.domNode.removeAttribute("monaco-visible-content-widget");
        this._isVisible = false;
        this.domNode.setVisibility("hidden");
      }
      return;
    }
    if (this.allowEditorOverflow) {
      this.domNode.setTop(this._renderData.top);
      this.domNode.setLeft(this._renderData.left);
    } else {
      this.domNode.setTop(this._renderData.top + ctx.scrollTop - ctx.bigNumbersDelta);
      this.domNode.setLeft(this._renderData.left);
    }
    if (!this._isVisible) {
      this.domNode.setVisibility("inherit");
      this.domNode.setAttribute("monaco-visible-content-widget", "true");
      this._isVisible = true;
    }
  }
};
function __snowpack__injectStyle$6(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$6("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-editor .view-overlays .current-line {\r\n	display: block;\r\n	position: absolute;\r\n	left: 0;\r\n	top: 0;\r\n	box-sizing: border-box;\r\n}\r\n\r\n.monaco-editor .margin-view-overlays .current-line {\r\n	display: block;\r\n	position: absolute;\r\n	left: 0;\r\n	top: 0;\r\n	box-sizing: border-box;\r\n}\r\n\r\n.monaco-editor .margin-view-overlays .current-line.current-line-margin.current-line-margin-both {\r\n	border-right: 0;\r\n}\r\n");
var isRenderedUsingBorder = true;
var AbstractLineHighlightOverlay = class extends DynamicViewOverlay {
  constructor(context2) {
    super();
    this._context = context2;
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._lineHeight = options.get(51);
    this._renderLineHighlight = options.get(77);
    this._renderLineHightlightOnlyWhenFocus = options.get(78);
    this._contentLeft = layoutInfo.contentLeft;
    this._contentWidth = layoutInfo.contentWidth;
    this._selectionIsEmpty = true;
    this._focused = false;
    this._cursorLineNumbers = [];
    this._selections = [];
    this._renderData = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    super.dispose();
  }
  _readFromSelections() {
    let hasChanged = false;
    const renderSelections = isRenderedUsingBorder ? this._selections.slice(0, 1) : this._selections;
    const cursorsLineNumbers = renderSelections.map((s2) => s2.positionLineNumber);
    cursorsLineNumbers.sort((a2, b2) => a2 - b2);
    if (!equals(this._cursorLineNumbers, cursorsLineNumbers)) {
      this._cursorLineNumbers = cursorsLineNumbers;
      hasChanged = true;
    }
    const selectionIsEmpty = renderSelections.every((s2) => s2.isEmpty());
    if (this._selectionIsEmpty !== selectionIsEmpty) {
      this._selectionIsEmpty = selectionIsEmpty;
      hasChanged = true;
    }
    return hasChanged;
  }
  onThemeChanged(e2) {
    return this._readFromSelections();
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._lineHeight = options.get(51);
    this._renderLineHighlight = options.get(77);
    this._renderLineHightlightOnlyWhenFocus = options.get(78);
    this._contentLeft = layoutInfo.contentLeft;
    this._contentWidth = layoutInfo.contentWidth;
    return true;
  }
  onCursorStateChanged(e2) {
    this._selections = e2.selections;
    return this._readFromSelections();
  }
  onFlushed(e2) {
    return true;
  }
  onLinesDeleted(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollWidthChanged || e2.scrollTopChanged;
  }
  onZonesChanged(e2) {
    return true;
  }
  onFocusChanged(e2) {
    if (!this._renderLineHightlightOnlyWhenFocus) {
      return false;
    }
    this._focused = e2.isFocused;
    return true;
  }
  prepareRender(ctx) {
    if (!this._shouldRenderThis()) {
      this._renderData = null;
      return;
    }
    const renderedLine = this._renderOne(ctx);
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const len2 = this._cursorLineNumbers.length;
    let index3 = 0;
    const renderData = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      while (index3 < len2 && this._cursorLineNumbers[index3] < lineNumber) {
        index3++;
      }
      if (index3 < len2 && this._cursorLineNumbers[index3] === lineNumber) {
        renderData[lineIndex] = renderedLine;
      } else {
        renderData[lineIndex] = "";
      }
    }
    this._renderData = renderData;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderData) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex >= this._renderData.length) {
      return "";
    }
    return this._renderData[lineIndex];
  }
};
var CurrentLineHighlightOverlay = class extends AbstractLineHighlightOverlay {
  _renderOne(ctx) {
    const className = "current-line" + (this._shouldRenderOther() ? " current-line-both" : "");
    return `<div class="${className}" style="width:${Math.max(ctx.scrollWidth, this._contentWidth)}px; height:${this._lineHeight}px;"></div>`;
  }
  _shouldRenderThis() {
    return (this._renderLineHighlight === "line" || this._renderLineHighlight === "all") && this._selectionIsEmpty && (!this._renderLineHightlightOnlyWhenFocus || this._focused);
  }
  _shouldRenderOther() {
    return (this._renderLineHighlight === "gutter" || this._renderLineHighlight === "all") && (!this._renderLineHightlightOnlyWhenFocus || this._focused);
  }
};
var CurrentLineMarginHighlightOverlay = class extends AbstractLineHighlightOverlay {
  _renderOne(ctx) {
    const className = "current-line current-line-margin" + (this._shouldRenderOther() ? " current-line-margin-both" : "");
    return `<div class="${className}" style="width:${this._contentLeft}px; height:${this._lineHeight}px;"></div>`;
  }
  _shouldRenderThis() {
    return (this._renderLineHighlight === "gutter" || this._renderLineHighlight === "all") && (!this._renderLineHightlightOnlyWhenFocus || this._focused);
  }
  _shouldRenderOther() {
    return (this._renderLineHighlight === "line" || this._renderLineHighlight === "all") && this._selectionIsEmpty && (!this._renderLineHightlightOnlyWhenFocus || this._focused);
  }
};
registerThemingParticipant((theme, collector) => {
  isRenderedUsingBorder = false;
  const lineHighlight = theme.getColor(editorLineHighlight);
  if (lineHighlight) {
    collector.addRule(`.monaco-editor .view-overlays .current-line { background-color: ${lineHighlight}; }`);
    collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { background-color: ${lineHighlight}; border: none; }`);
  }
  if (!lineHighlight || lineHighlight.isTransparent() || theme.defines(editorLineHighlightBorder)) {
    const lineHighlightBorder = theme.getColor(editorLineHighlightBorder);
    if (lineHighlightBorder) {
      isRenderedUsingBorder = true;
      collector.addRule(`.monaco-editor .view-overlays .current-line { border: 2px solid ${lineHighlightBorder}; }`);
      collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { border: 2px solid ${lineHighlightBorder}; }`);
      if (theme.type === "hc") {
        collector.addRule(`.monaco-editor .view-overlays .current-line { border-width: 1px; }`);
        collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { border-width: 1px; }`);
      }
    }
  }
});
function __snowpack__injectStyle$7(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$7("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n/*\r\n	Keeping name short for faster parsing.\r\n	cdr = core decorations rendering (div)\r\n*/\r\n.monaco-editor .lines-content .cdr {\r\n	position: absolute;\r\n}");
var DecorationsOverlay = class extends DynamicViewOverlay {
  constructor(context2) {
    super();
    this._context = context2;
    const options = this._context.configuration.options;
    this._lineHeight = options.get(51);
    this._typicalHalfwidthCharacterWidth = options.get(36).typicalHalfwidthCharacterWidth;
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    this._lineHeight = options.get(51);
    this._typicalHalfwidthCharacterWidth = options.get(36).typicalHalfwidthCharacterWidth;
    return true;
  }
  onDecorationsChanged(e2) {
    return true;
  }
  onFlushed(e2) {
    return true;
  }
  onLinesChanged(e2) {
    return true;
  }
  onLinesDeleted(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollTopChanged || e2.scrollWidthChanged;
  }
  onZonesChanged(e2) {
    return true;
  }
  prepareRender(ctx) {
    const _decorations = ctx.getDecorationsInViewport();
    let decorations = [], decorationsLen = 0;
    for (let i3 = 0, len2 = _decorations.length; i3 < len2; i3++) {
      const d2 = _decorations[i3];
      if (d2.options.className) {
        decorations[decorationsLen++] = d2;
      }
    }
    decorations = decorations.sort((a2, b2) => {
      if (a2.options.zIndex < b2.options.zIndex) {
        return -1;
      }
      if (a2.options.zIndex > b2.options.zIndex) {
        return 1;
      }
      const aClassName = a2.options.className;
      const bClassName = b2.options.className;
      if (aClassName < bClassName) {
        return -1;
      }
      if (aClassName > bClassName) {
        return 1;
      }
      return Range.compareRangesUsingStarts(a2.range, b2.range);
    });
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const output2 = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      output2[lineIndex] = "";
    }
    this._renderWholeLineDecorations(ctx, decorations, output2);
    this._renderNormalDecorations(ctx, decorations, output2);
    this._renderResult = output2;
  }
  _renderWholeLineDecorations(ctx, decorations, output2) {
    const lineHeight = String(this._lineHeight);
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    for (let i3 = 0, lenI = decorations.length; i3 < lenI; i3++) {
      const d2 = decorations[i3];
      if (!d2.options.isWholeLine) {
        continue;
      }
      const decorationOutput = '<div class="cdr ' + d2.options.className + '" style="left:0;width:100%;height:' + lineHeight + 'px;"></div>';
      const startLineNumber = Math.max(d2.range.startLineNumber, visibleStartLineNumber);
      const endLineNumber = Math.min(d2.range.endLineNumber, visibleEndLineNumber);
      for (let j = startLineNumber; j <= endLineNumber; j++) {
        const lineIndex = j - visibleStartLineNumber;
        output2[lineIndex] += decorationOutput;
      }
    }
  }
  _renderNormalDecorations(ctx, decorations, output2) {
    const lineHeight = String(this._lineHeight);
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    let prevClassName = null;
    let prevShowIfCollapsed = false;
    let prevRange = null;
    for (let i3 = 0, lenI = decorations.length; i3 < lenI; i3++) {
      const d2 = decorations[i3];
      if (d2.options.isWholeLine) {
        continue;
      }
      const className = d2.options.className;
      const showIfCollapsed = Boolean(d2.options.showIfCollapsed);
      let range3 = d2.range;
      if (showIfCollapsed && range3.endColumn === 1 && range3.endLineNumber !== range3.startLineNumber) {
        range3 = new Range(range3.startLineNumber, range3.startColumn, range3.endLineNumber - 1, this._context.model.getLineMaxColumn(range3.endLineNumber - 1));
      }
      if (prevClassName === className && prevShowIfCollapsed === showIfCollapsed && Range.areIntersectingOrTouching(prevRange, range3)) {
        prevRange = Range.plusRange(prevRange, range3);
        continue;
      }
      if (prevClassName !== null) {
        this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output2);
      }
      prevClassName = className;
      prevShowIfCollapsed = showIfCollapsed;
      prevRange = range3;
    }
    if (prevClassName !== null) {
      this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output2);
    }
  }
  _renderNormalDecoration(ctx, range3, className, showIfCollapsed, lineHeight, visibleStartLineNumber, output2) {
    const linesVisibleRanges = ctx.linesVisibleRangesForRange(range3, className === "findMatch");
    if (!linesVisibleRanges) {
      return;
    }
    for (let j = 0, lenJ = linesVisibleRanges.length; j < lenJ; j++) {
      const lineVisibleRanges = linesVisibleRanges[j];
      if (lineVisibleRanges.outsideRenderedLine) {
        continue;
      }
      const lineIndex = lineVisibleRanges.lineNumber - visibleStartLineNumber;
      if (showIfCollapsed && lineVisibleRanges.ranges.length === 1) {
        const singleVisibleRange = lineVisibleRanges.ranges[0];
        if (singleVisibleRange.width === 0) {
          lineVisibleRanges.ranges[0] = new HorizontalRange(singleVisibleRange.left, this._typicalHalfwidthCharacterWidth);
        }
      }
      for (let k2 = 0, lenK = lineVisibleRanges.ranges.length; k2 < lenK; k2++) {
        const visibleRange = lineVisibleRanges.ranges[k2];
        const decorationOutput = '<div class="cdr ' + className + '" style="left:' + String(visibleRange.left) + "px;width:" + String(visibleRange.width) + "px;height:" + lineHeight + 'px;"></div>';
        output2[lineIndex] += decorationOutput;
      }
    }
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
      return "";
    }
    return this._renderResult[lineIndex];
  }
};
function __snowpack__injectStyle$8(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$8("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n/* Arrows */\r\n.monaco-scrollable-element > .scrollbar > .scra {\r\n	cursor: pointer;\r\n	font-size: 11px !important;\r\n}\r\n\r\n.monaco-scrollable-element > .visible {\r\n	opacity: 1;\r\n\r\n	/* Background rule added for IE9 - to allow clicks on dom node */\r\n	background:rgba(0,0,0,0);\r\n\r\n	transition: opacity 100ms linear;\r\n}\r\n.monaco-scrollable-element > .invisible {\r\n	opacity: 0;\r\n	pointer-events: none;\r\n}\r\n.monaco-scrollable-element > .invisible.fade {\r\n	transition: opacity 800ms linear;\r\n}\r\n\r\n/* Scrollable Content Inset Shadow */\r\n.monaco-scrollable-element > .shadow {\r\n	position: absolute;\r\n	display: none;\r\n}\r\n.monaco-scrollable-element > .shadow.top {\r\n	display: block;\r\n	top: 0;\r\n	left: 3px;\r\n	height: 3px;\r\n	width: 100%;\r\n	box-shadow: #DDD 0 6px 6px -6px inset;\r\n}\r\n.monaco-scrollable-element > .shadow.left {\r\n	display: block;\r\n	top: 3px;\r\n	left: 0;\r\n	height: 100%;\r\n	width: 3px;\r\n	box-shadow: #DDD 6px 0 6px -6px inset;\r\n}\r\n.monaco-scrollable-element > .shadow.top-left-corner {\r\n	display: block;\r\n	top: 0;\r\n	left: 0;\r\n	height: 3px;\r\n	width: 3px;\r\n}\r\n.monaco-scrollable-element > .shadow.top.left {\r\n	box-shadow: #DDD 6px 6px 6px -6px inset;\r\n}\r\n\r\n/* ---------- Default Style ---------- */\r\n\r\n.vs .monaco-scrollable-element > .scrollbar > .slider {\r\n	background: rgba(100, 100, 100, .4);\r\n}\r\n.vs-dark .monaco-scrollable-element > .scrollbar > .slider {\r\n	background: rgba(121, 121, 121, .4);\r\n}\r\n.hc-black .monaco-scrollable-element > .scrollbar > .slider {\r\n	background: rgba(111, 195, 223, .6);\r\n}\r\n\r\n.monaco-scrollable-element > .scrollbar > .slider:hover {\r\n	background: rgba(100, 100, 100, .7);\r\n}\r\n.hc-black .monaco-scrollable-element > .scrollbar > .slider:hover {\r\n	background: rgba(111, 195, 223, .8);\r\n}\r\n\r\n.monaco-scrollable-element > .scrollbar > .slider.active {\r\n	background: rgba(0, 0, 0, .6);\r\n}\r\n.vs-dark .monaco-scrollable-element > .scrollbar > .slider.active {\r\n	background: rgba(191, 191, 191, .4);\r\n}\r\n.hc-black .monaco-scrollable-element > .scrollbar > .slider.active {\r\n	background: rgba(111, 195, 223, 1);\r\n}\r\n\r\n.vs-dark .monaco-scrollable-element .shadow.top {\r\n	box-shadow: none;\r\n}\r\n\r\n.vs-dark .monaco-scrollable-element .shadow.left {\r\n	box-shadow: #000 6px 0 6px -6px inset;\r\n}\r\n\r\n.vs-dark .monaco-scrollable-element .shadow.top.left {\r\n	box-shadow: #000 6px 6px 6px -6px inset;\r\n}\r\n\r\n.hc-black .monaco-scrollable-element .shadow.top {\r\n	box-shadow: none;\r\n}\r\n\r\n.hc-black .monaco-scrollable-element .shadow.left {\r\n	box-shadow: none;\r\n}\r\n\r\n.hc-black .monaco-scrollable-element .shadow.top.left {\r\n	box-shadow: none;\r\n}\r\n");
var Widget$1 = class extends Disposable {
  onclick(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType.CLICK, (e2) => listener(new StandardMouseEvent(e2))));
  }
  onmousedown(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType.MOUSE_DOWN, (e2) => listener(new StandardMouseEvent(e2))));
  }
  onmouseover(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType.MOUSE_OVER, (e2) => listener(new StandardMouseEvent(e2))));
  }
  onnonbubblingmouseout(domNode, listener) {
    this._register(addDisposableNonBubblingMouseOutListener(domNode, (e2) => listener(new StandardMouseEvent(e2))));
  }
  onkeydown(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType.KEY_DOWN, (e2) => listener(new StandardKeyboardEvent(e2))));
  }
  onkeyup(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType.KEY_UP, (e2) => listener(new StandardKeyboardEvent(e2))));
  }
  oninput(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType.INPUT, listener));
  }
  onblur(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType.BLUR, listener));
  }
  onfocus(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType.FOCUS, listener));
  }
  ignoreGesture(domNode) {
    Gesture.ignoreTarget(domNode);
  }
};
var ARROW_IMG_SIZE = 11;
var ScrollbarArrow = class extends Widget$1 {
  constructor(opts) {
    super();
    this._onActivate = opts.onActivate;
    this.bgDomNode = document.createElement("div");
    this.bgDomNode.className = "arrow-background";
    this.bgDomNode.style.position = "absolute";
    this.bgDomNode.style.width = opts.bgWidth + "px";
    this.bgDomNode.style.height = opts.bgHeight + "px";
    if (typeof opts.top !== "undefined") {
      this.bgDomNode.style.top = "0px";
    }
    if (typeof opts.left !== "undefined") {
      this.bgDomNode.style.left = "0px";
    }
    if (typeof opts.bottom !== "undefined") {
      this.bgDomNode.style.bottom = "0px";
    }
    if (typeof opts.right !== "undefined") {
      this.bgDomNode.style.right = "0px";
    }
    this.domNode = document.createElement("div");
    this.domNode.className = opts.className;
    addClasses(this.domNode, opts.icon.classNames);
    this.domNode.style.position = "absolute";
    this.domNode.style.width = ARROW_IMG_SIZE + "px";
    this.domNode.style.height = ARROW_IMG_SIZE + "px";
    if (typeof opts.top !== "undefined") {
      this.domNode.style.top = opts.top + "px";
    }
    if (typeof opts.left !== "undefined") {
      this.domNode.style.left = opts.left + "px";
    }
    if (typeof opts.bottom !== "undefined") {
      this.domNode.style.bottom = opts.bottom + "px";
    }
    if (typeof opts.right !== "undefined") {
      this.domNode.style.right = opts.right + "px";
    }
    this._mouseMoveMonitor = this._register(new GlobalMouseMoveMonitor());
    this.onmousedown(this.bgDomNode, (e2) => this._arrowMouseDown(e2));
    this.onmousedown(this.domNode, (e2) => this._arrowMouseDown(e2));
    this._mousedownRepeatTimer = this._register(new IntervalTimer());
    this._mousedownScheduleRepeatTimer = this._register(new TimeoutTimer());
  }
  _arrowMouseDown(e2) {
    let scheduleRepeater = () => {
      this._mousedownRepeatTimer.cancelAndSet(() => this._onActivate(), 1e3 / 24);
    };
    this._onActivate();
    this._mousedownRepeatTimer.cancel();
    this._mousedownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200);
    this._mouseMoveMonitor.startMonitoring(e2.target, e2.buttons, standardMouseMoveMerger, (mouseMoveData) => {
    }, () => {
      this._mousedownRepeatTimer.cancel();
      this._mousedownScheduleRepeatTimer.cancel();
    });
    e2.preventDefault();
  }
};
var ScrollbarVisibilityController = class extends Disposable {
  constructor(visibility, visibleClassName, invisibleClassName) {
    super();
    this._visibility = visibility;
    this._visibleClassName = visibleClassName;
    this._invisibleClassName = invisibleClassName;
    this._domNode = null;
    this._isVisible = false;
    this._isNeeded = false;
    this._shouldBeVisible = false;
    this._revealTimer = this._register(new TimeoutTimer());
  }
  applyVisibilitySetting(shouldBeVisible) {
    if (this._visibility === 2) {
      return false;
    }
    if (this._visibility === 3) {
      return true;
    }
    return shouldBeVisible;
  }
  setShouldBeVisible(rawShouldBeVisible) {
    let shouldBeVisible = this.applyVisibilitySetting(rawShouldBeVisible);
    if (this._shouldBeVisible !== shouldBeVisible) {
      this._shouldBeVisible = shouldBeVisible;
      this.ensureVisibility();
    }
  }
  setIsNeeded(isNeeded) {
    if (this._isNeeded !== isNeeded) {
      this._isNeeded = isNeeded;
      this.ensureVisibility();
    }
  }
  setDomNode(domNode) {
    this._domNode = domNode;
    this._domNode.setClassName(this._invisibleClassName);
    this.setShouldBeVisible(false);
  }
  ensureVisibility() {
    if (!this._isNeeded) {
      this._hide(false);
      return;
    }
    if (this._shouldBeVisible) {
      this._reveal();
    } else {
      this._hide(true);
    }
  }
  _reveal() {
    if (this._isVisible) {
      return;
    }
    this._isVisible = true;
    this._revealTimer.setIfNotSet(() => {
      if (this._domNode) {
        this._domNode.setClassName(this._visibleClassName);
      }
    }, 0);
  }
  _hide(withFadeAway) {
    this._revealTimer.cancel();
    if (!this._isVisible) {
      return;
    }
    this._isVisible = false;
    if (this._domNode) {
      this._domNode.setClassName(this._invisibleClassName + (withFadeAway ? " fade" : ""));
    }
  }
};
var MOUSE_DRAG_RESET_DISTANCE = 140;
var AbstractScrollbar = class extends Widget$1 {
  constructor(opts) {
    super();
    this._lazyRender = opts.lazyRender;
    this._host = opts.host;
    this._scrollable = opts.scrollable;
    this._scrollbarState = opts.scrollbarState;
    this._visibilityController = this._register(new ScrollbarVisibilityController(opts.visibility, "visible scrollbar " + opts.extraScrollbarClassName, "invisible scrollbar " + opts.extraScrollbarClassName));
    this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
    this._mouseMoveMonitor = this._register(new GlobalMouseMoveMonitor());
    this._shouldRender = true;
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this._visibilityController.setDomNode(this.domNode);
    this.domNode.setPosition("absolute");
    this.onmousedown(this.domNode.domNode, (e2) => this._domNodeMouseDown(e2));
  }
  _createArrow(opts) {
    let arrow2 = this._register(new ScrollbarArrow(opts));
    this.domNode.domNode.appendChild(arrow2.bgDomNode);
    this.domNode.domNode.appendChild(arrow2.domNode);
  }
  _createSlider(top2, left2, width2, height) {
    this.slider = createFastDomNode(document.createElement("div"));
    this.slider.setClassName("slider");
    this.slider.setPosition("absolute");
    this.slider.setTop(top2);
    this.slider.setLeft(left2);
    if (typeof width2 === "number") {
      this.slider.setWidth(width2);
    }
    if (typeof height === "number") {
      this.slider.setHeight(height);
    }
    this.slider.setLayerHinting(true);
    this.slider.setContain("strict");
    this.domNode.domNode.appendChild(this.slider.domNode);
    this.onmousedown(this.slider.domNode, (e2) => {
      if (e2.leftButton) {
        e2.preventDefault();
        this._sliderMouseDown(e2, () => {
        });
      }
    });
    this.onclick(this.slider.domNode, (e2) => {
      if (e2.leftButton) {
        e2.stopPropagation();
      }
    });
  }
  _onElementSize(visibleSize) {
    if (this._scrollbarState.setVisibleSize(visibleSize)) {
      this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
      this._shouldRender = true;
      if (!this._lazyRender) {
        this.render();
      }
    }
    return this._shouldRender;
  }
  _onElementScrollSize(elementScrollSize) {
    if (this._scrollbarState.setScrollSize(elementScrollSize)) {
      this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
      this._shouldRender = true;
      if (!this._lazyRender) {
        this.render();
      }
    }
    return this._shouldRender;
  }
  _onElementScrollPosition(elementScrollPosition) {
    if (this._scrollbarState.setScrollPosition(elementScrollPosition)) {
      this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
      this._shouldRender = true;
      if (!this._lazyRender) {
        this.render();
      }
    }
    return this._shouldRender;
  }
  beginReveal() {
    this._visibilityController.setShouldBeVisible(true);
  }
  beginHide() {
    this._visibilityController.setShouldBeVisible(false);
  }
  render() {
    if (!this._shouldRender) {
      return;
    }
    this._shouldRender = false;
    this._renderDomNode(this._scrollbarState.getRectangleLargeSize(), this._scrollbarState.getRectangleSmallSize());
    this._updateSlider(this._scrollbarState.getSliderSize(), this._scrollbarState.getArrowSize() + this._scrollbarState.getSliderPosition());
  }
  _domNodeMouseDown(e2) {
    if (e2.target !== this.domNode.domNode) {
      return;
    }
    this._onMouseDown(e2);
  }
  delegateMouseDown(e2) {
    let domTop = this.domNode.domNode.getClientRects()[0].top;
    let sliderStart = domTop + this._scrollbarState.getSliderPosition();
    let sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize();
    let mousePos = this._sliderMousePosition(e2);
    if (sliderStart <= mousePos && mousePos <= sliderStop) {
      if (e2.leftButton) {
        e2.preventDefault();
        this._sliderMouseDown(e2, () => {
        });
      }
    } else {
      this._onMouseDown(e2);
    }
  }
  _onMouseDown(e2) {
    let offsetX;
    let offsetY;
    if (e2.target === this.domNode.domNode && typeof e2.browserEvent.offsetX === "number" && typeof e2.browserEvent.offsetY === "number") {
      offsetX = e2.browserEvent.offsetX;
      offsetY = e2.browserEvent.offsetY;
    } else {
      const domNodePosition = getDomNodePagePosition(this.domNode.domNode);
      offsetX = e2.posx - domNodePosition.left;
      offsetY = e2.posy - domNodePosition.top;
    }
    this._setDesiredScrollPositionNow(this._scrollbarState.getDesiredScrollPositionFromOffset(this._mouseDownRelativePosition(offsetX, offsetY)));
    if (e2.leftButton) {
      e2.preventDefault();
      this._sliderMouseDown(e2, () => {
      });
    }
  }
  _sliderMouseDown(e2, onDragFinished) {
    const initialMousePosition = this._sliderMousePosition(e2);
    const initialMouseOrthogonalPosition = this._sliderOrthogonalMousePosition(e2);
    const initialScrollbarState = this._scrollbarState.clone();
    this.slider.toggleClassName("active", true);
    this._mouseMoveMonitor.startMonitoring(e2.target, e2.buttons, standardMouseMoveMerger, (mouseMoveData) => {
      const mouseOrthogonalPosition = this._sliderOrthogonalMousePosition(mouseMoveData);
      const mouseOrthogonalDelta = Math.abs(mouseOrthogonalPosition - initialMouseOrthogonalPosition);
      if (isWindows && mouseOrthogonalDelta > MOUSE_DRAG_RESET_DISTANCE) {
        this._setDesiredScrollPositionNow(initialScrollbarState.getScrollPosition());
        return;
      }
      const mousePosition = this._sliderMousePosition(mouseMoveData);
      const mouseDelta = mousePosition - initialMousePosition;
      this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(mouseDelta));
    }, () => {
      this.slider.toggleClassName("active", false);
      this._host.onDragEnd();
      onDragFinished();
    });
    this._host.onDragStart();
  }
  _setDesiredScrollPositionNow(_desiredScrollPosition) {
    let desiredScrollPosition = {};
    this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition);
    this._scrollable.setScrollPositionNow(desiredScrollPosition);
  }
  updateScrollbarSize(scrollbarSize) {
    this._updateScrollbarSize(scrollbarSize);
    this._scrollbarState.setScrollbarSize(scrollbarSize);
    this._shouldRender = true;
    if (!this._lazyRender) {
      this.render();
    }
  }
};
var MINIMUM_SLIDER_SIZE = 20;
var ScrollbarState = class {
  constructor(arrowSize, scrollbarSize, oppositeScrollbarSize, visibleSize, scrollSize, scrollPosition) {
    this._scrollbarSize = Math.round(scrollbarSize);
    this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);
    this._arrowSize = Math.round(arrowSize);
    this._visibleSize = visibleSize;
    this._scrollSize = scrollSize;
    this._scrollPosition = scrollPosition;
    this._computedAvailableSize = 0;
    this._computedIsNeeded = false;
    this._computedSliderSize = 0;
    this._computedSliderRatio = 0;
    this._computedSliderPosition = 0;
    this._refreshComputedValues();
  }
  clone() {
    return new ScrollbarState(this._arrowSize, this._scrollbarSize, this._oppositeScrollbarSize, this._visibleSize, this._scrollSize, this._scrollPosition);
  }
  setVisibleSize(visibleSize) {
    let iVisibleSize = Math.round(visibleSize);
    if (this._visibleSize !== iVisibleSize) {
      this._visibleSize = iVisibleSize;
      this._refreshComputedValues();
      return true;
    }
    return false;
  }
  setScrollSize(scrollSize) {
    let iScrollSize = Math.round(scrollSize);
    if (this._scrollSize !== iScrollSize) {
      this._scrollSize = iScrollSize;
      this._refreshComputedValues();
      return true;
    }
    return false;
  }
  setScrollPosition(scrollPosition) {
    let iScrollPosition = Math.round(scrollPosition);
    if (this._scrollPosition !== iScrollPosition) {
      this._scrollPosition = iScrollPosition;
      this._refreshComputedValues();
      return true;
    }
    return false;
  }
  setScrollbarSize(scrollbarSize) {
    this._scrollbarSize = scrollbarSize;
  }
  static _computeValues(oppositeScrollbarSize, arrowSize, visibleSize, scrollSize, scrollPosition) {
    const computedAvailableSize = Math.max(0, visibleSize - oppositeScrollbarSize);
    const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * arrowSize);
    const computedIsNeeded = scrollSize > 0 && scrollSize > visibleSize;
    if (!computedIsNeeded) {
      return {
        computedAvailableSize: Math.round(computedAvailableSize),
        computedIsNeeded,
        computedSliderSize: Math.round(computedRepresentableSize),
        computedSliderRatio: 0,
        computedSliderPosition: 0
      };
    }
    const computedSliderSize = Math.round(Math.max(MINIMUM_SLIDER_SIZE, Math.floor(visibleSize * computedRepresentableSize / scrollSize)));
    const computedSliderRatio = (computedRepresentableSize - computedSliderSize) / (scrollSize - visibleSize);
    const computedSliderPosition = scrollPosition * computedSliderRatio;
    return {
      computedAvailableSize: Math.round(computedAvailableSize),
      computedIsNeeded,
      computedSliderSize: Math.round(computedSliderSize),
      computedSliderRatio,
      computedSliderPosition: Math.round(computedSliderPosition)
    };
  }
  _refreshComputedValues() {
    const r3 = ScrollbarState._computeValues(this._oppositeScrollbarSize, this._arrowSize, this._visibleSize, this._scrollSize, this._scrollPosition);
    this._computedAvailableSize = r3.computedAvailableSize;
    this._computedIsNeeded = r3.computedIsNeeded;
    this._computedSliderSize = r3.computedSliderSize;
    this._computedSliderRatio = r3.computedSliderRatio;
    this._computedSliderPosition = r3.computedSliderPosition;
  }
  getArrowSize() {
    return this._arrowSize;
  }
  getScrollPosition() {
    return this._scrollPosition;
  }
  getRectangleLargeSize() {
    return this._computedAvailableSize;
  }
  getRectangleSmallSize() {
    return this._scrollbarSize;
  }
  isNeeded() {
    return this._computedIsNeeded;
  }
  getSliderSize() {
    return this._computedSliderSize;
  }
  getSliderPosition() {
    return this._computedSliderPosition;
  }
  getDesiredScrollPositionFromOffset(offset2) {
    if (!this._computedIsNeeded) {
      return 0;
    }
    let desiredSliderPosition = offset2 - this._arrowSize - this._computedSliderSize / 2;
    return Math.round(desiredSliderPosition / this._computedSliderRatio);
  }
  getDesiredScrollPositionFromDelta(delta) {
    if (!this._computedIsNeeded) {
      return 0;
    }
    let desiredSliderPosition = this._computedSliderPosition + delta;
    return Math.round(desiredSliderPosition / this._computedSliderRatio);
  }
};
var scrollbarButtonLeftIcon = registerIcon("scrollbar-button-left", Codicon.triangleLeft);
var scrollbarButtonRightIcon = registerIcon("scrollbar-button-right", Codicon.triangleRight);
var HorizontalScrollbar = class extends AbstractScrollbar {
  constructor(scrollable, options, host) {
    const scrollDimensions = scrollable.getScrollDimensions();
    const scrollPosition = scrollable.getCurrentScrollPosition();
    super({
      lazyRender: options.lazyRender,
      host,
      scrollbarState: new ScrollbarState(options.horizontalHasArrows ? options.arrowSize : 0, options.horizontal === 2 ? 0 : options.horizontalScrollbarSize, options.vertical === 2 ? 0 : options.verticalScrollbarSize, scrollDimensions.width, scrollDimensions.scrollWidth, scrollPosition.scrollLeft),
      visibility: options.horizontal,
      extraScrollbarClassName: "horizontal",
      scrollable
    });
    if (options.horizontalHasArrows) {
      let arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;
      let scrollbarDelta = (options.horizontalScrollbarSize - ARROW_IMG_SIZE) / 2;
      this._createArrow({
        className: "scra",
        icon: scrollbarButtonLeftIcon,
        top: scrollbarDelta,
        left: arrowDelta,
        bottom: void 0,
        right: void 0,
        bgWidth: options.arrowSize,
        bgHeight: options.horizontalScrollbarSize,
        onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 1, 0))
      });
      this._createArrow({
        className: "scra",
        icon: scrollbarButtonRightIcon,
        top: scrollbarDelta,
        left: void 0,
        bottom: void 0,
        right: arrowDelta,
        bgWidth: options.arrowSize,
        bgHeight: options.horizontalScrollbarSize,
        onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, -1, 0))
      });
    }
    this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, void 0, options.horizontalSliderSize);
  }
  _updateSlider(sliderSize, sliderPosition) {
    this.slider.setWidth(sliderSize);
    this.slider.setLeft(sliderPosition);
  }
  _renderDomNode(largeSize, smallSize) {
    this.domNode.setWidth(largeSize);
    this.domNode.setHeight(smallSize);
    this.domNode.setLeft(0);
    this.domNode.setBottom(0);
  }
  onDidScroll(e2) {
    this._shouldRender = this._onElementScrollSize(e2.scrollWidth) || this._shouldRender;
    this._shouldRender = this._onElementScrollPosition(e2.scrollLeft) || this._shouldRender;
    this._shouldRender = this._onElementSize(e2.width) || this._shouldRender;
    return this._shouldRender;
  }
  _mouseDownRelativePosition(offsetX, offsetY) {
    return offsetX;
  }
  _sliderMousePosition(e2) {
    return e2.posx;
  }
  _sliderOrthogonalMousePosition(e2) {
    return e2.posy;
  }
  _updateScrollbarSize(size2) {
    this.slider.setHeight(size2);
  }
  writeScrollPosition(target, scrollPosition) {
    target.scrollLeft = scrollPosition;
  }
};
var scrollbarButtonUpIcon = registerIcon("scrollbar-button-up", Codicon.triangleUp);
var scrollbarButtonDownIcon = registerIcon("scrollbar-button-down", Codicon.triangleDown);
var VerticalScrollbar = class extends AbstractScrollbar {
  constructor(scrollable, options, host) {
    const scrollDimensions = scrollable.getScrollDimensions();
    const scrollPosition = scrollable.getCurrentScrollPosition();
    super({
      lazyRender: options.lazyRender,
      host,
      scrollbarState: new ScrollbarState(options.verticalHasArrows ? options.arrowSize : 0, options.vertical === 2 ? 0 : options.verticalScrollbarSize, 0, scrollDimensions.height, scrollDimensions.scrollHeight, scrollPosition.scrollTop),
      visibility: options.vertical,
      extraScrollbarClassName: "vertical",
      scrollable
    });
    if (options.verticalHasArrows) {
      let arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;
      let scrollbarDelta = (options.verticalScrollbarSize - ARROW_IMG_SIZE) / 2;
      this._createArrow({
        className: "scra",
        icon: scrollbarButtonUpIcon,
        top: arrowDelta,
        left: scrollbarDelta,
        bottom: void 0,
        right: void 0,
        bgWidth: options.verticalScrollbarSize,
        bgHeight: options.arrowSize,
        onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, 1))
      });
      this._createArrow({
        className: "scra",
        icon: scrollbarButtonDownIcon,
        top: void 0,
        left: scrollbarDelta,
        bottom: arrowDelta,
        right: void 0,
        bgWidth: options.verticalScrollbarSize,
        bgHeight: options.arrowSize,
        onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, -1))
      });
    }
    this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, void 0);
  }
  _updateSlider(sliderSize, sliderPosition) {
    this.slider.setHeight(sliderSize);
    this.slider.setTop(sliderPosition);
  }
  _renderDomNode(largeSize, smallSize) {
    this.domNode.setWidth(smallSize);
    this.domNode.setHeight(largeSize);
    this.domNode.setRight(0);
    this.domNode.setTop(0);
  }
  onDidScroll(e2) {
    this._shouldRender = this._onElementScrollSize(e2.scrollHeight) || this._shouldRender;
    this._shouldRender = this._onElementScrollPosition(e2.scrollTop) || this._shouldRender;
    this._shouldRender = this._onElementSize(e2.height) || this._shouldRender;
    return this._shouldRender;
  }
  _mouseDownRelativePosition(offsetX, offsetY) {
    return offsetY;
  }
  _sliderMousePosition(e2) {
    return e2.posy;
  }
  _sliderOrthogonalMousePosition(e2) {
    return e2.posx;
  }
  _updateScrollbarSize(size2) {
    this.slider.setWidth(size2);
  }
  writeScrollPosition(target, scrollPosition) {
    target.scrollTop = scrollPosition;
  }
};
var ScrollState = class {
  constructor(width2, scrollWidth, scrollLeft, height, scrollHeight, scrollTop) {
    width2 = width2 | 0;
    scrollWidth = scrollWidth | 0;
    scrollLeft = scrollLeft | 0;
    height = height | 0;
    scrollHeight = scrollHeight | 0;
    scrollTop = scrollTop | 0;
    this.rawScrollLeft = scrollLeft;
    this.rawScrollTop = scrollTop;
    if (width2 < 0) {
      width2 = 0;
    }
    if (scrollLeft + width2 > scrollWidth) {
      scrollLeft = scrollWidth - width2;
    }
    if (scrollLeft < 0) {
      scrollLeft = 0;
    }
    if (height < 0) {
      height = 0;
    }
    if (scrollTop + height > scrollHeight) {
      scrollTop = scrollHeight - height;
    }
    if (scrollTop < 0) {
      scrollTop = 0;
    }
    this.width = width2;
    this.scrollWidth = scrollWidth;
    this.scrollLeft = scrollLeft;
    this.height = height;
    this.scrollHeight = scrollHeight;
    this.scrollTop = scrollTop;
  }
  equals(other) {
    return this.rawScrollLeft === other.rawScrollLeft && this.rawScrollTop === other.rawScrollTop && this.width === other.width && this.scrollWidth === other.scrollWidth && this.scrollLeft === other.scrollLeft && this.height === other.height && this.scrollHeight === other.scrollHeight && this.scrollTop === other.scrollTop;
  }
  withScrollDimensions(update, useRawScrollPositions) {
    return new ScrollState(typeof update.width !== "undefined" ? update.width : this.width, typeof update.scrollWidth !== "undefined" ? update.scrollWidth : this.scrollWidth, useRawScrollPositions ? this.rawScrollLeft : this.scrollLeft, typeof update.height !== "undefined" ? update.height : this.height, typeof update.scrollHeight !== "undefined" ? update.scrollHeight : this.scrollHeight, useRawScrollPositions ? this.rawScrollTop : this.scrollTop);
  }
  withScrollPosition(update) {
    return new ScrollState(this.width, this.scrollWidth, typeof update.scrollLeft !== "undefined" ? update.scrollLeft : this.rawScrollLeft, this.height, this.scrollHeight, typeof update.scrollTop !== "undefined" ? update.scrollTop : this.rawScrollTop);
  }
  createScrollEvent(previous) {
    const widthChanged = this.width !== previous.width;
    const scrollWidthChanged = this.scrollWidth !== previous.scrollWidth;
    const scrollLeftChanged = this.scrollLeft !== previous.scrollLeft;
    const heightChanged = this.height !== previous.height;
    const scrollHeightChanged = this.scrollHeight !== previous.scrollHeight;
    const scrollTopChanged = this.scrollTop !== previous.scrollTop;
    return {
      oldWidth: previous.width,
      oldScrollWidth: previous.scrollWidth,
      oldScrollLeft: previous.scrollLeft,
      width: this.width,
      scrollWidth: this.scrollWidth,
      scrollLeft: this.scrollLeft,
      oldHeight: previous.height,
      oldScrollHeight: previous.scrollHeight,
      oldScrollTop: previous.scrollTop,
      height: this.height,
      scrollHeight: this.scrollHeight,
      scrollTop: this.scrollTop,
      widthChanged,
      scrollWidthChanged,
      scrollLeftChanged,
      heightChanged,
      scrollHeightChanged,
      scrollTopChanged
    };
  }
};
var Scrollable = class extends Disposable {
  constructor(smoothScrollDuration, scheduleAtNextAnimationFrame2) {
    super();
    this._onScroll = this._register(new Emitter());
    this.onScroll = this._onScroll.event;
    this._smoothScrollDuration = smoothScrollDuration;
    this._scheduleAtNextAnimationFrame = scheduleAtNextAnimationFrame2;
    this._state = new ScrollState(0, 0, 0, 0, 0, 0);
    this._smoothScrolling = null;
  }
  dispose() {
    if (this._smoothScrolling) {
      this._smoothScrolling.dispose();
      this._smoothScrolling = null;
    }
    super.dispose();
  }
  setSmoothScrollDuration(smoothScrollDuration) {
    this._smoothScrollDuration = smoothScrollDuration;
  }
  validateScrollPosition(scrollPosition) {
    return this._state.withScrollPosition(scrollPosition);
  }
  getScrollDimensions() {
    return this._state;
  }
  setScrollDimensions(dimensions, useRawScrollPositions) {
    const newState = this._state.withScrollDimensions(dimensions, useRawScrollPositions);
    this._setState(newState);
    if (this._smoothScrolling) {
      this._smoothScrolling.acceptScrollDimensions(this._state);
    }
  }
  getFutureScrollPosition() {
    if (this._smoothScrolling) {
      return this._smoothScrolling.to;
    }
    return this._state;
  }
  getCurrentScrollPosition() {
    return this._state;
  }
  setScrollPositionNow(update) {
    const newState = this._state.withScrollPosition(update);
    if (this._smoothScrolling) {
      this._smoothScrolling.dispose();
      this._smoothScrolling = null;
    }
    this._setState(newState);
  }
  setScrollPositionSmooth(update) {
    if (this._smoothScrollDuration === 0) {
      return this.setScrollPositionNow(update);
    }
    if (this._smoothScrolling) {
      update = {
        scrollLeft: typeof update.scrollLeft === "undefined" ? this._smoothScrolling.to.scrollLeft : update.scrollLeft,
        scrollTop: typeof update.scrollTop === "undefined" ? this._smoothScrolling.to.scrollTop : update.scrollTop
      };
      const validTarget = this._state.withScrollPosition(update);
      if (this._smoothScrolling.to.scrollLeft === validTarget.scrollLeft && this._smoothScrolling.to.scrollTop === validTarget.scrollTop) {
        return;
      }
      const newSmoothScrolling = this._smoothScrolling.combine(this._state, validTarget, this._smoothScrollDuration);
      this._smoothScrolling.dispose();
      this._smoothScrolling = newSmoothScrolling;
    } else {
      const validTarget = this._state.withScrollPosition(update);
      this._smoothScrolling = SmoothScrollingOperation.start(this._state, validTarget, this._smoothScrollDuration);
    }
    this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {
      if (!this._smoothScrolling) {
        return;
      }
      this._smoothScrolling.animationFrameDisposable = null;
      this._performSmoothScrolling();
    });
  }
  _performSmoothScrolling() {
    if (!this._smoothScrolling) {
      return;
    }
    const update = this._smoothScrolling.tick();
    const newState = this._state.withScrollPosition(update);
    this._setState(newState);
    if (!this._smoothScrolling) {
      return;
    }
    if (update.isDone) {
      this._smoothScrolling.dispose();
      this._smoothScrolling = null;
      return;
    }
    this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {
      if (!this._smoothScrolling) {
        return;
      }
      this._smoothScrolling.animationFrameDisposable = null;
      this._performSmoothScrolling();
    });
  }
  _setState(newState) {
    const oldState = this._state;
    if (oldState.equals(newState)) {
      return;
    }
    this._state = newState;
    this._onScroll.fire(this._state.createScrollEvent(oldState));
  }
};
var SmoothScrollingUpdate = class {
  constructor(scrollLeft, scrollTop, isDone) {
    this.scrollLeft = scrollLeft;
    this.scrollTop = scrollTop;
    this.isDone = isDone;
  }
};
function createEaseOutCubic(from, to) {
  const delta = to - from;
  return function(completion) {
    return from + delta * easeOutCubic(completion);
  };
}
function createComposed(a2, b2, cut) {
  return function(completion) {
    if (completion < cut) {
      return a2(completion / cut);
    }
    return b2((completion - cut) / (1 - cut));
  };
}
var SmoothScrollingOperation = class {
  constructor(from, to, startTime2, duration) {
    this.from = from;
    this.to = to;
    this.duration = duration;
    this._startTime = startTime2;
    this.animationFrameDisposable = null;
    this._initAnimations();
  }
  _initAnimations() {
    this.scrollLeft = this._initAnimation(this.from.scrollLeft, this.to.scrollLeft, this.to.width);
    this.scrollTop = this._initAnimation(this.from.scrollTop, this.to.scrollTop, this.to.height);
  }
  _initAnimation(from, to, viewportSize) {
    const delta = Math.abs(from - to);
    if (delta > 2.5 * viewportSize) {
      let stop1, stop2;
      if (from < to) {
        stop1 = from + 0.75 * viewportSize;
        stop2 = to - 0.75 * viewportSize;
      } else {
        stop1 = from - 0.75 * viewportSize;
        stop2 = to + 0.75 * viewportSize;
      }
      return createComposed(createEaseOutCubic(from, stop1), createEaseOutCubic(stop2, to), 0.33);
    }
    return createEaseOutCubic(from, to);
  }
  dispose() {
    if (this.animationFrameDisposable !== null) {
      this.animationFrameDisposable.dispose();
      this.animationFrameDisposable = null;
    }
  }
  acceptScrollDimensions(state) {
    this.to = state.withScrollPosition(this.to);
    this._initAnimations();
  }
  tick() {
    return this._tick(Date.now());
  }
  _tick(now3) {
    const completion = (now3 - this._startTime) / this.duration;
    if (completion < 1) {
      const newScrollLeft = this.scrollLeft(completion);
      const newScrollTop = this.scrollTop(completion);
      return new SmoothScrollingUpdate(newScrollLeft, newScrollTop, false);
    }
    return new SmoothScrollingUpdate(this.to.scrollLeft, this.to.scrollTop, true);
  }
  combine(from, to, duration) {
    return SmoothScrollingOperation.start(from, to, duration);
  }
  static start(from, to, duration) {
    duration = duration + 10;
    const startTime2 = Date.now() - 10;
    return new SmoothScrollingOperation(from, to, startTime2, duration);
  }
};
function easeInCubic(t5) {
  return Math.pow(t5, 3);
}
function easeOutCubic(t5) {
  return 1 - easeInCubic(1 - t5);
}
var HIDE_TIMEOUT = 500;
var SCROLL_WHEEL_SENSITIVITY = 50;
var MouseWheelClassifierItem = class {
  constructor(timestamp, deltaX, deltaY) {
    this.timestamp = timestamp;
    this.deltaX = deltaX;
    this.deltaY = deltaY;
    this.score = 0;
  }
};
var MouseWheelClassifier = class {
  constructor() {
    this._capacity = 5;
    this._memory = [];
    this._front = -1;
    this._rear = -1;
  }
  isPhysicalMouseWheel() {
    if (this._front === -1 && this._rear === -1) {
      return false;
    }
    let remainingInfluence = 1;
    let score2 = 0;
    let iteration = 1;
    let index3 = this._rear;
    do {
      const influence = index3 === this._front ? remainingInfluence : Math.pow(2, -iteration);
      remainingInfluence -= influence;
      score2 += this._memory[index3].score * influence;
      if (index3 === this._front) {
        break;
      }
      index3 = (this._capacity + index3 - 1) % this._capacity;
      iteration++;
    } while (true);
    return score2 <= 0.5;
  }
  accept(timestamp, deltaX, deltaY) {
    const item = new MouseWheelClassifierItem(timestamp, deltaX, deltaY);
    item.score = this._computeScore(item);
    if (this._front === -1 && this._rear === -1) {
      this._memory[0] = item;
      this._front = 0;
      this._rear = 0;
    } else {
      this._rear = (this._rear + 1) % this._capacity;
      if (this._rear === this._front) {
        this._front = (this._front + 1) % this._capacity;
      }
      this._memory[this._rear] = item;
    }
  }
  _computeScore(item) {
    if (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) {
      return 1;
    }
    let score2 = 0.5;
    const prev = this._front === -1 && this._rear === -1 ? null : this._memory[this._rear];
    if (!this._isAlmostInt(item.deltaX) || !this._isAlmostInt(item.deltaY)) {
      score2 += 0.25;
    }
    return Math.min(Math.max(score2, 0), 1);
  }
  _isAlmostInt(value) {
    const delta = Math.abs(Math.round(value) - value);
    return delta < 0.01;
  }
};
MouseWheelClassifier.INSTANCE = new MouseWheelClassifier();
var AbstractScrollableElement = class extends Widget$1 {
  constructor(element, options, scrollable) {
    super();
    this._onScroll = this._register(new Emitter());
    this.onScroll = this._onScroll.event;
    this._onWillScroll = this._register(new Emitter());
    element.style.overflow = "hidden";
    this._options = resolveOptions(options);
    this._scrollable = scrollable;
    this._register(this._scrollable.onScroll((e2) => {
      this._onWillScroll.fire(e2);
      this._onDidScroll(e2);
      this._onScroll.fire(e2);
    }));
    let scrollbarHost = {
      onMouseWheel: (mouseWheelEvent) => this._onMouseWheel(mouseWheelEvent),
      onDragStart: () => this._onDragStart(),
      onDragEnd: () => this._onDragEnd()
    };
    this._verticalScrollbar = this._register(new VerticalScrollbar(this._scrollable, this._options, scrollbarHost));
    this._horizontalScrollbar = this._register(new HorizontalScrollbar(this._scrollable, this._options, scrollbarHost));
    this._domNode = document.createElement("div");
    this._domNode.className = "monaco-scrollable-element " + this._options.className;
    this._domNode.setAttribute("role", "presentation");
    this._domNode.style.position = "relative";
    this._domNode.style.overflow = "hidden";
    this._domNode.appendChild(element);
    this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode);
    this._domNode.appendChild(this._verticalScrollbar.domNode.domNode);
    if (this._options.useShadows) {
      this._leftShadowDomNode = createFastDomNode(document.createElement("div"));
      this._leftShadowDomNode.setClassName("shadow");
      this._domNode.appendChild(this._leftShadowDomNode.domNode);
      this._topShadowDomNode = createFastDomNode(document.createElement("div"));
      this._topShadowDomNode.setClassName("shadow");
      this._domNode.appendChild(this._topShadowDomNode.domNode);
      this._topLeftShadowDomNode = createFastDomNode(document.createElement("div"));
      this._topLeftShadowDomNode.setClassName("shadow top-left-corner");
      this._domNode.appendChild(this._topLeftShadowDomNode.domNode);
    } else {
      this._leftShadowDomNode = null;
      this._topShadowDomNode = null;
      this._topLeftShadowDomNode = null;
    }
    this._listenOnDomNode = this._options.listenOnDomNode || this._domNode;
    this._mouseWheelToDispose = [];
    this._setListeningToMouseWheel(this._options.handleMouseWheel);
    this.onmouseover(this._listenOnDomNode, (e2) => this._onMouseOver(e2));
    this.onnonbubblingmouseout(this._listenOnDomNode, (e2) => this._onMouseOut(e2));
    this._hideTimeout = this._register(new TimeoutTimer());
    this._isDragging = false;
    this._mouseIsOver = false;
    this._shouldRender = true;
    this._revealOnScroll = true;
  }
  dispose() {
    this._mouseWheelToDispose = dispose(this._mouseWheelToDispose);
    super.dispose();
  }
  getDomNode() {
    return this._domNode;
  }
  getOverviewRulerLayoutInfo() {
    return {
      parent: this._domNode,
      insertBefore: this._verticalScrollbar.domNode.domNode
    };
  }
  delegateVerticalScrollbarMouseDown(browserEvent) {
    this._verticalScrollbar.delegateMouseDown(browserEvent);
  }
  getScrollDimensions() {
    return this._scrollable.getScrollDimensions();
  }
  setScrollDimensions(dimensions) {
    this._scrollable.setScrollDimensions(dimensions, false);
  }
  updateClassName(newClassName) {
    this._options.className = newClassName;
    if (isMacintosh) {
      this._options.className += " mac";
    }
    this._domNode.className = "monaco-scrollable-element " + this._options.className;
  }
  updateOptions(newOptions) {
    if (typeof newOptions.handleMouseWheel !== "undefined") {
      this._options.handleMouseWheel = newOptions.handleMouseWheel;
      this._setListeningToMouseWheel(this._options.handleMouseWheel);
    }
    if (typeof newOptions.mouseWheelScrollSensitivity !== "undefined") {
      this._options.mouseWheelScrollSensitivity = newOptions.mouseWheelScrollSensitivity;
    }
    if (typeof newOptions.fastScrollSensitivity !== "undefined") {
      this._options.fastScrollSensitivity = newOptions.fastScrollSensitivity;
    }
    if (typeof newOptions.scrollPredominantAxis !== "undefined") {
      this._options.scrollPredominantAxis = newOptions.scrollPredominantAxis;
    }
    if (typeof newOptions.horizontalScrollbarSize !== "undefined") {
      this._horizontalScrollbar.updateScrollbarSize(newOptions.horizontalScrollbarSize);
    }
    if (!this._options.lazyRender) {
      this._render();
    }
  }
  _setListeningToMouseWheel(shouldListen) {
    let isListening = this._mouseWheelToDispose.length > 0;
    if (isListening === shouldListen) {
      return;
    }
    this._mouseWheelToDispose = dispose(this._mouseWheelToDispose);
    if (shouldListen) {
      let onMouseWheel = (browserEvent) => {
        this._onMouseWheel(new StandardWheelEvent(browserEvent));
      };
      this._mouseWheelToDispose.push(addDisposableListener(this._listenOnDomNode, EventType.MOUSE_WHEEL, onMouseWheel, {passive: false}));
    }
  }
  _onMouseWheel(e2) {
    const classifier = MouseWheelClassifier.INSTANCE;
    {
      const osZoomFactor = window.devicePixelRatio / getZoomFactor();
      if (isWindows || isLinux) {
        classifier.accept(Date.now(), e2.deltaX / osZoomFactor, e2.deltaY / osZoomFactor);
      } else {
        classifier.accept(Date.now(), e2.deltaX, e2.deltaY);
      }
    }
    if (e2.deltaY || e2.deltaX) {
      let deltaY = e2.deltaY * this._options.mouseWheelScrollSensitivity;
      let deltaX = e2.deltaX * this._options.mouseWheelScrollSensitivity;
      if (this._options.scrollPredominantAxis) {
        if (Math.abs(deltaY) >= Math.abs(deltaX)) {
          deltaX = 0;
        } else {
          deltaY = 0;
        }
      }
      if (this._options.flipAxes) {
        [deltaY, deltaX] = [deltaX, deltaY];
      }
      const shiftConvert = !isMacintosh && e2.browserEvent && e2.browserEvent.shiftKey;
      if ((this._options.scrollYToX || shiftConvert) && !deltaX) {
        deltaX = deltaY;
        deltaY = 0;
      }
      if (e2.browserEvent && e2.browserEvent.altKey) {
        deltaX = deltaX * this._options.fastScrollSensitivity;
        deltaY = deltaY * this._options.fastScrollSensitivity;
      }
      const futureScrollPosition = this._scrollable.getFutureScrollPosition();
      let desiredScrollPosition = {};
      if (deltaY) {
        const desiredScrollTop = futureScrollPosition.scrollTop - SCROLL_WHEEL_SENSITIVITY * deltaY;
        this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop);
      }
      if (deltaX) {
        const desiredScrollLeft = futureScrollPosition.scrollLeft - SCROLL_WHEEL_SENSITIVITY * deltaX;
        this._horizontalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollLeft);
      }
      desiredScrollPosition = this._scrollable.validateScrollPosition(desiredScrollPosition);
      if (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) {
        const canPerformSmoothScroll = this._options.mouseWheelSmoothScroll && classifier.isPhysicalMouseWheel();
        if (canPerformSmoothScroll) {
          this._scrollable.setScrollPositionSmooth(desiredScrollPosition);
        } else {
          this._scrollable.setScrollPositionNow(desiredScrollPosition);
        }
        this._shouldRender = true;
      }
    }
    if (this._options.alwaysConsumeMouseWheel || this._shouldRender) {
      e2.preventDefault();
      e2.stopPropagation();
    }
  }
  _onDidScroll(e2) {
    this._shouldRender = this._horizontalScrollbar.onDidScroll(e2) || this._shouldRender;
    this._shouldRender = this._verticalScrollbar.onDidScroll(e2) || this._shouldRender;
    if (this._options.useShadows) {
      this._shouldRender = true;
    }
    if (this._revealOnScroll) {
      this._reveal();
    }
    if (!this._options.lazyRender) {
      this._render();
    }
  }
  renderNow() {
    if (!this._options.lazyRender) {
      throw new Error("Please use `lazyRender` together with `renderNow`!");
    }
    this._render();
  }
  _render() {
    if (!this._shouldRender) {
      return;
    }
    this._shouldRender = false;
    this._horizontalScrollbar.render();
    this._verticalScrollbar.render();
    if (this._options.useShadows) {
      const scrollState = this._scrollable.getCurrentScrollPosition();
      let enableTop = scrollState.scrollTop > 0;
      let enableLeft = scrollState.scrollLeft > 0;
      this._leftShadowDomNode.setClassName("shadow" + (enableLeft ? " left" : ""));
      this._topShadowDomNode.setClassName("shadow" + (enableTop ? " top" : ""));
      this._topLeftShadowDomNode.setClassName("shadow top-left-corner" + (enableTop ? " top" : "") + (enableLeft ? " left" : ""));
    }
  }
  _onDragStart() {
    this._isDragging = true;
    this._reveal();
  }
  _onDragEnd() {
    this._isDragging = false;
    this._hide();
  }
  _onMouseOut(e2) {
    this._mouseIsOver = false;
    this._hide();
  }
  _onMouseOver(e2) {
    this._mouseIsOver = true;
    this._reveal();
  }
  _reveal() {
    this._verticalScrollbar.beginReveal();
    this._horizontalScrollbar.beginReveal();
    this._scheduleHide();
  }
  _hide() {
    if (!this._mouseIsOver && !this._isDragging) {
      this._verticalScrollbar.beginHide();
      this._horizontalScrollbar.beginHide();
    }
  }
  _scheduleHide() {
    if (!this._mouseIsOver && !this._isDragging) {
      this._hideTimeout.cancelAndSet(() => this._hide(), HIDE_TIMEOUT);
    }
  }
};
var ScrollableElement = class extends AbstractScrollableElement {
  constructor(element, options) {
    options = options || {};
    options.mouseWheelSmoothScroll = false;
    const scrollable = new Scrollable(0, (callback) => scheduleAtNextAnimationFrame(callback));
    super(element, options, scrollable);
    this._register(scrollable);
  }
  setScrollPosition(update) {
    this._scrollable.setScrollPositionNow(update);
  }
};
var SmoothScrollableElement = class extends AbstractScrollableElement {
  constructor(element, options, scrollable) {
    super(element, options, scrollable);
  }
  setScrollPosition(update) {
    this._scrollable.setScrollPositionNow(update);
  }
  getScrollPosition() {
    return this._scrollable.getCurrentScrollPosition();
  }
};
var DomScrollableElement = class extends ScrollableElement {
  constructor(element, options) {
    super(element, options);
    this._element = element;
    this.onScroll((e2) => {
      if (e2.scrollTopChanged) {
        this._element.scrollTop = e2.scrollTop;
      }
      if (e2.scrollLeftChanged) {
        this._element.scrollLeft = e2.scrollLeft;
      }
    });
    this.scanDomNode();
  }
  scanDomNode() {
    this.setScrollDimensions({
      width: this._element.clientWidth,
      scrollWidth: this._element.scrollWidth,
      height: this._element.clientHeight,
      scrollHeight: this._element.scrollHeight
    });
    this.setScrollPosition({
      scrollLeft: this._element.scrollLeft,
      scrollTop: this._element.scrollTop
    });
  }
};
function resolveOptions(opts) {
  let result = {
    lazyRender: typeof opts.lazyRender !== "undefined" ? opts.lazyRender : false,
    className: typeof opts.className !== "undefined" ? opts.className : "",
    useShadows: typeof opts.useShadows !== "undefined" ? opts.useShadows : true,
    handleMouseWheel: typeof opts.handleMouseWheel !== "undefined" ? opts.handleMouseWheel : true,
    flipAxes: typeof opts.flipAxes !== "undefined" ? opts.flipAxes : false,
    alwaysConsumeMouseWheel: typeof opts.alwaysConsumeMouseWheel !== "undefined" ? opts.alwaysConsumeMouseWheel : false,
    scrollYToX: typeof opts.scrollYToX !== "undefined" ? opts.scrollYToX : false,
    mouseWheelScrollSensitivity: typeof opts.mouseWheelScrollSensitivity !== "undefined" ? opts.mouseWheelScrollSensitivity : 1,
    fastScrollSensitivity: typeof opts.fastScrollSensitivity !== "undefined" ? opts.fastScrollSensitivity : 5,
    scrollPredominantAxis: typeof opts.scrollPredominantAxis !== "undefined" ? opts.scrollPredominantAxis : true,
    mouseWheelSmoothScroll: typeof opts.mouseWheelSmoothScroll !== "undefined" ? opts.mouseWheelSmoothScroll : true,
    arrowSize: typeof opts.arrowSize !== "undefined" ? opts.arrowSize : 11,
    listenOnDomNode: typeof opts.listenOnDomNode !== "undefined" ? opts.listenOnDomNode : null,
    horizontal: typeof opts.horizontal !== "undefined" ? opts.horizontal : 1,
    horizontalScrollbarSize: typeof opts.horizontalScrollbarSize !== "undefined" ? opts.horizontalScrollbarSize : 10,
    horizontalSliderSize: typeof opts.horizontalSliderSize !== "undefined" ? opts.horizontalSliderSize : 0,
    horizontalHasArrows: typeof opts.horizontalHasArrows !== "undefined" ? opts.horizontalHasArrows : false,
    vertical: typeof opts.vertical !== "undefined" ? opts.vertical : 1,
    verticalScrollbarSize: typeof opts.verticalScrollbarSize !== "undefined" ? opts.verticalScrollbarSize : 10,
    verticalHasArrows: typeof opts.verticalHasArrows !== "undefined" ? opts.verticalHasArrows : false,
    verticalSliderSize: typeof opts.verticalSliderSize !== "undefined" ? opts.verticalSliderSize : 0
  };
  result.horizontalSliderSize = typeof opts.horizontalSliderSize !== "undefined" ? opts.horizontalSliderSize : result.horizontalScrollbarSize;
  result.verticalSliderSize = typeof opts.verticalSliderSize !== "undefined" ? opts.verticalSliderSize : result.verticalScrollbarSize;
  if (isMacintosh) {
    result.className += " mac";
  }
  return result;
}
var EditorScrollbar$1 = class extends ViewPart {
  constructor(context2, linesContent, viewDomNode, overflowGuardDomNode) {
    super(context2);
    const options = this._context.configuration.options;
    const scrollbar = options.get(84);
    const mouseWheelScrollSensitivity = options.get(58);
    const fastScrollSensitivity = options.get(28);
    const scrollPredominantAxis = options.get(87);
    const scrollbarOptions = {
      listenOnDomNode: viewDomNode.domNode,
      className: "editor-scrollable " + getThemeTypeSelector(context2.theme.type),
      useShadows: false,
      lazyRender: true,
      vertical: scrollbar.vertical,
      horizontal: scrollbar.horizontal,
      verticalHasArrows: scrollbar.verticalHasArrows,
      horizontalHasArrows: scrollbar.horizontalHasArrows,
      verticalScrollbarSize: scrollbar.verticalScrollbarSize,
      verticalSliderSize: scrollbar.verticalSliderSize,
      horizontalScrollbarSize: scrollbar.horizontalScrollbarSize,
      horizontalSliderSize: scrollbar.horizontalSliderSize,
      handleMouseWheel: scrollbar.handleMouseWheel,
      alwaysConsumeMouseWheel: scrollbar.alwaysConsumeMouseWheel,
      arrowSize: scrollbar.arrowSize,
      mouseWheelScrollSensitivity,
      fastScrollSensitivity,
      scrollPredominantAxis
    };
    this.scrollbar = this._register(new SmoothScrollableElement(linesContent.domNode, scrollbarOptions, this._context.viewLayout.getScrollable()));
    PartFingerprints.write(this.scrollbar.getDomNode(), 5);
    this.scrollbarDomNode = createFastDomNode(this.scrollbar.getDomNode());
    this.scrollbarDomNode.setPosition("absolute");
    this._setLayout();
    const onBrowserDesperateReveal = (domNode, lookAtScrollTop, lookAtScrollLeft) => {
      const newScrollPosition = {};
      if (lookAtScrollTop) {
        const deltaTop = domNode.scrollTop;
        if (deltaTop) {
          newScrollPosition.scrollTop = this._context.viewLayout.getCurrentScrollTop() + deltaTop;
          domNode.scrollTop = 0;
        }
      }
      if (lookAtScrollLeft) {
        const deltaLeft = domNode.scrollLeft;
        if (deltaLeft) {
          newScrollPosition.scrollLeft = this._context.viewLayout.getCurrentScrollLeft() + deltaLeft;
          domNode.scrollLeft = 0;
        }
      }
      this._context.model.setScrollPosition(newScrollPosition, 1);
    };
    this._register(addDisposableListener(viewDomNode.domNode, "scroll", (e2) => onBrowserDesperateReveal(viewDomNode.domNode, true, true)));
    this._register(addDisposableListener(linesContent.domNode, "scroll", (e2) => onBrowserDesperateReveal(linesContent.domNode, true, false)));
    this._register(addDisposableListener(overflowGuardDomNode.domNode, "scroll", (e2) => onBrowserDesperateReveal(overflowGuardDomNode.domNode, true, false)));
    this._register(addDisposableListener(this.scrollbarDomNode.domNode, "scroll", (e2) => onBrowserDesperateReveal(this.scrollbarDomNode.domNode, true, false)));
  }
  dispose() {
    super.dispose();
  }
  _setLayout() {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this.scrollbarDomNode.setLeft(layoutInfo.contentLeft);
    const minimap = options.get(56);
    const side = minimap.side;
    if (side === "right") {
      this.scrollbarDomNode.setWidth(layoutInfo.contentWidth + layoutInfo.minimap.minimapWidth);
    } else {
      this.scrollbarDomNode.setWidth(layoutInfo.contentWidth);
    }
    this.scrollbarDomNode.setHeight(layoutInfo.height);
  }
  getOverviewRulerLayoutInfo() {
    return this.scrollbar.getOverviewRulerLayoutInfo();
  }
  getDomNode() {
    return this.scrollbarDomNode;
  }
  delegateVerticalScrollbarMouseDown(browserEvent) {
    this.scrollbar.delegateVerticalScrollbarMouseDown(browserEvent);
  }
  onConfigurationChanged(e2) {
    if (e2.hasChanged(84) || e2.hasChanged(58) || e2.hasChanged(28)) {
      const options = this._context.configuration.options;
      const scrollbar = options.get(84);
      const mouseWheelScrollSensitivity = options.get(58);
      const fastScrollSensitivity = options.get(28);
      const scrollPredominantAxis = options.get(87);
      const newOpts = {
        handleMouseWheel: scrollbar.handleMouseWheel,
        mouseWheelScrollSensitivity,
        fastScrollSensitivity,
        scrollPredominantAxis
      };
      this.scrollbar.updateOptions(newOpts);
    }
    if (e2.hasChanged(117)) {
      this._setLayout();
    }
    return true;
  }
  onScrollChanged(e2) {
    return true;
  }
  onThemeChanged(e2) {
    this.scrollbar.updateClassName("editor-scrollable " + getThemeTypeSelector(this._context.theme.type));
    return true;
  }
  prepareRender(ctx) {
  }
  render(ctx) {
    this.scrollbar.renderNow();
  }
};
function __snowpack__injectStyle$9(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$9("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-editor .glyph-margin {\r\n	position: absolute;\r\n	top: 0;\r\n}\r\n\r\n/*\r\n	Keeping name short for faster parsing.\r\n	cgmr = core glyph margin rendering (div)\r\n*/\r\n.monaco-editor .margin-view-overlays .cgmr {\r\n	position: absolute;\r\n	display: flex;\r\n	align-items: center;\r\n	justify-content: center;\r\n}\r\n");
var DecorationToRender = class {
  constructor(startLineNumber, endLineNumber, className) {
    this.startLineNumber = +startLineNumber;
    this.endLineNumber = +endLineNumber;
    this.className = String(className);
  }
};
var DedupOverlay = class extends DynamicViewOverlay {
  _render(visibleStartLineNumber, visibleEndLineNumber, decorations) {
    const output2 = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      output2[lineIndex] = [];
    }
    if (decorations.length === 0) {
      return output2;
    }
    decorations.sort((a2, b2) => {
      if (a2.className === b2.className) {
        if (a2.startLineNumber === b2.startLineNumber) {
          return a2.endLineNumber - b2.endLineNumber;
        }
        return a2.startLineNumber - b2.startLineNumber;
      }
      return a2.className < b2.className ? -1 : 1;
    });
    let prevClassName = null;
    let prevEndLineIndex = 0;
    for (let i3 = 0, len2 = decorations.length; i3 < len2; i3++) {
      const d2 = decorations[i3];
      const className = d2.className;
      let startLineIndex = Math.max(d2.startLineNumber, visibleStartLineNumber) - visibleStartLineNumber;
      const endLineIndex = Math.min(d2.endLineNumber, visibleEndLineNumber) - visibleStartLineNumber;
      if (prevClassName === className) {
        startLineIndex = Math.max(prevEndLineIndex + 1, startLineIndex);
        prevEndLineIndex = Math.max(prevEndLineIndex, endLineIndex);
      } else {
        prevClassName = className;
        prevEndLineIndex = endLineIndex;
      }
      for (let i4 = startLineIndex; i4 <= prevEndLineIndex; i4++) {
        output2[i4].push(prevClassName);
      }
    }
    return output2;
  }
};
var GlyphMarginOverlay = class extends DedupOverlay {
  constructor(context2) {
    super();
    this._context = context2;
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._lineHeight = options.get(51);
    this._glyphMargin = options.get(42);
    this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
    this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._lineHeight = options.get(51);
    this._glyphMargin = options.get(42);
    this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
    this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
    return true;
  }
  onDecorationsChanged(e2) {
    return true;
  }
  onFlushed(e2) {
    return true;
  }
  onLinesChanged(e2) {
    return true;
  }
  onLinesDeleted(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollTopChanged;
  }
  onZonesChanged(e2) {
    return true;
  }
  _getDecorations(ctx) {
    const decorations = ctx.getDecorationsInViewport();
    let r3 = [], rLen = 0;
    for (let i3 = 0, len2 = decorations.length; i3 < len2; i3++) {
      const d2 = decorations[i3];
      const glyphMarginClassName = d2.options.glyphMarginClassName;
      if (glyphMarginClassName) {
        r3[rLen++] = new DecorationToRender(d2.range.startLineNumber, d2.range.endLineNumber, glyphMarginClassName);
      }
    }
    return r3;
  }
  prepareRender(ctx) {
    if (!this._glyphMargin) {
      this._renderResult = null;
      return;
    }
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
    const lineHeight = this._lineHeight.toString();
    const left2 = this._glyphMarginLeft.toString();
    const width2 = this._glyphMarginWidth.toString();
    const common = '" style="left:' + left2 + "px;width:" + width2 + "px;height:" + lineHeight + 'px;"></div>';
    const output2 = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      const classNames2 = toRender[lineIndex];
      if (classNames2.length === 0) {
        output2[lineIndex] = "";
      } else {
        output2[lineIndex] = '<div class="cgmr codicon ' + classNames2.join(" ") + common;
      }
    }
    this._renderResult = output2;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
      return "";
    }
    return this._renderResult[lineIndex];
  }
};
function __snowpack__injectStyle$a(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$a("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n/*\r\n	Keeping name short for faster parsing.\r\n	cigr = core ident guides rendering (div)\r\n*/\r\n.monaco-editor .lines-content .cigr {\r\n	position: absolute;\r\n}\r\n.monaco-editor .lines-content .cigra {\r\n	position: absolute;\r\n}\r\n");
var IndentGuidesOverlay = class extends DynamicViewOverlay {
  constructor(context2) {
    super();
    this._context = context2;
    this._primaryLineNumber = 0;
    const options = this._context.configuration.options;
    const wrappingInfo = options.get(118);
    const fontInfo = options.get(36);
    this._lineHeight = options.get(51);
    this._spaceWidth = fontInfo.spaceWidth;
    this._enabled = options.get(75);
    this._activeIndentEnabled = options.get(45);
    this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth;
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    const wrappingInfo = options.get(118);
    const fontInfo = options.get(36);
    this._lineHeight = options.get(51);
    this._spaceWidth = fontInfo.spaceWidth;
    this._enabled = options.get(75);
    this._activeIndentEnabled = options.get(45);
    this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth;
    return true;
  }
  onCursorStateChanged(e2) {
    const selection2 = e2.selections[0];
    const newPrimaryLineNumber = selection2.isEmpty() ? selection2.positionLineNumber : 0;
    if (this._primaryLineNumber !== newPrimaryLineNumber) {
      this._primaryLineNumber = newPrimaryLineNumber;
      return true;
    }
    return false;
  }
  onDecorationsChanged(e2) {
    return true;
  }
  onFlushed(e2) {
    return true;
  }
  onLinesChanged(e2) {
    return true;
  }
  onLinesDeleted(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollTopChanged;
  }
  onZonesChanged(e2) {
    return true;
  }
  onLanguageConfigurationChanged(e2) {
    return true;
  }
  prepareRender(ctx) {
    if (!this._enabled) {
      this._renderResult = null;
      return;
    }
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const {indentSize} = this._context.model.getTextModelOptions();
    const indentWidth = indentSize * this._spaceWidth;
    const scrollWidth = ctx.scrollWidth;
    const lineHeight = this._lineHeight;
    const indents = this._context.model.getLinesIndentGuides(visibleStartLineNumber, visibleEndLineNumber);
    let activeIndentStartLineNumber = 0;
    let activeIndentEndLineNumber = 0;
    let activeIndentLevel = 0;
    if (this._activeIndentEnabled && this._primaryLineNumber) {
      const activeIndentInfo = this._context.model.getActiveIndentGuide(this._primaryLineNumber, visibleStartLineNumber, visibleEndLineNumber);
      activeIndentStartLineNumber = activeIndentInfo.startLineNumber;
      activeIndentEndLineNumber = activeIndentInfo.endLineNumber;
      activeIndentLevel = activeIndentInfo.indent;
    }
    const output2 = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const containsActiveIndentGuide = activeIndentStartLineNumber <= lineNumber && lineNumber <= activeIndentEndLineNumber;
      const lineIndex = lineNumber - visibleStartLineNumber;
      const indent = indents[lineIndex];
      let result = "";
      if (indent >= 1) {
        const leftMostVisiblePosition = ctx.visibleRangeForPosition(new Position(lineNumber, 1));
        let left2 = leftMostVisiblePosition ? leftMostVisiblePosition.left : 0;
        for (let i3 = 1; i3 <= indent; i3++) {
          const className = containsActiveIndentGuide && i3 === activeIndentLevel ? "cigra" : "cigr";
          result += `<div class="${className}" style="left:${left2}px;height:${lineHeight}px;width:${indentWidth}px"></div>`;
          left2 += indentWidth;
          if (left2 > scrollWidth || this._maxIndentLeft > 0 && left2 > this._maxIndentLeft) {
            break;
          }
        }
      }
      output2[lineIndex] = result;
    }
    this._renderResult = output2;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
      return "";
    }
    return this._renderResult[lineIndex];
  }
};
registerThemingParticipant((theme, collector) => {
  const editorIndentGuidesColor = theme.getColor(editorIndentGuides);
  if (editorIndentGuidesColor) {
    collector.addRule(`.monaco-editor .lines-content .cigr { box-shadow: 1px 0 0 0 ${editorIndentGuidesColor} inset; }`);
  }
  const editorActiveIndentGuidesColor = theme.getColor(editorActiveIndentGuides) || editorIndentGuidesColor;
  if (editorActiveIndentGuidesColor) {
    collector.addRule(`.monaco-editor .lines-content .cigra { box-shadow: 1px 0 0 0 ${editorActiveIndentGuidesColor} inset; }`);
  }
});
function __snowpack__injectStyle$b(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$b("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n/* Uncomment to see lines flashing when they're painted */\r\n/*.monaco-editor .view-lines > .view-line {\r\n	background-color: none;\r\n	animation-name: flash-background;\r\n	animation-duration: 800ms;\r\n}\r\n@keyframes flash-background {\r\n	0%   { background-color: lightgreen; }\r\n	100% { background-color: none }\r\n}*/\r\n\r\n.monaco-editor.no-user-select .lines-content,\r\n.monaco-editor.no-user-select .view-line,\r\n.monaco-editor.no-user-select .view-lines {\r\n	user-select: none;\r\n	-webkit-user-select: none;\r\n	-ms-user-select: none;\r\n}\r\n\r\n.monaco-editor .view-lines {\r\n	white-space: nowrap;\r\n}\r\n\r\n.monaco-editor .view-line {\r\n	position: absolute;\r\n	width: 100%;\r\n}\r\n\r\n.monaco-editor .mtkz {\r\n	display: inline-block;\r\n}\r\n\r\n/* TODO@tokenization bootstrap fix */\r\n/*.monaco-editor .view-line > span > span {\r\n	float: none;\r\n	min-height: inherit;\r\n	margin-left: inherit;\r\n}*/\r\n");
var LastRenderedData = class {
  constructor() {
    this._currentVisibleRange = new Range(1, 1, 1, 1);
  }
  getCurrentVisibleRange() {
    return this._currentVisibleRange;
  }
  setCurrentVisibleRange(currentVisibleRange) {
    this._currentVisibleRange = currentVisibleRange;
  }
};
var HorizontalRevealRangeRequest = class {
  constructor(lineNumber, startColumn, endColumn, startScrollTop, stopScrollTop, scrollType) {
    this.lineNumber = lineNumber;
    this.startColumn = startColumn;
    this.endColumn = endColumn;
    this.startScrollTop = startScrollTop;
    this.stopScrollTop = stopScrollTop;
    this.scrollType = scrollType;
    this.type = "range";
    this.minLineNumber = lineNumber;
    this.maxLineNumber = lineNumber;
  }
};
var HorizontalRevealSelectionsRequest = class {
  constructor(selections, startScrollTop, stopScrollTop, scrollType) {
    this.selections = selections;
    this.startScrollTop = startScrollTop;
    this.stopScrollTop = stopScrollTop;
    this.scrollType = scrollType;
    this.type = "selections";
    let minLineNumber = selections[0].startLineNumber;
    let maxLineNumber = selections[0].endLineNumber;
    for (let i3 = 1, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      minLineNumber = Math.min(minLineNumber, selection2.startLineNumber);
      maxLineNumber = Math.max(maxLineNumber, selection2.endLineNumber);
    }
    this.minLineNumber = minLineNumber;
    this.maxLineNumber = maxLineNumber;
  }
};
var ViewLines = class extends ViewPart {
  constructor(context2, linesContent) {
    super(context2);
    this._linesContent = linesContent;
    this._textRangeRestingSpot = document.createElement("div");
    this._visibleLines = new VisibleLinesCollection(this);
    this.domNode = this._visibleLines.domNode;
    const conf = this._context.configuration;
    const options = this._context.configuration.options;
    const fontInfo = options.get(36);
    const wrappingInfo = options.get(118);
    this._lineHeight = options.get(51);
    this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this._isViewportWrapping = wrappingInfo.isViewportWrapping;
    this._revealHorizontalRightPadding = options.get(81);
    this._cursorSurroundingLines = options.get(20);
    this._cursorSurroundingLinesStyle = options.get(21);
    this._canUseLayerHinting = !options.get(23);
    this._viewLineOptions = new ViewLineOptions(conf, this._context.theme.type);
    PartFingerprints.write(this.domNode, 7);
    this.domNode.setClassName(`view-lines ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
    Configuration$1.applyFontInfo(this.domNode, fontInfo);
    this._maxLineWidth = 0;
    this._asyncUpdateLineWidths = new RunOnceScheduler(() => {
      this._updateLineWidthsSlow();
    }, 200);
    this._asyncCheckMonospaceFontAssumptions = new RunOnceScheduler(() => {
      this._checkMonospaceFontAssumptions();
    }, 2e3);
    this._lastRenderedData = new LastRenderedData();
    this._horizontalRevealRequest = null;
  }
  dispose() {
    this._asyncUpdateLineWidths.dispose();
    this._asyncCheckMonospaceFontAssumptions.dispose();
    super.dispose();
  }
  getDomNode() {
    return this.domNode;
  }
  createVisibleLine() {
    return new ViewLine(this._viewLineOptions);
  }
  onConfigurationChanged(e2) {
    this._visibleLines.onConfigurationChanged(e2);
    if (e2.hasChanged(118)) {
      this._maxLineWidth = 0;
    }
    const options = this._context.configuration.options;
    const fontInfo = options.get(36);
    const wrappingInfo = options.get(118);
    this._lineHeight = options.get(51);
    this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this._isViewportWrapping = wrappingInfo.isViewportWrapping;
    this._revealHorizontalRightPadding = options.get(81);
    this._cursorSurroundingLines = options.get(20);
    this._cursorSurroundingLinesStyle = options.get(21);
    this._canUseLayerHinting = !options.get(23);
    Configuration$1.applyFontInfo(this.domNode, fontInfo);
    this._onOptionsMaybeChanged();
    if (e2.hasChanged(117)) {
      this._maxLineWidth = 0;
    }
    return true;
  }
  _onOptionsMaybeChanged() {
    const conf = this._context.configuration;
    const newViewLineOptions = new ViewLineOptions(conf, this._context.theme.type);
    if (!this._viewLineOptions.equals(newViewLineOptions)) {
      this._viewLineOptions = newViewLineOptions;
      const startLineNumber = this._visibleLines.getStartLineNumber();
      const endLineNumber = this._visibleLines.getEndLineNumber();
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const line = this._visibleLines.getVisibleLine(lineNumber);
        line.onOptionsChanged(this._viewLineOptions);
      }
      return true;
    }
    return false;
  }
  onCursorStateChanged(e2) {
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    let r3 = false;
    for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
      r3 = this._visibleLines.getVisibleLine(lineNumber).onSelectionChanged() || r3;
    }
    return r3;
  }
  onDecorationsChanged(e2) {
    {
      const rendStartLineNumber = this._visibleLines.getStartLineNumber();
      const rendEndLineNumber = this._visibleLines.getEndLineNumber();
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        this._visibleLines.getVisibleLine(lineNumber).onDecorationsChanged();
      }
    }
    return true;
  }
  onFlushed(e2) {
    const shouldRender = this._visibleLines.onFlushed(e2);
    this._maxLineWidth = 0;
    return shouldRender;
  }
  onLinesChanged(e2) {
    return this._visibleLines.onLinesChanged(e2);
  }
  onLinesDeleted(e2) {
    return this._visibleLines.onLinesDeleted(e2);
  }
  onLinesInserted(e2) {
    return this._visibleLines.onLinesInserted(e2);
  }
  onRevealRangeRequest(e2) {
    const desiredScrollTop = this._computeScrollTopToRevealRange(this._context.viewLayout.getFutureViewport(), e2.source, e2.range, e2.selections, e2.verticalType);
    if (desiredScrollTop === -1) {
      return false;
    }
    let newScrollPosition = this._context.viewLayout.validateScrollPosition({scrollTop: desiredScrollTop});
    if (e2.revealHorizontal) {
      if (e2.range && e2.range.startLineNumber !== e2.range.endLineNumber) {
        newScrollPosition = {
          scrollTop: newScrollPosition.scrollTop,
          scrollLeft: 0
        };
      } else if (e2.range) {
        this._horizontalRevealRequest = new HorizontalRevealRangeRequest(e2.range.startLineNumber, e2.range.startColumn, e2.range.endColumn, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e2.scrollType);
      } else if (e2.selections && e2.selections.length > 0) {
        this._horizontalRevealRequest = new HorizontalRevealSelectionsRequest(e2.selections, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e2.scrollType);
      }
    } else {
      this._horizontalRevealRequest = null;
    }
    const scrollTopDelta = Math.abs(this._context.viewLayout.getCurrentScrollTop() - newScrollPosition.scrollTop);
    const scrollType = scrollTopDelta <= this._lineHeight ? 1 : e2.scrollType;
    this._context.model.setScrollPosition(newScrollPosition, scrollType);
    return true;
  }
  onScrollChanged(e2) {
    if (this._horizontalRevealRequest && e2.scrollLeftChanged) {
      this._horizontalRevealRequest = null;
    }
    if (this._horizontalRevealRequest && e2.scrollTopChanged) {
      const min2 = Math.min(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);
      const max2 = Math.max(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);
      if (e2.scrollTop < min2 || e2.scrollTop > max2) {
        this._horizontalRevealRequest = null;
      }
    }
    this.domNode.setWidth(e2.scrollWidth);
    return this._visibleLines.onScrollChanged(e2) || true;
  }
  onTokensChanged(e2) {
    return this._visibleLines.onTokensChanged(e2);
  }
  onZonesChanged(e2) {
    this._context.model.setMaxLineWidth(this._maxLineWidth);
    return this._visibleLines.onZonesChanged(e2);
  }
  onThemeChanged(e2) {
    return this._onOptionsMaybeChanged();
  }
  getPositionFromDOMInfo(spanNode, offset2) {
    const viewLineDomNode = this._getViewLineDomNode(spanNode);
    if (viewLineDomNode === null) {
      return null;
    }
    const lineNumber = this._getLineNumberFor(viewLineDomNode);
    if (lineNumber === -1) {
      return null;
    }
    if (lineNumber < 1 || lineNumber > this._context.model.getLineCount()) {
      return null;
    }
    if (this._context.model.getLineMaxColumn(lineNumber) === 1) {
      return new Position(lineNumber, 1);
    }
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
      return null;
    }
    let column = this._visibleLines.getVisibleLine(lineNumber).getColumnOfNodeOffset(lineNumber, spanNode, offset2);
    const minColumn = this._context.model.getLineMinColumn(lineNumber);
    if (column < minColumn) {
      column = minColumn;
    }
    return new Position(lineNumber, column);
  }
  _getViewLineDomNode(node) {
    while (node && node.nodeType === 1) {
      if (node.className === ViewLine.CLASS_NAME) {
        return node;
      }
      node = node.parentElement;
    }
    return null;
  }
  _getLineNumberFor(domNode) {
    const startLineNumber = this._visibleLines.getStartLineNumber();
    const endLineNumber = this._visibleLines.getEndLineNumber();
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const line = this._visibleLines.getVisibleLine(lineNumber);
      if (domNode === line.getDomNode()) {
        return lineNumber;
      }
    }
    return -1;
  }
  getLineWidth(lineNumber) {
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
      return -1;
    }
    return this._visibleLines.getVisibleLine(lineNumber).getWidth();
  }
  linesVisibleRangesForRange(_range, includeNewLines) {
    if (this.shouldRender()) {
      return null;
    }
    const originalEndLineNumber = _range.endLineNumber;
    const range3 = Range.intersectRanges(_range, this._lastRenderedData.getCurrentVisibleRange());
    if (!range3) {
      return null;
    }
    let visibleRanges = [], visibleRangesLen = 0;
    const domReadingContext = new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
    let nextLineModelLineNumber = 0;
    if (includeNewLines) {
      nextLineModelLineNumber = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new Position(range3.startLineNumber, 1)).lineNumber;
    }
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    for (let lineNumber = range3.startLineNumber; lineNumber <= range3.endLineNumber; lineNumber++) {
      if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
        continue;
      }
      const startColumn = lineNumber === range3.startLineNumber ? range3.startColumn : 1;
      const endColumn = lineNumber === range3.endLineNumber ? range3.endColumn : this._context.model.getLineMaxColumn(lineNumber);
      const visibleRangesForLine = this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(startColumn, endColumn, domReadingContext);
      if (!visibleRangesForLine) {
        continue;
      }
      if (includeNewLines && lineNumber < originalEndLineNumber) {
        const currentLineModelLineNumber = nextLineModelLineNumber;
        nextLineModelLineNumber = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new Position(lineNumber + 1, 1)).lineNumber;
        if (currentLineModelLineNumber !== nextLineModelLineNumber) {
          visibleRangesForLine.ranges[visibleRangesForLine.ranges.length - 1].width += this._typicalHalfwidthCharacterWidth;
        }
      }
      visibleRanges[visibleRangesLen++] = new LineVisibleRanges(visibleRangesForLine.outsideRenderedLine, lineNumber, visibleRangesForLine.ranges);
    }
    if (visibleRangesLen === 0) {
      return null;
    }
    return visibleRanges;
  }
  _visibleRangesForLineRange(lineNumber, startColumn, endColumn) {
    if (this.shouldRender()) {
      return null;
    }
    if (lineNumber < this._visibleLines.getStartLineNumber() || lineNumber > this._visibleLines.getEndLineNumber()) {
      return null;
    }
    return this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(startColumn, endColumn, new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot));
  }
  visibleRangeForPosition(position2) {
    const visibleRanges = this._visibleRangesForLineRange(position2.lineNumber, position2.column, position2.column);
    if (!visibleRanges) {
      return null;
    }
    return new HorizontalPosition(visibleRanges.outsideRenderedLine, visibleRanges.ranges[0].left);
  }
  updateLineWidths() {
    this._updateLineWidths(false);
  }
  _updateLineWidthsFast() {
    return this._updateLineWidths(true);
  }
  _updateLineWidthsSlow() {
    this._updateLineWidths(false);
  }
  _updateLineWidths(fast) {
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    let localMaxLineWidth = 1;
    let allWidthsComputed = true;
    for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
      const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
      if (fast && !visibleLine.getWidthIsFast()) {
        allWidthsComputed = false;
        continue;
      }
      localMaxLineWidth = Math.max(localMaxLineWidth, visibleLine.getWidth());
    }
    if (allWidthsComputed && rendStartLineNumber === 1 && rendEndLineNumber === this._context.model.getLineCount()) {
      this._maxLineWidth = 0;
    }
    this._ensureMaxLineWidth(localMaxLineWidth);
    return allWidthsComputed;
  }
  _checkMonospaceFontAssumptions() {
    let longestLineNumber = -1;
    let longestWidth = -1;
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
      const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
      if (visibleLine.needsMonospaceFontCheck()) {
        const lineWidth = visibleLine.getWidth();
        if (lineWidth > longestWidth) {
          longestWidth = lineWidth;
          longestLineNumber = lineNumber;
        }
      }
    }
    if (longestLineNumber === -1) {
      return;
    }
    if (!this._visibleLines.getVisibleLine(longestLineNumber).monospaceAssumptionsAreValid()) {
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
        visibleLine.onMonospaceAssumptionsInvalidated();
      }
    }
  }
  prepareRender() {
    throw new Error("Not supported");
  }
  render() {
    throw new Error("Not supported");
  }
  renderText(viewportData) {
    this._visibleLines.renderLines(viewportData);
    this._lastRenderedData.setCurrentVisibleRange(viewportData.visibleRange);
    this.domNode.setWidth(this._context.viewLayout.getScrollWidth());
    this.domNode.setHeight(Math.min(this._context.viewLayout.getScrollHeight(), 1e6));
    if (this._horizontalRevealRequest) {
      const horizontalRevealRequest = this._horizontalRevealRequest;
      if (viewportData.startLineNumber <= horizontalRevealRequest.minLineNumber && horizontalRevealRequest.maxLineNumber <= viewportData.endLineNumber) {
        this._horizontalRevealRequest = null;
        this.onDidRender();
        const newScrollLeft = this._computeScrollLeftToReveal(horizontalRevealRequest);
        if (newScrollLeft) {
          if (!this._isViewportWrapping) {
            this._ensureMaxLineWidth(newScrollLeft.maxHorizontalOffset);
          }
          this._context.model.setScrollPosition({
            scrollLeft: newScrollLeft.scrollLeft
          }, horizontalRevealRequest.scrollType);
        }
      }
    }
    if (!this._updateLineWidthsFast()) {
      this._asyncUpdateLineWidths.schedule();
    }
    if (isLinux && !this._asyncCheckMonospaceFontAssumptions.isScheduled()) {
      const rendStartLineNumber = this._visibleLines.getStartLineNumber();
      const rendEndLineNumber = this._visibleLines.getEndLineNumber();
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
        if (visibleLine.needsMonospaceFontCheck()) {
          this._asyncCheckMonospaceFontAssumptions.schedule();
          break;
        }
      }
    }
    this._linesContent.setLayerHinting(this._canUseLayerHinting);
    this._linesContent.setContain("strict");
    const adjustedScrollTop = this._context.viewLayout.getCurrentScrollTop() - viewportData.bigNumbersDelta;
    this._linesContent.setTop(-adjustedScrollTop);
    this._linesContent.setLeft(-this._context.viewLayout.getCurrentScrollLeft());
  }
  _ensureMaxLineWidth(lineWidth) {
    const iLineWidth = Math.ceil(lineWidth);
    if (this._maxLineWidth < iLineWidth) {
      this._maxLineWidth = iLineWidth;
      this._context.model.setMaxLineWidth(this._maxLineWidth);
    }
  }
  _computeScrollTopToRevealRange(viewport2, source2, range3, selections, verticalType) {
    const viewportStartY = viewport2.top;
    const viewportHeight = viewport2.height;
    const viewportEndY = viewportStartY + viewportHeight;
    let boxIsSingleRange;
    let boxStartY;
    let boxEndY;
    if (selections && selections.length > 0) {
      let minLineNumber = selections[0].startLineNumber;
      let maxLineNumber = selections[0].endLineNumber;
      for (let i3 = 1, len2 = selections.length; i3 < len2; i3++) {
        const selection2 = selections[i3];
        minLineNumber = Math.min(minLineNumber, selection2.startLineNumber);
        maxLineNumber = Math.max(maxLineNumber, selection2.endLineNumber);
      }
      boxIsSingleRange = false;
      boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(minLineNumber);
      boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(maxLineNumber) + this._lineHeight;
    } else if (range3) {
      boxIsSingleRange = true;
      boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(range3.startLineNumber);
      boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(range3.endLineNumber) + this._lineHeight;
    } else {
      return -1;
    }
    const shouldIgnoreScrollOff = source2 === "mouse" && this._cursorSurroundingLinesStyle === "default";
    if (!shouldIgnoreScrollOff) {
      const context2 = Math.min(viewportHeight / this._lineHeight / 2, this._cursorSurroundingLines);
      boxStartY -= context2 * this._lineHeight;
      boxEndY += Math.max(0, context2 - 1) * this._lineHeight;
    }
    if (verticalType === 0 || verticalType === 4) {
      boxEndY += this._lineHeight;
    }
    let newScrollTop;
    if (boxEndY - boxStartY > viewportHeight) {
      if (!boxIsSingleRange) {
        return -1;
      }
      newScrollTop = boxStartY;
    } else if (verticalType === 5 || verticalType === 6) {
      if (verticalType === 6 && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
        newScrollTop = viewportStartY;
      } else {
        const desiredGapAbove = Math.max(5 * this._lineHeight, viewportHeight * 0.2);
        const desiredScrollTop = boxStartY - desiredGapAbove;
        const minScrollTop = boxEndY - viewportHeight;
        newScrollTop = Math.max(minScrollTop, desiredScrollTop);
      }
    } else if (verticalType === 1 || verticalType === 2) {
      if (verticalType === 2 && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
        newScrollTop = viewportStartY;
      } else {
        const boxMiddleY = (boxStartY + boxEndY) / 2;
        newScrollTop = Math.max(0, boxMiddleY - viewportHeight / 2);
      }
    } else {
      newScrollTop = this._computeMinimumScrolling(viewportStartY, viewportEndY, boxStartY, boxEndY, verticalType === 3, verticalType === 4);
    }
    return newScrollTop;
  }
  _computeScrollLeftToReveal(horizontalRevealRequest) {
    const viewport2 = this._context.viewLayout.getCurrentViewport();
    const viewportStartX = viewport2.left;
    const viewportEndX = viewportStartX + viewport2.width;
    let boxStartX = 1073741824;
    let boxEndX = 0;
    if (horizontalRevealRequest.type === "range") {
      const visibleRanges = this._visibleRangesForLineRange(horizontalRevealRequest.lineNumber, horizontalRevealRequest.startColumn, horizontalRevealRequest.endColumn);
      if (!visibleRanges) {
        return null;
      }
      for (const visibleRange of visibleRanges.ranges) {
        boxStartX = Math.min(boxStartX, visibleRange.left);
        boxEndX = Math.max(boxEndX, visibleRange.left + visibleRange.width);
      }
    } else {
      for (const selection2 of horizontalRevealRequest.selections) {
        if (selection2.startLineNumber !== selection2.endLineNumber) {
          return null;
        }
        const visibleRanges = this._visibleRangesForLineRange(selection2.startLineNumber, selection2.startColumn, selection2.endColumn);
        if (!visibleRanges) {
          return null;
        }
        for (const visibleRange of visibleRanges.ranges) {
          boxStartX = Math.min(boxStartX, visibleRange.left);
          boxEndX = Math.max(boxEndX, visibleRange.left + visibleRange.width);
        }
      }
    }
    boxStartX = Math.max(0, boxStartX - ViewLines.HORIZONTAL_EXTRA_PX);
    boxEndX += this._revealHorizontalRightPadding;
    if (horizontalRevealRequest.type === "selections" && boxEndX - boxStartX > viewport2.width) {
      return null;
    }
    const newScrollLeft = this._computeMinimumScrolling(viewportStartX, viewportEndX, boxStartX, boxEndX);
    return {
      scrollLeft: newScrollLeft,
      maxHorizontalOffset: boxEndX
    };
  }
  _computeMinimumScrolling(viewportStart, viewportEnd, boxStart, boxEnd, revealAtStart, revealAtEnd) {
    viewportStart = viewportStart | 0;
    viewportEnd = viewportEnd | 0;
    boxStart = boxStart | 0;
    boxEnd = boxEnd | 0;
    revealAtStart = !!revealAtStart;
    revealAtEnd = !!revealAtEnd;
    const viewportLength = viewportEnd - viewportStart;
    const boxLength = boxEnd - boxStart;
    if (boxLength < viewportLength) {
      if (revealAtStart) {
        return boxStart;
      }
      if (revealAtEnd) {
        return Math.max(0, boxEnd - viewportLength);
      }
      if (boxStart < viewportStart) {
        return boxStart;
      } else if (boxEnd > viewportEnd) {
        return Math.max(0, boxEnd - viewportLength);
      }
    } else {
      return boxStart;
    }
    return viewportStart;
  }
};
ViewLines.HORIZONTAL_EXTRA_PX = 30;
function __snowpack__injectStyle$c(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$c("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n.monaco-editor .lines-decorations {\r\n	position: absolute;\r\n	top: 0;\r\n	background: white;\r\n}\r\n\r\n/*\r\n	Keeping name short for faster parsing.\r\n	cldr = core lines decorations rendering (div)\r\n*/\r\n.monaco-editor .margin-view-overlays .cldr {\r\n	position: absolute;\r\n	height: 100%;\r\n}");
var LinesDecorationsOverlay = class extends DedupOverlay {
  constructor(context2) {
    super();
    this._context = context2;
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._decorationsLeft = layoutInfo.decorationsLeft;
    this._decorationsWidth = layoutInfo.decorationsWidth;
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._decorationsLeft = layoutInfo.decorationsLeft;
    this._decorationsWidth = layoutInfo.decorationsWidth;
    return true;
  }
  onDecorationsChanged(e2) {
    return true;
  }
  onFlushed(e2) {
    return true;
  }
  onLinesChanged(e2) {
    return true;
  }
  onLinesDeleted(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollTopChanged;
  }
  onZonesChanged(e2) {
    return true;
  }
  _getDecorations(ctx) {
    const decorations = ctx.getDecorationsInViewport();
    let r3 = [], rLen = 0;
    for (let i3 = 0, len2 = decorations.length; i3 < len2; i3++) {
      const d2 = decorations[i3];
      const linesDecorationsClassName = d2.options.linesDecorationsClassName;
      if (linesDecorationsClassName) {
        r3[rLen++] = new DecorationToRender(d2.range.startLineNumber, d2.range.endLineNumber, linesDecorationsClassName);
      }
      const firstLineDecorationClassName = d2.options.firstLineDecorationClassName;
      if (firstLineDecorationClassName) {
        r3[rLen++] = new DecorationToRender(d2.range.startLineNumber, d2.range.startLineNumber, firstLineDecorationClassName);
      }
    }
    return r3;
  }
  prepareRender(ctx) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
    const left2 = this._decorationsLeft.toString();
    const width2 = this._decorationsWidth.toString();
    const common = '" style="left:' + left2 + "px;width:" + width2 + 'px;"></div>';
    const output2 = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      const classNames2 = toRender[lineIndex];
      let lineOutput = "";
      for (let i3 = 0, len2 = classNames2.length; i3 < len2; i3++) {
        lineOutput += '<div class="cldr ' + classNames2[i3] + common;
      }
      output2[lineIndex] = lineOutput;
    }
    this._renderResult = output2;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    return this._renderResult[lineNumber - startLineNumber];
  }
};
function __snowpack__injectStyle$d(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$d("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n/*\r\n	Keeping name short for faster parsing.\r\n	cmdr = core margin decorations rendering (div)\r\n*/\r\n.monaco-editor .margin-view-overlays .cmdr {\r\n	position: absolute;\r\n	left: 0;\r\n	width: 100%;\r\n	height: 100%;\r\n}");
var MarginViewLineDecorationsOverlay = class extends DedupOverlay {
  constructor(context2) {
    super();
    this._context = context2;
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  onConfigurationChanged(e2) {
    return true;
  }
  onDecorationsChanged(e2) {
    return true;
  }
  onFlushed(e2) {
    return true;
  }
  onLinesChanged(e2) {
    return true;
  }
  onLinesDeleted(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollTopChanged;
  }
  onZonesChanged(e2) {
    return true;
  }
  _getDecorations(ctx) {
    const decorations = ctx.getDecorationsInViewport();
    let r3 = [], rLen = 0;
    for (let i3 = 0, len2 = decorations.length; i3 < len2; i3++) {
      const d2 = decorations[i3];
      const marginClassName = d2.options.marginClassName;
      if (marginClassName) {
        r3[rLen++] = new DecorationToRender(d2.range.startLineNumber, d2.range.endLineNumber, marginClassName);
      }
    }
    return r3;
  }
  prepareRender(ctx) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
    const output2 = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      const classNames2 = toRender[lineIndex];
      let lineOutput = "";
      for (let i3 = 0, len2 = classNames2.length; i3 < len2; i3++) {
        lineOutput += '<div class="cmdr ' + classNames2[i3] + '" style=""></div>';
      }
      output2[lineIndex] = lineOutput;
    }
    this._renderResult = output2;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    return this._renderResult[lineNumber - startLineNumber];
  }
};
function __snowpack__injectStyle$e(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$e("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n/* START cover the case that slider is visible on mouseover */\r\n.monaco-editor .minimap.slider-mouseover .minimap-slider {\r\n	opacity: 0;\r\n	transition: opacity 100ms linear;\r\n}\r\n.monaco-editor .minimap.slider-mouseover:hover .minimap-slider {\r\n	opacity: 1;\r\n}\r\n.monaco-editor .minimap.slider-mouseover .minimap-slider.active {\r\n	opacity: 1;\r\n}\r\n/* END cover the case that slider is visible on mouseover */\r\n\r\n.monaco-editor .minimap-shadow-hidden {\r\n	position: absolute;\r\n	width: 0;\r\n}\r\n.monaco-editor .minimap-shadow-visible {\r\n	position: absolute;\r\n	left: -6px;\r\n	width: 6px;\r\n}\r\n");
var RGBA8 = class {
  constructor(r3, g2, b2, a2) {
    this.r = RGBA8._clamp(r3);
    this.g = RGBA8._clamp(g2);
    this.b = RGBA8._clamp(b2);
    this.a = RGBA8._clamp(a2);
  }
  equals(other) {
    return this.r === other.r && this.g === other.g && this.b === other.b && this.a === other.a;
  }
  static _clamp(c3) {
    if (c3 < 0) {
      return 0;
    }
    if (c3 > 255) {
      return 255;
    }
    return c3 | 0;
  }
};
RGBA8.Empty = new RGBA8(0, 0, 0, 0);
var MinimapTokensColorTracker = class {
  constructor() {
    this._onDidChange = new Emitter();
    this.onDidChange = this._onDidChange.event;
    this._updateColorMap();
    TokenizationRegistry.onDidChange((e2) => {
      if (e2.changedColorMap) {
        this._updateColorMap();
      }
    });
  }
  static getInstance() {
    if (!this._INSTANCE) {
      this._INSTANCE = new MinimapTokensColorTracker();
    }
    return this._INSTANCE;
  }
  _updateColorMap() {
    const colorMap = TokenizationRegistry.getColorMap();
    if (!colorMap) {
      this._colors = [RGBA8.Empty];
      this._backgroundIsLight = true;
      return;
    }
    this._colors = [RGBA8.Empty];
    for (let colorId = 1; colorId < colorMap.length; colorId++) {
      const source2 = colorMap[colorId].rgba;
      this._colors[colorId] = new RGBA8(source2.r, source2.g, source2.b, Math.round(source2.a * 255));
    }
    let backgroundLuminosity = colorMap[2].getRelativeLuminance();
    this._backgroundIsLight = backgroundLuminosity >= 0.5;
    this._onDidChange.fire(void 0);
  }
  getColor(colorId) {
    if (colorId < 1 || colorId >= this._colors.length) {
      colorId = 2;
    }
    return this._colors[colorId];
  }
  backgroundIsLight() {
    return this._backgroundIsLight;
  }
};
MinimapTokensColorTracker._INSTANCE = null;
var allCharCodes = (() => {
  const v2 = [];
  for (let i3 = 32; i3 <= 126; i3++) {
    v2.push(i3);
  }
  v2.push(65533);
  return v2;
})();
var getCharIndex = (chCode, fontScale) => {
  chCode -= 32;
  if (chCode < 0 || chCode > 96) {
    if (fontScale <= 2) {
      return (chCode + 96) % 96;
    }
    return 96 - 1;
  }
  return chCode;
};
var MinimapCharRenderer = class {
  constructor(charData, scale) {
    this.scale = scale;
    this.charDataNormal = MinimapCharRenderer.soften(charData, 12 / 15);
    this.charDataLight = MinimapCharRenderer.soften(charData, 50 / 60);
  }
  static soften(input, ratio) {
    let result = new Uint8ClampedArray(input.length);
    for (let i3 = 0, len2 = input.length; i3 < len2; i3++) {
      result[i3] = toUint8(input[i3] * ratio);
    }
    return result;
  }
  renderChar(target, dx, dy, chCode, color2, backgroundColor, fontScale, useLighterFont, force1pxHeight) {
    const charWidth = 1 * this.scale;
    const charHeight = 2 * this.scale;
    const renderHeight = force1pxHeight ? 1 : charHeight;
    if (dx + charWidth > target.width || dy + renderHeight > target.height) {
      console.warn("bad render request outside image data");
      return;
    }
    const charData = useLighterFont ? this.charDataLight : this.charDataNormal;
    const charIndex = getCharIndex(chCode, fontScale);
    const destWidth = target.width * 4;
    const backgroundR = backgroundColor.r;
    const backgroundG = backgroundColor.g;
    const backgroundB = backgroundColor.b;
    const deltaR = color2.r - backgroundR;
    const deltaG = color2.g - backgroundG;
    const deltaB = color2.b - backgroundB;
    const dest = target.data;
    let sourceOffset = charIndex * charWidth * charHeight;
    let row = dy * destWidth + dx * 4;
    for (let y3 = 0; y3 < renderHeight; y3++) {
      let column = row;
      for (let x2 = 0; x2 < charWidth; x2++) {
        const c3 = charData[sourceOffset++] / 255;
        dest[column++] = backgroundR + deltaR * c3;
        dest[column++] = backgroundG + deltaG * c3;
        dest[column++] = backgroundB + deltaB * c3;
        column++;
      }
      row += destWidth;
    }
  }
  blockRenderChar(target, dx, dy, color2, backgroundColor, useLighterFont, force1pxHeight) {
    const charWidth = 1 * this.scale;
    const charHeight = 2 * this.scale;
    const renderHeight = force1pxHeight ? 1 : charHeight;
    if (dx + charWidth > target.width || dy + renderHeight > target.height) {
      console.warn("bad render request outside image data");
      return;
    }
    const destWidth = target.width * 4;
    const c3 = 0.5;
    const backgroundR = backgroundColor.r;
    const backgroundG = backgroundColor.g;
    const backgroundB = backgroundColor.b;
    const deltaR = color2.r - backgroundR;
    const deltaG = color2.g - backgroundG;
    const deltaB = color2.b - backgroundB;
    const colorR = backgroundR + deltaR * c3;
    const colorG = backgroundG + deltaG * c3;
    const colorB = backgroundB + deltaB * c3;
    const dest = target.data;
    let row = dy * destWidth + dx * 4;
    for (let y3 = 0; y3 < renderHeight; y3++) {
      let column = row;
      for (let x2 = 0; x2 < charWidth; x2++) {
        dest[column++] = colorR;
        dest[column++] = colorG;
        dest[column++] = colorB;
        column++;
      }
      row += destWidth;
    }
  }
};
function once$1(fn) {
  const _this = this;
  let didCall = false;
  let result;
  return function() {
    if (didCall) {
      return result;
    }
    didCall = true;
    result = fn.apply(_this, arguments);
    return result;
  };
}
var charTable = {
  "0": 0,
  "1": 1,
  "2": 2,
  "3": 3,
  "4": 4,
  "5": 5,
  "6": 6,
  "7": 7,
  "8": 8,
  "9": 9,
  A: 10,
  B: 11,
  C: 12,
  D: 13,
  E: 14,
  F: 15
};
var decodeData = (str) => {
  const output2 = new Uint8ClampedArray(str.length / 2);
  for (let i3 = 0; i3 < str.length; i3 += 2) {
    output2[i3 >> 1] = charTable[str[i3]] << 4 | charTable[str[i3 + 1]] & 15;
  }
  return output2;
};
var prebakedMiniMaps = {
  1: once$1(() => decodeData("0000511D6300CF609C709645A78432005642574171487021003C451900274D35D762755E8B629C5BA856AF57BA649530C167D1512A272A3F6038604460398526BCA2A968DB6F8957C768BE5FBE2FB467CF5D8D5B795DC7625B5DFF50DE64C466DB2FC47CD860A65E9A2EB96CB54CE06DA763AB2EA26860524D3763536601005116008177A8705E53AB738E6A982F88BAA35B5F5B626D9C636B449B737E5B7B678598869A662F6B5B8542706C704C80736A607578685B70594A49715A4522E792")),
  2: once$1(() => decodeData("000000000000000055394F383D2800008B8B1F210002000081B1CBCBCC820000847AAF6B9AAF2119BE08B8881AD60000A44FD07DCCF107015338130C00000000385972265F390B406E2437634B4B48031B12B8A0847000001E15B29A402F0000000000004B33460B00007A752C2A0000000000004D3900000084394B82013400ABA5CFC7AD9C0302A45A3E5A98AB000089A43382D97900008BA54AA087A70A0248A6A7AE6DBE0000BF6F94987EA40A01A06DCFA7A7A9030496C32F77891D0000A99FB1A0AFA80603B29AB9CA75930D010C0948354D3900000C0948354F37460D0028BE673D8400000000AF9D7B6E00002B007AA8933400007AA642675C2700007984CFB9C3985B768772A8A6B7B20000CAAECAAFC4B700009F94A6009F840009D09F9BA4CA9C0000CC8FC76DC87F0000C991C472A2000000A894A48CA7B501079BA2C9C69BA20000B19A5D3FA89000005CA6009DA2960901B0A7F0669FB200009D009E00B7890000DAD0F5D092820000D294D4C48BD10000B5A7A4A3B1A50402CAB6CBA6A2000000B5A7A4A3B1A8044FCDADD19D9CB00000B7778F7B8AAE0803C9AB5D3F5D3F00009EA09EA0BAB006039EA0989A8C7900009B9EF4D6B7C00000A9A7816CACA80000ABAC84705D3F000096DA635CDC8C00006F486F266F263D4784006124097B00374F6D2D6D2D6D4A3A95872322000000030000000000008D8939130000000000002E22A5C9CBC70600AB25C0B5C9B400061A2DB04CA67001082AA6BEBEBFC606002321DACBC19E03087AA08B6768380000282FBAC0B8CA7A88AD25BBA5A29900004C396C5894A6000040485A6E356E9442A32CD17EADA70000B4237923628600003E2DE9C1D7B500002F25BBA5A2990000231DB6AFB4A804023025C0B5CAB588062B2CBDBEC0C706882435A75CA20000002326BD6A82A908048B4B9A5A668000002423A09CB4BB060025259C9D8A7900001C1FCAB2C7C700002A2A9387ABA200002626A4A47D6E9D14333163A0C87500004B6F9C2D643A257049364936493647358A34438355497F1A0000A24C1D590000D38DFFBDD4CD3126"))
};
var MinimapCharRendererFactory = class {
  static create(scale, fontFamily) {
    if (this.lastCreated && scale === this.lastCreated.scale && fontFamily === this.lastFontFamily) {
      return this.lastCreated;
    }
    let factory;
    if (prebakedMiniMaps[scale]) {
      factory = new MinimapCharRenderer(prebakedMiniMaps[scale](), scale);
    } else {
      factory = MinimapCharRendererFactory.createFromSampleData(MinimapCharRendererFactory.createSampleData(fontFamily).data, scale);
    }
    this.lastFontFamily = fontFamily;
    this.lastCreated = factory;
    return factory;
  }
  static createSampleData(fontFamily) {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    canvas.style.height = `${16}px`;
    canvas.height = 16;
    canvas.width = 96 * 10;
    canvas.style.width = 96 * 10 + "px";
    ctx.fillStyle = "#ffffff";
    ctx.font = `bold ${16}px ${fontFamily}`;
    ctx.textBaseline = "middle";
    let x2 = 0;
    for (const code2 of allCharCodes) {
      ctx.fillText(String.fromCharCode(code2), x2, 16 / 2);
      x2 += 10;
    }
    return ctx.getImageData(0, 0, 96 * 10, 16);
  }
  static createFromSampleData(source2, scale) {
    const expectedLength = 16 * 10 * 4 * 96;
    if (source2.length !== expectedLength) {
      throw new Error("Unexpected source in MinimapCharRenderer");
    }
    let charData = MinimapCharRendererFactory._downsample(source2, scale);
    return new MinimapCharRenderer(charData, scale);
  }
  static _downsampleChar(source2, sourceOffset, dest, destOffset, scale) {
    const width2 = 1 * scale;
    const height = 2 * scale;
    let targetIndex = destOffset;
    let brightest = 0;
    for (let y3 = 0; y3 < height; y3++) {
      const sourceY1 = y3 / height * 16;
      const sourceY2 = (y3 + 1) / height * 16;
      for (let x2 = 0; x2 < width2; x2++) {
        const sourceX1 = x2 / width2 * 10;
        const sourceX2 = (x2 + 1) / width2 * 10;
        let value = 0;
        let samples = 0;
        for (let sy = sourceY1; sy < sourceY2; sy++) {
          const sourceRow = sourceOffset + Math.floor(sy) * 3840;
          const yBalance = 1 - (sy - Math.floor(sy));
          for (let sx = sourceX1; sx < sourceX2; sx++) {
            const xBalance = 1 - (sx - Math.floor(sx));
            const sourceIndex = sourceRow + Math.floor(sx) * 4;
            const weight = xBalance * yBalance;
            samples += weight;
            value += source2[sourceIndex] * source2[sourceIndex + 3] / 255 * weight;
          }
        }
        const final = value / samples;
        brightest = Math.max(brightest, final);
        dest[targetIndex++] = toUint8(final);
      }
    }
    return brightest;
  }
  static _downsample(data2, scale) {
    const pixelsPerCharacter = 2 * scale * 1 * scale;
    const resultLen = pixelsPerCharacter * 96;
    const result = new Uint8ClampedArray(resultLen);
    let resultOffset = 0;
    let sourceOffset = 0;
    let brightest = 0;
    for (let charIndex = 0; charIndex < 96; charIndex++) {
      brightest = Math.max(brightest, this._downsampleChar(data2, sourceOffset, result, resultOffset, scale));
      resultOffset += pixelsPerCharacter;
      sourceOffset += 10 * 4;
    }
    if (brightest > 0) {
      const adjust2 = 255 / brightest;
      for (let i3 = 0; i3 < resultLen; i3++) {
        result[i3] *= adjust2;
      }
    }
    return result;
  }
};
var MOUSE_DRAG_RESET_DISTANCE$1 = 140;
var GUTTER_DECORATION_WIDTH = 2;
var MinimapOptions = class {
  constructor(configuration, theme, tokensColorTracker) {
    const options = configuration.options;
    const pixelRatio = options.get(115);
    const layoutInfo = options.get(117);
    const minimapLayout = layoutInfo.minimap;
    const fontInfo = options.get(36);
    const minimapOpts = options.get(56);
    this.renderMinimap = minimapLayout.renderMinimap;
    this.size = minimapOpts.size;
    this.minimapHeightIsEditorHeight = minimapLayout.minimapHeightIsEditorHeight;
    this.scrollBeyondLastLine = options.get(86);
    this.showSlider = minimapOpts.showSlider;
    this.pixelRatio = pixelRatio;
    this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this.lineHeight = options.get(51);
    this.minimapLeft = minimapLayout.minimapLeft;
    this.minimapWidth = minimapLayout.minimapWidth;
    this.minimapHeight = layoutInfo.height;
    this.canvasInnerWidth = minimapLayout.minimapCanvasInnerWidth;
    this.canvasInnerHeight = minimapLayout.minimapCanvasInnerHeight;
    this.canvasOuterWidth = minimapLayout.minimapCanvasOuterWidth;
    this.canvasOuterHeight = minimapLayout.minimapCanvasOuterHeight;
    this.isSampling = minimapLayout.minimapIsSampling;
    this.editorHeight = layoutInfo.height;
    this.fontScale = minimapLayout.minimapScale;
    this.minimapLineHeight = minimapLayout.minimapLineHeight;
    this.minimapCharWidth = 1 * this.fontScale;
    this.charRenderer = once$1(() => MinimapCharRendererFactory.create(this.fontScale, fontInfo.fontFamily));
    this.backgroundColor = MinimapOptions._getMinimapBackground(theme, tokensColorTracker);
  }
  static _getMinimapBackground(theme, tokensColorTracker) {
    const themeColor = theme.getColor(minimapBackground);
    if (themeColor) {
      return new RGBA8(themeColor.rgba.r, themeColor.rgba.g, themeColor.rgba.b, themeColor.rgba.a);
    }
    return tokensColorTracker.getColor(2);
  }
  equals(other) {
    return this.renderMinimap === other.renderMinimap && this.size === other.size && this.minimapHeightIsEditorHeight === other.minimapHeightIsEditorHeight && this.scrollBeyondLastLine === other.scrollBeyondLastLine && this.showSlider === other.showSlider && this.pixelRatio === other.pixelRatio && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth && this.lineHeight === other.lineHeight && this.minimapLeft === other.minimapLeft && this.minimapWidth === other.minimapWidth && this.minimapHeight === other.minimapHeight && this.canvasInnerWidth === other.canvasInnerWidth && this.canvasInnerHeight === other.canvasInnerHeight && this.canvasOuterWidth === other.canvasOuterWidth && this.canvasOuterHeight === other.canvasOuterHeight && this.isSampling === other.isSampling && this.editorHeight === other.editorHeight && this.fontScale === other.fontScale && this.minimapLineHeight === other.minimapLineHeight && this.minimapCharWidth === other.minimapCharWidth && this.backgroundColor && this.backgroundColor.equals(other.backgroundColor);
  }
};
var MinimapLayout = class {
  constructor(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber) {
    this.scrollTop = scrollTop;
    this.scrollHeight = scrollHeight;
    this.sliderNeeded = sliderNeeded;
    this._computedSliderRatio = computedSliderRatio;
    this.sliderTop = sliderTop;
    this.sliderHeight = sliderHeight;
    this.startLineNumber = startLineNumber;
    this.endLineNumber = endLineNumber;
  }
  getDesiredScrollTopFromDelta(delta) {
    const desiredSliderPosition = this.sliderTop + delta;
    return Math.round(desiredSliderPosition / this._computedSliderRatio);
  }
  getDesiredScrollTopFromTouchLocation(pageY) {
    return Math.round((pageY - this.sliderHeight / 2) / this._computedSliderRatio);
  }
  static create(options, viewportStartLineNumber, viewportEndLineNumber, viewportHeight, viewportContainsWhitespaceGaps, lineCount, realLineCount, scrollTop, scrollHeight, previousLayout) {
    const pixelRatio = options.pixelRatio;
    const minimapLineHeight = options.minimapLineHeight;
    const minimapLinesFitting = Math.floor(options.canvasInnerHeight / minimapLineHeight);
    const lineHeight = options.lineHeight;
    if (options.minimapHeightIsEditorHeight) {
      const logicalScrollHeight = realLineCount * options.lineHeight + (options.scrollBeyondLastLine ? viewportHeight - options.lineHeight : 0);
      const sliderHeight2 = Math.max(1, Math.floor(viewportHeight * viewportHeight / logicalScrollHeight));
      const maxMinimapSliderTop2 = Math.max(0, options.minimapHeight - sliderHeight2);
      const computedSliderRatio2 = maxMinimapSliderTop2 / (scrollHeight - viewportHeight);
      const sliderTop2 = scrollTop * computedSliderRatio2;
      const sliderNeeded = maxMinimapSliderTop2 > 0;
      const maxLinesFitting = Math.floor(options.canvasInnerHeight / options.minimapLineHeight);
      return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio2, sliderTop2, sliderHeight2, 1, Math.min(lineCount, maxLinesFitting));
    }
    let sliderHeight;
    if (viewportContainsWhitespaceGaps && viewportEndLineNumber !== lineCount) {
      const viewportLineCount = viewportEndLineNumber - viewportStartLineNumber + 1;
      sliderHeight = Math.floor(viewportLineCount * minimapLineHeight / pixelRatio);
    } else {
      const expectedViewportLineCount = viewportHeight / lineHeight;
      sliderHeight = Math.floor(expectedViewportLineCount * minimapLineHeight / pixelRatio);
    }
    let maxMinimapSliderTop;
    if (options.scrollBeyondLastLine) {
      maxMinimapSliderTop = (lineCount - 1) * minimapLineHeight / pixelRatio;
    } else {
      maxMinimapSliderTop = Math.max(0, lineCount * minimapLineHeight / pixelRatio - sliderHeight);
    }
    maxMinimapSliderTop = Math.min(options.minimapHeight - sliderHeight, maxMinimapSliderTop);
    const computedSliderRatio = maxMinimapSliderTop / (scrollHeight - viewportHeight);
    const sliderTop = scrollTop * computedSliderRatio;
    let extraLinesAtTheBottom = 0;
    if (options.scrollBeyondLastLine) {
      const expectedViewportLineCount = viewportHeight / lineHeight;
      extraLinesAtTheBottom = expectedViewportLineCount - 1;
    }
    if (minimapLinesFitting >= lineCount + extraLinesAtTheBottom) {
      const startLineNumber = 1;
      const endLineNumber = lineCount;
      const sliderNeeded = maxMinimapSliderTop > 0;
      return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber);
    } else {
      let startLineNumber = Math.max(1, Math.floor(viewportStartLineNumber - sliderTop * pixelRatio / minimapLineHeight));
      if (previousLayout && previousLayout.scrollHeight === scrollHeight) {
        if (previousLayout.scrollTop > scrollTop) {
          startLineNumber = Math.min(startLineNumber, previousLayout.startLineNumber);
        }
        if (previousLayout.scrollTop < scrollTop) {
          startLineNumber = Math.max(startLineNumber, previousLayout.startLineNumber);
        }
      }
      const endLineNumber = Math.min(lineCount, startLineNumber + minimapLinesFitting - 1);
      return new MinimapLayout(scrollTop, scrollHeight, true, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber);
    }
  }
};
var MinimapLine = class {
  constructor(dy) {
    this.dy = dy;
  }
  onContentChanged() {
    this.dy = -1;
  }
  onTokensChanged() {
    this.dy = -1;
  }
};
MinimapLine.INVALID = new MinimapLine(-1);
var RenderData = class {
  constructor(renderedLayout, imageData, lines) {
    this.renderedLayout = renderedLayout;
    this._imageData = imageData;
    this._renderedLines = new RenderedLinesCollection(() => MinimapLine.INVALID);
    this._renderedLines._set(renderedLayout.startLineNumber, lines);
  }
  linesEquals(layout3) {
    if (!this.scrollEquals(layout3)) {
      return false;
    }
    const tmp = this._renderedLines._get();
    const lines = tmp.lines;
    for (let i3 = 0, len2 = lines.length; i3 < len2; i3++) {
      if (lines[i3].dy === -1) {
        return false;
      }
    }
    return true;
  }
  scrollEquals(layout3) {
    return this.renderedLayout.startLineNumber === layout3.startLineNumber && this.renderedLayout.endLineNumber === layout3.endLineNumber;
  }
  _get() {
    const tmp = this._renderedLines._get();
    return {
      imageData: this._imageData,
      rendLineNumberStart: tmp.rendLineNumberStart,
      lines: tmp.lines
    };
  }
  onLinesChanged(changeFromLineNumber, changeToLineNumber) {
    return this._renderedLines.onLinesChanged(changeFromLineNumber, changeToLineNumber);
  }
  onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
    this._renderedLines.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
  }
  onLinesInserted(insertFromLineNumber, insertToLineNumber) {
    this._renderedLines.onLinesInserted(insertFromLineNumber, insertToLineNumber);
  }
  onTokensChanged(ranges) {
    return this._renderedLines.onTokensChanged(ranges);
  }
};
var MinimapBuffers = class {
  constructor(ctx, WIDTH, HEIGHT, background) {
    this._backgroundFillData = MinimapBuffers._createBackgroundFillData(WIDTH, HEIGHT, background);
    this._buffers = [
      ctx.createImageData(WIDTH, HEIGHT),
      ctx.createImageData(WIDTH, HEIGHT)
    ];
    this._lastUsedBuffer = 0;
  }
  getBuffer() {
    this._lastUsedBuffer = 1 - this._lastUsedBuffer;
    const result = this._buffers[this._lastUsedBuffer];
    result.data.set(this._backgroundFillData);
    return result;
  }
  static _createBackgroundFillData(WIDTH, HEIGHT, background) {
    const backgroundR = background.r;
    const backgroundG = background.g;
    const backgroundB = background.b;
    const result = new Uint8ClampedArray(WIDTH * HEIGHT * 4);
    let offset2 = 0;
    for (let i3 = 0; i3 < HEIGHT; i3++) {
      for (let j = 0; j < WIDTH; j++) {
        result[offset2] = backgroundR;
        result[offset2 + 1] = backgroundG;
        result[offset2 + 2] = backgroundB;
        result[offset2 + 3] = 255;
        offset2 += 4;
      }
    }
    return result;
  }
};
var MinimapSamplingState = class {
  constructor(samplingRatio, minimapLines) {
    this.samplingRatio = samplingRatio;
    this.minimapLines = minimapLines;
  }
  static compute(options, viewLineCount, oldSamplingState) {
    if (options.renderMinimap === 0 || !options.isSampling) {
      return [null, []];
    }
    const pixelRatio = options.pixelRatio;
    const lineHeight = options.lineHeight;
    const scrollBeyondLastLine = options.scrollBeyondLastLine;
    const {minimapLineCount} = EditorLayoutInfoComputer.computeContainedMinimapLineCount({
      viewLineCount,
      scrollBeyondLastLine,
      height: options.editorHeight,
      lineHeight,
      pixelRatio
    });
    const ratio = viewLineCount / minimapLineCount;
    const halfRatio = ratio / 2;
    if (!oldSamplingState || oldSamplingState.minimapLines.length === 0) {
      let result2 = [];
      result2[0] = 1;
      if (minimapLineCount > 1) {
        for (let i3 = 0, lastIndex = minimapLineCount - 1; i3 < lastIndex; i3++) {
          result2[i3] = Math.round(i3 * ratio + halfRatio);
        }
        result2[minimapLineCount - 1] = viewLineCount;
      }
      return [new MinimapSamplingState(ratio, result2), []];
    }
    const oldMinimapLines = oldSamplingState.minimapLines;
    const oldLength = oldMinimapLines.length;
    let result = [];
    let oldIndex = 0;
    let oldDeltaLineCount = 0;
    let minViewLineNumber = 1;
    const MAX_EVENT_COUNT = 10;
    let events = [];
    let lastEvent = null;
    for (let i3 = 0; i3 < minimapLineCount; i3++) {
      const fromViewLineNumber = Math.max(minViewLineNumber, Math.round(i3 * ratio));
      const toViewLineNumber = Math.max(fromViewLineNumber, Math.round((i3 + 1) * ratio));
      while (oldIndex < oldLength && oldMinimapLines[oldIndex] < fromViewLineNumber) {
        if (events.length < MAX_EVENT_COUNT) {
          const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
          if (lastEvent && lastEvent.type === "deleted" && lastEvent._oldIndex === oldIndex - 1) {
            lastEvent.deleteToLineNumber++;
          } else {
            lastEvent = {type: "deleted", _oldIndex: oldIndex, deleteFromLineNumber: oldMinimapLineNumber, deleteToLineNumber: oldMinimapLineNumber};
            events.push(lastEvent);
          }
          oldDeltaLineCount--;
        }
        oldIndex++;
      }
      let selectedViewLineNumber;
      if (oldIndex < oldLength && oldMinimapLines[oldIndex] <= toViewLineNumber) {
        selectedViewLineNumber = oldMinimapLines[oldIndex];
        oldIndex++;
      } else {
        if (i3 === 0) {
          selectedViewLineNumber = 1;
        } else if (i3 + 1 === minimapLineCount) {
          selectedViewLineNumber = viewLineCount;
        } else {
          selectedViewLineNumber = Math.round(i3 * ratio + halfRatio);
        }
        if (events.length < MAX_EVENT_COUNT) {
          const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
          if (lastEvent && lastEvent.type === "inserted" && lastEvent._i === i3 - 1) {
            lastEvent.insertToLineNumber++;
          } else {
            lastEvent = {type: "inserted", _i: i3, insertFromLineNumber: oldMinimapLineNumber, insertToLineNumber: oldMinimapLineNumber};
            events.push(lastEvent);
          }
          oldDeltaLineCount++;
        }
      }
      result[i3] = selectedViewLineNumber;
      minViewLineNumber = selectedViewLineNumber;
    }
    if (events.length < MAX_EVENT_COUNT) {
      while (oldIndex < oldLength) {
        const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
        if (lastEvent && lastEvent.type === "deleted" && lastEvent._oldIndex === oldIndex - 1) {
          lastEvent.deleteToLineNumber++;
        } else {
          lastEvent = {type: "deleted", _oldIndex: oldIndex, deleteFromLineNumber: oldMinimapLineNumber, deleteToLineNumber: oldMinimapLineNumber};
          events.push(lastEvent);
        }
        oldDeltaLineCount--;
        oldIndex++;
      }
    } else {
      events = [{type: "flush"}];
    }
    return [new MinimapSamplingState(ratio, result), events];
  }
  modelLineToMinimapLine(lineNumber) {
    return Math.min(this.minimapLines.length, Math.max(1, Math.round(lineNumber / this.samplingRatio)));
  }
  modelLineRangeToMinimapLineRange(fromLineNumber, toLineNumber) {
    let fromLineIndex = this.modelLineToMinimapLine(fromLineNumber) - 1;
    while (fromLineIndex > 0 && this.minimapLines[fromLineIndex - 1] >= fromLineNumber) {
      fromLineIndex--;
    }
    let toLineIndex = this.modelLineToMinimapLine(toLineNumber) - 1;
    while (toLineIndex + 1 < this.minimapLines.length && this.minimapLines[toLineIndex + 1] <= toLineNumber) {
      toLineIndex++;
    }
    if (fromLineIndex === toLineIndex) {
      const sampledLineNumber = this.minimapLines[fromLineIndex];
      if (sampledLineNumber < fromLineNumber || sampledLineNumber > toLineNumber) {
        return null;
      }
    }
    return [fromLineIndex + 1, toLineIndex + 1];
  }
  decorationLineRangeToMinimapLineRange(startLineNumber, endLineNumber) {
    let minimapLineStart = this.modelLineToMinimapLine(startLineNumber);
    let minimapLineEnd = this.modelLineToMinimapLine(endLineNumber);
    if (startLineNumber !== endLineNumber && minimapLineEnd === minimapLineStart) {
      if (minimapLineEnd === this.minimapLines.length) {
        if (minimapLineStart > 1) {
          minimapLineStart--;
        }
      } else {
        minimapLineEnd++;
      }
    }
    return [minimapLineStart, minimapLineEnd];
  }
  onLinesDeleted(e2) {
    const deletedLineCount = e2.toLineNumber - e2.fromLineNumber + 1;
    let changeStartIndex = this.minimapLines.length;
    let changeEndIndex = 0;
    for (let i3 = this.minimapLines.length - 1; i3 >= 0; i3--) {
      if (this.minimapLines[i3] < e2.fromLineNumber) {
        break;
      }
      if (this.minimapLines[i3] <= e2.toLineNumber) {
        this.minimapLines[i3] = Math.max(1, e2.fromLineNumber - 1);
        changeStartIndex = Math.min(changeStartIndex, i3);
        changeEndIndex = Math.max(changeEndIndex, i3);
      } else {
        this.minimapLines[i3] -= deletedLineCount;
      }
    }
    return [changeStartIndex, changeEndIndex];
  }
  onLinesInserted(e2) {
    const insertedLineCount = e2.toLineNumber - e2.fromLineNumber + 1;
    for (let i3 = this.minimapLines.length - 1; i3 >= 0; i3--) {
      if (this.minimapLines[i3] < e2.fromLineNumber) {
        break;
      }
      this.minimapLines[i3] += insertedLineCount;
    }
  }
};
var Minimap = class extends ViewPart {
  constructor(context2) {
    super(context2);
    this.tokensColorTracker = MinimapTokensColorTracker.getInstance();
    this._selections = [];
    this._minimapSelections = null;
    this.options = new MinimapOptions(this._context.configuration, this._context.theme, this.tokensColorTracker);
    const [samplingState] = MinimapSamplingState.compute(this.options, this._context.model.getLineCount(), null);
    this._samplingState = samplingState;
    this._shouldCheckSampling = false;
    this._actual = new InnerMinimap(context2.theme, this);
  }
  dispose() {
    this._actual.dispose();
    super.dispose();
  }
  getDomNode() {
    return this._actual.getDomNode();
  }
  _onOptionsMaybeChanged() {
    const opts = new MinimapOptions(this._context.configuration, this._context.theme, this.tokensColorTracker);
    if (this.options.equals(opts)) {
      return false;
    }
    this.options = opts;
    this._recreateLineSampling();
    this._actual.onDidChangeOptions();
    return true;
  }
  onConfigurationChanged(e2) {
    return this._onOptionsMaybeChanged();
  }
  onCursorStateChanged(e2) {
    this._selections = e2.selections;
    this._minimapSelections = null;
    return this._actual.onSelectionChanged();
  }
  onDecorationsChanged(e2) {
    if (e2.affectsMinimap) {
      return this._actual.onDecorationsChanged();
    }
    return false;
  }
  onFlushed(e2) {
    if (this._samplingState) {
      this._shouldCheckSampling = true;
    }
    return this._actual.onFlushed();
  }
  onLinesChanged(e2) {
    if (this._samplingState) {
      const minimapLineRange = this._samplingState.modelLineRangeToMinimapLineRange(e2.fromLineNumber, e2.toLineNumber);
      if (minimapLineRange) {
        return this._actual.onLinesChanged(minimapLineRange[0], minimapLineRange[1]);
      } else {
        return false;
      }
    } else {
      return this._actual.onLinesChanged(e2.fromLineNumber, e2.toLineNumber);
    }
  }
  onLinesDeleted(e2) {
    if (this._samplingState) {
      const [changeStartIndex, changeEndIndex] = this._samplingState.onLinesDeleted(e2);
      if (changeStartIndex <= changeEndIndex) {
        this._actual.onLinesChanged(changeStartIndex + 1, changeEndIndex + 1);
      }
      this._shouldCheckSampling = true;
      return true;
    } else {
      return this._actual.onLinesDeleted(e2.fromLineNumber, e2.toLineNumber);
    }
  }
  onLinesInserted(e2) {
    if (this._samplingState) {
      this._samplingState.onLinesInserted(e2);
      this._shouldCheckSampling = true;
      return true;
    } else {
      return this._actual.onLinesInserted(e2.fromLineNumber, e2.toLineNumber);
    }
  }
  onScrollChanged(e2) {
    return this._actual.onScrollChanged();
  }
  onThemeChanged(e2) {
    this._context.model.invalidateMinimapColorCache();
    this._actual.onThemeChanged();
    this._onOptionsMaybeChanged();
    return true;
  }
  onTokensChanged(e2) {
    if (this._samplingState) {
      let ranges = [];
      for (const range3 of e2.ranges) {
        const minimapLineRange = this._samplingState.modelLineRangeToMinimapLineRange(range3.fromLineNumber, range3.toLineNumber);
        if (minimapLineRange) {
          ranges.push({fromLineNumber: minimapLineRange[0], toLineNumber: minimapLineRange[1]});
        }
      }
      if (ranges.length) {
        return this._actual.onTokensChanged(ranges);
      } else {
        return false;
      }
    } else {
      return this._actual.onTokensChanged(e2.ranges);
    }
  }
  onTokensColorsChanged(e2) {
    return this._actual.onTokensColorsChanged();
  }
  onZonesChanged(e2) {
    return this._actual.onZonesChanged();
  }
  prepareRender(ctx) {
    if (this._shouldCheckSampling) {
      this._shouldCheckSampling = false;
      this._recreateLineSampling();
    }
  }
  render(ctx) {
    let viewportStartLineNumber = ctx.visibleRange.startLineNumber;
    let viewportEndLineNumber = ctx.visibleRange.endLineNumber;
    if (this._samplingState) {
      viewportStartLineNumber = this._samplingState.modelLineToMinimapLine(viewportStartLineNumber);
      viewportEndLineNumber = this._samplingState.modelLineToMinimapLine(viewportEndLineNumber);
    }
    const minimapCtx = {
      viewportContainsWhitespaceGaps: ctx.viewportData.whitespaceViewportData.length > 0,
      scrollWidth: ctx.scrollWidth,
      scrollHeight: ctx.scrollHeight,
      viewportStartLineNumber,
      viewportEndLineNumber,
      scrollTop: ctx.scrollTop,
      scrollLeft: ctx.scrollLeft,
      viewportWidth: ctx.viewportWidth,
      viewportHeight: ctx.viewportHeight
    };
    this._actual.render(minimapCtx);
  }
  _recreateLineSampling() {
    this._minimapSelections = null;
    const wasSampling = Boolean(this._samplingState);
    const [samplingState, events] = MinimapSamplingState.compute(this.options, this._context.model.getLineCount(), this._samplingState);
    this._samplingState = samplingState;
    if (wasSampling && this._samplingState) {
      for (const event of events) {
        switch (event.type) {
          case "deleted":
            this._actual.onLinesDeleted(event.deleteFromLineNumber, event.deleteToLineNumber);
            break;
          case "inserted":
            this._actual.onLinesInserted(event.insertFromLineNumber, event.insertToLineNumber);
            break;
          case "flush":
            this._actual.onFlushed();
            break;
        }
      }
    }
  }
  getLineCount() {
    if (this._samplingState) {
      return this._samplingState.minimapLines.length;
    }
    return this._context.model.getLineCount();
  }
  getRealLineCount() {
    return this._context.model.getLineCount();
  }
  getLineContent(lineNumber) {
    if (this._samplingState) {
      return this._context.model.getLineContent(this._samplingState.minimapLines[lineNumber - 1]);
    }
    return this._context.model.getLineContent(lineNumber);
  }
  getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
    if (this._samplingState) {
      let result = [];
      for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
        if (needed[lineIndex]) {
          result[lineIndex] = this._context.model.getViewLineData(this._samplingState.minimapLines[startLineNumber + lineIndex - 1]);
        } else {
          result[lineIndex] = null;
        }
      }
      return result;
    }
    return this._context.model.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed).data;
  }
  getSelections() {
    if (this._minimapSelections === null) {
      if (this._samplingState) {
        this._minimapSelections = [];
        for (const selection2 of this._selections) {
          const [minimapLineStart, minimapLineEnd] = this._samplingState.decorationLineRangeToMinimapLineRange(selection2.startLineNumber, selection2.endLineNumber);
          this._minimapSelections.push(new Selection(minimapLineStart, selection2.startColumn, minimapLineEnd, selection2.endColumn));
        }
      } else {
        this._minimapSelections = this._selections;
      }
    }
    return this._minimapSelections;
  }
  getMinimapDecorationsInViewport(startLineNumber, endLineNumber) {
    let visibleRange;
    if (this._samplingState) {
      const modelStartLineNumber = this._samplingState.minimapLines[startLineNumber - 1];
      const modelEndLineNumber = this._samplingState.minimapLines[endLineNumber - 1];
      visibleRange = new Range(modelStartLineNumber, 1, modelEndLineNumber, this._context.model.getLineMaxColumn(modelEndLineNumber));
    } else {
      visibleRange = new Range(startLineNumber, 1, endLineNumber, this._context.model.getLineMaxColumn(endLineNumber));
    }
    const decorations = this._context.model.getDecorationsInViewport(visibleRange);
    if (this._samplingState) {
      let result = [];
      for (const decoration of decorations) {
        if (!decoration.options.minimap) {
          continue;
        }
        const range3 = decoration.range;
        const minimapStartLineNumber = this._samplingState.modelLineToMinimapLine(range3.startLineNumber);
        const minimapEndLineNumber = this._samplingState.modelLineToMinimapLine(range3.endLineNumber);
        result.push(new ViewModelDecoration(new Range(minimapStartLineNumber, range3.startColumn, minimapEndLineNumber, range3.endColumn), decoration.options));
      }
      return result;
    }
    return decorations;
  }
  getOptions() {
    return this._context.model.getTextModelOptions();
  }
  revealLineNumber(lineNumber) {
    if (this._samplingState) {
      lineNumber = this._samplingState.minimapLines[lineNumber - 1];
    }
    this._context.model.revealRange("mouse", false, new Range(lineNumber, 1, lineNumber, 1), 1, 0);
  }
  setScrollTop(scrollTop) {
    this._context.model.setScrollPosition({
      scrollTop
    }, 1);
  }
};
var InnerMinimap = class extends Disposable {
  constructor(theme, model) {
    super();
    this._renderDecorations = false;
    this._gestureInProgress = false;
    this._theme = theme;
    this._model = model;
    this._lastRenderData = null;
    this._buffers = null;
    this._selectionColor = this._theme.getColor(minimapSelection);
    this._domNode = createFastDomNode(document.createElement("div"));
    PartFingerprints.write(this._domNode, 8);
    this._domNode.setClassName(this._getMinimapDomNodeClassName());
    this._domNode.setPosition("absolute");
    this._domNode.setAttribute("role", "presentation");
    this._domNode.setAttribute("aria-hidden", "true");
    this._shadow = createFastDomNode(document.createElement("div"));
    this._shadow.setClassName("minimap-shadow-hidden");
    this._domNode.appendChild(this._shadow);
    this._canvas = createFastDomNode(document.createElement("canvas"));
    this._canvas.setPosition("absolute");
    this._canvas.setLeft(0);
    this._domNode.appendChild(this._canvas);
    this._decorationsCanvas = createFastDomNode(document.createElement("canvas"));
    this._decorationsCanvas.setPosition("absolute");
    this._decorationsCanvas.setClassName("minimap-decorations-layer");
    this._decorationsCanvas.setLeft(0);
    this._domNode.appendChild(this._decorationsCanvas);
    this._slider = createFastDomNode(document.createElement("div"));
    this._slider.setPosition("absolute");
    this._slider.setClassName("minimap-slider");
    this._slider.setLayerHinting(true);
    this._slider.setContain("strict");
    this._domNode.appendChild(this._slider);
    this._sliderHorizontal = createFastDomNode(document.createElement("div"));
    this._sliderHorizontal.setPosition("absolute");
    this._sliderHorizontal.setClassName("minimap-slider-horizontal");
    this._slider.appendChild(this._sliderHorizontal);
    this._applyLayout();
    this._mouseDownListener = addStandardDisposableListener(this._domNode.domNode, "mousedown", (e2) => {
      e2.preventDefault();
      const renderMinimap = this._model.options.renderMinimap;
      if (renderMinimap === 0) {
        return;
      }
      if (!this._lastRenderData) {
        return;
      }
      if (this._model.options.size !== "proportional") {
        if (e2.leftButton && this._lastRenderData) {
          const position2 = getDomNodePagePosition(this._slider.domNode);
          const initialPosY = position2.top + position2.height / 2;
          this._startSliderDragging(e2.buttons, e2.posx, initialPosY, e2.posy, this._lastRenderData.renderedLayout);
        }
        return;
      }
      const minimapLineHeight = this._model.options.minimapLineHeight;
      const internalOffsetY = this._model.options.canvasInnerHeight / this._model.options.canvasOuterHeight * e2.browserEvent.offsetY;
      const lineIndex = Math.floor(internalOffsetY / minimapLineHeight);
      let lineNumber = lineIndex + this._lastRenderData.renderedLayout.startLineNumber;
      lineNumber = Math.min(lineNumber, this._model.getLineCount());
      this._model.revealLineNumber(lineNumber);
    });
    this._sliderMouseMoveMonitor = new GlobalMouseMoveMonitor();
    this._sliderMouseDownListener = addStandardDisposableListener(this._slider.domNode, "mousedown", (e2) => {
      e2.preventDefault();
      e2.stopPropagation();
      if (e2.leftButton && this._lastRenderData) {
        this._startSliderDragging(e2.buttons, e2.posx, e2.posy, e2.posy, this._lastRenderData.renderedLayout);
      }
    });
    this._gestureDisposable = Gesture.addTarget(this._domNode.domNode);
    this._sliderTouchStartListener = addDisposableListener(this._domNode.domNode, EventType$1.Start, (e2) => {
      e2.preventDefault();
      e2.stopPropagation();
      if (this._lastRenderData) {
        this._slider.toggleClassName("active", true);
        this._gestureInProgress = true;
        this.scrollDueToTouchEvent(e2);
      }
    }, {passive: false});
    this._sliderTouchMoveListener = addDisposableListener(this._domNode.domNode, EventType$1.Change, (e2) => {
      e2.preventDefault();
      e2.stopPropagation();
      if (this._lastRenderData && this._gestureInProgress) {
        this.scrollDueToTouchEvent(e2);
      }
    }, {passive: false});
    this._sliderTouchEndListener = addStandardDisposableListener(this._domNode.domNode, EventType$1.End, (e2) => {
      e2.preventDefault();
      e2.stopPropagation();
      this._gestureInProgress = false;
      this._slider.toggleClassName("active", false);
    });
  }
  _startSliderDragging(initialButtons, initialPosX, initialPosY, posy, initialSliderState) {
    this._slider.toggleClassName("active", true);
    const handleMouseMove = (posy2, posx) => {
      const mouseOrthogonalDelta = Math.abs(posx - initialPosX);
      if (isWindows && mouseOrthogonalDelta > MOUSE_DRAG_RESET_DISTANCE$1) {
        this._model.setScrollTop(initialSliderState.scrollTop);
        return;
      }
      const mouseDelta = posy2 - initialPosY;
      this._model.setScrollTop(initialSliderState.getDesiredScrollTopFromDelta(mouseDelta));
    };
    if (posy !== initialPosY) {
      handleMouseMove(posy, initialPosX);
    }
    this._sliderMouseMoveMonitor.startMonitoring(this._slider.domNode, initialButtons, standardMouseMoveMerger, (mouseMoveData) => handleMouseMove(mouseMoveData.posy, mouseMoveData.posx), () => {
      this._slider.toggleClassName("active", false);
    });
  }
  scrollDueToTouchEvent(touch) {
    const startY = this._domNode.domNode.getBoundingClientRect().top;
    const scrollTop = this._lastRenderData.renderedLayout.getDesiredScrollTopFromTouchLocation(touch.pageY - startY);
    this._model.setScrollTop(scrollTop);
  }
  dispose() {
    this._mouseDownListener.dispose();
    this._sliderMouseMoveMonitor.dispose();
    this._sliderMouseDownListener.dispose();
    this._gestureDisposable.dispose();
    this._sliderTouchStartListener.dispose();
    this._sliderTouchMoveListener.dispose();
    this._sliderTouchEndListener.dispose();
    super.dispose();
  }
  _getMinimapDomNodeClassName() {
    if (this._model.options.showSlider === "always") {
      return "minimap slider-always";
    }
    return "minimap slider-mouseover";
  }
  getDomNode() {
    return this._domNode;
  }
  _applyLayout() {
    this._domNode.setLeft(this._model.options.minimapLeft);
    this._domNode.setWidth(this._model.options.minimapWidth);
    this._domNode.setHeight(this._model.options.minimapHeight);
    this._shadow.setHeight(this._model.options.minimapHeight);
    this._canvas.setWidth(this._model.options.canvasOuterWidth);
    this._canvas.setHeight(this._model.options.canvasOuterHeight);
    this._canvas.domNode.width = this._model.options.canvasInnerWidth;
    this._canvas.domNode.height = this._model.options.canvasInnerHeight;
    this._decorationsCanvas.setWidth(this._model.options.canvasOuterWidth);
    this._decorationsCanvas.setHeight(this._model.options.canvasOuterHeight);
    this._decorationsCanvas.domNode.width = this._model.options.canvasInnerWidth;
    this._decorationsCanvas.domNode.height = this._model.options.canvasInnerHeight;
    this._slider.setWidth(this._model.options.minimapWidth);
  }
  _getBuffer() {
    if (!this._buffers) {
      if (this._model.options.canvasInnerWidth > 0 && this._model.options.canvasInnerHeight > 0) {
        this._buffers = new MinimapBuffers(this._canvas.domNode.getContext("2d"), this._model.options.canvasInnerWidth, this._model.options.canvasInnerHeight, this._model.options.backgroundColor);
      }
    }
    return this._buffers ? this._buffers.getBuffer() : null;
  }
  onDidChangeOptions() {
    this._lastRenderData = null;
    this._buffers = null;
    this._applyLayout();
    this._domNode.setClassName(this._getMinimapDomNodeClassName());
  }
  onSelectionChanged() {
    this._renderDecorations = true;
    return true;
  }
  onDecorationsChanged() {
    this._renderDecorations = true;
    return true;
  }
  onFlushed() {
    this._lastRenderData = null;
    return true;
  }
  onLinesChanged(changeFromLineNumber, changeToLineNumber) {
    if (this._lastRenderData) {
      return this._lastRenderData.onLinesChanged(changeFromLineNumber, changeToLineNumber);
    }
    return false;
  }
  onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
    if (this._lastRenderData) {
      this._lastRenderData.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
    }
    return true;
  }
  onLinesInserted(insertFromLineNumber, insertToLineNumber) {
    if (this._lastRenderData) {
      this._lastRenderData.onLinesInserted(insertFromLineNumber, insertToLineNumber);
    }
    return true;
  }
  onScrollChanged() {
    this._renderDecorations = true;
    return true;
  }
  onThemeChanged() {
    this._selectionColor = this._theme.getColor(minimapSelection);
    this._renderDecorations = true;
    return true;
  }
  onTokensChanged(ranges) {
    if (this._lastRenderData) {
      return this._lastRenderData.onTokensChanged(ranges);
    }
    return false;
  }
  onTokensColorsChanged() {
    this._lastRenderData = null;
    this._buffers = null;
    return true;
  }
  onZonesChanged() {
    this._lastRenderData = null;
    return true;
  }
  render(renderingCtx) {
    const renderMinimap = this._model.options.renderMinimap;
    if (renderMinimap === 0) {
      this._shadow.setClassName("minimap-shadow-hidden");
      this._sliderHorizontal.setWidth(0);
      this._sliderHorizontal.setHeight(0);
      return;
    }
    if (renderingCtx.scrollLeft + renderingCtx.viewportWidth >= renderingCtx.scrollWidth) {
      this._shadow.setClassName("minimap-shadow-hidden");
    } else {
      this._shadow.setClassName("minimap-shadow-visible");
    }
    const layout3 = MinimapLayout.create(this._model.options, renderingCtx.viewportStartLineNumber, renderingCtx.viewportEndLineNumber, renderingCtx.viewportHeight, renderingCtx.viewportContainsWhitespaceGaps, this._model.getLineCount(), this._model.getRealLineCount(), renderingCtx.scrollTop, renderingCtx.scrollHeight, this._lastRenderData ? this._lastRenderData.renderedLayout : null);
    this._slider.setDisplay(layout3.sliderNeeded ? "block" : "none");
    this._slider.setTop(layout3.sliderTop);
    this._slider.setHeight(layout3.sliderHeight);
    const scrollLeftChars = renderingCtx.scrollLeft / this._model.options.typicalHalfwidthCharacterWidth;
    const horizontalSliderLeft = Math.min(this._model.options.minimapWidth, Math.round(scrollLeftChars * this._model.options.minimapCharWidth / this._model.options.pixelRatio));
    this._sliderHorizontal.setLeft(horizontalSliderLeft);
    this._sliderHorizontal.setWidth(this._model.options.minimapWidth - horizontalSliderLeft);
    this._sliderHorizontal.setTop(0);
    this._sliderHorizontal.setHeight(layout3.sliderHeight);
    this.renderDecorations(layout3);
    this._lastRenderData = this.renderLines(layout3);
  }
  renderDecorations(layout3) {
    if (this._renderDecorations) {
      this._renderDecorations = false;
      const selections = this._model.getSelections();
      const decorations = this._model.getMinimapDecorationsInViewport(layout3.startLineNumber, layout3.endLineNumber);
      const {canvasInnerWidth, canvasInnerHeight} = this._model.options;
      const lineHeight = this._model.options.minimapLineHeight;
      const characterWidth = this._model.options.minimapCharWidth;
      const tabSize = this._model.getOptions().tabSize;
      const canvasContext = this._decorationsCanvas.domNode.getContext("2d");
      canvasContext.clearRect(0, 0, canvasInnerWidth, canvasInnerHeight);
      const lineOffsetMap = new Map();
      for (let i3 = 0; i3 < selections.length; i3++) {
        const selection2 = selections[i3];
        for (let line = selection2.startLineNumber; line <= selection2.endLineNumber; line++) {
          this.renderDecorationOnLine(canvasContext, lineOffsetMap, selection2, this._selectionColor, layout3, line, lineHeight, lineHeight, tabSize, characterWidth);
        }
      }
      for (let i3 = 0; i3 < decorations.length; i3++) {
        const decoration = decorations[i3];
        if (!decoration.options.minimap) {
          continue;
        }
        const decorationColor = decoration.options.minimap.getColor(this._theme);
        for (let line = decoration.range.startLineNumber; line <= decoration.range.endLineNumber; line++) {
          switch (decoration.options.minimap.position) {
            case MinimapPosition$1.Inline:
              this.renderDecorationOnLine(canvasContext, lineOffsetMap, decoration.range, decorationColor, layout3, line, lineHeight, lineHeight, tabSize, characterWidth);
              continue;
            case MinimapPosition$1.Gutter:
              const y3 = (line - layout3.startLineNumber) * lineHeight;
              const x2 = 2;
              this.renderDecoration(canvasContext, decorationColor, x2, y3, GUTTER_DECORATION_WIDTH, lineHeight);
              continue;
          }
        }
      }
    }
  }
  renderDecorationOnLine(canvasContext, lineOffsetMap, decorationRange, decorationColor, layout3, lineNumber, height, lineHeight, tabSize, charWidth) {
    const y3 = (lineNumber - layout3.startLineNumber) * lineHeight;
    if (y3 + height < 0 || y3 > this._model.options.canvasInnerHeight) {
      return;
    }
    let lineIndexToXOffset = lineOffsetMap.get(lineNumber);
    const isFirstDecorationForLine = !lineIndexToXOffset;
    if (!lineIndexToXOffset) {
      const lineData = this._model.getLineContent(lineNumber);
      lineIndexToXOffset = [MINIMAP_GUTTER_WIDTH];
      for (let i3 = 1; i3 < lineData.length + 1; i3++) {
        const charCode = lineData.charCodeAt(i3 - 1);
        const dx = charCode === 9 ? tabSize * charWidth : isFullWidthCharacter(charCode) ? 2 * charWidth : charWidth;
        lineIndexToXOffset[i3] = lineIndexToXOffset[i3 - 1] + dx;
      }
      lineOffsetMap.set(lineNumber, lineIndexToXOffset);
    }
    const {startColumn, endColumn, startLineNumber, endLineNumber} = decorationRange;
    const x2 = startLineNumber === lineNumber ? lineIndexToXOffset[startColumn - 1] : MINIMAP_GUTTER_WIDTH;
    const endColumnForLine = endLineNumber > lineNumber ? lineIndexToXOffset.length - 1 : endColumn - 1;
    if (endColumnForLine > 0) {
      const width2 = lineIndexToXOffset[endColumnForLine] - x2 || 2;
      this.renderDecoration(canvasContext, decorationColor, x2, y3, width2, height);
    }
    if (isFirstDecorationForLine) {
      this.renderLineHighlight(canvasContext, decorationColor, y3, height);
    }
  }
  renderLineHighlight(canvasContext, decorationColor, y3, height) {
    canvasContext.fillStyle = decorationColor && decorationColor.transparent(0.5).toString() || "";
    canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y3, canvasContext.canvas.width, height);
  }
  renderDecoration(canvasContext, decorationColor, x2, y3, width2, height) {
    canvasContext.fillStyle = decorationColor && decorationColor.toString() || "";
    canvasContext.fillRect(x2, y3, width2, height);
  }
  renderLines(layout3) {
    const startLineNumber = layout3.startLineNumber;
    const endLineNumber = layout3.endLineNumber;
    const minimapLineHeight = this._model.options.minimapLineHeight;
    if (this._lastRenderData && this._lastRenderData.linesEquals(layout3)) {
      const _lastData = this._lastRenderData._get();
      return new RenderData(layout3, _lastData.imageData, _lastData.lines);
    }
    const imageData = this._getBuffer();
    if (!imageData) {
      return null;
    }
    let [_dirtyY1, _dirtyY2, needed] = InnerMinimap._renderUntouchedLines(imageData, startLineNumber, endLineNumber, minimapLineHeight, this._lastRenderData);
    const lineInfo = this._model.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed);
    const tabSize = this._model.getOptions().tabSize;
    const background = this._model.options.backgroundColor;
    const tokensColorTracker = this._model.tokensColorTracker;
    const useLighterFont = tokensColorTracker.backgroundIsLight();
    const renderMinimap = this._model.options.renderMinimap;
    const charRenderer = this._model.options.charRenderer();
    const fontScale = this._model.options.fontScale;
    const minimapCharWidth = this._model.options.minimapCharWidth;
    const baseCharHeight = renderMinimap === 1 ? 2 : 2 + 1;
    const renderMinimapLineHeight = baseCharHeight * fontScale;
    const innerLinePadding = minimapLineHeight > renderMinimapLineHeight ? Math.floor((minimapLineHeight - renderMinimapLineHeight) / 2) : 0;
    let dy = 0;
    const renderedLines = [];
    for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
      if (needed[lineIndex]) {
        InnerMinimap._renderLine(imageData, background, useLighterFont, renderMinimap, minimapCharWidth, tokensColorTracker, charRenderer, dy, innerLinePadding, tabSize, lineInfo[lineIndex], fontScale, minimapLineHeight);
      }
      renderedLines[lineIndex] = new MinimapLine(dy);
      dy += minimapLineHeight;
    }
    const dirtyY1 = _dirtyY1 === -1 ? 0 : _dirtyY1;
    const dirtyY2 = _dirtyY2 === -1 ? imageData.height : _dirtyY2;
    const dirtyHeight = dirtyY2 - dirtyY1;
    const ctx = this._canvas.domNode.getContext("2d");
    ctx.putImageData(imageData, 0, 0, 0, dirtyY1, imageData.width, dirtyHeight);
    return new RenderData(layout3, imageData, renderedLines);
  }
  static _renderUntouchedLines(target, startLineNumber, endLineNumber, minimapLineHeight, lastRenderData) {
    const needed = [];
    if (!lastRenderData) {
      for (let i3 = 0, len2 = endLineNumber - startLineNumber + 1; i3 < len2; i3++) {
        needed[i3] = true;
      }
      return [-1, -1, needed];
    }
    const _lastData = lastRenderData._get();
    const lastTargetData = _lastData.imageData.data;
    const lastStartLineNumber = _lastData.rendLineNumberStart;
    const lastLines = _lastData.lines;
    const lastLinesLength = lastLines.length;
    const WIDTH = target.width;
    const targetData = target.data;
    const maxDestPixel = (endLineNumber - startLineNumber + 1) * minimapLineHeight * WIDTH * 4;
    let dirtyPixel1 = -1;
    let dirtyPixel2 = -1;
    let copySourceStart = -1;
    let copySourceEnd = -1;
    let copyDestStart = -1;
    let copyDestEnd = -1;
    let dest_dy = 0;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const lineIndex = lineNumber - startLineNumber;
      const lastLineIndex = lineNumber - lastStartLineNumber;
      const source_dy = lastLineIndex >= 0 && lastLineIndex < lastLinesLength ? lastLines[lastLineIndex].dy : -1;
      if (source_dy === -1) {
        needed[lineIndex] = true;
        dest_dy += minimapLineHeight;
        continue;
      }
      const sourceStart = source_dy * WIDTH * 4;
      const sourceEnd = (source_dy + minimapLineHeight) * WIDTH * 4;
      const destStart = dest_dy * WIDTH * 4;
      const destEnd = (dest_dy + minimapLineHeight) * WIDTH * 4;
      if (copySourceEnd === sourceStart && copyDestEnd === destStart) {
        copySourceEnd = sourceEnd;
        copyDestEnd = destEnd;
      } else {
        if (copySourceStart !== -1) {
          targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
          if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) {
            dirtyPixel1 = copySourceEnd;
          }
          if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) {
            dirtyPixel2 = copySourceStart;
          }
        }
        copySourceStart = sourceStart;
        copySourceEnd = sourceEnd;
        copyDestStart = destStart;
        copyDestEnd = destEnd;
      }
      needed[lineIndex] = false;
      dest_dy += minimapLineHeight;
    }
    if (copySourceStart !== -1) {
      targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
      if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) {
        dirtyPixel1 = copySourceEnd;
      }
      if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) {
        dirtyPixel2 = copySourceStart;
      }
    }
    const dirtyY1 = dirtyPixel1 === -1 ? -1 : dirtyPixel1 / (WIDTH * 4);
    const dirtyY2 = dirtyPixel2 === -1 ? -1 : dirtyPixel2 / (WIDTH * 4);
    return [dirtyY1, dirtyY2, needed];
  }
  static _renderLine(target, backgroundColor, useLighterFont, renderMinimap, charWidth, colorTracker, minimapCharRenderer, dy, innerLinePadding, tabSize, lineData, fontScale, minimapLineHeight) {
    const content2 = lineData.content;
    const tokens = lineData.tokens;
    const maxDx = target.width - charWidth;
    const force1pxHeight = minimapLineHeight === 1;
    let dx = MINIMAP_GUTTER_WIDTH;
    let charIndex = 0;
    let tabsCharDelta = 0;
    for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
      const tokenEndIndex = tokens.getEndOffset(tokenIndex);
      const tokenColorId = tokens.getForeground(tokenIndex);
      const tokenColor = colorTracker.getColor(tokenColorId);
      for (; charIndex < tokenEndIndex; charIndex++) {
        if (dx > maxDx) {
          return;
        }
        const charCode = content2.charCodeAt(charIndex);
        if (charCode === 9) {
          const insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
          tabsCharDelta += insertSpacesCount - 1;
          dx += insertSpacesCount * charWidth;
        } else if (charCode === 32) {
          dx += charWidth;
        } else {
          const count = isFullWidthCharacter(charCode) ? 2 : 1;
          for (let i3 = 0; i3 < count; i3++) {
            if (renderMinimap === 2) {
              minimapCharRenderer.blockRenderChar(target, dx, dy + innerLinePadding, tokenColor, backgroundColor, useLighterFont, force1pxHeight);
            } else {
              minimapCharRenderer.renderChar(target, dx, dy + innerLinePadding, charCode, tokenColor, backgroundColor, fontScale, useLighterFont, force1pxHeight);
            }
            dx += charWidth;
            if (dx > maxDx) {
              return;
            }
          }
        }
      }
    }
  }
};
registerThemingParticipant((theme, collector) => {
  const minimapBackgroundValue = theme.getColor(minimapBackground);
  if (minimapBackgroundValue) {
    collector.addRule(`.monaco-editor .minimap > canvas { opacity: ${minimapBackgroundValue.rgba.a}; will-change: opacity; }`);
  }
  const sliderBackground = theme.getColor(minimapSliderBackground);
  if (sliderBackground) {
    collector.addRule(`.monaco-editor .minimap-slider .minimap-slider-horizontal { background: ${sliderBackground}; }`);
  }
  const sliderHoverBackground = theme.getColor(minimapSliderHoverBackground);
  if (sliderHoverBackground) {
    collector.addRule(`.monaco-editor .minimap-slider:hover .minimap-slider-horizontal { background: ${sliderHoverBackground}; }`);
  }
  const sliderActiveBackground = theme.getColor(minimapSliderActiveBackground);
  if (sliderActiveBackground) {
    collector.addRule(`.monaco-editor .minimap-slider.active .minimap-slider-horizontal { background: ${sliderActiveBackground}; }`);
  }
  const shadow = theme.getColor(scrollbarShadow);
  if (shadow) {
    collector.addRule(`.monaco-editor .minimap-shadow-visible { box-shadow: ${shadow} -6px 0 6px -6px inset; }`);
  }
});
function __snowpack__injectStyle$f(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$f("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n.monaco-editor .overlayWidgets {\r\n	position: absolute;\r\n	top: 0;\r\n	left:0;\r\n}");
var ViewOverlayWidgets = class extends ViewPart {
  constructor(context2) {
    super(context2);
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._widgets = {};
    this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
    this._minimapWidth = layoutInfo.minimap.minimapWidth;
    this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
    this._editorHeight = layoutInfo.height;
    this._editorWidth = layoutInfo.width;
    this._domNode = createFastDomNode(document.createElement("div"));
    PartFingerprints.write(this._domNode, 4);
    this._domNode.setClassName("overlayWidgets");
  }
  dispose() {
    super.dispose();
    this._widgets = {};
  }
  getDomNode() {
    return this._domNode;
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
    this._minimapWidth = layoutInfo.minimap.minimapWidth;
    this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
    this._editorHeight = layoutInfo.height;
    this._editorWidth = layoutInfo.width;
    return true;
  }
  addWidget(widget) {
    const domNode = createFastDomNode(widget.getDomNode());
    this._widgets[widget.getId()] = {
      widget,
      preference: null,
      domNode
    };
    domNode.setPosition("absolute");
    domNode.setAttribute("widgetId", widget.getId());
    this._domNode.appendChild(domNode);
    this.setShouldRender();
  }
  setWidgetPosition(widget, preference) {
    const widgetData = this._widgets[widget.getId()];
    if (widgetData.preference === preference) {
      return false;
    }
    widgetData.preference = preference;
    this.setShouldRender();
    return true;
  }
  removeWidget(widget) {
    const widgetId = widget.getId();
    if (this._widgets.hasOwnProperty(widgetId)) {
      const widgetData = this._widgets[widgetId];
      const domNode = widgetData.domNode.domNode;
      delete this._widgets[widgetId];
      domNode.parentNode.removeChild(domNode);
      this.setShouldRender();
    }
  }
  _renderWidget(widgetData) {
    const domNode = widgetData.domNode;
    if (widgetData.preference === null) {
      domNode.unsetTop();
      return;
    }
    if (widgetData.preference === 0) {
      domNode.setTop(0);
      domNode.setRight(2 * this._verticalScrollbarWidth + this._minimapWidth);
    } else if (widgetData.preference === 1) {
      const widgetHeight = domNode.domNode.clientHeight;
      domNode.setTop(this._editorHeight - widgetHeight - 2 * this._horizontalScrollbarHeight);
      domNode.setRight(2 * this._verticalScrollbarWidth + this._minimapWidth);
    } else if (widgetData.preference === 2) {
      domNode.setTop(0);
      domNode.domNode.style.right = "50%";
    }
  }
  prepareRender(ctx) {
  }
  render(ctx) {
    this._domNode.setWidth(this._editorWidth);
    const keys2 = Object.keys(this._widgets);
    for (let i3 = 0, len2 = keys2.length; i3 < len2; i3++) {
      const widgetId = keys2[i3];
      this._renderWidget(this._widgets[widgetId]);
    }
  }
};
var Settings = class {
  constructor(config2, theme) {
    const options = config2.options;
    this.lineHeight = options.get(51);
    this.pixelRatio = options.get(115);
    this.overviewRulerLanes = options.get(65);
    this.renderBorder = options.get(64);
    const borderColor = theme.getColor(editorOverviewRulerBorder);
    this.borderColor = borderColor ? borderColor.toString() : null;
    this.hideCursor = options.get(44);
    const cursorColor = theme.getColor(editorCursorForeground);
    this.cursorColor = cursorColor ? cursorColor.transparent(0.7).toString() : null;
    this.themeType = theme.type;
    const minimapOpts = options.get(56);
    const minimapEnabled = minimapOpts.enabled;
    const minimapSide = minimapOpts.side;
    const backgroundColor = minimapEnabled ? theme.getColor(editorOverviewRulerBackground) || TokenizationRegistry.getDefaultBackground() : null;
    if (backgroundColor === null || minimapSide === "left") {
      this.backgroundColor = null;
    } else {
      this.backgroundColor = Color.Format.CSS.formatHex(backgroundColor);
    }
    const layoutInfo = options.get(117);
    const position2 = layoutInfo.overviewRuler;
    this.top = position2.top;
    this.right = position2.right;
    this.domWidth = position2.width;
    this.domHeight = position2.height;
    if (this.overviewRulerLanes === 0) {
      this.canvasWidth = 0;
      this.canvasHeight = 0;
    } else {
      this.canvasWidth = this.domWidth * this.pixelRatio | 0;
      this.canvasHeight = this.domHeight * this.pixelRatio | 0;
    }
    const [x2, w2] = this._initLanes(1, this.canvasWidth, this.overviewRulerLanes);
    this.x = x2;
    this.w = w2;
  }
  _initLanes(canvasLeftOffset, canvasWidth, laneCount) {
    const remainingWidth = canvasWidth - canvasLeftOffset;
    if (laneCount >= 3) {
      const leftWidth = Math.floor(remainingWidth / 3);
      const rightWidth = Math.floor(remainingWidth / 3);
      const centerWidth = remainingWidth - leftWidth - rightWidth;
      const leftOffset = canvasLeftOffset;
      const centerOffset = leftOffset + leftWidth;
      const rightOffset = leftOffset + leftWidth + centerWidth;
      return [
        [
          0,
          leftOffset,
          centerOffset,
          leftOffset,
          rightOffset,
          leftOffset,
          centerOffset,
          leftOffset
        ],
        [
          0,
          leftWidth,
          centerWidth,
          leftWidth + centerWidth,
          rightWidth,
          leftWidth + centerWidth + rightWidth,
          centerWidth + rightWidth,
          leftWidth + centerWidth + rightWidth
        ]
      ];
    } else if (laneCount === 2) {
      const leftWidth = Math.floor(remainingWidth / 2);
      const rightWidth = remainingWidth - leftWidth;
      const leftOffset = canvasLeftOffset;
      const rightOffset = leftOffset + leftWidth;
      return [
        [
          0,
          leftOffset,
          leftOffset,
          leftOffset,
          rightOffset,
          leftOffset,
          leftOffset,
          leftOffset
        ],
        [
          0,
          leftWidth,
          leftWidth,
          leftWidth,
          rightWidth,
          leftWidth + rightWidth,
          leftWidth + rightWidth,
          leftWidth + rightWidth
        ]
      ];
    } else {
      const offset2 = canvasLeftOffset;
      const width2 = remainingWidth;
      return [
        [
          0,
          offset2,
          offset2,
          offset2,
          offset2,
          offset2,
          offset2,
          offset2
        ],
        [
          0,
          width2,
          width2,
          width2,
          width2,
          width2,
          width2,
          width2
        ]
      ];
    }
  }
  equals(other) {
    return this.lineHeight === other.lineHeight && this.pixelRatio === other.pixelRatio && this.overviewRulerLanes === other.overviewRulerLanes && this.renderBorder === other.renderBorder && this.borderColor === other.borderColor && this.hideCursor === other.hideCursor && this.cursorColor === other.cursorColor && this.themeType === other.themeType && this.backgroundColor === other.backgroundColor && this.top === other.top && this.right === other.right && this.domWidth === other.domWidth && this.domHeight === other.domHeight && this.canvasWidth === other.canvasWidth && this.canvasHeight === other.canvasHeight;
  }
};
var DecorationsOverviewRuler = class extends ViewPart {
  constructor(context2) {
    super(context2);
    this._domNode = createFastDomNode(document.createElement("canvas"));
    this._domNode.setClassName("decorationsOverviewRuler");
    this._domNode.setPosition("absolute");
    this._domNode.setLayerHinting(true);
    this._domNode.setContain("strict");
    this._domNode.setAttribute("aria-hidden", "true");
    this._updateSettings(false);
    this._tokensColorTrackerListener = TokenizationRegistry.onDidChange((e2) => {
      if (e2.changedColorMap) {
        this._updateSettings(true);
      }
    });
    this._cursorPositions = [];
  }
  dispose() {
    super.dispose();
    this._tokensColorTrackerListener.dispose();
  }
  _updateSettings(renderNow) {
    const newSettings = new Settings(this._context.configuration, this._context.theme);
    if (this._settings && this._settings.equals(newSettings)) {
      return false;
    }
    this._settings = newSettings;
    this._domNode.setTop(this._settings.top);
    this._domNode.setRight(this._settings.right);
    this._domNode.setWidth(this._settings.domWidth);
    this._domNode.setHeight(this._settings.domHeight);
    this._domNode.domNode.width = this._settings.canvasWidth;
    this._domNode.domNode.height = this._settings.canvasHeight;
    if (renderNow) {
      this._render();
    }
    return true;
  }
  onConfigurationChanged(e2) {
    return this._updateSettings(false);
  }
  onCursorStateChanged(e2) {
    this._cursorPositions = [];
    for (let i3 = 0, len2 = e2.selections.length; i3 < len2; i3++) {
      this._cursorPositions[i3] = e2.selections[i3].getPosition();
    }
    this._cursorPositions.sort(Position.compare);
    return true;
  }
  onDecorationsChanged(e2) {
    if (e2.affectsOverviewRuler) {
      return true;
    }
    return false;
  }
  onFlushed(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollHeightChanged;
  }
  onZonesChanged(e2) {
    return true;
  }
  onThemeChanged(e2) {
    this._context.model.invalidateOverviewRulerColorCache();
    return this._updateSettings(false);
  }
  getDomNode() {
    return this._domNode.domNode;
  }
  prepareRender(ctx) {
  }
  render(editorCtx) {
    this._render();
  }
  _render() {
    if (this._settings.overviewRulerLanes === 0) {
      this._domNode.setBackgroundColor(this._settings.backgroundColor ? this._settings.backgroundColor : "");
      return;
    }
    const canvasWidth = this._settings.canvasWidth;
    const canvasHeight = this._settings.canvasHeight;
    const lineHeight = this._settings.lineHeight;
    const viewLayout = this._context.viewLayout;
    const outerHeight2 = this._context.viewLayout.getScrollHeight();
    const heightRatio = canvasHeight / outerHeight2;
    const decorations = this._context.model.getAllOverviewRulerDecorations(this._context.theme);
    const minDecorationHeight = 6 * this._settings.pixelRatio | 0;
    const halfMinDecorationHeight = minDecorationHeight / 2 | 0;
    const canvasCtx = this._domNode.domNode.getContext("2d");
    if (this._settings.backgroundColor === null) {
      canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
    } else {
      canvasCtx.fillStyle = this._settings.backgroundColor;
      canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
    }
    const x2 = this._settings.x;
    const w2 = this._settings.w;
    const colors = Object.keys(decorations);
    colors.sort();
    for (let cIndex = 0, cLen = colors.length; cIndex < cLen; cIndex++) {
      const color2 = colors[cIndex];
      const colorDecorations = decorations[color2];
      canvasCtx.fillStyle = color2;
      let prevLane = 0;
      let prevY1 = 0;
      let prevY2 = 0;
      for (let i3 = 0, len2 = colorDecorations.length; i3 < len2; i3++) {
        const lane = colorDecorations[3 * i3];
        const startLineNumber = colorDecorations[3 * i3 + 1];
        const endLineNumber = colorDecorations[3 * i3 + 2];
        let y1 = viewLayout.getVerticalOffsetForLineNumber(startLineNumber) * heightRatio | 0;
        let y22 = (viewLayout.getVerticalOffsetForLineNumber(endLineNumber) + lineHeight) * heightRatio | 0;
        const height = y22 - y1;
        if (height < minDecorationHeight) {
          let yCenter = (y1 + y22) / 2 | 0;
          if (yCenter < halfMinDecorationHeight) {
            yCenter = halfMinDecorationHeight;
          } else if (yCenter + halfMinDecorationHeight > canvasHeight) {
            yCenter = canvasHeight - halfMinDecorationHeight;
          }
          y1 = yCenter - halfMinDecorationHeight;
          y22 = yCenter + halfMinDecorationHeight;
        }
        if (y1 > prevY2 + 1 || lane !== prevLane) {
          if (i3 !== 0) {
            canvasCtx.fillRect(x2[prevLane], prevY1, w2[prevLane], prevY2 - prevY1);
          }
          prevLane = lane;
          prevY1 = y1;
          prevY2 = y22;
        } else {
          if (y22 > prevY2) {
            prevY2 = y22;
          }
        }
      }
      canvasCtx.fillRect(x2[prevLane], prevY1, w2[prevLane], prevY2 - prevY1);
    }
    if (!this._settings.hideCursor && this._settings.cursorColor) {
      const cursorHeight = 2 * this._settings.pixelRatio | 0;
      const halfCursorHeight = cursorHeight / 2 | 0;
      const cursorX = this._settings.x[7];
      const cursorW = this._settings.w[7];
      canvasCtx.fillStyle = this._settings.cursorColor;
      let prevY1 = -100;
      let prevY2 = -100;
      for (let i3 = 0, len2 = this._cursorPositions.length; i3 < len2; i3++) {
        const cursor = this._cursorPositions[i3];
        let yCenter = viewLayout.getVerticalOffsetForLineNumber(cursor.lineNumber) * heightRatio | 0;
        if (yCenter < halfCursorHeight) {
          yCenter = halfCursorHeight;
        } else if (yCenter + halfCursorHeight > canvasHeight) {
          yCenter = canvasHeight - halfCursorHeight;
        }
        const y1 = yCenter - halfCursorHeight;
        const y22 = y1 + cursorHeight;
        if (y1 > prevY2 + 1) {
          if (i3 !== 0) {
            canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
          }
          prevY1 = y1;
          prevY2 = y22;
        } else {
          if (y22 > prevY2) {
            prevY2 = y22;
          }
        }
      }
      canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
    }
    if (this._settings.renderBorder && this._settings.borderColor && this._settings.overviewRulerLanes > 0) {
      canvasCtx.beginPath();
      canvasCtx.lineWidth = 1;
      canvasCtx.strokeStyle = this._settings.borderColor;
      canvasCtx.moveTo(0, 0);
      canvasCtx.lineTo(0, canvasHeight);
      canvasCtx.stroke();
      canvasCtx.moveTo(0, 0);
      canvasCtx.lineTo(canvasWidth, 0);
      canvasCtx.stroke();
    }
  }
};
var ColorZone = class {
  constructor(from, to, colorId) {
    this.from = from | 0;
    this.to = to | 0;
    this.colorId = colorId | 0;
  }
  static compare(a2, b2) {
    if (a2.colorId === b2.colorId) {
      if (a2.from === b2.from) {
        return a2.to - b2.to;
      }
      return a2.from - b2.from;
    }
    return a2.colorId - b2.colorId;
  }
};
var OverviewRulerZone = class {
  constructor(startLineNumber, endLineNumber, color2) {
    this.startLineNumber = startLineNumber;
    this.endLineNumber = endLineNumber;
    this.color = color2;
    this._colorZone = null;
  }
  static compare(a2, b2) {
    if (a2.color === b2.color) {
      if (a2.startLineNumber === b2.startLineNumber) {
        return a2.endLineNumber - b2.endLineNumber;
      }
      return a2.startLineNumber - b2.startLineNumber;
    }
    return a2.color < b2.color ? -1 : 1;
  }
  setColorZone(colorZone) {
    this._colorZone = colorZone;
  }
  getColorZones() {
    return this._colorZone;
  }
};
var OverviewZoneManager = class {
  constructor(getVerticalOffsetForLine) {
    this._getVerticalOffsetForLine = getVerticalOffsetForLine;
    this._zones = [];
    this._colorZonesInvalid = false;
    this._lineHeight = 0;
    this._domWidth = 0;
    this._domHeight = 0;
    this._outerHeight = 0;
    this._pixelRatio = 1;
    this._lastAssignedId = 0;
    this._color2Id = Object.create(null);
    this._id2Color = [];
  }
  getId2Color() {
    return this._id2Color;
  }
  setZones(newZones) {
    this._zones = newZones;
    this._zones.sort(OverviewRulerZone.compare);
  }
  setLineHeight(lineHeight) {
    if (this._lineHeight === lineHeight) {
      return false;
    }
    this._lineHeight = lineHeight;
    this._colorZonesInvalid = true;
    return true;
  }
  setPixelRatio(pixelRatio) {
    this._pixelRatio = pixelRatio;
    this._colorZonesInvalid = true;
  }
  getDOMWidth() {
    return this._domWidth;
  }
  getCanvasWidth() {
    return this._domWidth * this._pixelRatio;
  }
  setDOMWidth(width2) {
    if (this._domWidth === width2) {
      return false;
    }
    this._domWidth = width2;
    this._colorZonesInvalid = true;
    return true;
  }
  getDOMHeight() {
    return this._domHeight;
  }
  getCanvasHeight() {
    return this._domHeight * this._pixelRatio;
  }
  setDOMHeight(height) {
    if (this._domHeight === height) {
      return false;
    }
    this._domHeight = height;
    this._colorZonesInvalid = true;
    return true;
  }
  getOuterHeight() {
    return this._outerHeight;
  }
  setOuterHeight(outerHeight2) {
    if (this._outerHeight === outerHeight2) {
      return false;
    }
    this._outerHeight = outerHeight2;
    this._colorZonesInvalid = true;
    return true;
  }
  resolveColorZones() {
    const colorZonesInvalid = this._colorZonesInvalid;
    const lineHeight = Math.floor(this._lineHeight);
    const totalHeight = Math.floor(this.getCanvasHeight());
    const outerHeight2 = Math.floor(this._outerHeight);
    const heightRatio = totalHeight / outerHeight2;
    const halfMinimumHeight = Math.floor(4 * this._pixelRatio / 2);
    let allColorZones = [];
    for (let i3 = 0, len2 = this._zones.length; i3 < len2; i3++) {
      const zone = this._zones[i3];
      if (!colorZonesInvalid) {
        const colorZone2 = zone.getColorZones();
        if (colorZone2) {
          allColorZones.push(colorZone2);
          continue;
        }
      }
      const y1 = Math.floor(heightRatio * this._getVerticalOffsetForLine(zone.startLineNumber));
      const y22 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.endLineNumber) + lineHeight));
      let ycenter = Math.floor((y1 + y22) / 2);
      let halfHeight = y22 - ycenter;
      if (halfHeight < halfMinimumHeight) {
        halfHeight = halfMinimumHeight;
      }
      if (ycenter - halfHeight < 0) {
        ycenter = halfHeight;
      }
      if (ycenter + halfHeight > totalHeight) {
        ycenter = totalHeight - halfHeight;
      }
      const color2 = zone.color;
      let colorId = this._color2Id[color2];
      if (!colorId) {
        colorId = ++this._lastAssignedId;
        this._color2Id[color2] = colorId;
        this._id2Color[colorId] = color2;
      }
      const colorZone = new ColorZone(ycenter - halfHeight, ycenter + halfHeight, colorId);
      zone.setColorZone(colorZone);
      allColorZones.push(colorZone);
    }
    this._colorZonesInvalid = false;
    allColorZones.sort(ColorZone.compare);
    return allColorZones;
  }
};
var OverviewRuler = class extends ViewEventHandler {
  constructor(context2, cssClassName) {
    super();
    this._context = context2;
    const options = this._context.configuration.options;
    this._domNode = createFastDomNode(document.createElement("canvas"));
    this._domNode.setClassName(cssClassName);
    this._domNode.setPosition("absolute");
    this._domNode.setLayerHinting(true);
    this._domNode.setContain("strict");
    this._zoneManager = new OverviewZoneManager((lineNumber) => this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber));
    this._zoneManager.setDOMWidth(0);
    this._zoneManager.setDOMHeight(0);
    this._zoneManager.setOuterHeight(this._context.viewLayout.getScrollHeight());
    this._zoneManager.setLineHeight(options.get(51));
    this._zoneManager.setPixelRatio(options.get(115));
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    super.dispose();
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    if (e2.hasChanged(51)) {
      this._zoneManager.setLineHeight(options.get(51));
      this._render();
    }
    if (e2.hasChanged(115)) {
      this._zoneManager.setPixelRatio(options.get(115));
      this._domNode.setWidth(this._zoneManager.getDOMWidth());
      this._domNode.setHeight(this._zoneManager.getDOMHeight());
      this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
      this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
      this._render();
    }
    return true;
  }
  onFlushed(e2) {
    this._render();
    return true;
  }
  onScrollChanged(e2) {
    if (e2.scrollHeightChanged) {
      this._zoneManager.setOuterHeight(e2.scrollHeight);
      this._render();
    }
    return true;
  }
  onZonesChanged(e2) {
    this._render();
    return true;
  }
  getDomNode() {
    return this._domNode.domNode;
  }
  setLayout(position2) {
    this._domNode.setTop(position2.top);
    this._domNode.setRight(position2.right);
    let hasChanged = false;
    hasChanged = this._zoneManager.setDOMWidth(position2.width) || hasChanged;
    hasChanged = this._zoneManager.setDOMHeight(position2.height) || hasChanged;
    if (hasChanged) {
      this._domNode.setWidth(this._zoneManager.getDOMWidth());
      this._domNode.setHeight(this._zoneManager.getDOMHeight());
      this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
      this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
      this._render();
    }
  }
  setZones(zones) {
    this._zoneManager.setZones(zones);
    this._render();
  }
  _render() {
    if (this._zoneManager.getOuterHeight() === 0) {
      return false;
    }
    const width2 = this._zoneManager.getCanvasWidth();
    const height = this._zoneManager.getCanvasHeight();
    const colorZones = this._zoneManager.resolveColorZones();
    const id2Color = this._zoneManager.getId2Color();
    const ctx = this._domNode.domNode.getContext("2d");
    ctx.clearRect(0, 0, width2, height);
    if (colorZones.length > 0) {
      this._renderOneLane(ctx, colorZones, id2Color, width2);
    }
    return true;
  }
  _renderOneLane(ctx, colorZones, id2Color, width2) {
    let currentColorId = 0;
    let currentFrom = 0;
    let currentTo = 0;
    for (const zone of colorZones) {
      const zoneColorId = zone.colorId;
      const zoneFrom = zone.from;
      const zoneTo = zone.to;
      if (zoneColorId !== currentColorId) {
        ctx.fillRect(0, currentFrom, width2, currentTo - currentFrom);
        currentColorId = zoneColorId;
        ctx.fillStyle = id2Color[currentColorId];
        currentFrom = zoneFrom;
        currentTo = zoneTo;
      } else {
        if (currentTo >= zoneFrom) {
          currentTo = Math.max(currentTo, zoneTo);
        } else {
          ctx.fillRect(0, currentFrom, width2, currentTo - currentFrom);
          currentFrom = zoneFrom;
          currentTo = zoneTo;
        }
      }
    }
    ctx.fillRect(0, currentFrom, width2, currentTo - currentFrom);
  }
};
function __snowpack__injectStyle$g(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$g("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-editor .view-ruler {\r\n	position: absolute;\r\n	top: 0;\r\n}");
var Rulers = class extends ViewPart {
  constructor(context2) {
    super(context2);
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this.domNode.setClassName("view-rulers");
    this._renderedRulers = [];
    const options = this._context.configuration.options;
    this._rulers = options.get(83);
    this._typicalHalfwidthCharacterWidth = options.get(36).typicalHalfwidthCharacterWidth;
  }
  dispose() {
    super.dispose();
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    this._rulers = options.get(83);
    this._typicalHalfwidthCharacterWidth = options.get(36).typicalHalfwidthCharacterWidth;
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollHeightChanged;
  }
  prepareRender(ctx) {
  }
  _ensureRulersCount() {
    const currentCount = this._renderedRulers.length;
    const desiredCount = this._rulers.length;
    if (currentCount === desiredCount) {
      return;
    }
    if (currentCount < desiredCount) {
      const {tabSize} = this._context.model.getTextModelOptions();
      const rulerWidth = tabSize;
      let addCount = desiredCount - currentCount;
      while (addCount > 0) {
        const node = createFastDomNode(document.createElement("div"));
        node.setClassName("view-ruler");
        node.setWidth(rulerWidth);
        this.domNode.appendChild(node);
        this._renderedRulers.push(node);
        addCount--;
      }
      return;
    }
    let removeCount = currentCount - desiredCount;
    while (removeCount > 0) {
      const node = this._renderedRulers.pop();
      this.domNode.removeChild(node);
      removeCount--;
    }
  }
  render(ctx) {
    this._ensureRulersCount();
    for (let i3 = 0, len2 = this._rulers.length; i3 < len2; i3++) {
      const node = this._renderedRulers[i3];
      const ruler = this._rulers[i3];
      node.setBoxShadow(ruler.color ? `1px 0 0 0 ${ruler.color} inset` : ``);
      node.setHeight(Math.min(ctx.scrollHeight, 1e6));
      node.setLeft(ruler.column * this._typicalHalfwidthCharacterWidth);
    }
  }
};
registerThemingParticipant((theme, collector) => {
  const rulerColor = theme.getColor(editorRuler);
  if (rulerColor) {
    collector.addRule(`.monaco-editor .view-ruler { box-shadow: 1px 0 0 0 ${rulerColor} inset; }`);
  }
});
function __snowpack__injectStyle$h(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$h("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-editor .scroll-decoration {\r\n	position: absolute;\r\n	top: 0;\r\n	left: 0;\r\n	height: 6px;\r\n}");
var ScrollDecorationViewPart = class extends ViewPart {
  constructor(context2) {
    super(context2);
    this._scrollTop = 0;
    this._width = 0;
    this._updateWidth();
    this._shouldShow = false;
    const options = this._context.configuration.options;
    const scrollbar = options.get(84);
    this._useShadows = scrollbar.useShadows;
    this._domNode = createFastDomNode(document.createElement("div"));
    this._domNode.setAttribute("role", "presentation");
    this._domNode.setAttribute("aria-hidden", "true");
  }
  dispose() {
    super.dispose();
  }
  _updateShouldShow() {
    const newShouldShow = this._useShadows && this._scrollTop > 0;
    if (this._shouldShow !== newShouldShow) {
      this._shouldShow = newShouldShow;
      return true;
    }
    return false;
  }
  getDomNode() {
    return this._domNode;
  }
  _updateWidth() {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    if (layoutInfo.minimap.renderMinimap === 0 || layoutInfo.minimap.minimapWidth > 0 && layoutInfo.minimap.minimapLeft === 0) {
      this._width = layoutInfo.width;
    } else {
      this._width = layoutInfo.width - layoutInfo.minimap.minimapWidth - layoutInfo.verticalScrollbarWidth;
    }
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    const scrollbar = options.get(84);
    this._useShadows = scrollbar.useShadows;
    this._updateWidth();
    this._updateShouldShow();
    return true;
  }
  onScrollChanged(e2) {
    this._scrollTop = e2.scrollTop;
    return this._updateShouldShow();
  }
  prepareRender(ctx) {
  }
  render(ctx) {
    this._domNode.setWidth(this._width);
    this._domNode.setClassName(this._shouldShow ? "scroll-decoration" : "");
  }
};
registerThemingParticipant((theme, collector) => {
  const shadow = theme.getColor(scrollbarShadow);
  if (shadow) {
    collector.addRule(`.monaco-editor .scroll-decoration { box-shadow: ${shadow} 0 6px 6px -6px inset; }`);
  }
});
function __snowpack__injectStyle$i(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$i("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n/*\r\n	Keeping name short for faster parsing.\r\n	cslr = core selections layer rendering (div)\r\n*/\r\n.monaco-editor .lines-content .cslr {\r\n	position: absolute;\r\n}\r\n\r\n.monaco-editor			.top-left-radius		{ border-top-left-radius: 3px; }\r\n.monaco-editor			.bottom-left-radius		{ border-bottom-left-radius: 3px; }\r\n.monaco-editor			.top-right-radius		{ border-top-right-radius: 3px; }\r\n.monaco-editor			.bottom-right-radius	{ border-bottom-right-radius: 3px; }\r\n\r\n.monaco-editor.hc-black .top-left-radius		{ border-top-left-radius: 0; }\r\n.monaco-editor.hc-black .bottom-left-radius		{ border-bottom-left-radius: 0; }\r\n.monaco-editor.hc-black .top-right-radius		{ border-top-right-radius: 0; }\r\n.monaco-editor.hc-black .bottom-right-radius	{ border-bottom-right-radius: 0; }\r\n");
var HorizontalRangeWithStyle = class {
  constructor(other) {
    this.left = other.left;
    this.width = other.width;
    this.startStyle = null;
    this.endStyle = null;
  }
};
var LineVisibleRangesWithStyle = class {
  constructor(lineNumber, ranges) {
    this.lineNumber = lineNumber;
    this.ranges = ranges;
  }
};
function toStyledRange(item) {
  return new HorizontalRangeWithStyle(item);
}
function toStyled(item) {
  return new LineVisibleRangesWithStyle(item.lineNumber, item.ranges.map(toStyledRange));
}
var isIEWithZoomingIssuesNearRoundedBorders = isEdge2;
var SelectionsOverlay = class extends DynamicViewOverlay {
  constructor(context2) {
    super();
    this._previousFrameVisibleRangesWithStyle = [];
    this._context = context2;
    const options = this._context.configuration.options;
    this._lineHeight = options.get(51);
    this._roundedSelection = options.get(82);
    this._typicalHalfwidthCharacterWidth = options.get(36).typicalHalfwidthCharacterWidth;
    this._selections = [];
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    this._lineHeight = options.get(51);
    this._roundedSelection = options.get(82);
    this._typicalHalfwidthCharacterWidth = options.get(36).typicalHalfwidthCharacterWidth;
    return true;
  }
  onCursorStateChanged(e2) {
    this._selections = e2.selections.slice(0);
    return true;
  }
  onDecorationsChanged(e2) {
    return true;
  }
  onFlushed(e2) {
    return true;
  }
  onLinesChanged(e2) {
    return true;
  }
  onLinesDeleted(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollTopChanged;
  }
  onZonesChanged(e2) {
    return true;
  }
  _visibleRangesHaveGaps(linesVisibleRanges) {
    for (let i3 = 0, len2 = linesVisibleRanges.length; i3 < len2; i3++) {
      const lineVisibleRanges = linesVisibleRanges[i3];
      if (lineVisibleRanges.ranges.length > 1) {
        return true;
      }
    }
    return false;
  }
  _enrichVisibleRangesWithStyle(viewport2, linesVisibleRanges, previousFrame) {
    const epsilon = this._typicalHalfwidthCharacterWidth / 4;
    let previousFrameTop = null;
    let previousFrameBottom = null;
    if (previousFrame && previousFrame.length > 0 && linesVisibleRanges.length > 0) {
      const topLineNumber = linesVisibleRanges[0].lineNumber;
      if (topLineNumber === viewport2.startLineNumber) {
        for (let i3 = 0; !previousFrameTop && i3 < previousFrame.length; i3++) {
          if (previousFrame[i3].lineNumber === topLineNumber) {
            previousFrameTop = previousFrame[i3].ranges[0];
          }
        }
      }
      const bottomLineNumber = linesVisibleRanges[linesVisibleRanges.length - 1].lineNumber;
      if (bottomLineNumber === viewport2.endLineNumber) {
        for (let i3 = previousFrame.length - 1; !previousFrameBottom && i3 >= 0; i3--) {
          if (previousFrame[i3].lineNumber === bottomLineNumber) {
            previousFrameBottom = previousFrame[i3].ranges[0];
          }
        }
      }
      if (previousFrameTop && !previousFrameTop.startStyle) {
        previousFrameTop = null;
      }
      if (previousFrameBottom && !previousFrameBottom.startStyle) {
        previousFrameBottom = null;
      }
    }
    for (let i3 = 0, len2 = linesVisibleRanges.length; i3 < len2; i3++) {
      const curLineRange = linesVisibleRanges[i3].ranges[0];
      const curLeft = curLineRange.left;
      const curRight = curLineRange.left + curLineRange.width;
      const startStyle = {
        top: 0,
        bottom: 0
      };
      const endStyle = {
        top: 0,
        bottom: 0
      };
      if (i3 > 0) {
        const prevLeft = linesVisibleRanges[i3 - 1].ranges[0].left;
        const prevRight = linesVisibleRanges[i3 - 1].ranges[0].left + linesVisibleRanges[i3 - 1].ranges[0].width;
        if (abs(curLeft - prevLeft) < epsilon) {
          startStyle.top = 2;
        } else if (curLeft > prevLeft) {
          startStyle.top = 1;
        }
        if (abs(curRight - prevRight) < epsilon) {
          endStyle.top = 2;
        } else if (prevLeft < curRight && curRight < prevRight) {
          endStyle.top = 1;
        }
      } else if (previousFrameTop) {
        startStyle.top = previousFrameTop.startStyle.top;
        endStyle.top = previousFrameTop.endStyle.top;
      }
      if (i3 + 1 < len2) {
        const nextLeft = linesVisibleRanges[i3 + 1].ranges[0].left;
        const nextRight = linesVisibleRanges[i3 + 1].ranges[0].left + linesVisibleRanges[i3 + 1].ranges[0].width;
        if (abs(curLeft - nextLeft) < epsilon) {
          startStyle.bottom = 2;
        } else if (nextLeft < curLeft && curLeft < nextRight) {
          startStyle.bottom = 1;
        }
        if (abs(curRight - nextRight) < epsilon) {
          endStyle.bottom = 2;
        } else if (curRight < nextRight) {
          endStyle.bottom = 1;
        }
      } else if (previousFrameBottom) {
        startStyle.bottom = previousFrameBottom.startStyle.bottom;
        endStyle.bottom = previousFrameBottom.endStyle.bottom;
      }
      curLineRange.startStyle = startStyle;
      curLineRange.endStyle = endStyle;
    }
  }
  _getVisibleRangesWithStyle(selection2, ctx, previousFrame) {
    const _linesVisibleRanges = ctx.linesVisibleRangesForRange(selection2, true) || [];
    const linesVisibleRanges = _linesVisibleRanges.map(toStyled);
    const visibleRangesHaveGaps = this._visibleRangesHaveGaps(linesVisibleRanges);
    if (!isIEWithZoomingIssuesNearRoundedBorders && !visibleRangesHaveGaps && this._roundedSelection) {
      this._enrichVisibleRangesWithStyle(ctx.visibleRange, linesVisibleRanges, previousFrame);
    }
    return linesVisibleRanges;
  }
  _createSelectionPiece(top2, height, className, left2, width2) {
    return '<div class="cslr ' + className + '" style="top:' + top2.toString() + "px;left:" + left2.toString() + "px;width:" + width2.toString() + "px;height:" + height + 'px;"></div>';
  }
  _actualRenderOneSelection(output2, visibleStartLineNumber, hasMultipleSelections, visibleRanges) {
    if (visibleRanges.length === 0) {
      return;
    }
    const visibleRangesHaveStyle = !!visibleRanges[0].ranges[0].startStyle;
    const fullLineHeight = this._lineHeight.toString();
    const reducedLineHeight = (this._lineHeight - 1).toString();
    const firstLineNumber = visibleRanges[0].lineNumber;
    const lastLineNumber = visibleRanges[visibleRanges.length - 1].lineNumber;
    for (let i3 = 0, len2 = visibleRanges.length; i3 < len2; i3++) {
      const lineVisibleRanges = visibleRanges[i3];
      const lineNumber = lineVisibleRanges.lineNumber;
      const lineIndex = lineNumber - visibleStartLineNumber;
      const lineHeight = hasMultipleSelections ? lineNumber === lastLineNumber || lineNumber === firstLineNumber ? reducedLineHeight : fullLineHeight : fullLineHeight;
      const top2 = hasMultipleSelections ? lineNumber === firstLineNumber ? 1 : 0 : 0;
      let innerCornerOutput = "";
      let restOfSelectionOutput = "";
      for (let j = 0, lenJ = lineVisibleRanges.ranges.length; j < lenJ; j++) {
        const visibleRange = lineVisibleRanges.ranges[j];
        if (visibleRangesHaveStyle) {
          const startStyle = visibleRange.startStyle;
          const endStyle = visibleRange.endStyle;
          if (startStyle.top === 1 || startStyle.bottom === 1) {
            innerCornerOutput += this._createSelectionPiece(top2, lineHeight, SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left - SelectionsOverlay.ROUNDED_PIECE_WIDTH, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
            let className2 = SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME;
            if (startStyle.top === 1) {
              className2 += " " + SelectionsOverlay.SELECTION_TOP_RIGHT;
            }
            if (startStyle.bottom === 1) {
              className2 += " " + SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
            }
            innerCornerOutput += this._createSelectionPiece(top2, lineHeight, className2, visibleRange.left - SelectionsOverlay.ROUNDED_PIECE_WIDTH, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
          }
          if (endStyle.top === 1 || endStyle.bottom === 1) {
            innerCornerOutput += this._createSelectionPiece(top2, lineHeight, SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left + visibleRange.width, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
            let className2 = SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME;
            if (endStyle.top === 1) {
              className2 += " " + SelectionsOverlay.SELECTION_TOP_LEFT;
            }
            if (endStyle.bottom === 1) {
              className2 += " " + SelectionsOverlay.SELECTION_BOTTOM_LEFT;
            }
            innerCornerOutput += this._createSelectionPiece(top2, lineHeight, className2, visibleRange.left + visibleRange.width, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
          }
        }
        let className = SelectionsOverlay.SELECTION_CLASS_NAME;
        if (visibleRangesHaveStyle) {
          const startStyle = visibleRange.startStyle;
          const endStyle = visibleRange.endStyle;
          if (startStyle.top === 0) {
            className += " " + SelectionsOverlay.SELECTION_TOP_LEFT;
          }
          if (startStyle.bottom === 0) {
            className += " " + SelectionsOverlay.SELECTION_BOTTOM_LEFT;
          }
          if (endStyle.top === 0) {
            className += " " + SelectionsOverlay.SELECTION_TOP_RIGHT;
          }
          if (endStyle.bottom === 0) {
            className += " " + SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
          }
        }
        restOfSelectionOutput += this._createSelectionPiece(top2, lineHeight, className, visibleRange.left, visibleRange.width);
      }
      output2[lineIndex][0] += innerCornerOutput;
      output2[lineIndex][1] += restOfSelectionOutput;
    }
  }
  prepareRender(ctx) {
    const output2 = [];
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      output2[lineIndex] = ["", ""];
    }
    const thisFrameVisibleRangesWithStyle = [];
    for (let i3 = 0, len2 = this._selections.length; i3 < len2; i3++) {
      const selection2 = this._selections[i3];
      if (selection2.isEmpty()) {
        thisFrameVisibleRangesWithStyle[i3] = null;
        continue;
      }
      const visibleRangesWithStyle = this._getVisibleRangesWithStyle(selection2, ctx, this._previousFrameVisibleRangesWithStyle[i3]);
      thisFrameVisibleRangesWithStyle[i3] = visibleRangesWithStyle;
      this._actualRenderOneSelection(output2, visibleStartLineNumber, this._selections.length > 1, visibleRangesWithStyle);
    }
    this._previousFrameVisibleRangesWithStyle = thisFrameVisibleRangesWithStyle;
    this._renderResult = output2.map(([internalCorners, restOfSelection]) => internalCorners + restOfSelection);
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
      return "";
    }
    return this._renderResult[lineIndex];
  }
};
SelectionsOverlay.SELECTION_CLASS_NAME = "selected-text";
SelectionsOverlay.SELECTION_TOP_LEFT = "top-left-radius";
SelectionsOverlay.SELECTION_BOTTOM_LEFT = "bottom-left-radius";
SelectionsOverlay.SELECTION_TOP_RIGHT = "top-right-radius";
SelectionsOverlay.SELECTION_BOTTOM_RIGHT = "bottom-right-radius";
SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME = "monaco-editor-background";
SelectionsOverlay.ROUNDED_PIECE_WIDTH = 10;
registerThemingParticipant((theme, collector) => {
  const editorSelectionColor = theme.getColor(editorSelectionBackground);
  if (editorSelectionColor) {
    collector.addRule(`.monaco-editor .focused .selected-text { background-color: ${editorSelectionColor}; }`);
  }
  const editorInactiveSelectionColor = theme.getColor(editorInactiveSelection);
  if (editorInactiveSelectionColor) {
    collector.addRule(`.monaco-editor .selected-text { background-color: ${editorInactiveSelectionColor}; }`);
  }
  const editorSelectionForegroundColor = theme.getColor(editorSelectionForeground);
  if (editorSelectionForegroundColor && !editorSelectionForegroundColor.isTransparent()) {
    collector.addRule(`.monaco-editor .view-line span.inline-selected-text { color: ${editorSelectionForegroundColor}; }`);
  }
});
function abs(n3) {
  return n3 < 0 ? -n3 : n3;
}
function __snowpack__injectStyle$j(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$j("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n.monaco-editor .cursors-layer {\r\n	position: absolute;\r\n	top: 0;\r\n}\r\n\r\n.monaco-editor .cursors-layer > .cursor {\r\n	position: absolute;\r\n	overflow: hidden;\r\n}\r\n\r\n/* -- smooth-caret-animation -- */\r\n.monaco-editor .cursors-layer.cursor-smooth-caret-animation > .cursor {\r\n	transition: all 80ms;\r\n}\r\n\r\n/* -- block-outline-style -- */\r\n.monaco-editor .cursors-layer.cursor-block-outline-style > .cursor {\r\n	box-sizing: border-box;\r\n	background: transparent !important;\r\n	border-style: solid;\r\n	border-width: 1px;\r\n}\r\n\r\n/* -- underline-style -- */\r\n.monaco-editor .cursors-layer.cursor-underline-style > .cursor {\r\n	border-bottom-width: 2px;\r\n	border-bottom-style: solid;\r\n	background: transparent !important;\r\n	box-sizing: border-box;\r\n}\r\n\r\n/* -- underline-thin-style -- */\r\n.monaco-editor .cursors-layer.cursor-underline-thin-style > .cursor {\r\n	border-bottom-width: 1px;\r\n	border-bottom-style: solid;\r\n	background: transparent !important;\r\n	box-sizing: border-box;\r\n}\r\n\r\n@keyframes monaco-cursor-smooth {\r\n	0%,\r\n	20% {\r\n		opacity: 1;\r\n	}\r\n	60%,\r\n	100% {\r\n		opacity: 0;\r\n	}\r\n}\r\n\r\n@keyframes monaco-cursor-phase {\r\n	0%,\r\n	20% {\r\n		opacity: 1;\r\n	}\r\n	90%,\r\n	100% {\r\n		opacity: 0;\r\n	}\r\n}\r\n\r\n@keyframes monaco-cursor-expand {\r\n	0%,\r\n	20% {\r\n		transform: scaleY(1);\r\n	}\r\n	80%,\r\n	100% {\r\n		transform: scaleY(0);\r\n	}\r\n}\r\n\r\n.cursor-smooth {\r\n	animation: monaco-cursor-smooth 0.5s ease-in-out 0s 20 alternate;\r\n}\r\n\r\n.cursor-phase {\r\n	animation: monaco-cursor-phase 0.5s ease-in-out 0s 20 alternate;\r\n}\r\n\r\n.cursor-expand > .cursor {\r\n	animation: monaco-cursor-expand 0.5s ease-in-out 0s 20 alternate;\r\n}\r\n");
var ViewCursorRenderData = class {
  constructor(top2, left2, width2, height, textContent, textContentClassName) {
    this.top = top2;
    this.left = left2;
    this.width = width2;
    this.height = height;
    this.textContent = textContent;
    this.textContentClassName = textContentClassName;
  }
};
var ViewCursor = class {
  constructor(context2) {
    this._context = context2;
    const options = this._context.configuration.options;
    const fontInfo = options.get(36);
    this._cursorStyle = options.get(19);
    this._lineHeight = options.get(51);
    this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this._lineCursorWidth = Math.min(options.get(22), this._typicalHalfwidthCharacterWidth);
    this._isVisible = true;
    this._domNode = createFastDomNode(document.createElement("div"));
    this._domNode.setClassName(`cursor ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
    this._domNode.setHeight(this._lineHeight);
    this._domNode.setTop(0);
    this._domNode.setLeft(0);
    Configuration$1.applyFontInfo(this._domNode, fontInfo);
    this._domNode.setDisplay("none");
    this._position = new Position(1, 1);
    this._lastRenderedContent = "";
    this._renderData = null;
  }
  getDomNode() {
    return this._domNode;
  }
  getPosition() {
    return this._position;
  }
  show() {
    if (!this._isVisible) {
      this._domNode.setVisibility("inherit");
      this._isVisible = true;
    }
  }
  hide() {
    if (this._isVisible) {
      this._domNode.setVisibility("hidden");
      this._isVisible = false;
    }
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    const fontInfo = options.get(36);
    this._cursorStyle = options.get(19);
    this._lineHeight = options.get(51);
    this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this._lineCursorWidth = Math.min(options.get(22), this._typicalHalfwidthCharacterWidth);
    Configuration$1.applyFontInfo(this._domNode, fontInfo);
    return true;
  }
  onCursorPositionChanged(position2) {
    this._position = position2;
    return true;
  }
  _prepareRender(ctx) {
    let textContent = "";
    if (this._cursorStyle === TextEditorCursorStyle.Line || this._cursorStyle === TextEditorCursorStyle.LineThin) {
      const visibleRange = ctx.visibleRangeForPosition(this._position);
      if (!visibleRange || visibleRange.outsideRenderedLine) {
        return null;
      }
      let width3;
      if (this._cursorStyle === TextEditorCursorStyle.Line) {
        width3 = computeScreenAwareSize(this._lineCursorWidth > 0 ? this._lineCursorWidth : 2);
        if (width3 > 2) {
          const lineContent2 = this._context.model.getLineContent(this._position.lineNumber);
          const nextCharLength$12 = nextCharLength(lineContent2, this._position.column - 1);
          textContent = lineContent2.substr(this._position.column - 1, nextCharLength$12);
        }
      } else {
        width3 = computeScreenAwareSize(1);
      }
      let left2 = visibleRange.left;
      if (width3 >= 2 && left2 >= 1) {
        left2 -= 1;
      }
      const top3 = ctx.getVerticalOffsetForLineNumber(this._position.lineNumber) - ctx.bigNumbersDelta;
      return new ViewCursorRenderData(top3, left2, width3, this._lineHeight, textContent, "");
    }
    const lineContent = this._context.model.getLineContent(this._position.lineNumber);
    const nextCharLength$1 = nextCharLength(lineContent, this._position.column - 1);
    const visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new Range(this._position.lineNumber, this._position.column, this._position.lineNumber, this._position.column + nextCharLength$1), false);
    if (!visibleRangeForCharacter || visibleRangeForCharacter.length === 0) {
      return null;
    }
    const firstVisibleRangeForCharacter = visibleRangeForCharacter[0];
    if (firstVisibleRangeForCharacter.outsideRenderedLine || firstVisibleRangeForCharacter.ranges.length === 0) {
      return null;
    }
    const range3 = firstVisibleRangeForCharacter.ranges[0];
    const width2 = range3.width < 1 ? this._typicalHalfwidthCharacterWidth : range3.width;
    let textContentClassName = "";
    if (this._cursorStyle === TextEditorCursorStyle.Block) {
      const lineData = this._context.model.getViewLineData(this._position.lineNumber);
      textContent = lineContent.substr(this._position.column - 1, nextCharLength$1);
      const tokenIndex = lineData.tokens.findTokenIndexAtOffset(this._position.column - 1);
      textContentClassName = lineData.tokens.getClassName(tokenIndex);
    }
    let top2 = ctx.getVerticalOffsetForLineNumber(this._position.lineNumber) - ctx.bigNumbersDelta;
    let height = this._lineHeight;
    if (this._cursorStyle === TextEditorCursorStyle.Underline || this._cursorStyle === TextEditorCursorStyle.UnderlineThin) {
      top2 += this._lineHeight - 2;
      height = 2;
    }
    return new ViewCursorRenderData(top2, range3.left, width2, height, textContent, textContentClassName);
  }
  prepareRender(ctx) {
    this._renderData = this._prepareRender(ctx);
  }
  render(ctx) {
    if (!this._renderData) {
      this._domNode.setDisplay("none");
      return null;
    }
    if (this._lastRenderedContent !== this._renderData.textContent) {
      this._lastRenderedContent = this._renderData.textContent;
      this._domNode.domNode.textContent = this._lastRenderedContent;
    }
    this._domNode.setClassName(`cursor ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ${this._renderData.textContentClassName}`);
    this._domNode.setDisplay("block");
    this._domNode.setTop(this._renderData.top);
    this._domNode.setLeft(this._renderData.left);
    this._domNode.setWidth(this._renderData.width);
    this._domNode.setLineHeight(this._renderData.height);
    this._domNode.setHeight(this._renderData.height);
    return {
      domNode: this._domNode.domNode,
      position: this._position,
      contentLeft: this._renderData.left,
      height: this._renderData.height,
      width: 2
    };
  }
};
var ViewCursors = class extends ViewPart {
  constructor(context2) {
    super(context2);
    const options = this._context.configuration.options;
    this._readOnly = options.get(72);
    this._cursorBlinking = options.get(17);
    this._cursorStyle = options.get(19);
    this._cursorSmoothCaretAnimation = options.get(18);
    this._selectionIsEmpty = true;
    this._isVisible = false;
    this._primaryCursor = new ViewCursor(this._context);
    this._secondaryCursors = [];
    this._renderData = [];
    this._domNode = createFastDomNode(document.createElement("div"));
    this._domNode.setAttribute("role", "presentation");
    this._domNode.setAttribute("aria-hidden", "true");
    this._updateDomClassName();
    this._domNode.appendChild(this._primaryCursor.getDomNode());
    this._startCursorBlinkAnimation = new TimeoutTimer();
    this._cursorFlatBlinkInterval = new IntervalTimer();
    this._blinkingEnabled = false;
    this._editorHasFocus = false;
    this._updateBlinking();
  }
  dispose() {
    super.dispose();
    this._startCursorBlinkAnimation.dispose();
    this._cursorFlatBlinkInterval.dispose();
  }
  getDomNode() {
    return this._domNode;
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    this._readOnly = options.get(72);
    this._cursorBlinking = options.get(17);
    this._cursorStyle = options.get(19);
    this._cursorSmoothCaretAnimation = options.get(18);
    this._updateBlinking();
    this._updateDomClassName();
    this._primaryCursor.onConfigurationChanged(e2);
    for (let i3 = 0, len2 = this._secondaryCursors.length; i3 < len2; i3++) {
      this._secondaryCursors[i3].onConfigurationChanged(e2);
    }
    return true;
  }
  _onCursorPositionChanged(position2, secondaryPositions) {
    this._primaryCursor.onCursorPositionChanged(position2);
    this._updateBlinking();
    if (this._secondaryCursors.length < secondaryPositions.length) {
      const addCnt = secondaryPositions.length - this._secondaryCursors.length;
      for (let i3 = 0; i3 < addCnt; i3++) {
        const newCursor = new ViewCursor(this._context);
        this._domNode.domNode.insertBefore(newCursor.getDomNode().domNode, this._primaryCursor.getDomNode().domNode.nextSibling);
        this._secondaryCursors.push(newCursor);
      }
    } else if (this._secondaryCursors.length > secondaryPositions.length) {
      const removeCnt = this._secondaryCursors.length - secondaryPositions.length;
      for (let i3 = 0; i3 < removeCnt; i3++) {
        this._domNode.removeChild(this._secondaryCursors[0].getDomNode());
        this._secondaryCursors.splice(0, 1);
      }
    }
    for (let i3 = 0; i3 < secondaryPositions.length; i3++) {
      this._secondaryCursors[i3].onCursorPositionChanged(secondaryPositions[i3]);
    }
  }
  onCursorStateChanged(e2) {
    const positions = [];
    for (let i3 = 0, len2 = e2.selections.length; i3 < len2; i3++) {
      positions[i3] = e2.selections[i3].getPosition();
    }
    this._onCursorPositionChanged(positions[0], positions.slice(1));
    const selectionIsEmpty = e2.selections[0].isEmpty();
    if (this._selectionIsEmpty !== selectionIsEmpty) {
      this._selectionIsEmpty = selectionIsEmpty;
      this._updateDomClassName();
    }
    return true;
  }
  onDecorationsChanged(e2) {
    return true;
  }
  onFlushed(e2) {
    return true;
  }
  onFocusChanged(e2) {
    this._editorHasFocus = e2.isFocused;
    this._updateBlinking();
    return false;
  }
  onLinesChanged(e2) {
    return true;
  }
  onLinesDeleted(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return true;
  }
  onTokensChanged(e2) {
    const shouldRender = (position2) => {
      for (let i3 = 0, len2 = e2.ranges.length; i3 < len2; i3++) {
        if (e2.ranges[i3].fromLineNumber <= position2.lineNumber && position2.lineNumber <= e2.ranges[i3].toLineNumber) {
          return true;
        }
      }
      return false;
    };
    if (shouldRender(this._primaryCursor.getPosition())) {
      return true;
    }
    for (const secondaryCursor of this._secondaryCursors) {
      if (shouldRender(secondaryCursor.getPosition())) {
        return true;
      }
    }
    return false;
  }
  onZonesChanged(e2) {
    return true;
  }
  _getCursorBlinking() {
    if (!this._editorHasFocus) {
      return 0;
    }
    if (this._readOnly) {
      return 5;
    }
    return this._cursorBlinking;
  }
  _updateBlinking() {
    this._startCursorBlinkAnimation.cancel();
    this._cursorFlatBlinkInterval.cancel();
    const blinkingStyle = this._getCursorBlinking();
    const isHidden3 = blinkingStyle === 0;
    const isSolid = blinkingStyle === 5;
    if (isHidden3) {
      this._hide();
    } else {
      this._show();
    }
    this._blinkingEnabled = false;
    this._updateDomClassName();
    if (!isHidden3 && !isSolid) {
      if (blinkingStyle === 1) {
        this._cursorFlatBlinkInterval.cancelAndSet(() => {
          if (this._isVisible) {
            this._hide();
          } else {
            this._show();
          }
        }, ViewCursors.BLINK_INTERVAL);
      } else {
        this._startCursorBlinkAnimation.setIfNotSet(() => {
          this._blinkingEnabled = true;
          this._updateDomClassName();
        }, ViewCursors.BLINK_INTERVAL);
      }
    }
  }
  _updateDomClassName() {
    this._domNode.setClassName(this._getClassName());
  }
  _getClassName() {
    let result = "cursors-layer";
    if (!this._selectionIsEmpty) {
      result += " has-selection";
    }
    switch (this._cursorStyle) {
      case TextEditorCursorStyle.Line:
        result += " cursor-line-style";
        break;
      case TextEditorCursorStyle.Block:
        result += " cursor-block-style";
        break;
      case TextEditorCursorStyle.Underline:
        result += " cursor-underline-style";
        break;
      case TextEditorCursorStyle.LineThin:
        result += " cursor-line-thin-style";
        break;
      case TextEditorCursorStyle.BlockOutline:
        result += " cursor-block-outline-style";
        break;
      case TextEditorCursorStyle.UnderlineThin:
        result += " cursor-underline-thin-style";
        break;
      default:
        result += " cursor-line-style";
    }
    if (this._blinkingEnabled) {
      switch (this._getCursorBlinking()) {
        case 1:
          result += " cursor-blink";
          break;
        case 2:
          result += " cursor-smooth";
          break;
        case 3:
          result += " cursor-phase";
          break;
        case 4:
          result += " cursor-expand";
          break;
        case 5:
          result += " cursor-solid";
          break;
        default:
          result += " cursor-solid";
      }
    } else {
      result += " cursor-solid";
    }
    if (this._cursorSmoothCaretAnimation) {
      result += " cursor-smooth-caret-animation";
    }
    return result;
  }
  _show() {
    this._primaryCursor.show();
    for (let i3 = 0, len2 = this._secondaryCursors.length; i3 < len2; i3++) {
      this._secondaryCursors[i3].show();
    }
    this._isVisible = true;
  }
  _hide() {
    this._primaryCursor.hide();
    for (let i3 = 0, len2 = this._secondaryCursors.length; i3 < len2; i3++) {
      this._secondaryCursors[i3].hide();
    }
    this._isVisible = false;
  }
  prepareRender(ctx) {
    this._primaryCursor.prepareRender(ctx);
    for (let i3 = 0, len2 = this._secondaryCursors.length; i3 < len2; i3++) {
      this._secondaryCursors[i3].prepareRender(ctx);
    }
  }
  render(ctx) {
    let renderData = [], renderDataLen = 0;
    const primaryRenderData = this._primaryCursor.render(ctx);
    if (primaryRenderData) {
      renderData[renderDataLen++] = primaryRenderData;
    }
    for (let i3 = 0, len2 = this._secondaryCursors.length; i3 < len2; i3++) {
      const secondaryRenderData = this._secondaryCursors[i3].render(ctx);
      if (secondaryRenderData) {
        renderData[renderDataLen++] = secondaryRenderData;
      }
    }
    this._renderData = renderData;
  }
  getLastRenderData() {
    return this._renderData;
  }
};
ViewCursors.BLINK_INTERVAL = 500;
registerThemingParticipant((theme, collector) => {
  const caret = theme.getColor(editorCursorForeground);
  if (caret) {
    let caretBackground = theme.getColor(editorCursorBackground);
    if (!caretBackground) {
      caretBackground = caret.opposite();
    }
    collector.addRule(`.monaco-editor .cursors-layer .cursor { background-color: ${caret}; border-color: ${caret}; color: ${caretBackground}; }`);
    if (theme.type === "hc") {
      collector.addRule(`.monaco-editor .cursors-layer.has-selection .cursor { border-left: 1px solid ${caretBackground}; border-right: 1px solid ${caretBackground}; }`);
    }
  }
});
var invalidFunc$1 = () => {
  throw new Error(`Invalid change accessor`);
};
var ViewZones = class extends ViewPart {
  constructor(context2) {
    super(context2);
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._lineHeight = options.get(51);
    this._contentWidth = layoutInfo.contentWidth;
    this._contentLeft = layoutInfo.contentLeft;
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setClassName("view-zones");
    this.domNode.setPosition("absolute");
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this.marginDomNode = createFastDomNode(document.createElement("div"));
    this.marginDomNode.setClassName("margin-view-zones");
    this.marginDomNode.setPosition("absolute");
    this.marginDomNode.setAttribute("role", "presentation");
    this.marginDomNode.setAttribute("aria-hidden", "true");
    this._zones = {};
  }
  dispose() {
    super.dispose();
    this._zones = {};
  }
  _recomputeWhitespacesProps() {
    const whitespaces = this._context.viewLayout.getWhitespaces();
    const oldWhitespaces = new Map();
    for (const whitespace of whitespaces) {
      oldWhitespaces.set(whitespace.id, whitespace);
    }
    let hadAChange = false;
    this._context.model.changeWhitespace((whitespaceAccessor) => {
      const keys2 = Object.keys(this._zones);
      for (let i3 = 0, len2 = keys2.length; i3 < len2; i3++) {
        const id3 = keys2[i3];
        const zone = this._zones[id3];
        const props = this._computeWhitespaceProps(zone.delegate);
        const oldWhitespace = oldWhitespaces.get(id3);
        if (oldWhitespace && (oldWhitespace.afterLineNumber !== props.afterViewLineNumber || oldWhitespace.height !== props.heightInPx)) {
          whitespaceAccessor.changeOneWhitespace(id3, props.afterViewLineNumber, props.heightInPx);
          this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
          hadAChange = true;
        }
      }
    });
    return hadAChange;
  }
  onConfigurationChanged(e2) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this._lineHeight = options.get(51);
    this._contentWidth = layoutInfo.contentWidth;
    this._contentLeft = layoutInfo.contentLeft;
    if (e2.hasChanged(51)) {
      this._recomputeWhitespacesProps();
    }
    return true;
  }
  onLineMappingChanged(e2) {
    return this._recomputeWhitespacesProps();
  }
  onLinesDeleted(e2) {
    return true;
  }
  onScrollChanged(e2) {
    return e2.scrollTopChanged || e2.scrollWidthChanged;
  }
  onZonesChanged(e2) {
    return true;
  }
  onLinesInserted(e2) {
    return true;
  }
  _getZoneOrdinal(zone) {
    if (typeof zone.afterColumn !== "undefined") {
      return zone.afterColumn;
    }
    return 1e4;
  }
  _computeWhitespaceProps(zone) {
    if (zone.afterLineNumber === 0) {
      return {
        afterViewLineNumber: 0,
        heightInPx: this._heightInPixels(zone),
        minWidthInPx: this._minWidthInPixels(zone)
      };
    }
    let zoneAfterModelPosition;
    if (typeof zone.afterColumn !== "undefined") {
      zoneAfterModelPosition = this._context.model.validateModelPosition({
        lineNumber: zone.afterLineNumber,
        column: zone.afterColumn
      });
    } else {
      const validAfterLineNumber = this._context.model.validateModelPosition({
        lineNumber: zone.afterLineNumber,
        column: 1
      }).lineNumber;
      zoneAfterModelPosition = new Position(validAfterLineNumber, this._context.model.getModelLineMaxColumn(validAfterLineNumber));
    }
    let zoneBeforeModelPosition;
    if (zoneAfterModelPosition.column === this._context.model.getModelLineMaxColumn(zoneAfterModelPosition.lineNumber)) {
      zoneBeforeModelPosition = this._context.model.validateModelPosition({
        lineNumber: zoneAfterModelPosition.lineNumber + 1,
        column: 1
      });
    } else {
      zoneBeforeModelPosition = this._context.model.validateModelPosition({
        lineNumber: zoneAfterModelPosition.lineNumber,
        column: zoneAfterModelPosition.column + 1
      });
    }
    const viewPosition = this._context.model.coordinatesConverter.convertModelPositionToViewPosition(zoneAfterModelPosition);
    const isVisible = this._context.model.coordinatesConverter.modelPositionIsVisible(zoneBeforeModelPosition);
    return {
      afterViewLineNumber: viewPosition.lineNumber,
      heightInPx: isVisible ? this._heightInPixels(zone) : 0,
      minWidthInPx: this._minWidthInPixels(zone)
    };
  }
  changeViewZones(callback) {
    let zonesHaveChanged = false;
    this._context.model.changeWhitespace((whitespaceAccessor) => {
      const changeAccessor = {
        addZone: (zone) => {
          zonesHaveChanged = true;
          return this._addZone(whitespaceAccessor, zone);
        },
        removeZone: (id3) => {
          if (!id3) {
            return;
          }
          zonesHaveChanged = this._removeZone(whitespaceAccessor, id3) || zonesHaveChanged;
        },
        layoutZone: (id3) => {
          if (!id3) {
            return;
          }
          zonesHaveChanged = this._layoutZone(whitespaceAccessor, id3) || zonesHaveChanged;
        }
      };
      safeInvoke1Arg(callback, changeAccessor);
      changeAccessor.addZone = invalidFunc$1;
      changeAccessor.removeZone = invalidFunc$1;
      changeAccessor.layoutZone = invalidFunc$1;
    });
    return zonesHaveChanged;
  }
  _addZone(whitespaceAccessor, zone) {
    const props = this._computeWhitespaceProps(zone);
    const whitespaceId = whitespaceAccessor.insertWhitespace(props.afterViewLineNumber, this._getZoneOrdinal(zone), props.heightInPx, props.minWidthInPx);
    const myZone = {
      whitespaceId,
      delegate: zone,
      isVisible: false,
      domNode: createFastDomNode(zone.domNode),
      marginDomNode: zone.marginDomNode ? createFastDomNode(zone.marginDomNode) : null
    };
    this._safeCallOnComputedHeight(myZone.delegate, props.heightInPx);
    myZone.domNode.setPosition("absolute");
    myZone.domNode.domNode.style.width = "100%";
    myZone.domNode.setDisplay("none");
    myZone.domNode.setAttribute("monaco-view-zone", myZone.whitespaceId);
    this.domNode.appendChild(myZone.domNode);
    if (myZone.marginDomNode) {
      myZone.marginDomNode.setPosition("absolute");
      myZone.marginDomNode.domNode.style.width = "100%";
      myZone.marginDomNode.setDisplay("none");
      myZone.marginDomNode.setAttribute("monaco-view-zone", myZone.whitespaceId);
      this.marginDomNode.appendChild(myZone.marginDomNode);
    }
    this._zones[myZone.whitespaceId] = myZone;
    this.setShouldRender();
    return myZone.whitespaceId;
  }
  _removeZone(whitespaceAccessor, id3) {
    if (this._zones.hasOwnProperty(id3)) {
      const zone = this._zones[id3];
      delete this._zones[id3];
      whitespaceAccessor.removeWhitespace(zone.whitespaceId);
      zone.domNode.removeAttribute("monaco-visible-view-zone");
      zone.domNode.removeAttribute("monaco-view-zone");
      zone.domNode.domNode.parentNode.removeChild(zone.domNode.domNode);
      if (zone.marginDomNode) {
        zone.marginDomNode.removeAttribute("monaco-visible-view-zone");
        zone.marginDomNode.removeAttribute("monaco-view-zone");
        zone.marginDomNode.domNode.parentNode.removeChild(zone.marginDomNode.domNode);
      }
      this.setShouldRender();
      return true;
    }
    return false;
  }
  _layoutZone(whitespaceAccessor, id3) {
    if (this._zones.hasOwnProperty(id3)) {
      const zone = this._zones[id3];
      const props = this._computeWhitespaceProps(zone.delegate);
      whitespaceAccessor.changeOneWhitespace(zone.whitespaceId, props.afterViewLineNumber, props.heightInPx);
      this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
      this.setShouldRender();
      return true;
    }
    return false;
  }
  shouldSuppressMouseDownOnViewZone(id3) {
    if (this._zones.hasOwnProperty(id3)) {
      const zone = this._zones[id3];
      return Boolean(zone.delegate.suppressMouseDown);
    }
    return false;
  }
  _heightInPixels(zone) {
    if (typeof zone.heightInPx === "number") {
      return zone.heightInPx;
    }
    if (typeof zone.heightInLines === "number") {
      return this._lineHeight * zone.heightInLines;
    }
    return this._lineHeight;
  }
  _minWidthInPixels(zone) {
    if (typeof zone.minWidthInPx === "number") {
      return zone.minWidthInPx;
    }
    return 0;
  }
  _safeCallOnComputedHeight(zone, height) {
    if (typeof zone.onComputedHeight === "function") {
      try {
        zone.onComputedHeight(height);
      } catch (e2) {
        onUnexpectedError(e2);
      }
    }
  }
  _safeCallOnDomNodeTop(zone, top2) {
    if (typeof zone.onDomNodeTop === "function") {
      try {
        zone.onDomNodeTop(top2);
      } catch (e2) {
        onUnexpectedError(e2);
      }
    }
  }
  prepareRender(ctx) {
  }
  render(ctx) {
    const visibleWhitespaces = ctx.viewportData.whitespaceViewportData;
    const visibleZones = {};
    let hasVisibleZone = false;
    for (let i3 = 0, len2 = visibleWhitespaces.length; i3 < len2; i3++) {
      visibleZones[visibleWhitespaces[i3].id] = visibleWhitespaces[i3];
      hasVisibleZone = true;
    }
    const keys2 = Object.keys(this._zones);
    for (let i3 = 0, len2 = keys2.length; i3 < len2; i3++) {
      const id3 = keys2[i3];
      const zone = this._zones[id3];
      let newTop = 0;
      let newHeight = 0;
      let newDisplay = "none";
      if (visibleZones.hasOwnProperty(id3)) {
        newTop = visibleZones[id3].verticalOffset - ctx.bigNumbersDelta;
        newHeight = visibleZones[id3].height;
        newDisplay = "block";
        if (!zone.isVisible) {
          zone.domNode.setAttribute("monaco-visible-view-zone", "true");
          zone.isVisible = true;
        }
        this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(visibleZones[id3].verticalOffset));
      } else {
        if (zone.isVisible) {
          zone.domNode.removeAttribute("monaco-visible-view-zone");
          zone.isVisible = false;
        }
        this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(-1e6));
      }
      zone.domNode.setTop(newTop);
      zone.domNode.setHeight(newHeight);
      zone.domNode.setDisplay(newDisplay);
      if (zone.marginDomNode) {
        zone.marginDomNode.setTop(newTop);
        zone.marginDomNode.setHeight(newHeight);
        zone.marginDomNode.setDisplay(newDisplay);
      }
    }
    if (hasVisibleZone) {
      this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth));
      this.marginDomNode.setWidth(this._contentLeft);
    }
  }
};
function safeInvoke1Arg(func, arg1) {
  try {
    return func(arg1);
  } catch (e2) {
    onUnexpectedError(e2);
  }
}
var EditorTheme = class {
  constructor(theme) {
    this._theme = theme;
  }
  get type() {
    return this._theme.type;
  }
  update(theme) {
    this._theme = theme;
  }
  getColor(color2) {
    return this._theme.getColor(color2);
  }
};
var ViewContext = class {
  constructor(configuration, theme, model) {
    this.configuration = configuration;
    this.theme = new EditorTheme(theme);
    this.model = model;
    this.viewLayout = model.viewLayout;
  }
  addEventHandler(eventHandler) {
    this.model.addViewEventHandler(eventHandler);
  }
  removeEventHandler(eventHandler) {
    this.model.removeViewEventHandler(eventHandler);
  }
};
var ViewportData = class {
  constructor(selections, partialData, whitespaceViewportData, model) {
    this.selections = selections;
    this.startLineNumber = partialData.startLineNumber | 0;
    this.endLineNumber = partialData.endLineNumber | 0;
    this.relativeVerticalOffset = partialData.relativeVerticalOffset;
    this.bigNumbersDelta = partialData.bigNumbersDelta | 0;
    this.whitespaceViewportData = whitespaceViewportData;
    this._model = model;
    this.visibleRange = new Range(partialData.startLineNumber, this._model.getLineMinColumn(partialData.startLineNumber), partialData.endLineNumber, this._model.getLineMaxColumn(partialData.endLineNumber));
  }
  getViewLineRenderingData(lineNumber) {
    return this._model.getViewLineRenderingData(this.visibleRange, lineNumber);
  }
  getDecorationsInViewport() {
    return this._model.getDecorationsInViewport(this.visibleRange);
  }
};
var View = class extends ViewEventHandler {
  constructor(commandDelegate, configuration, themeService, model, userInputEvents, overflowWidgetsDomNode) {
    super();
    this._selections = [new Selection(1, 1, 1, 1)];
    this._renderAnimationFrame = null;
    const viewController = new ViewController(configuration, model, userInputEvents, commandDelegate);
    this._context = new ViewContext(configuration, themeService.getColorTheme(), model);
    this._context.addEventHandler(this);
    this._register(themeService.onDidColorThemeChange((theme) => {
      this._context.theme.update(theme);
      this._context.model.onDidColorThemeChange();
      this.render(true, false);
    }));
    this._viewParts = [];
    this._textAreaHandler = new TextAreaHandler(this._context, viewController, this._createTextAreaHandlerHelper());
    this._viewParts.push(this._textAreaHandler);
    this._linesContent = createFastDomNode(document.createElement("div"));
    this._linesContent.setClassName("lines-content monaco-editor-background");
    this._linesContent.setPosition("absolute");
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setClassName(this._getEditorClassName());
    this.domNode.setAttribute("role", "code");
    this._overflowGuardContainer = createFastDomNode(document.createElement("div"));
    PartFingerprints.write(this._overflowGuardContainer, 3);
    this._overflowGuardContainer.setClassName("overflow-guard");
    this._scrollbar = new EditorScrollbar$1(this._context, this._linesContent, this.domNode, this._overflowGuardContainer);
    this._viewParts.push(this._scrollbar);
    this._viewLines = new ViewLines(this._context, this._linesContent);
    this._viewZones = new ViewZones(this._context);
    this._viewParts.push(this._viewZones);
    const decorationsOverviewRuler = new DecorationsOverviewRuler(this._context);
    this._viewParts.push(decorationsOverviewRuler);
    const scrollDecoration = new ScrollDecorationViewPart(this._context);
    this._viewParts.push(scrollDecoration);
    const contentViewOverlays = new ContentViewOverlays(this._context);
    this._viewParts.push(contentViewOverlays);
    contentViewOverlays.addDynamicOverlay(new CurrentLineHighlightOverlay(this._context));
    contentViewOverlays.addDynamicOverlay(new SelectionsOverlay(this._context));
    contentViewOverlays.addDynamicOverlay(new IndentGuidesOverlay(this._context));
    contentViewOverlays.addDynamicOverlay(new DecorationsOverlay(this._context));
    const marginViewOverlays = new MarginViewOverlays(this._context);
    this._viewParts.push(marginViewOverlays);
    marginViewOverlays.addDynamicOverlay(new CurrentLineMarginHighlightOverlay(this._context));
    marginViewOverlays.addDynamicOverlay(new GlyphMarginOverlay(this._context));
    marginViewOverlays.addDynamicOverlay(new MarginViewLineDecorationsOverlay(this._context));
    marginViewOverlays.addDynamicOverlay(new LinesDecorationsOverlay(this._context));
    marginViewOverlays.addDynamicOverlay(new LineNumbersOverlay(this._context));
    const margin = new Margin(this._context);
    margin.getDomNode().appendChild(this._viewZones.marginDomNode);
    margin.getDomNode().appendChild(marginViewOverlays.getDomNode());
    this._viewParts.push(margin);
    this._contentWidgets = new ViewContentWidgets(this._context, this.domNode);
    this._viewParts.push(this._contentWidgets);
    this._viewCursors = new ViewCursors(this._context);
    this._viewParts.push(this._viewCursors);
    this._overlayWidgets = new ViewOverlayWidgets(this._context);
    this._viewParts.push(this._overlayWidgets);
    const rulers = new Rulers(this._context);
    this._viewParts.push(rulers);
    const minimap = new Minimap(this._context);
    this._viewParts.push(minimap);
    if (decorationsOverviewRuler) {
      const overviewRulerData = this._scrollbar.getOverviewRulerLayoutInfo();
      overviewRulerData.parent.insertBefore(decorationsOverviewRuler.getDomNode(), overviewRulerData.insertBefore);
    }
    this._linesContent.appendChild(contentViewOverlays.getDomNode());
    this._linesContent.appendChild(rulers.domNode);
    this._linesContent.appendChild(this._viewZones.domNode);
    this._linesContent.appendChild(this._viewLines.getDomNode());
    this._linesContent.appendChild(this._contentWidgets.domNode);
    this._linesContent.appendChild(this._viewCursors.getDomNode());
    this._overflowGuardContainer.appendChild(margin.getDomNode());
    this._overflowGuardContainer.appendChild(this._scrollbar.getDomNode());
    this._overflowGuardContainer.appendChild(scrollDecoration.getDomNode());
    this._overflowGuardContainer.appendChild(this._textAreaHandler.textArea);
    this._overflowGuardContainer.appendChild(this._textAreaHandler.textAreaCover);
    this._overflowGuardContainer.appendChild(this._overlayWidgets.getDomNode());
    this._overflowGuardContainer.appendChild(minimap.getDomNode());
    this.domNode.appendChild(this._overflowGuardContainer);
    if (overflowWidgetsDomNode) {
      overflowWidgetsDomNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode.domNode);
    } else {
      this.domNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode);
    }
    this._applyLayout();
    this._pointerHandler = this._register(new PointerHandler(this._context, viewController, this._createPointerHandlerHelper()));
  }
  _flushAccumulatedAndRenderNow() {
    this._renderNow();
  }
  _createPointerHandlerHelper() {
    return {
      viewDomNode: this.domNode.domNode,
      linesContentDomNode: this._linesContent.domNode,
      focusTextArea: () => {
        this.focus();
      },
      getLastRenderData: () => {
        const lastViewCursorsRenderData = this._viewCursors.getLastRenderData() || [];
        const lastTextareaPosition = this._textAreaHandler.getLastRenderData();
        return new PointerHandlerLastRenderData(lastViewCursorsRenderData, lastTextareaPosition);
      },
      shouldSuppressMouseDownOnViewZone: (viewZoneId) => {
        return this._viewZones.shouldSuppressMouseDownOnViewZone(viewZoneId);
      },
      shouldSuppressMouseDownOnWidget: (widgetId) => {
        return this._contentWidgets.shouldSuppressMouseDownOnWidget(widgetId);
      },
      getPositionFromDOMInfo: (spanNode, offset2) => {
        this._flushAccumulatedAndRenderNow();
        return this._viewLines.getPositionFromDOMInfo(spanNode, offset2);
      },
      visibleRangeForPosition: (lineNumber, column) => {
        this._flushAccumulatedAndRenderNow();
        return this._viewLines.visibleRangeForPosition(new Position(lineNumber, column));
      },
      getLineWidth: (lineNumber) => {
        this._flushAccumulatedAndRenderNow();
        return this._viewLines.getLineWidth(lineNumber);
      }
    };
  }
  _createTextAreaHandlerHelper() {
    return {
      visibleRangeForPositionRelativeToEditor: (lineNumber, column) => {
        this._flushAccumulatedAndRenderNow();
        return this._viewLines.visibleRangeForPosition(new Position(lineNumber, column));
      }
    };
  }
  _applyLayout() {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(117);
    this.domNode.setWidth(layoutInfo.width);
    this.domNode.setHeight(layoutInfo.height);
    this._overflowGuardContainer.setWidth(layoutInfo.width);
    this._overflowGuardContainer.setHeight(layoutInfo.height);
    this._linesContent.setWidth(1e6);
    this._linesContent.setHeight(1e6);
  }
  _getEditorClassName() {
    const focused = this._textAreaHandler.isFocused() ? " focused" : "";
    return this._context.configuration.options.get(114) + " " + getThemeTypeSelector(this._context.theme.type) + focused;
  }
  handleEvents(events) {
    super.handleEvents(events);
    this._scheduleRender();
  }
  onConfigurationChanged(e2) {
    this.domNode.setClassName(this._getEditorClassName());
    this._applyLayout();
    return false;
  }
  onCursorStateChanged(e2) {
    this._selections = e2.selections;
    return false;
  }
  onFocusChanged(e2) {
    this.domNode.setClassName(this._getEditorClassName());
    return false;
  }
  onThemeChanged(e2) {
    this.domNode.setClassName(this._getEditorClassName());
    return false;
  }
  dispose() {
    if (this._renderAnimationFrame !== null) {
      this._renderAnimationFrame.dispose();
      this._renderAnimationFrame = null;
    }
    this._contentWidgets.overflowingContentWidgetsDomNode.domNode.remove();
    this._context.removeEventHandler(this);
    this._viewLines.dispose();
    for (let i3 = 0, len2 = this._viewParts.length; i3 < len2; i3++) {
      this._viewParts[i3].dispose();
    }
    super.dispose();
  }
  _scheduleRender() {
    if (this._renderAnimationFrame === null) {
      this._renderAnimationFrame = runAtThisOrScheduleAtNextAnimationFrame(this._onRenderScheduled.bind(this), 100);
    }
  }
  _onRenderScheduled() {
    this._renderAnimationFrame = null;
    this._flushAccumulatedAndRenderNow();
  }
  _renderNow() {
    safeInvokeNoArg(() => this._actualRender());
  }
  _getViewPartsToRender() {
    let result = [], resultLen = 0;
    for (let i3 = 0, len2 = this._viewParts.length; i3 < len2; i3++) {
      const viewPart = this._viewParts[i3];
      if (viewPart.shouldRender()) {
        result[resultLen++] = viewPart;
      }
    }
    return result;
  }
  _actualRender() {
    if (!isInDOM(this.domNode.domNode)) {
      return;
    }
    let viewPartsToRender = this._getViewPartsToRender();
    if (!this._viewLines.shouldRender() && viewPartsToRender.length === 0) {
      return;
    }
    const partialViewportData = this._context.viewLayout.getLinesViewportData();
    this._context.model.setViewport(partialViewportData.startLineNumber, partialViewportData.endLineNumber, partialViewportData.centeredLineNumber);
    const viewportData = new ViewportData(this._selections, partialViewportData, this._context.viewLayout.getWhitespaceViewportData(), this._context.model);
    if (this._contentWidgets.shouldRender()) {
      this._contentWidgets.onBeforeRender(viewportData);
    }
    if (this._viewLines.shouldRender()) {
      this._viewLines.renderText(viewportData);
      this._viewLines.onDidRender();
      viewPartsToRender = this._getViewPartsToRender();
    }
    const renderingContext = new RenderingContext(this._context.viewLayout, viewportData, this._viewLines);
    for (let i3 = 0, len2 = viewPartsToRender.length; i3 < len2; i3++) {
      const viewPart = viewPartsToRender[i3];
      viewPart.prepareRender(renderingContext);
    }
    for (let i3 = 0, len2 = viewPartsToRender.length; i3 < len2; i3++) {
      const viewPart = viewPartsToRender[i3];
      viewPart.render(renderingContext);
      viewPart.onDidRender();
    }
  }
  delegateVerticalScrollbarMouseDown(browserEvent) {
    this._scrollbar.delegateVerticalScrollbarMouseDown(browserEvent);
  }
  restoreState(scrollPosition) {
    this._context.model.setScrollPosition({scrollTop: scrollPosition.scrollTop}, 1);
    this._context.model.tokenizeViewport();
    this._renderNow();
    this._viewLines.updateLineWidths();
    this._context.model.setScrollPosition({scrollLeft: scrollPosition.scrollLeft}, 1);
  }
  getOffsetForColumn(modelLineNumber, modelColumn) {
    const modelPosition = this._context.model.validateModelPosition({
      lineNumber: modelLineNumber,
      column: modelColumn
    });
    const viewPosition = this._context.model.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
    this._flushAccumulatedAndRenderNow();
    const visibleRange = this._viewLines.visibleRangeForPosition(new Position(viewPosition.lineNumber, viewPosition.column));
    if (!visibleRange) {
      return -1;
    }
    return visibleRange.left;
  }
  getTargetAtClientPoint(clientX, clientY) {
    const mouseTarget = this._pointerHandler.getTargetAtClientPoint(clientX, clientY);
    if (!mouseTarget) {
      return null;
    }
    return ViewUserInputEvents.convertViewToModelMouseTarget(mouseTarget, this._context.model.coordinatesConverter);
  }
  createOverviewRuler(cssClassName) {
    return new OverviewRuler(this._context, cssClassName);
  }
  change(callback) {
    this._viewZones.changeViewZones(callback);
    this._scheduleRender();
  }
  render(now3, everything) {
    if (everything) {
      this._viewLines.forceShouldRender();
      for (let i3 = 0, len2 = this._viewParts.length; i3 < len2; i3++) {
        const viewPart = this._viewParts[i3];
        viewPart.forceShouldRender();
      }
    }
    if (now3) {
      this._flushAccumulatedAndRenderNow();
    } else {
      this._scheduleRender();
    }
  }
  focus() {
    this._textAreaHandler.focusTextArea();
  }
  isFocused() {
    return this._textAreaHandler.isFocused();
  }
  setAriaOptions(options) {
    this._textAreaHandler.setAriaOptions(options);
  }
  addContentWidget(widgetData) {
    this._contentWidgets.addWidget(widgetData.widget);
    this.layoutContentWidget(widgetData);
    this._scheduleRender();
  }
  layoutContentWidget(widgetData) {
    let newRange = widgetData.position ? widgetData.position.range || null : null;
    if (newRange === null) {
      const newPosition = widgetData.position ? widgetData.position.position : null;
      if (newPosition !== null) {
        newRange = new Range(newPosition.lineNumber, newPosition.column, newPosition.lineNumber, newPosition.column);
      }
    }
    const newPreference = widgetData.position ? widgetData.position.preference : null;
    this._contentWidgets.setWidgetPosition(widgetData.widget, newRange, newPreference);
    this._scheduleRender();
  }
  removeContentWidget(widgetData) {
    this._contentWidgets.removeWidget(widgetData.widget);
    this._scheduleRender();
  }
  addOverlayWidget(widgetData) {
    this._overlayWidgets.addWidget(widgetData.widget);
    this.layoutOverlayWidget(widgetData);
    this._scheduleRender();
  }
  layoutOverlayWidget(widgetData) {
    const newPreference = widgetData.position ? widgetData.position.preference : null;
    const shouldRender = this._overlayWidgets.setWidgetPosition(widgetData.widget, newPreference);
    if (shouldRender) {
      this._scheduleRender();
    }
  }
  removeOverlayWidget(widgetData) {
    this._overlayWidgets.removeWidget(widgetData.widget);
    this._scheduleRender();
  }
};
function safeInvokeNoArg(func) {
  try {
    return func();
  } catch (e2) {
    onUnexpectedError(e2);
  }
}
var OneCursor = class {
  constructor(context2) {
    this._selTrackedRange = null;
    this._trackSelection = true;
    this._setState(context2, new SingleCursorState(new Range(1, 1, 1, 1), 0, new Position(1, 1), 0), new SingleCursorState(new Range(1, 1, 1, 1), 0, new Position(1, 1), 0));
  }
  dispose(context2) {
    this._removeTrackedRange(context2);
  }
  startTrackingSelection(context2) {
    this._trackSelection = true;
    this._updateTrackedRange(context2);
  }
  stopTrackingSelection(context2) {
    this._trackSelection = false;
    this._removeTrackedRange(context2);
  }
  _updateTrackedRange(context2) {
    if (!this._trackSelection) {
      return;
    }
    this._selTrackedRange = context2.model._setTrackedRange(this._selTrackedRange, this.modelState.selection, 0);
  }
  _removeTrackedRange(context2) {
    this._selTrackedRange = context2.model._setTrackedRange(this._selTrackedRange, null, 0);
  }
  asCursorState() {
    return new CursorState(this.modelState, this.viewState);
  }
  readSelectionFromMarkers(context2) {
    const range3 = context2.model._getTrackedRange(this._selTrackedRange);
    if (this.modelState.selection.getDirection() === 0) {
      return new Selection(range3.startLineNumber, range3.startColumn, range3.endLineNumber, range3.endColumn);
    }
    return new Selection(range3.endLineNumber, range3.endColumn, range3.startLineNumber, range3.startColumn);
  }
  ensureValidState(context2) {
    this._setState(context2, this.modelState, this.viewState);
  }
  setState(context2, modelState, viewState) {
    this._setState(context2, modelState, viewState);
  }
  _setState(context2, modelState, viewState) {
    if (!modelState) {
      if (!viewState) {
        return;
      }
      const selectionStart = context2.model.validateRange(context2.coordinatesConverter.convertViewRangeToModelRange(viewState.selectionStart));
      const position2 = context2.model.validatePosition(context2.coordinatesConverter.convertViewPositionToModelPosition(viewState.position));
      modelState = new SingleCursorState(selectionStart, viewState.selectionStartLeftoverVisibleColumns, position2, viewState.leftoverVisibleColumns);
    } else {
      const selectionStart = context2.model.validateRange(modelState.selectionStart);
      const selectionStartLeftoverVisibleColumns = modelState.selectionStart.equalsRange(selectionStart) ? modelState.selectionStartLeftoverVisibleColumns : 0;
      const position2 = context2.model.validatePosition(modelState.position);
      const leftoverVisibleColumns = modelState.position.equals(position2) ? modelState.leftoverVisibleColumns : 0;
      modelState = new SingleCursorState(selectionStart, selectionStartLeftoverVisibleColumns, position2, leftoverVisibleColumns);
    }
    if (!viewState) {
      const viewSelectionStart1 = context2.coordinatesConverter.convertModelPositionToViewPosition(new Position(modelState.selectionStart.startLineNumber, modelState.selectionStart.startColumn));
      const viewSelectionStart2 = context2.coordinatesConverter.convertModelPositionToViewPosition(new Position(modelState.selectionStart.endLineNumber, modelState.selectionStart.endColumn));
      const viewSelectionStart = new Range(viewSelectionStart1.lineNumber, viewSelectionStart1.column, viewSelectionStart2.lineNumber, viewSelectionStart2.column);
      const viewPosition = context2.coordinatesConverter.convertModelPositionToViewPosition(modelState.position);
      viewState = new SingleCursorState(viewSelectionStart, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
    } else {
      const viewSelectionStart = context2.coordinatesConverter.validateViewRange(viewState.selectionStart, modelState.selectionStart);
      const viewPosition = context2.coordinatesConverter.validateViewPosition(viewState.position, modelState.position);
      viewState = new SingleCursorState(viewSelectionStart, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
    }
    this.modelState = modelState;
    this.viewState = viewState;
    this._updateTrackedRange(context2);
  }
};
var CursorCollection = class {
  constructor(context2) {
    this.context = context2;
    this.primaryCursor = new OneCursor(context2);
    this.secondaryCursors = [];
    this.lastAddedCursorIndex = 0;
  }
  dispose() {
    this.primaryCursor.dispose(this.context);
    this.killSecondaryCursors();
  }
  startTrackingSelections() {
    this.primaryCursor.startTrackingSelection(this.context);
    for (let i3 = 0, len2 = this.secondaryCursors.length; i3 < len2; i3++) {
      this.secondaryCursors[i3].startTrackingSelection(this.context);
    }
  }
  stopTrackingSelections() {
    this.primaryCursor.stopTrackingSelection(this.context);
    for (let i3 = 0, len2 = this.secondaryCursors.length; i3 < len2; i3++) {
      this.secondaryCursors[i3].stopTrackingSelection(this.context);
    }
  }
  updateContext(context2) {
    this.context = context2;
  }
  ensureValidState() {
    this.primaryCursor.ensureValidState(this.context);
    for (let i3 = 0, len2 = this.secondaryCursors.length; i3 < len2; i3++) {
      this.secondaryCursors[i3].ensureValidState(this.context);
    }
  }
  readSelectionFromMarkers() {
    let result = [];
    result[0] = this.primaryCursor.readSelectionFromMarkers(this.context);
    for (let i3 = 0, len2 = this.secondaryCursors.length; i3 < len2; i3++) {
      result[i3 + 1] = this.secondaryCursors[i3].readSelectionFromMarkers(this.context);
    }
    return result;
  }
  getAll() {
    let result = [];
    result[0] = this.primaryCursor.asCursorState();
    for (let i3 = 0, len2 = this.secondaryCursors.length; i3 < len2; i3++) {
      result[i3 + 1] = this.secondaryCursors[i3].asCursorState();
    }
    return result;
  }
  getViewPositions() {
    let result = [];
    result[0] = this.primaryCursor.viewState.position;
    for (let i3 = 0, len2 = this.secondaryCursors.length; i3 < len2; i3++) {
      result[i3 + 1] = this.secondaryCursors[i3].viewState.position;
    }
    return result;
  }
  getTopMostViewPosition() {
    let result = this.primaryCursor.viewState.position;
    for (let i3 = 0, len2 = this.secondaryCursors.length; i3 < len2; i3++) {
      const viewPosition = this.secondaryCursors[i3].viewState.position;
      if (viewPosition.isBefore(result)) {
        result = viewPosition;
      }
    }
    return result;
  }
  getBottomMostViewPosition() {
    let result = this.primaryCursor.viewState.position;
    for (let i3 = 0, len2 = this.secondaryCursors.length; i3 < len2; i3++) {
      const viewPosition = this.secondaryCursors[i3].viewState.position;
      if (result.isBeforeOrEqual(viewPosition)) {
        result = viewPosition;
      }
    }
    return result;
  }
  getSelections() {
    let result = [];
    result[0] = this.primaryCursor.modelState.selection;
    for (let i3 = 0, len2 = this.secondaryCursors.length; i3 < len2; i3++) {
      result[i3 + 1] = this.secondaryCursors[i3].modelState.selection;
    }
    return result;
  }
  getViewSelections() {
    let result = [];
    result[0] = this.primaryCursor.viewState.selection;
    for (let i3 = 0, len2 = this.secondaryCursors.length; i3 < len2; i3++) {
      result[i3 + 1] = this.secondaryCursors[i3].viewState.selection;
    }
    return result;
  }
  setSelections(selections) {
    this.setStates(CursorState.fromModelSelections(selections));
  }
  getPrimaryCursor() {
    return this.primaryCursor.asCursorState();
  }
  setStates(states) {
    if (states === null) {
      return;
    }
    this.primaryCursor.setState(this.context, states[0].modelState, states[0].viewState);
    this._setSecondaryStates(states.slice(1));
  }
  _setSecondaryStates(secondaryStates) {
    const secondaryCursorsLength = this.secondaryCursors.length;
    const secondaryStatesLength = secondaryStates.length;
    if (secondaryCursorsLength < secondaryStatesLength) {
      let createCnt = secondaryStatesLength - secondaryCursorsLength;
      for (let i3 = 0; i3 < createCnt; i3++) {
        this._addSecondaryCursor();
      }
    } else if (secondaryCursorsLength > secondaryStatesLength) {
      let removeCnt = secondaryCursorsLength - secondaryStatesLength;
      for (let i3 = 0; i3 < removeCnt; i3++) {
        this._removeSecondaryCursor(this.secondaryCursors.length - 1);
      }
    }
    for (let i3 = 0; i3 < secondaryStatesLength; i3++) {
      this.secondaryCursors[i3].setState(this.context, secondaryStates[i3].modelState, secondaryStates[i3].viewState);
    }
  }
  killSecondaryCursors() {
    this._setSecondaryStates([]);
  }
  _addSecondaryCursor() {
    this.secondaryCursors.push(new OneCursor(this.context));
    this.lastAddedCursorIndex = this.secondaryCursors.length;
  }
  getLastAddedCursorIndex() {
    if (this.secondaryCursors.length === 0 || this.lastAddedCursorIndex === 0) {
      return 0;
    }
    return this.lastAddedCursorIndex;
  }
  _removeSecondaryCursor(removeIndex) {
    if (this.lastAddedCursorIndex >= removeIndex + 1) {
      this.lastAddedCursorIndex--;
    }
    this.secondaryCursors[removeIndex].dispose(this.context);
    this.secondaryCursors.splice(removeIndex, 1);
  }
  _getAll() {
    let result = [];
    result[0] = this.primaryCursor;
    for (let i3 = 0, len2 = this.secondaryCursors.length; i3 < len2; i3++) {
      result[i3 + 1] = this.secondaryCursors[i3];
    }
    return result;
  }
  normalize() {
    if (this.secondaryCursors.length === 0) {
      return;
    }
    let cursors = this._getAll();
    let sortedCursors = [];
    for (let i3 = 0, len2 = cursors.length; i3 < len2; i3++) {
      sortedCursors.push({
        index: i3,
        selection: cursors[i3].modelState.selection
      });
    }
    sortedCursors.sort((a2, b2) => {
      if (a2.selection.startLineNumber === b2.selection.startLineNumber) {
        return a2.selection.startColumn - b2.selection.startColumn;
      }
      return a2.selection.startLineNumber - b2.selection.startLineNumber;
    });
    for (let sortedCursorIndex = 0; sortedCursorIndex < sortedCursors.length - 1; sortedCursorIndex++) {
      const current = sortedCursors[sortedCursorIndex];
      const next = sortedCursors[sortedCursorIndex + 1];
      const currentSelection = current.selection;
      const nextSelection = next.selection;
      if (!this.context.cursorConfig.multiCursorMergeOverlapping) {
        continue;
      }
      let shouldMergeCursors;
      if (nextSelection.isEmpty() || currentSelection.isEmpty()) {
        shouldMergeCursors = nextSelection.getStartPosition().isBeforeOrEqual(currentSelection.getEndPosition());
      } else {
        shouldMergeCursors = nextSelection.getStartPosition().isBefore(currentSelection.getEndPosition());
      }
      if (shouldMergeCursors) {
        const winnerSortedCursorIndex = current.index < next.index ? sortedCursorIndex : sortedCursorIndex + 1;
        const looserSortedCursorIndex = current.index < next.index ? sortedCursorIndex + 1 : sortedCursorIndex;
        const looserIndex = sortedCursors[looserSortedCursorIndex].index;
        const winnerIndex = sortedCursors[winnerSortedCursorIndex].index;
        const looserSelection = sortedCursors[looserSortedCursorIndex].selection;
        const winnerSelection = sortedCursors[winnerSortedCursorIndex].selection;
        if (!looserSelection.equalsSelection(winnerSelection)) {
          const resultingRange = looserSelection.plusRange(winnerSelection);
          const looserSelectionIsLTR = looserSelection.selectionStartLineNumber === looserSelection.startLineNumber && looserSelection.selectionStartColumn === looserSelection.startColumn;
          const winnerSelectionIsLTR = winnerSelection.selectionStartLineNumber === winnerSelection.startLineNumber && winnerSelection.selectionStartColumn === winnerSelection.startColumn;
          let resultingSelectionIsLTR;
          if (looserIndex === this.lastAddedCursorIndex) {
            resultingSelectionIsLTR = looserSelectionIsLTR;
            this.lastAddedCursorIndex = winnerIndex;
          } else {
            resultingSelectionIsLTR = winnerSelectionIsLTR;
          }
          let resultingSelection;
          if (resultingSelectionIsLTR) {
            resultingSelection = new Selection(resultingRange.startLineNumber, resultingRange.startColumn, resultingRange.endLineNumber, resultingRange.endColumn);
          } else {
            resultingSelection = new Selection(resultingRange.endLineNumber, resultingRange.endColumn, resultingRange.startLineNumber, resultingRange.startColumn);
          }
          sortedCursors[winnerSortedCursorIndex].selection = resultingSelection;
          const resultingState = CursorState.fromModelSelection(resultingSelection);
          cursors[winnerIndex].setState(this.context, resultingState.modelState, resultingState.viewState);
        }
        for (const sortedCursor of sortedCursors) {
          if (sortedCursor.index > looserIndex) {
            sortedCursor.index--;
          }
        }
        cursors.splice(looserIndex, 1);
        sortedCursors.splice(looserSortedCursorIndex, 1);
        this._removeSecondaryCursor(looserIndex - 1);
        sortedCursorIndex--;
      }
    }
  }
};
var ViewConfigurationChangedEvent = class {
  constructor(source2) {
    this.type = 0;
    this._source = source2;
  }
  hasChanged(id3) {
    return this._source.hasChanged(id3);
  }
};
var ViewCursorStateChangedEvent = class {
  constructor(selections, modelSelections) {
    this.type = 1;
    this.selections = selections;
    this.modelSelections = modelSelections;
  }
};
var ViewDecorationsChangedEvent = class {
  constructor(source2) {
    this.type = 2;
    if (source2) {
      this.affectsMinimap = source2.affectsMinimap;
      this.affectsOverviewRuler = source2.affectsOverviewRuler;
    } else {
      this.affectsMinimap = true;
      this.affectsOverviewRuler = true;
    }
  }
};
var ViewFlushedEvent = class {
  constructor() {
    this.type = 3;
  }
};
var ViewFocusChangedEvent = class {
  constructor(isFocused) {
    this.type = 4;
    this.isFocused = isFocused;
  }
};
var ViewLanguageConfigurationEvent = class {
  constructor() {
    this.type = 5;
  }
};
var ViewLineMappingChangedEvent = class {
  constructor() {
    this.type = 6;
  }
};
var ViewLinesChangedEvent = class {
  constructor(fromLineNumber, toLineNumber) {
    this.type = 7;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
  }
};
var ViewLinesDeletedEvent = class {
  constructor(fromLineNumber, toLineNumber) {
    this.type = 8;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
  }
};
var ViewLinesInsertedEvent = class {
  constructor(fromLineNumber, toLineNumber) {
    this.type = 9;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
  }
};
var ViewRevealRangeRequestEvent = class {
  constructor(source2, range3, selections, verticalType, revealHorizontal, scrollType) {
    this.type = 10;
    this.source = source2;
    this.range = range3;
    this.selections = selections;
    this.verticalType = verticalType;
    this.revealHorizontal = revealHorizontal;
    this.scrollType = scrollType;
  }
};
var ViewScrollChangedEvent = class {
  constructor(source2) {
    this.type = 11;
    this.scrollWidth = source2.scrollWidth;
    this.scrollLeft = source2.scrollLeft;
    this.scrollHeight = source2.scrollHeight;
    this.scrollTop = source2.scrollTop;
    this.scrollWidthChanged = source2.scrollWidthChanged;
    this.scrollLeftChanged = source2.scrollLeftChanged;
    this.scrollHeightChanged = source2.scrollHeightChanged;
    this.scrollTopChanged = source2.scrollTopChanged;
  }
};
var ViewThemeChangedEvent = class {
  constructor() {
    this.type = 12;
  }
};
var ViewTokensChangedEvent = class {
  constructor(ranges) {
    this.type = 13;
    this.ranges = ranges;
  }
};
var ViewTokensColorsChangedEvent = class {
  constructor() {
    this.type = 14;
  }
};
var ViewZonesChangedEvent = class {
  constructor() {
    this.type = 15;
  }
};
var ViewModelEventDispatcher = class extends Disposable {
  constructor() {
    super();
    this._onEvent = this._register(new Emitter());
    this.onEvent = this._onEvent.event;
    this._eventHandlers = [];
    this._viewEventQueue = null;
    this._isConsumingViewEventQueue = false;
    this._collector = null;
    this._collectorCnt = 0;
    this._outgoingEvents = [];
  }
  emitOutgoingEvent(e2) {
    this._addOutgoingEvent(e2);
    this._emitOugoingEvents();
  }
  _addOutgoingEvent(e2) {
    for (let i3 = 0, len2 = this._outgoingEvents.length; i3 < len2; i3++) {
      if (this._outgoingEvents[i3].kind === e2.kind) {
        this._outgoingEvents[i3] = this._outgoingEvents[i3].merge(e2);
        return;
      }
    }
    this._outgoingEvents.push(e2);
  }
  _emitOugoingEvents() {
    while (this._outgoingEvents.length > 0) {
      if (this._collector || this._isConsumingViewEventQueue) {
        return;
      }
      const event = this._outgoingEvents.shift();
      if (event.isNoOp()) {
        continue;
      }
      this._onEvent.fire(event);
    }
  }
  addViewEventHandler(eventHandler) {
    for (let i3 = 0, len2 = this._eventHandlers.length; i3 < len2; i3++) {
      if (this._eventHandlers[i3] === eventHandler) {
        console.warn("Detected duplicate listener in ViewEventDispatcher", eventHandler);
      }
    }
    this._eventHandlers.push(eventHandler);
  }
  removeViewEventHandler(eventHandler) {
    for (let i3 = 0; i3 < this._eventHandlers.length; i3++) {
      if (this._eventHandlers[i3] === eventHandler) {
        this._eventHandlers.splice(i3, 1);
        break;
      }
    }
  }
  beginEmitViewEvents() {
    this._collectorCnt++;
    if (this._collectorCnt === 1) {
      this._collector = new ViewModelEventsCollector();
    }
    return this._collector;
  }
  endEmitViewEvents() {
    this._collectorCnt--;
    if (this._collectorCnt === 0) {
      const outgoingEvents = this._collector.outgoingEvents;
      const viewEvents = this._collector.viewEvents;
      this._collector = null;
      for (const outgoingEvent of outgoingEvents) {
        this._addOutgoingEvent(outgoingEvent);
      }
      if (viewEvents.length > 0) {
        this._emitMany(viewEvents);
      }
    }
    this._emitOugoingEvents();
  }
  emitSingleViewEvent(event) {
    try {
      const eventsCollector = this.beginEmitViewEvents();
      eventsCollector.emitViewEvent(event);
    } finally {
      this.endEmitViewEvents();
    }
  }
  _emitMany(events) {
    if (this._viewEventQueue) {
      this._viewEventQueue = this._viewEventQueue.concat(events);
    } else {
      this._viewEventQueue = events;
    }
    if (!this._isConsumingViewEventQueue) {
      this._consumeViewEventQueue();
    }
  }
  _consumeViewEventQueue() {
    try {
      this._isConsumingViewEventQueue = true;
      this._doConsumeQueue();
    } finally {
      this._isConsumingViewEventQueue = false;
    }
  }
  _doConsumeQueue() {
    while (this._viewEventQueue) {
      const events = this._viewEventQueue;
      this._viewEventQueue = null;
      const eventHandlers = this._eventHandlers.slice(0);
      for (const eventHandler of eventHandlers) {
        eventHandler.handleEvents(events);
      }
    }
  }
};
var ViewModelEventsCollector = class {
  constructor() {
    this.viewEvents = [];
    this.outgoingEvents = [];
  }
  emitViewEvent(event) {
    this.viewEvents.push(event);
  }
  emitOutgoingEvent(e2) {
    this.outgoingEvents.push(e2);
  }
};
var ContentSizeChangedEvent = class {
  constructor(oldContentWidth, oldContentHeight, contentWidth, contentHeight) {
    this.kind = 0;
    this._oldContentWidth = oldContentWidth;
    this._oldContentHeight = oldContentHeight;
    this.contentWidth = contentWidth;
    this.contentHeight = contentHeight;
    this.contentWidthChanged = this._oldContentWidth !== this.contentWidth;
    this.contentHeightChanged = this._oldContentHeight !== this.contentHeight;
  }
  isNoOp() {
    return !this.contentWidthChanged && !this.contentHeightChanged;
  }
  merge(other) {
    if (other.kind !== 0) {
      return this;
    }
    return new ContentSizeChangedEvent(this._oldContentWidth, this._oldContentHeight, other.contentWidth, other.contentHeight);
  }
};
var FocusChangedEvent = class {
  constructor(oldHasFocus, hasFocus) {
    this.kind = 1;
    this.oldHasFocus = oldHasFocus;
    this.hasFocus = hasFocus;
  }
  isNoOp() {
    return this.oldHasFocus === this.hasFocus;
  }
  merge(other) {
    if (other.kind !== 1) {
      return this;
    }
    return new FocusChangedEvent(this.oldHasFocus, other.hasFocus);
  }
};
var ScrollChangedEvent = class {
  constructor(oldScrollWidth, oldScrollLeft, oldScrollHeight, oldScrollTop, scrollWidth, scrollLeft, scrollHeight, scrollTop) {
    this.kind = 2;
    this._oldScrollWidth = oldScrollWidth;
    this._oldScrollLeft = oldScrollLeft;
    this._oldScrollHeight = oldScrollHeight;
    this._oldScrollTop = oldScrollTop;
    this.scrollWidth = scrollWidth;
    this.scrollLeft = scrollLeft;
    this.scrollHeight = scrollHeight;
    this.scrollTop = scrollTop;
    this.scrollWidthChanged = this._oldScrollWidth !== this.scrollWidth;
    this.scrollLeftChanged = this._oldScrollLeft !== this.scrollLeft;
    this.scrollHeightChanged = this._oldScrollHeight !== this.scrollHeight;
    this.scrollTopChanged = this._oldScrollTop !== this.scrollTop;
  }
  isNoOp() {
    return !this.scrollWidthChanged && !this.scrollLeftChanged && !this.scrollHeightChanged && !this.scrollTopChanged;
  }
  merge(other) {
    if (other.kind !== 2) {
      return this;
    }
    return new ScrollChangedEvent(this._oldScrollWidth, this._oldScrollLeft, this._oldScrollHeight, this._oldScrollTop, other.scrollWidth, other.scrollLeft, other.scrollHeight, other.scrollTop);
  }
};
var ViewZonesChangedEvent$1 = class {
  constructor() {
    this.kind = 3;
  }
  isNoOp() {
    return false;
  }
  merge(other) {
    return this;
  }
};
var CursorStateChangedEvent = class {
  constructor(oldSelections, selections, oldModelVersionId, modelVersionId, source2, reason, reachedMaxCursorCount) {
    this.kind = 5;
    this.oldSelections = oldSelections;
    this.selections = selections;
    this.oldModelVersionId = oldModelVersionId;
    this.modelVersionId = modelVersionId;
    this.source = source2;
    this.reason = reason;
    this.reachedMaxCursorCount = reachedMaxCursorCount;
  }
  static _selectionsAreEqual(a2, b2) {
    if (!a2 && !b2) {
      return true;
    }
    if (!a2 || !b2) {
      return false;
    }
    const aLen = a2.length;
    const bLen = b2.length;
    if (aLen !== bLen) {
      return false;
    }
    for (let i3 = 0; i3 < aLen; i3++) {
      if (!a2[i3].equalsSelection(b2[i3])) {
        return false;
      }
    }
    return true;
  }
  isNoOp() {
    return CursorStateChangedEvent._selectionsAreEqual(this.oldSelections, this.selections) && this.oldModelVersionId === this.modelVersionId;
  }
  merge(other) {
    if (other.kind !== 5) {
      return this;
    }
    return new CursorStateChangedEvent(this.oldSelections, other.selections, this.oldModelVersionId, other.modelVersionId, other.source, other.reason, this.reachedMaxCursorCount || other.reachedMaxCursorCount);
  }
};
var ReadOnlyEditAttemptEvent = class {
  constructor() {
    this.kind = 4;
  }
  isNoOp() {
    return false;
  }
  merge(other) {
    return this;
  }
};
var CursorModelState = class {
  constructor(model, cursor) {
    this.modelVersionId = model.getVersionId();
    this.cursorState = cursor.getCursorStates();
  }
  equals(other) {
    if (!other) {
      return false;
    }
    if (this.modelVersionId !== other.modelVersionId) {
      return false;
    }
    if (this.cursorState.length !== other.cursorState.length) {
      return false;
    }
    for (let i3 = 0, len2 = this.cursorState.length; i3 < len2; i3++) {
      if (!this.cursorState[i3].equals(other.cursorState[i3])) {
        return false;
      }
    }
    return true;
  }
};
var AutoClosedAction = class {
  constructor(model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations) {
    this._model = model;
    this._autoClosedCharactersDecorations = autoClosedCharactersDecorations;
    this._autoClosedEnclosingDecorations = autoClosedEnclosingDecorations;
  }
  static getAllAutoClosedCharacters(autoClosedActions) {
    let autoClosedCharacters = [];
    for (const autoClosedAction of autoClosedActions) {
      autoClosedCharacters = autoClosedCharacters.concat(autoClosedAction.getAutoClosedCharactersRanges());
    }
    return autoClosedCharacters;
  }
  dispose() {
    this._autoClosedCharactersDecorations = this._model.deltaDecorations(this._autoClosedCharactersDecorations, []);
    this._autoClosedEnclosingDecorations = this._model.deltaDecorations(this._autoClosedEnclosingDecorations, []);
  }
  getAutoClosedCharactersRanges() {
    let result = [];
    for (let i3 = 0; i3 < this._autoClosedCharactersDecorations.length; i3++) {
      const decorationRange = this._model.getDecorationRange(this._autoClosedCharactersDecorations[i3]);
      if (decorationRange) {
        result.push(decorationRange);
      }
    }
    return result;
  }
  isValid(selections) {
    let enclosingRanges = [];
    for (let i3 = 0; i3 < this._autoClosedEnclosingDecorations.length; i3++) {
      const decorationRange = this._model.getDecorationRange(this._autoClosedEnclosingDecorations[i3]);
      if (decorationRange) {
        enclosingRanges.push(decorationRange);
        if (decorationRange.startLineNumber !== decorationRange.endLineNumber) {
          return false;
        }
      }
    }
    enclosingRanges.sort(Range.compareRangesUsingStarts);
    selections.sort(Range.compareRangesUsingStarts);
    for (let i3 = 0; i3 < selections.length; i3++) {
      if (i3 >= enclosingRanges.length) {
        return false;
      }
      if (!enclosingRanges[i3].strictContainsRange(selections[i3])) {
        return false;
      }
    }
    return true;
  }
};
var Cursor = class extends Disposable {
  constructor(model, viewModel, coordinatesConverter, cursorConfig) {
    super();
    this._model = model;
    this._knownModelVersionId = this._model.getVersionId();
    this._viewModel = viewModel;
    this._coordinatesConverter = coordinatesConverter;
    this.context = new CursorContext(this._model, this._coordinatesConverter, cursorConfig);
    this._cursors = new CursorCollection(this.context);
    this._hasFocus = false;
    this._isHandling = false;
    this._isDoingComposition = false;
    this._selectionsWhenCompositionStarted = null;
    this._columnSelectData = null;
    this._autoClosedActions = [];
    this._prevEditOperationType = 0;
  }
  dispose() {
    this._cursors.dispose();
    this._autoClosedActions = dispose(this._autoClosedActions);
    super.dispose();
  }
  updateConfiguration(cursorConfig) {
    this.context = new CursorContext(this._model, this._coordinatesConverter, cursorConfig);
    this._cursors.updateContext(this.context);
  }
  onLineMappingChanged(eventsCollector) {
    if (this._knownModelVersionId !== this._model.getVersionId()) {
      return;
    }
    this.setStates(eventsCollector, "viewModel", 0, this.getCursorStates());
  }
  setHasFocus(hasFocus) {
    this._hasFocus = hasFocus;
  }
  _validateAutoClosedActions() {
    if (this._autoClosedActions.length > 0) {
      let selections = this._cursors.getSelections();
      for (let i3 = 0; i3 < this._autoClosedActions.length; i3++) {
        const autoClosedAction = this._autoClosedActions[i3];
        if (!autoClosedAction.isValid(selections)) {
          autoClosedAction.dispose();
          this._autoClosedActions.splice(i3, 1);
          i3--;
        }
      }
    }
  }
  getPrimaryCursorState() {
    return this._cursors.getPrimaryCursor();
  }
  getLastAddedCursorIndex() {
    return this._cursors.getLastAddedCursorIndex();
  }
  getCursorStates() {
    return this._cursors.getAll();
  }
  setStates(eventsCollector, source2, reason, states) {
    let reachedMaxCursorCount = false;
    if (states !== null && states.length > Cursor.MAX_CURSOR_COUNT) {
      states = states.slice(0, Cursor.MAX_CURSOR_COUNT);
      reachedMaxCursorCount = true;
    }
    const oldState = new CursorModelState(this._model, this);
    this._cursors.setStates(states);
    this._cursors.normalize();
    this._columnSelectData = null;
    this._validateAutoClosedActions();
    return this._emitStateChangedIfNecessary(eventsCollector, source2, reason, oldState, reachedMaxCursorCount);
  }
  setCursorColumnSelectData(columnSelectData) {
    this._columnSelectData = columnSelectData;
  }
  revealPrimary(eventsCollector, source2, revealHorizontal, scrollType) {
    const viewPositions = this._cursors.getViewPositions();
    if (viewPositions.length > 1) {
      this._emitCursorRevealRange(eventsCollector, source2, null, this._cursors.getViewSelections(), 0, revealHorizontal, scrollType);
      return;
    } else {
      const viewPosition = viewPositions[0];
      const viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
      this._emitCursorRevealRange(eventsCollector, source2, viewRange, null, 0, revealHorizontal, scrollType);
    }
  }
  _revealPrimaryCursor(eventsCollector, source2, verticalType, revealHorizontal, scrollType) {
    const viewPositions = this._cursors.getViewPositions();
    if (viewPositions.length > 1) {
      this._emitCursorRevealRange(eventsCollector, source2, null, this._cursors.getViewSelections(), verticalType, revealHorizontal, scrollType);
    } else {
      const viewPosition = viewPositions[0];
      const viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
      this._emitCursorRevealRange(eventsCollector, source2, viewRange, null, verticalType, revealHorizontal, scrollType);
    }
  }
  _emitCursorRevealRange(eventsCollector, source2, viewRange, viewSelections, verticalType, revealHorizontal, scrollType) {
    eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source2, viewRange, viewSelections, verticalType, revealHorizontal, scrollType));
  }
  saveState() {
    let result = [];
    const selections = this._cursors.getSelections();
    for (let i3 = 0, len2 = selections.length; i3 < len2; i3++) {
      const selection2 = selections[i3];
      result.push({
        inSelectionMode: !selection2.isEmpty(),
        selectionStart: {
          lineNumber: selection2.selectionStartLineNumber,
          column: selection2.selectionStartColumn
        },
        position: {
          lineNumber: selection2.positionLineNumber,
          column: selection2.positionColumn
        }
      });
    }
    return result;
  }
  restoreState(eventsCollector, states) {
    let desiredSelections = [];
    for (let i3 = 0, len2 = states.length; i3 < len2; i3++) {
      const state = states[i3];
      let positionLineNumber = 1;
      let positionColumn = 1;
      if (state.position && state.position.lineNumber) {
        positionLineNumber = state.position.lineNumber;
      }
      if (state.position && state.position.column) {
        positionColumn = state.position.column;
      }
      let selectionStartLineNumber = positionLineNumber;
      let selectionStartColumn = positionColumn;
      if (state.selectionStart && state.selectionStart.lineNumber) {
        selectionStartLineNumber = state.selectionStart.lineNumber;
      }
      if (state.selectionStart && state.selectionStart.column) {
        selectionStartColumn = state.selectionStart.column;
      }
      desiredSelections.push({
        selectionStartLineNumber,
        selectionStartColumn,
        positionLineNumber,
        positionColumn
      });
    }
    this.setStates(eventsCollector, "restoreState", 0, CursorState.fromModelSelections(desiredSelections));
    this.revealPrimary(eventsCollector, "restoreState", true, 1);
  }
  onModelContentChanged(eventsCollector, e2) {
    this._knownModelVersionId = e2.versionId;
    if (this._isHandling) {
      return;
    }
    const hadFlushEvent = e2.containsEvent(1);
    this._prevEditOperationType = 0;
    if (hadFlushEvent) {
      this._cursors.dispose();
      this._cursors = new CursorCollection(this.context);
      this._validateAutoClosedActions();
      this._emitStateChangedIfNecessary(eventsCollector, "model", 1, null, false);
    } else {
      if (this._hasFocus && e2.resultingSelection && e2.resultingSelection.length > 0) {
        const cursorState = CursorState.fromModelSelections(e2.resultingSelection);
        if (this.setStates(eventsCollector, "modelChange", e2.isUndoing ? 5 : e2.isRedoing ? 6 : 2, cursorState)) {
          this._revealPrimaryCursor(eventsCollector, "modelChange", 0, true, 0);
        }
      } else {
        const selectionsFromMarkers = this._cursors.readSelectionFromMarkers();
        this.setStates(eventsCollector, "modelChange", 2, CursorState.fromModelSelections(selectionsFromMarkers));
      }
    }
  }
  getSelection() {
    return this._cursors.getPrimaryCursor().modelState.selection;
  }
  getTopMostViewPosition() {
    return this._cursors.getTopMostViewPosition();
  }
  getBottomMostViewPosition() {
    return this._cursors.getBottomMostViewPosition();
  }
  getCursorColumnSelectData() {
    if (this._columnSelectData) {
      return this._columnSelectData;
    }
    const primaryCursor = this._cursors.getPrimaryCursor();
    const viewSelectionStart = primaryCursor.viewState.selectionStart.getStartPosition();
    const viewPosition = primaryCursor.viewState.position;
    return {
      isReal: false,
      fromViewLineNumber: viewSelectionStart.lineNumber,
      fromViewVisualColumn: CursorColumns.visibleColumnFromColumn2(this.context.cursorConfig, this._viewModel, viewSelectionStart),
      toViewLineNumber: viewPosition.lineNumber,
      toViewVisualColumn: CursorColumns.visibleColumnFromColumn2(this.context.cursorConfig, this._viewModel, viewPosition)
    };
  }
  getSelections() {
    return this._cursors.getSelections();
  }
  setSelections(eventsCollector, source2, selections) {
    this.setStates(eventsCollector, source2, 0, CursorState.fromModelSelections(selections));
  }
  getPrevEditOperationType() {
    return this._prevEditOperationType;
  }
  setPrevEditOperationType(type) {
    this._prevEditOperationType = type;
  }
  _pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges) {
    let autoClosedCharactersDeltaDecorations = [];
    let autoClosedEnclosingDeltaDecorations = [];
    for (let i3 = 0, len2 = autoClosedCharactersRanges.length; i3 < len2; i3++) {
      autoClosedCharactersDeltaDecorations.push({
        range: autoClosedCharactersRanges[i3],
        options: {
          inlineClassName: "auto-closed-character",
          stickiness: 1
        }
      });
      autoClosedEnclosingDeltaDecorations.push({
        range: autoClosedEnclosingRanges[i3],
        options: {
          stickiness: 1
        }
      });
    }
    const autoClosedCharactersDecorations = this._model.deltaDecorations([], autoClosedCharactersDeltaDecorations);
    const autoClosedEnclosingDecorations = this._model.deltaDecorations([], autoClosedEnclosingDeltaDecorations);
    this._autoClosedActions.push(new AutoClosedAction(this._model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations));
  }
  _executeEditOperation(opResult) {
    if (!opResult) {
      return;
    }
    if (opResult.shouldPushStackElementBefore) {
      this._model.pushStackElement();
    }
    const result = CommandExecutor.executeCommands(this._model, this._cursors.getSelections(), opResult.commands);
    if (result) {
      this._interpretCommandResult(result);
      let autoClosedCharactersRanges = [];
      let autoClosedEnclosingRanges = [];
      for (let i3 = 0; i3 < opResult.commands.length; i3++) {
        const command = opResult.commands[i3];
        if (command instanceof TypeWithAutoClosingCommand && command.enclosingRange && command.closeCharacterRange) {
          autoClosedCharactersRanges.push(command.closeCharacterRange);
          autoClosedEnclosingRanges.push(command.enclosingRange);
        }
      }
      if (autoClosedCharactersRanges.length > 0) {
        this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
      }
      this._prevEditOperationType = opResult.type;
    }
    if (opResult.shouldPushStackElementAfter) {
      this._model.pushStackElement();
    }
  }
  _interpretCommandResult(cursorState) {
    if (!cursorState || cursorState.length === 0) {
      cursorState = this._cursors.readSelectionFromMarkers();
    }
    this._columnSelectData = null;
    this._cursors.setSelections(cursorState);
    this._cursors.normalize();
  }
  _emitStateChangedIfNecessary(eventsCollector, source2, reason, oldState, reachedMaxCursorCount) {
    const newState = new CursorModelState(this._model, this);
    if (newState.equals(oldState)) {
      return false;
    }
    const selections = this._cursors.getSelections();
    const viewSelections = this._cursors.getViewSelections();
    eventsCollector.emitViewEvent(new ViewCursorStateChangedEvent(viewSelections, selections));
    if (!oldState || oldState.cursorState.length !== newState.cursorState.length || newState.cursorState.some((newCursorState, i3) => !newCursorState.modelState.equals(oldState.cursorState[i3].modelState))) {
      const oldSelections = oldState ? oldState.cursorState.map((s2) => s2.modelState.selection) : null;
      const oldModelVersionId = oldState ? oldState.modelVersionId : 0;
      eventsCollector.emitOutgoingEvent(new CursorStateChangedEvent(oldSelections, selections, oldModelVersionId, newState.modelVersionId, source2 || "keyboard", reason, reachedMaxCursorCount));
    }
    return true;
  }
  _findAutoClosingPairs(edits) {
    if (!edits.length) {
      return null;
    }
    let indices = [];
    for (let i3 = 0, len2 = edits.length; i3 < len2; i3++) {
      const edit = edits[i3];
      if (!edit.text || edit.text.indexOf("\n") >= 0) {
        return null;
      }
      const m2 = edit.text.match(/([)\]}>'"`])([^)\]}>'"`]*)$/);
      if (!m2) {
        return null;
      }
      const closeChar = m2[1];
      const autoClosingPairsCandidates = this.context.cursorConfig.autoClosingPairsClose2.get(closeChar);
      if (!autoClosingPairsCandidates || autoClosingPairsCandidates.length !== 1) {
        return null;
      }
      const openChar = autoClosingPairsCandidates[0].open;
      const closeCharIndex = edit.text.length - m2[2].length - 1;
      const openCharIndex = edit.text.lastIndexOf(openChar, closeCharIndex - 1);
      if (openCharIndex === -1) {
        return null;
      }
      indices.push([openCharIndex, closeCharIndex]);
    }
    return indices;
  }
  executeEdits(eventsCollector, source2, edits, cursorStateComputer) {
    let autoClosingIndices = null;
    if (source2 === "snippet") {
      autoClosingIndices = this._findAutoClosingPairs(edits);
    }
    if (autoClosingIndices) {
      edits[0]._isTracked = true;
    }
    let autoClosedCharactersRanges = [];
    let autoClosedEnclosingRanges = [];
    const selections = this._model.pushEditOperations(this.getSelections(), edits, (undoEdits) => {
      if (autoClosingIndices) {
        for (let i3 = 0, len2 = autoClosingIndices.length; i3 < len2; i3++) {
          const [openCharInnerIndex, closeCharInnerIndex] = autoClosingIndices[i3];
          const undoEdit = undoEdits[i3];
          const lineNumber = undoEdit.range.startLineNumber;
          const openCharIndex = undoEdit.range.startColumn - 1 + openCharInnerIndex;
          const closeCharIndex = undoEdit.range.startColumn - 1 + closeCharInnerIndex;
          autoClosedCharactersRanges.push(new Range(lineNumber, closeCharIndex + 1, lineNumber, closeCharIndex + 2));
          autoClosedEnclosingRanges.push(new Range(lineNumber, openCharIndex + 1, lineNumber, closeCharIndex + 2));
        }
      }
      const selections2 = cursorStateComputer(undoEdits);
      if (selections2) {
        this._isHandling = true;
      }
      return selections2;
    });
    if (selections) {
      this._isHandling = false;
      this.setSelections(eventsCollector, source2, selections);
    }
    if (autoClosedCharactersRanges.length > 0) {
      this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
    }
  }
  _executeEdit(callback, eventsCollector, source2, cursorChangeReason = 0) {
    if (this.context.cursorConfig.readOnly) {
      return;
    }
    const oldState = new CursorModelState(this._model, this);
    this._cursors.stopTrackingSelections();
    this._isHandling = true;
    try {
      this._cursors.ensureValidState();
      callback();
    } catch (err) {
      onUnexpectedError(err);
    }
    this._isHandling = false;
    this._cursors.startTrackingSelections();
    this._validateAutoClosedActions();
    if (this._emitStateChangedIfNecessary(eventsCollector, source2, cursorChangeReason, oldState, false)) {
      this._revealPrimaryCursor(eventsCollector, source2, 0, true, 0);
    }
  }
  setIsDoingComposition(isDoingComposition) {
    this._isDoingComposition = isDoingComposition;
  }
  startComposition(eventsCollector) {
    this._selectionsWhenCompositionStarted = this.getSelections().slice(0);
  }
  endComposition(eventsCollector, source2) {
    this._executeEdit(() => {
      if (source2 === "keyboard") {
        const autoClosedCharacters = AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions);
        this._executeEditOperation(TypeOperations.compositionEndWithInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, this._selectionsWhenCompositionStarted, this.getSelections(), autoClosedCharacters));
        this._selectionsWhenCompositionStarted = null;
      }
    }, eventsCollector, source2);
  }
  type(eventsCollector, text, source2) {
    this._executeEdit(() => {
      if (source2 === "keyboard") {
        const len2 = text.length;
        let offset2 = 0;
        while (offset2 < len2) {
          const charLength = nextCharLength(text, offset2);
          const chr = text.substr(offset2, charLength);
          const autoClosedCharacters = AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions);
          this._executeEditOperation(TypeOperations.typeWithInterceptors(this._isDoingComposition, this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), autoClosedCharacters, chr));
          offset2 += charLength;
        }
      } else {
        this._executeEditOperation(TypeOperations.typeWithoutInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text));
      }
    }, eventsCollector, source2);
  }
  replacePreviousChar(eventsCollector, text, replaceCharCnt, source2) {
    this._executeEdit(() => {
      this._executeEditOperation(TypeOperations.replacePreviousChar(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text, replaceCharCnt));
    }, eventsCollector, source2);
  }
  paste(eventsCollector, text, pasteOnNewLine, multicursorText, source2) {
    this._executeEdit(() => {
      this._executeEditOperation(TypeOperations.paste(this.context.cursorConfig, this._model, this.getSelections(), text, pasteOnNewLine, multicursorText || []));
    }, eventsCollector, source2, 4);
  }
  cut(eventsCollector, source2) {
    this._executeEdit(() => {
      this._executeEditOperation(DeleteOperations.cut(this.context.cursorConfig, this._model, this.getSelections()));
    }, eventsCollector, source2);
  }
  executeCommand(eventsCollector, command, source2) {
    this._executeEdit(() => {
      this._cursors.killSecondaryCursors();
      this._executeEditOperation(new EditOperationResult(0, [command], {
        shouldPushStackElementBefore: false,
        shouldPushStackElementAfter: false
      }));
    }, eventsCollector, source2);
  }
  executeCommands(eventsCollector, commands, source2) {
    this._executeEdit(() => {
      this._executeEditOperation(new EditOperationResult(0, commands, {
        shouldPushStackElementBefore: false,
        shouldPushStackElementAfter: false
      }));
    }, eventsCollector, source2);
  }
};
Cursor.MAX_CURSOR_COUNT = 1e4;
var CommandExecutor = class {
  static executeCommands(model, selectionsBefore, commands) {
    const ctx = {
      model,
      selectionsBefore,
      trackedRanges: [],
      trackedRangesDirection: []
    };
    const result = this._innerExecuteCommands(ctx, commands);
    for (let i3 = 0, len2 = ctx.trackedRanges.length; i3 < len2; i3++) {
      ctx.model._setTrackedRange(ctx.trackedRanges[i3], null, 0);
    }
    return result;
  }
  static _innerExecuteCommands(ctx, commands) {
    if (this._arrayIsEmpty(commands)) {
      return null;
    }
    const commandsData = this._getEditOperations(ctx, commands);
    if (commandsData.operations.length === 0) {
      return null;
    }
    const rawOperations = commandsData.operations;
    const loserCursorsMap = this._getLoserCursorMap(rawOperations);
    if (loserCursorsMap.hasOwnProperty("0")) {
      console.warn("Ignoring commands");
      return null;
    }
    let filteredOperations = [];
    for (let i3 = 0, len2 = rawOperations.length; i3 < len2; i3++) {
      if (!loserCursorsMap.hasOwnProperty(rawOperations[i3].identifier.major.toString())) {
        filteredOperations.push(rawOperations[i3]);
      }
    }
    if (commandsData.hadTrackedEditOperation && filteredOperations.length > 0) {
      filteredOperations[0]._isTracked = true;
    }
    let selectionsAfter = ctx.model.pushEditOperations(ctx.selectionsBefore, filteredOperations, (inverseEditOperations) => {
      let groupedInverseEditOperations = [];
      for (let i3 = 0; i3 < ctx.selectionsBefore.length; i3++) {
        groupedInverseEditOperations[i3] = [];
      }
      for (const op of inverseEditOperations) {
        if (!op.identifier) {
          continue;
        }
        groupedInverseEditOperations[op.identifier.major].push(op);
      }
      const minorBasedSorter = (a2, b2) => {
        return a2.identifier.minor - b2.identifier.minor;
      };
      let cursorSelections = [];
      for (let i3 = 0; i3 < ctx.selectionsBefore.length; i3++) {
        if (groupedInverseEditOperations[i3].length > 0) {
          groupedInverseEditOperations[i3].sort(minorBasedSorter);
          cursorSelections[i3] = commands[i3].computeCursorState(ctx.model, {
            getInverseEditOperations: () => {
              return groupedInverseEditOperations[i3];
            },
            getTrackedSelection: (id3) => {
              const idx = parseInt(id3, 10);
              const range3 = ctx.model._getTrackedRange(ctx.trackedRanges[idx]);
              if (ctx.trackedRangesDirection[idx] === 0) {
                return new Selection(range3.startLineNumber, range3.startColumn, range3.endLineNumber, range3.endColumn);
              }
              return new Selection(range3.endLineNumber, range3.endColumn, range3.startLineNumber, range3.startColumn);
            }
          });
        } else {
          cursorSelections[i3] = ctx.selectionsBefore[i3];
        }
      }
      return cursorSelections;
    });
    if (!selectionsAfter) {
      selectionsAfter = ctx.selectionsBefore;
    }
    let losingCursors = [];
    for (let losingCursorIndex in loserCursorsMap) {
      if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) {
        losingCursors.push(parseInt(losingCursorIndex, 10));
      }
    }
    losingCursors.sort((a2, b2) => {
      return b2 - a2;
    });
    for (const losingCursor of losingCursors) {
      selectionsAfter.splice(losingCursor, 1);
    }
    return selectionsAfter;
  }
  static _arrayIsEmpty(commands) {
    for (let i3 = 0, len2 = commands.length; i3 < len2; i3++) {
      if (commands[i3]) {
        return false;
      }
    }
    return true;
  }
  static _getEditOperations(ctx, commands) {
    let operations = [];
    let hadTrackedEditOperation = false;
    for (let i3 = 0, len2 = commands.length; i3 < len2; i3++) {
      const command = commands[i3];
      if (command) {
        const r3 = this._getEditOperationsFromCommand(ctx, i3, command);
        operations = operations.concat(r3.operations);
        hadTrackedEditOperation = hadTrackedEditOperation || r3.hadTrackedEditOperation;
      }
    }
    return {
      operations,
      hadTrackedEditOperation
    };
  }
  static _getEditOperationsFromCommand(ctx, majorIdentifier, command) {
    let operations = [];
    let operationMinor = 0;
    const addEditOperation = (range3, text, forceMoveMarkers = false) => {
      if (Range.isEmpty(range3) && text === "") {
        return;
      }
      operations.push({
        identifier: {
          major: majorIdentifier,
          minor: operationMinor++
        },
        range: range3,
        text,
        forceMoveMarkers,
        isAutoWhitespaceEdit: command.insertsAutoWhitespace
      });
    };
    let hadTrackedEditOperation = false;
    const addTrackedEditOperation = (selection2, text, forceMoveMarkers) => {
      hadTrackedEditOperation = true;
      addEditOperation(selection2, text, forceMoveMarkers);
    };
    const trackSelection = (_selection, trackPreviousOnEmpty) => {
      const selection2 = Selection.liftSelection(_selection);
      let stickiness;
      if (selection2.isEmpty()) {
        if (typeof trackPreviousOnEmpty === "boolean") {
          if (trackPreviousOnEmpty) {
            stickiness = 2;
          } else {
            stickiness = 3;
          }
        } else {
          const maxLineColumn = ctx.model.getLineMaxColumn(selection2.startLineNumber);
          if (selection2.startColumn === maxLineColumn) {
            stickiness = 2;
          } else {
            stickiness = 3;
          }
        }
      } else {
        stickiness = 1;
      }
      const l2 = ctx.trackedRanges.length;
      const id3 = ctx.model._setTrackedRange(null, selection2, stickiness);
      ctx.trackedRanges[l2] = id3;
      ctx.trackedRangesDirection[l2] = selection2.getDirection();
      return l2.toString();
    };
    const editOperationBuilder = {
      addEditOperation,
      addTrackedEditOperation,
      trackSelection
    };
    try {
      command.getEditOperations(ctx.model, editOperationBuilder);
    } catch (e2) {
      onUnexpectedError(e2);
      return {
        operations: [],
        hadTrackedEditOperation: false
      };
    }
    return {
      operations,
      hadTrackedEditOperation
    };
  }
  static _getLoserCursorMap(operations) {
    operations = operations.slice(0);
    operations.sort((a2, b2) => {
      return -Range.compareRangesUsingEnds(a2.range, b2.range);
    });
    let loserCursorsMap = {};
    for (let i3 = 1; i3 < operations.length; i3++) {
      const previousOp = operations[i3 - 1];
      const currentOp = operations[i3];
      if (Range.getStartPosition(previousOp.range).isBefore(Range.getEndPosition(currentOp.range))) {
        let loserMajor;
        if (previousOp.identifier.major > currentOp.identifier.major) {
          loserMajor = previousOp.identifier.major;
        } else {
          loserMajor = currentOp.identifier.major;
        }
        loserCursorsMap[loserMajor.toString()] = true;
        for (let j = 0; j < operations.length; j++) {
          if (operations[j].identifier.major === loserMajor) {
            operations.splice(j, 1);
            if (j < i3) {
              i3--;
            }
            j--;
          }
        }
        if (i3 > 0) {
          i3--;
        }
      }
    }
    return loserCursorsMap;
  }
};
var InternalEditorAction = class {
  constructor(id3, label2, alias, precondition, run2, contextKeyService) {
    this.id = id3;
    this.label = label2;
    this.alias = alias;
    this._precondition = precondition;
    this._run = run2;
    this._contextKeyService = contextKeyService;
  }
  isSupported() {
    return this._contextKeyService.contextMatchesRules(this._precondition);
  }
  run() {
    if (!this.isSupported()) {
      return Promise.resolve(void 0);
    }
    return this._run();
  }
};
function tokenizeLineToHTML(text, viewLineTokens, colorMap, startOffset, endOffset, tabSize, useNbsp) {
  let result = `<div>`;
  let charIndex = startOffset;
  let tabsCharDelta = 0;
  for (let tokenIndex = 0, tokenCount = viewLineTokens.getCount(); tokenIndex < tokenCount; tokenIndex++) {
    const tokenEndIndex = viewLineTokens.getEndOffset(tokenIndex);
    if (tokenEndIndex <= startOffset) {
      continue;
    }
    let partContent = "";
    for (; charIndex < tokenEndIndex && charIndex < endOffset; charIndex++) {
      const charCode = text.charCodeAt(charIndex);
      switch (charCode) {
        case 9:
          let insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
          tabsCharDelta += insertSpacesCount - 1;
          while (insertSpacesCount > 0) {
            partContent += useNbsp ? "&#160;" : " ";
            insertSpacesCount--;
          }
          break;
        case 60:
          partContent += "&lt;";
          break;
        case 62:
          partContent += "&gt;";
          break;
        case 38:
          partContent += "&amp;";
          break;
        case 0:
          partContent += "&#00;";
          break;
        case 65279:
        case 8232:
        case 8233:
        case 133:
          partContent += "�";
          break;
        case 13:
          partContent += "&#8203";
          break;
        case 32:
          partContent += useNbsp ? "&#160;" : " ";
          break;
        default:
          partContent += String.fromCharCode(charCode);
      }
    }
    result += `<span style="${viewLineTokens.getInlineStyle(tokenIndex, colorMap)}">${partContent}</span>`;
    if (tokenEndIndex > endOffset || charIndex >= endOffset) {
      break;
    }
  }
  result += `</div>`;
  return result;
}
var PendingChanges = class {
  constructor() {
    this._hasPending = false;
    this._inserts = [];
    this._changes = [];
    this._removes = [];
  }
  insert(x2) {
    this._hasPending = true;
    this._inserts.push(x2);
  }
  change(x2) {
    this._hasPending = true;
    this._changes.push(x2);
  }
  remove(x2) {
    this._hasPending = true;
    this._removes.push(x2);
  }
  mustCommit() {
    return this._hasPending;
  }
  commit(linesLayout) {
    if (!this._hasPending) {
      return;
    }
    const inserts = this._inserts;
    const changes = this._changes;
    const removes = this._removes;
    this._hasPending = false;
    this._inserts = [];
    this._changes = [];
    this._removes = [];
    linesLayout._commitPendingChanges(inserts, changes, removes);
  }
};
var EditorWhitespace = class {
  constructor(id3, afterLineNumber, ordinal, height, minWidth) {
    this.id = id3;
    this.afterLineNumber = afterLineNumber;
    this.ordinal = ordinal;
    this.height = height;
    this.minWidth = minWidth;
    this.prefixSum = 0;
  }
};
var LinesLayout = class {
  constructor(lineCount, lineHeight, paddingTop, paddingBottom) {
    this._instanceId = singleLetterHash(++LinesLayout.INSTANCE_COUNT);
    this._pendingChanges = new PendingChanges();
    this._lastWhitespaceId = 0;
    this._arr = [];
    this._prefixSumValidIndex = -1;
    this._minWidth = -1;
    this._lineCount = lineCount;
    this._lineHeight = lineHeight;
    this._paddingTop = paddingTop;
    this._paddingBottom = paddingBottom;
  }
  static findInsertionIndex(arr, afterLineNumber, ordinal) {
    let low = 0;
    let high = arr.length;
    while (low < high) {
      const mid = low + high >>> 1;
      if (afterLineNumber === arr[mid].afterLineNumber) {
        if (ordinal < arr[mid].ordinal) {
          high = mid;
        } else {
          low = mid + 1;
        }
      } else if (afterLineNumber < arr[mid].afterLineNumber) {
        high = mid;
      } else {
        low = mid + 1;
      }
    }
    return low;
  }
  setLineHeight(lineHeight) {
    this._checkPendingChanges();
    this._lineHeight = lineHeight;
  }
  setPadding(paddingTop, paddingBottom) {
    this._paddingTop = paddingTop;
    this._paddingBottom = paddingBottom;
  }
  onFlushed(lineCount) {
    this._checkPendingChanges();
    this._lineCount = lineCount;
  }
  changeWhitespace(callback) {
    let hadAChange = false;
    try {
      const accessor = {
        insertWhitespace: (afterLineNumber, ordinal, heightInPx, minWidth) => {
          hadAChange = true;
          afterLineNumber = afterLineNumber | 0;
          ordinal = ordinal | 0;
          heightInPx = heightInPx | 0;
          minWidth = minWidth | 0;
          const id3 = this._instanceId + ++this._lastWhitespaceId;
          this._pendingChanges.insert(new EditorWhitespace(id3, afterLineNumber, ordinal, heightInPx, minWidth));
          return id3;
        },
        changeOneWhitespace: (id3, newAfterLineNumber, newHeight) => {
          hadAChange = true;
          newAfterLineNumber = newAfterLineNumber | 0;
          newHeight = newHeight | 0;
          this._pendingChanges.change({id: id3, newAfterLineNumber, newHeight});
        },
        removeWhitespace: (id3) => {
          hadAChange = true;
          this._pendingChanges.remove({id: id3});
        }
      };
      callback(accessor);
    } finally {
      this._pendingChanges.commit(this);
    }
    return hadAChange;
  }
  _commitPendingChanges(inserts, changes, removes) {
    if (inserts.length > 0 || removes.length > 0) {
      this._minWidth = -1;
    }
    if (inserts.length + changes.length + removes.length <= 1) {
      for (const insert2 of inserts) {
        this._insertWhitespace(insert2);
      }
      for (const change of changes) {
        this._changeOneWhitespace(change.id, change.newAfterLineNumber, change.newHeight);
      }
      for (const remove3 of removes) {
        const index3 = this._findWhitespaceIndex(remove3.id);
        if (index3 === -1) {
          continue;
        }
        this._removeWhitespace(index3);
      }
      return;
    }
    const toRemove = new Set();
    for (const remove3 of removes) {
      toRemove.add(remove3.id);
    }
    const toChange = new Map();
    for (const change of changes) {
      toChange.set(change.id, change);
    }
    const applyRemoveAndChange = (whitespaces) => {
      let result2 = [];
      for (const whitespace of whitespaces) {
        if (toRemove.has(whitespace.id)) {
          continue;
        }
        if (toChange.has(whitespace.id)) {
          const change = toChange.get(whitespace.id);
          whitespace.afterLineNumber = change.newAfterLineNumber;
          whitespace.height = change.newHeight;
        }
        result2.push(whitespace);
      }
      return result2;
    };
    const result = applyRemoveAndChange(this._arr).concat(applyRemoveAndChange(inserts));
    result.sort((a2, b2) => {
      if (a2.afterLineNumber === b2.afterLineNumber) {
        return a2.ordinal - b2.ordinal;
      }
      return a2.afterLineNumber - b2.afterLineNumber;
    });
    this._arr = result;
    this._prefixSumValidIndex = -1;
  }
  _checkPendingChanges() {
    if (this._pendingChanges.mustCommit()) {
      this._pendingChanges.commit(this);
    }
  }
  _insertWhitespace(whitespace) {
    const insertIndex = LinesLayout.findInsertionIndex(this._arr, whitespace.afterLineNumber, whitespace.ordinal);
    this._arr.splice(insertIndex, 0, whitespace);
    this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1);
  }
  _findWhitespaceIndex(id3) {
    const arr = this._arr;
    for (let i3 = 0, len2 = arr.length; i3 < len2; i3++) {
      if (arr[i3].id === id3) {
        return i3;
      }
    }
    return -1;
  }
  _changeOneWhitespace(id3, newAfterLineNumber, newHeight) {
    const index3 = this._findWhitespaceIndex(id3);
    if (index3 === -1) {
      return;
    }
    if (this._arr[index3].height !== newHeight) {
      this._arr[index3].height = newHeight;
      this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, index3 - 1);
    }
    if (this._arr[index3].afterLineNumber !== newAfterLineNumber) {
      const whitespace = this._arr[index3];
      this._removeWhitespace(index3);
      whitespace.afterLineNumber = newAfterLineNumber;
      this._insertWhitespace(whitespace);
    }
  }
  _removeWhitespace(removeIndex) {
    this._arr.splice(removeIndex, 1);
    this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, removeIndex - 1);
  }
  onLinesDeleted(fromLineNumber, toLineNumber) {
    this._checkPendingChanges();
    fromLineNumber = fromLineNumber | 0;
    toLineNumber = toLineNumber | 0;
    this._lineCount -= toLineNumber - fromLineNumber + 1;
    for (let i3 = 0, len2 = this._arr.length; i3 < len2; i3++) {
      const afterLineNumber = this._arr[i3].afterLineNumber;
      if (fromLineNumber <= afterLineNumber && afterLineNumber <= toLineNumber) {
        this._arr[i3].afterLineNumber = fromLineNumber - 1;
      } else if (afterLineNumber > toLineNumber) {
        this._arr[i3].afterLineNumber -= toLineNumber - fromLineNumber + 1;
      }
    }
  }
  onLinesInserted(fromLineNumber, toLineNumber) {
    this._checkPendingChanges();
    fromLineNumber = fromLineNumber | 0;
    toLineNumber = toLineNumber | 0;
    this._lineCount += toLineNumber - fromLineNumber + 1;
    for (let i3 = 0, len2 = this._arr.length; i3 < len2; i3++) {
      const afterLineNumber = this._arr[i3].afterLineNumber;
      if (fromLineNumber <= afterLineNumber) {
        this._arr[i3].afterLineNumber += toLineNumber - fromLineNumber + 1;
      }
    }
  }
  getWhitespacesTotalHeight() {
    this._checkPendingChanges();
    if (this._arr.length === 0) {
      return 0;
    }
    return this.getWhitespacesAccumulatedHeight(this._arr.length - 1);
  }
  getWhitespacesAccumulatedHeight(index3) {
    this._checkPendingChanges();
    index3 = index3 | 0;
    let startIndex = Math.max(0, this._prefixSumValidIndex + 1);
    if (startIndex === 0) {
      this._arr[0].prefixSum = this._arr[0].height;
      startIndex++;
    }
    for (let i3 = startIndex; i3 <= index3; i3++) {
      this._arr[i3].prefixSum = this._arr[i3 - 1].prefixSum + this._arr[i3].height;
    }
    this._prefixSumValidIndex = Math.max(this._prefixSumValidIndex, index3);
    return this._arr[index3].prefixSum;
  }
  getLinesTotalHeight() {
    this._checkPendingChanges();
    const linesHeight = this._lineHeight * this._lineCount;
    const whitespacesHeight = this.getWhitespacesTotalHeight();
    return linesHeight + whitespacesHeight + this._paddingTop + this._paddingBottom;
  }
  getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber) {
    this._checkPendingChanges();
    lineNumber = lineNumber | 0;
    const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
    if (lastWhitespaceBeforeLineNumber === -1) {
      return 0;
    }
    return this.getWhitespacesAccumulatedHeight(lastWhitespaceBeforeLineNumber);
  }
  _findLastWhitespaceBeforeLineNumber(lineNumber) {
    lineNumber = lineNumber | 0;
    const arr = this._arr;
    let low = 0;
    let high = arr.length - 1;
    while (low <= high) {
      const delta = high - low | 0;
      const halfDelta = delta / 2 | 0;
      const mid = low + halfDelta | 0;
      if (arr[mid].afterLineNumber < lineNumber) {
        if (mid + 1 >= arr.length || arr[mid + 1].afterLineNumber >= lineNumber) {
          return mid;
        } else {
          low = mid + 1 | 0;
        }
      } else {
        high = mid - 1 | 0;
      }
    }
    return -1;
  }
  _findFirstWhitespaceAfterLineNumber(lineNumber) {
    lineNumber = lineNumber | 0;
    const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
    const firstWhitespaceAfterLineNumber = lastWhitespaceBeforeLineNumber + 1;
    if (firstWhitespaceAfterLineNumber < this._arr.length) {
      return firstWhitespaceAfterLineNumber;
    }
    return -1;
  }
  getFirstWhitespaceIndexAfterLineNumber(lineNumber) {
    this._checkPendingChanges();
    lineNumber = lineNumber | 0;
    return this._findFirstWhitespaceAfterLineNumber(lineNumber);
  }
  getVerticalOffsetForLineNumber(lineNumber) {
    this._checkPendingChanges();
    lineNumber = lineNumber | 0;
    let previousLinesHeight;
    if (lineNumber > 1) {
      previousLinesHeight = this._lineHeight * (lineNumber - 1);
    } else {
      previousLinesHeight = 0;
    }
    const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber);
    return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
  }
  getWhitespaceMinWidth() {
    this._checkPendingChanges();
    if (this._minWidth === -1) {
      let minWidth = 0;
      for (let i3 = 0, len2 = this._arr.length; i3 < len2; i3++) {
        minWidth = Math.max(minWidth, this._arr[i3].minWidth);
      }
      this._minWidth = minWidth;
    }
    return this._minWidth;
  }
  isAfterLines(verticalOffset) {
    this._checkPendingChanges();
    const totalHeight = this.getLinesTotalHeight();
    return verticalOffset > totalHeight;
  }
  getLineNumberAtOrAfterVerticalOffset(verticalOffset) {
    this._checkPendingChanges();
    verticalOffset = verticalOffset | 0;
    if (verticalOffset < 0) {
      return 1;
    }
    const linesCount = this._lineCount | 0;
    const lineHeight = this._lineHeight;
    let minLineNumber = 1;
    let maxLineNumber = linesCount;
    while (minLineNumber < maxLineNumber) {
      const midLineNumber = (minLineNumber + maxLineNumber) / 2 | 0;
      const midLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(midLineNumber) | 0;
      if (verticalOffset >= midLineNumberVerticalOffset + lineHeight) {
        minLineNumber = midLineNumber + 1;
      } else if (verticalOffset >= midLineNumberVerticalOffset) {
        return midLineNumber;
      } else {
        maxLineNumber = midLineNumber;
      }
    }
    if (minLineNumber > linesCount) {
      return linesCount;
    }
    return minLineNumber;
  }
  getLinesViewportData(verticalOffset1, verticalOffset2) {
    this._checkPendingChanges();
    verticalOffset1 = verticalOffset1 | 0;
    verticalOffset2 = verticalOffset2 | 0;
    const lineHeight = this._lineHeight;
    const startLineNumber = this.getLineNumberAtOrAfterVerticalOffset(verticalOffset1) | 0;
    const startLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(startLineNumber) | 0;
    let endLineNumber = this._lineCount | 0;
    let whitespaceIndex = this.getFirstWhitespaceIndexAfterLineNumber(startLineNumber) | 0;
    const whitespaceCount = this.getWhitespacesCount() | 0;
    let currentWhitespaceHeight;
    let currentWhitespaceAfterLineNumber;
    if (whitespaceIndex === -1) {
      whitespaceIndex = whitespaceCount;
      currentWhitespaceAfterLineNumber = endLineNumber + 1;
      currentWhitespaceHeight = 0;
    } else {
      currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
      currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
    }
    let currentVerticalOffset = startLineNumberVerticalOffset;
    let currentLineRelativeOffset = currentVerticalOffset;
    const STEP_SIZE = 5e5;
    let bigNumbersDelta = 0;
    if (startLineNumberVerticalOffset >= STEP_SIZE) {
      bigNumbersDelta = Math.floor(startLineNumberVerticalOffset / STEP_SIZE) * STEP_SIZE;
      bigNumbersDelta = Math.floor(bigNumbersDelta / lineHeight) * lineHeight;
      currentLineRelativeOffset -= bigNumbersDelta;
    }
    const linesOffsets = [];
    const verticalCenter = verticalOffset1 + (verticalOffset2 - verticalOffset1) / 2;
    let centeredLineNumber = -1;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      if (centeredLineNumber === -1) {
        const currentLineTop = currentVerticalOffset;
        const currentLineBottom = currentVerticalOffset + lineHeight;
        if (currentLineTop <= verticalCenter && verticalCenter < currentLineBottom || currentLineTop > verticalCenter) {
          centeredLineNumber = lineNumber;
        }
      }
      currentVerticalOffset += lineHeight;
      linesOffsets[lineNumber - startLineNumber] = currentLineRelativeOffset;
      currentLineRelativeOffset += lineHeight;
      while (currentWhitespaceAfterLineNumber === lineNumber) {
        currentLineRelativeOffset += currentWhitespaceHeight;
        currentVerticalOffset += currentWhitespaceHeight;
        whitespaceIndex++;
        if (whitespaceIndex >= whitespaceCount) {
          currentWhitespaceAfterLineNumber = endLineNumber + 1;
        } else {
          currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
          currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
        }
      }
      if (currentVerticalOffset >= verticalOffset2) {
        endLineNumber = lineNumber;
        break;
      }
    }
    if (centeredLineNumber === -1) {
      centeredLineNumber = endLineNumber;
    }
    const endLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(endLineNumber) | 0;
    let completelyVisibleStartLineNumber = startLineNumber;
    let completelyVisibleEndLineNumber = endLineNumber;
    if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
      if (startLineNumberVerticalOffset < verticalOffset1) {
        completelyVisibleStartLineNumber++;
      }
    }
    if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
      if (endLineNumberVerticalOffset + lineHeight > verticalOffset2) {
        completelyVisibleEndLineNumber--;
      }
    }
    return {
      bigNumbersDelta,
      startLineNumber,
      endLineNumber,
      relativeVerticalOffset: linesOffsets,
      centeredLineNumber,
      completelyVisibleStartLineNumber,
      completelyVisibleEndLineNumber
    };
  }
  getVerticalOffsetForWhitespaceIndex(whitespaceIndex) {
    this._checkPendingChanges();
    whitespaceIndex = whitespaceIndex | 0;
    const afterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex);
    let previousLinesHeight;
    if (afterLineNumber >= 1) {
      previousLinesHeight = this._lineHeight * afterLineNumber;
    } else {
      previousLinesHeight = 0;
    }
    let previousWhitespacesHeight;
    if (whitespaceIndex > 0) {
      previousWhitespacesHeight = this.getWhitespacesAccumulatedHeight(whitespaceIndex - 1);
    } else {
      previousWhitespacesHeight = 0;
    }
    return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
  }
  getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset) {
    this._checkPendingChanges();
    verticalOffset = verticalOffset | 0;
    let minWhitespaceIndex = 0;
    let maxWhitespaceIndex = this.getWhitespacesCount() - 1;
    if (maxWhitespaceIndex < 0) {
      return -1;
    }
    const maxWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(maxWhitespaceIndex);
    const maxWhitespaceHeight = this.getHeightForWhitespaceIndex(maxWhitespaceIndex);
    if (verticalOffset >= maxWhitespaceVerticalOffset + maxWhitespaceHeight) {
      return -1;
    }
    while (minWhitespaceIndex < maxWhitespaceIndex) {
      const midWhitespaceIndex = Math.floor((minWhitespaceIndex + maxWhitespaceIndex) / 2);
      const midWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(midWhitespaceIndex);
      const midWhitespaceHeight = this.getHeightForWhitespaceIndex(midWhitespaceIndex);
      if (verticalOffset >= midWhitespaceVerticalOffset + midWhitespaceHeight) {
        minWhitespaceIndex = midWhitespaceIndex + 1;
      } else if (verticalOffset >= midWhitespaceVerticalOffset) {
        return midWhitespaceIndex;
      } else {
        maxWhitespaceIndex = midWhitespaceIndex;
      }
    }
    return minWhitespaceIndex;
  }
  getWhitespaceAtVerticalOffset(verticalOffset) {
    this._checkPendingChanges();
    verticalOffset = verticalOffset | 0;
    const candidateIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset);
    if (candidateIndex < 0) {
      return null;
    }
    if (candidateIndex >= this.getWhitespacesCount()) {
      return null;
    }
    const candidateTop = this.getVerticalOffsetForWhitespaceIndex(candidateIndex);
    if (candidateTop > verticalOffset) {
      return null;
    }
    const candidateHeight = this.getHeightForWhitespaceIndex(candidateIndex);
    const candidateId = this.getIdForWhitespaceIndex(candidateIndex);
    const candidateAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(candidateIndex);
    return {
      id: candidateId,
      afterLineNumber: candidateAfterLineNumber,
      verticalOffset: candidateTop,
      height: candidateHeight
    };
  }
  getWhitespaceViewportData(verticalOffset1, verticalOffset2) {
    this._checkPendingChanges();
    verticalOffset1 = verticalOffset1 | 0;
    verticalOffset2 = verticalOffset2 | 0;
    const startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1);
    const endIndex = this.getWhitespacesCount() - 1;
    if (startIndex < 0) {
      return [];
    }
    let result = [];
    for (let i3 = startIndex; i3 <= endIndex; i3++) {
      const top2 = this.getVerticalOffsetForWhitespaceIndex(i3);
      const height = this.getHeightForWhitespaceIndex(i3);
      if (top2 >= verticalOffset2) {
        break;
      }
      result.push({
        id: this.getIdForWhitespaceIndex(i3),
        afterLineNumber: this.getAfterLineNumberForWhitespaceIndex(i3),
        verticalOffset: top2,
        height
      });
    }
    return result;
  }
  getWhitespaces() {
    this._checkPendingChanges();
    return this._arr.slice(0);
  }
  getWhitespacesCount() {
    this._checkPendingChanges();
    return this._arr.length;
  }
  getIdForWhitespaceIndex(index3) {
    this._checkPendingChanges();
    index3 = index3 | 0;
    return this._arr[index3].id;
  }
  getAfterLineNumberForWhitespaceIndex(index3) {
    this._checkPendingChanges();
    index3 = index3 | 0;
    return this._arr[index3].afterLineNumber;
  }
  getHeightForWhitespaceIndex(index3) {
    this._checkPendingChanges();
    index3 = index3 | 0;
    return this._arr[index3].height;
  }
};
LinesLayout.INSTANCE_COUNT = 0;
var SMOOTH_SCROLLING_TIME = 125;
var EditorScrollDimensions = class {
  constructor(width2, contentWidth, height, contentHeight) {
    width2 = width2 | 0;
    contentWidth = contentWidth | 0;
    height = height | 0;
    contentHeight = contentHeight | 0;
    if (width2 < 0) {
      width2 = 0;
    }
    if (contentWidth < 0) {
      contentWidth = 0;
    }
    if (height < 0) {
      height = 0;
    }
    if (contentHeight < 0) {
      contentHeight = 0;
    }
    this.width = width2;
    this.contentWidth = contentWidth;
    this.scrollWidth = Math.max(width2, contentWidth);
    this.height = height;
    this.contentHeight = contentHeight;
    this.scrollHeight = Math.max(height, contentHeight);
  }
  equals(other) {
    return this.width === other.width && this.contentWidth === other.contentWidth && this.height === other.height && this.contentHeight === other.contentHeight;
  }
};
var EditorScrollable = class extends Disposable {
  constructor(smoothScrollDuration, scheduleAtNextAnimationFrame2) {
    super();
    this._onDidContentSizeChange = this._register(new Emitter());
    this.onDidContentSizeChange = this._onDidContentSizeChange.event;
    this._dimensions = new EditorScrollDimensions(0, 0, 0, 0);
    this._scrollable = this._register(new Scrollable(smoothScrollDuration, scheduleAtNextAnimationFrame2));
    this.onDidScroll = this._scrollable.onScroll;
  }
  getScrollable() {
    return this._scrollable;
  }
  setSmoothScrollDuration(smoothScrollDuration) {
    this._scrollable.setSmoothScrollDuration(smoothScrollDuration);
  }
  validateScrollPosition(scrollPosition) {
    return this._scrollable.validateScrollPosition(scrollPosition);
  }
  getScrollDimensions() {
    return this._dimensions;
  }
  setScrollDimensions(dimensions) {
    if (this._dimensions.equals(dimensions)) {
      return;
    }
    const oldDimensions = this._dimensions;
    this._dimensions = dimensions;
    this._scrollable.setScrollDimensions({
      width: dimensions.width,
      scrollWidth: dimensions.scrollWidth,
      height: dimensions.height,
      scrollHeight: dimensions.scrollHeight
    }, true);
    const contentWidthChanged = oldDimensions.contentWidth !== dimensions.contentWidth;
    const contentHeightChanged = oldDimensions.contentHeight !== dimensions.contentHeight;
    if (contentWidthChanged || contentHeightChanged) {
      this._onDidContentSizeChange.fire(new ContentSizeChangedEvent(oldDimensions.contentWidth, oldDimensions.contentHeight, dimensions.contentWidth, dimensions.contentHeight));
    }
  }
  getFutureScrollPosition() {
    return this._scrollable.getFutureScrollPosition();
  }
  getCurrentScrollPosition() {
    return this._scrollable.getCurrentScrollPosition();
  }
  setScrollPositionNow(update) {
    this._scrollable.setScrollPositionNow(update);
  }
  setScrollPositionSmooth(update) {
    this._scrollable.setScrollPositionSmooth(update);
  }
};
var ViewLayout = class extends Disposable {
  constructor(configuration, lineCount, scheduleAtNextAnimationFrame2) {
    super();
    this._configuration = configuration;
    const options = this._configuration.options;
    const layoutInfo = options.get(117);
    const padding = options.get(66);
    this._linesLayout = new LinesLayout(lineCount, options.get(51), padding.top, padding.bottom);
    this._scrollable = this._register(new EditorScrollable(0, scheduleAtNextAnimationFrame2));
    this._configureSmoothScrollDuration();
    this._scrollable.setScrollDimensions(new EditorScrollDimensions(layoutInfo.contentWidth, 0, layoutInfo.height, 0));
    this.onDidScroll = this._scrollable.onDidScroll;
    this.onDidContentSizeChange = this._scrollable.onDidContentSizeChange;
    this._updateHeight();
  }
  dispose() {
    super.dispose();
  }
  getScrollable() {
    return this._scrollable.getScrollable();
  }
  onHeightMaybeChanged() {
    this._updateHeight();
  }
  _configureSmoothScrollDuration() {
    this._scrollable.setSmoothScrollDuration(this._configuration.options.get(94) ? SMOOTH_SCROLLING_TIME : 0);
  }
  onConfigurationChanged(e2) {
    const options = this._configuration.options;
    if (e2.hasChanged(51)) {
      this._linesLayout.setLineHeight(options.get(51));
    }
    if (e2.hasChanged(66)) {
      const padding = options.get(66);
      this._linesLayout.setPadding(padding.top, padding.bottom);
    }
    if (e2.hasChanged(117)) {
      const layoutInfo = options.get(117);
      const width2 = layoutInfo.contentWidth;
      const height = layoutInfo.height;
      const scrollDimensions = this._scrollable.getScrollDimensions();
      const contentWidth = scrollDimensions.contentWidth;
      this._scrollable.setScrollDimensions(new EditorScrollDimensions(width2, scrollDimensions.contentWidth, height, this._getContentHeight(width2, height, contentWidth)));
    } else {
      this._updateHeight();
    }
    if (e2.hasChanged(94)) {
      this._configureSmoothScrollDuration();
    }
  }
  onFlushed(lineCount) {
    this._linesLayout.onFlushed(lineCount);
  }
  onLinesDeleted(fromLineNumber, toLineNumber) {
    this._linesLayout.onLinesDeleted(fromLineNumber, toLineNumber);
  }
  onLinesInserted(fromLineNumber, toLineNumber) {
    this._linesLayout.onLinesInserted(fromLineNumber, toLineNumber);
  }
  _getHorizontalScrollbarHeight(width2, scrollWidth) {
    const options = this._configuration.options;
    const scrollbar = options.get(84);
    if (scrollbar.horizontal === 2) {
      return 0;
    }
    if (width2 >= scrollWidth) {
      return 0;
    }
    return scrollbar.horizontalScrollbarSize;
  }
  _getContentHeight(width2, height, contentWidth) {
    const options = this._configuration.options;
    let result = this._linesLayout.getLinesTotalHeight();
    if (options.get(86)) {
      result += height - options.get(51);
    } else {
      result += this._getHorizontalScrollbarHeight(width2, contentWidth);
    }
    return result;
  }
  _updateHeight() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    const width2 = scrollDimensions.width;
    const height = scrollDimensions.height;
    const contentWidth = scrollDimensions.contentWidth;
    this._scrollable.setScrollDimensions(new EditorScrollDimensions(width2, scrollDimensions.contentWidth, height, this._getContentHeight(width2, height, contentWidth)));
  }
  getCurrentViewport() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
    return new Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
  }
  getFutureViewport() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    const currentScrollPosition = this._scrollable.getFutureScrollPosition();
    return new Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
  }
  _computeContentWidth(maxLineWidth) {
    const options = this._configuration.options;
    const wrappingInfo = options.get(118);
    const fontInfo = options.get(36);
    if (wrappingInfo.isViewportWrapping) {
      const layoutInfo = options.get(117);
      const minimap = options.get(56);
      if (maxLineWidth > layoutInfo.contentWidth + fontInfo.typicalHalfwidthCharacterWidth) {
        if (minimap.enabled && minimap.side === "right") {
          return maxLineWidth + layoutInfo.verticalScrollbarWidth;
        }
      }
      return maxLineWidth;
    } else {
      const extraHorizontalSpace = options.get(85) * fontInfo.typicalHalfwidthCharacterWidth;
      const whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth();
      return Math.max(maxLineWidth + extraHorizontalSpace, whitespaceMinWidth);
    }
  }
  setMaxLineWidth(maxLineWidth) {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    this._scrollable.setScrollDimensions(new EditorScrollDimensions(scrollDimensions.width, this._computeContentWidth(maxLineWidth), scrollDimensions.height, scrollDimensions.contentHeight));
    this._updateHeight();
  }
  saveState() {
    const currentScrollPosition = this._scrollable.getFutureScrollPosition();
    let scrollTop = currentScrollPosition.scrollTop;
    let firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop);
    let whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport);
    return {
      scrollTop,
      scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine,
      scrollLeft: currentScrollPosition.scrollLeft
    };
  }
  changeWhitespace(callback) {
    const hadAChange = this._linesLayout.changeWhitespace(callback);
    if (hadAChange) {
      this.onHeightMaybeChanged();
    }
    return hadAChange;
  }
  getVerticalOffsetForLineNumber(lineNumber) {
    return this._linesLayout.getVerticalOffsetForLineNumber(lineNumber);
  }
  isAfterLines(verticalOffset) {
    return this._linesLayout.isAfterLines(verticalOffset);
  }
  getLineNumberAtVerticalOffset(verticalOffset) {
    return this._linesLayout.getLineNumberAtOrAfterVerticalOffset(verticalOffset);
  }
  getWhitespaceAtVerticalOffset(verticalOffset) {
    return this._linesLayout.getWhitespaceAtVerticalOffset(verticalOffset);
  }
  getLinesViewportData() {
    const visibleBox = this.getCurrentViewport();
    return this._linesLayout.getLinesViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
  }
  getLinesViewportDataAtScrollTop(scrollTop) {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    if (scrollTop + scrollDimensions.height > scrollDimensions.scrollHeight) {
      scrollTop = scrollDimensions.scrollHeight - scrollDimensions.height;
    }
    if (scrollTop < 0) {
      scrollTop = 0;
    }
    return this._linesLayout.getLinesViewportData(scrollTop, scrollTop + scrollDimensions.height);
  }
  getWhitespaceViewportData() {
    const visibleBox = this.getCurrentViewport();
    return this._linesLayout.getWhitespaceViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
  }
  getWhitespaces() {
    return this._linesLayout.getWhitespaces();
  }
  getContentWidth() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    return scrollDimensions.contentWidth;
  }
  getScrollWidth() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    return scrollDimensions.scrollWidth;
  }
  getContentHeight() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    return scrollDimensions.contentHeight;
  }
  getScrollHeight() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    return scrollDimensions.scrollHeight;
  }
  getCurrentScrollLeft() {
    const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
    return currentScrollPosition.scrollLeft;
  }
  getCurrentScrollTop() {
    const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
    return currentScrollPosition.scrollTop;
  }
  validateScrollPosition(scrollPosition) {
    return this._scrollable.validateScrollPosition(scrollPosition);
  }
  setScrollPosition(position2, type) {
    if (type === 1) {
      this._scrollable.setScrollPositionNow(position2);
    } else {
      this._scrollable.setScrollPositionSmooth(position2);
    }
  }
  deltaScrollNow(deltaScrollLeft, deltaScrollTop) {
    const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
    this._scrollable.setScrollPositionNow({
      scrollLeft: currentScrollPosition.scrollLeft + deltaScrollLeft,
      scrollTop: currentScrollPosition.scrollTop + deltaScrollTop
    });
  }
};
var OutputPosition = class {
  constructor(outputLineIndex, outputOffset) {
    this.outputLineIndex = outputLineIndex;
    this.outputOffset = outputOffset;
  }
};
var LineBreakData = class {
  constructor(breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength) {
    this.breakOffsets = breakOffsets;
    this.breakOffsetsVisibleColumn = breakOffsetsVisibleColumn;
    this.wrappedTextIndentLength = wrappedTextIndentLength;
  }
  static getInputOffsetOfOutputPosition(breakOffsets, outputLineIndex, outputOffset) {
    if (outputLineIndex === 0) {
      return outputOffset;
    } else {
      return breakOffsets[outputLineIndex - 1] + outputOffset;
    }
  }
  static getOutputPositionOfInputOffset(breakOffsets, inputOffset) {
    let low = 0;
    let high = breakOffsets.length - 1;
    let mid = 0;
    let midStart = 0;
    while (low <= high) {
      mid = low + (high - low) / 2 | 0;
      const midStop = breakOffsets[mid];
      midStart = mid > 0 ? breakOffsets[mid - 1] : 0;
      if (inputOffset < midStart) {
        high = mid - 1;
      } else if (inputOffset >= midStop) {
        low = mid + 1;
      } else {
        break;
      }
    }
    return new OutputPosition(mid, inputOffset - midStart);
  }
};
var CoordinatesConverter = class {
  constructor(lines) {
    this._lines = lines;
  }
  convertViewPositionToModelPosition(viewPosition) {
    return this._lines.convertViewPositionToModelPosition(viewPosition.lineNumber, viewPosition.column);
  }
  convertViewRangeToModelRange(viewRange) {
    return this._lines.convertViewRangeToModelRange(viewRange);
  }
  validateViewPosition(viewPosition, expectedModelPosition) {
    return this._lines.validateViewPosition(viewPosition.lineNumber, viewPosition.column, expectedModelPosition);
  }
  validateViewRange(viewRange, expectedModelRange) {
    return this._lines.validateViewRange(viewRange, expectedModelRange);
  }
  convertModelPositionToViewPosition(modelPosition) {
    return this._lines.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column);
  }
  convertModelRangeToViewRange(modelRange) {
    return this._lines.convertModelRangeToViewRange(modelRange);
  }
  modelPositionIsVisible(modelPosition) {
    return this._lines.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column);
  }
};
var LineNumberMapper = class {
  constructor(viewLineCounts) {
    this._counts = viewLineCounts;
    this._isValid = false;
    this._validEndIndex = -1;
    this._modelToView = [];
    this._viewToModel = [];
  }
  _invalidate(index3) {
    this._isValid = false;
    this._validEndIndex = Math.min(this._validEndIndex, index3 - 1);
  }
  _ensureValid() {
    if (this._isValid) {
      return;
    }
    for (let i3 = this._validEndIndex + 1, len2 = this._counts.length; i3 < len2; i3++) {
      const viewLineCount = this._counts[i3];
      const viewLinesAbove = i3 > 0 ? this._modelToView[i3 - 1] : 0;
      this._modelToView[i3] = viewLinesAbove + viewLineCount;
      for (let j = 0; j < viewLineCount; j++) {
        this._viewToModel[viewLinesAbove + j] = i3;
      }
    }
    this._modelToView.length = this._counts.length;
    this._viewToModel.length = this._modelToView[this._modelToView.length - 1];
    this._isValid = true;
    this._validEndIndex = this._counts.length - 1;
  }
  changeValue(index3, value) {
    if (this._counts[index3] === value) {
      return;
    }
    this._counts[index3] = value;
    this._invalidate(index3);
  }
  removeValues(start3, deleteCount) {
    this._counts.splice(start3, deleteCount);
    this._invalidate(start3);
  }
  insertValues(insertIndex, insertArr) {
    this._counts = arrayInsert(this._counts, insertIndex, insertArr);
    this._invalidate(insertIndex);
  }
  getTotalValue() {
    this._ensureValid();
    return this._viewToModel.length;
  }
  getAccumulatedValue(index3) {
    this._ensureValid();
    return this._modelToView[index3];
  }
  getIndexOf(accumulatedValue) {
    this._ensureValid();
    const modelLineIndex = this._viewToModel[accumulatedValue];
    const viewLinesAbove = modelLineIndex > 0 ? this._modelToView[modelLineIndex - 1] : 0;
    return new PrefixSumIndexOfResult(modelLineIndex, accumulatedValue - viewLinesAbove);
  }
};
var SplitLinesCollection = class {
  constructor(model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, tabSize, wrappingStrategy, wrappingColumn, wrappingIndent) {
    this.model = model;
    this._validModelVersionId = -1;
    this._domLineBreaksComputerFactory = domLineBreaksComputerFactory;
    this._monospaceLineBreaksComputerFactory = monospaceLineBreaksComputerFactory;
    this.fontInfo = fontInfo;
    this.tabSize = tabSize;
    this.wrappingStrategy = wrappingStrategy;
    this.wrappingColumn = wrappingColumn;
    this.wrappingIndent = wrappingIndent;
    this._constructLines(true, null);
  }
  dispose() {
    this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, []);
  }
  createCoordinatesConverter() {
    return new CoordinatesConverter(this);
  }
  _constructLines(resetHiddenAreas, previousLineBreaks) {
    this.lines = [];
    if (resetHiddenAreas) {
      this.hiddenAreasIds = [];
    }
    let linesContent = this.model.getLinesContent();
    const lineCount = linesContent.length;
    const lineBreaksComputer = this.createLineBreaksComputer();
    for (let i3 = 0; i3 < lineCount; i3++) {
      lineBreaksComputer.addRequest(linesContent[i3], previousLineBreaks ? previousLineBreaks[i3] : null);
    }
    const linesBreaks = lineBreaksComputer.finalize();
    let values2 = [];
    let hiddenAreas = this.hiddenAreasIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(Range.compareRangesUsingStarts);
    let hiddenAreaStart = 1, hiddenAreaEnd = 0;
    let hiddenAreaIdx = -1;
    let nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : lineCount + 2;
    for (let i3 = 0; i3 < lineCount; i3++) {
      let lineNumber = i3 + 1;
      if (lineNumber === nextLineNumberToUpdateHiddenArea) {
        hiddenAreaIdx++;
        hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
        hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
        nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : lineCount + 2;
      }
      let isInHiddenArea = lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd;
      let line = createSplitLine(linesBreaks[i3], !isInHiddenArea);
      values2[i3] = line.getViewLineCount();
      this.lines[i3] = line;
    }
    this._validModelVersionId = this.model.getVersionId();
    this.prefixSumComputer = new LineNumberMapper(values2);
  }
  getHiddenAreas() {
    return this.hiddenAreasIds.map((decId) => {
      return this.model.getDecorationRange(decId);
    });
  }
  _reduceRanges(_ranges) {
    if (_ranges.length === 0) {
      return [];
    }
    let ranges = _ranges.map((r3) => this.model.validateRange(r3)).sort(Range.compareRangesUsingStarts);
    let result = [];
    let currentRangeStart = ranges[0].startLineNumber;
    let currentRangeEnd = ranges[0].endLineNumber;
    for (let i3 = 1, len2 = ranges.length; i3 < len2; i3++) {
      let range3 = ranges[i3];
      if (range3.startLineNumber > currentRangeEnd + 1) {
        result.push(new Range(currentRangeStart, 1, currentRangeEnd, 1));
        currentRangeStart = range3.startLineNumber;
        currentRangeEnd = range3.endLineNumber;
      } else if (range3.endLineNumber > currentRangeEnd) {
        currentRangeEnd = range3.endLineNumber;
      }
    }
    result.push(new Range(currentRangeStart, 1, currentRangeEnd, 1));
    return result;
  }
  setHiddenAreas(_ranges) {
    let newRanges = this._reduceRanges(_ranges);
    let oldRanges = this.hiddenAreasIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(Range.compareRangesUsingStarts);
    if (newRanges.length === oldRanges.length) {
      let hasDifference = false;
      for (let i3 = 0; i3 < newRanges.length; i3++) {
        if (!newRanges[i3].equalsRange(oldRanges[i3])) {
          hasDifference = true;
          break;
        }
      }
      if (!hasDifference) {
        return false;
      }
    }
    let newDecorations = [];
    for (const newRange of newRanges) {
      newDecorations.push({
        range: newRange,
        options: ModelDecorationOptions.EMPTY
      });
    }
    this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, newDecorations);
    let hiddenAreas = newRanges;
    let hiddenAreaStart = 1, hiddenAreaEnd = 0;
    let hiddenAreaIdx = -1;
    let nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : this.lines.length + 2;
    let hasVisibleLine = false;
    for (let i3 = 0; i3 < this.lines.length; i3++) {
      let lineNumber = i3 + 1;
      if (lineNumber === nextLineNumberToUpdateHiddenArea) {
        hiddenAreaIdx++;
        hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
        hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
        nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : this.lines.length + 2;
      }
      let lineChanged = false;
      if (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd) {
        if (this.lines[i3].isVisible()) {
          this.lines[i3] = this.lines[i3].setVisible(false);
          lineChanged = true;
        }
      } else {
        hasVisibleLine = true;
        if (!this.lines[i3].isVisible()) {
          this.lines[i3] = this.lines[i3].setVisible(true);
          lineChanged = true;
        }
      }
      if (lineChanged) {
        let newOutputLineCount = this.lines[i3].getViewLineCount();
        this.prefixSumComputer.changeValue(i3, newOutputLineCount);
      }
    }
    if (!hasVisibleLine) {
      this.setHiddenAreas([]);
    }
    return true;
  }
  modelPositionIsVisible(modelLineNumber, _modelColumn) {
    if (modelLineNumber < 1 || modelLineNumber > this.lines.length) {
      return false;
    }
    return this.lines[modelLineNumber - 1].isVisible();
  }
  setTabSize(newTabSize) {
    if (this.tabSize === newTabSize) {
      return false;
    }
    this.tabSize = newTabSize;
    this._constructLines(false, null);
    return true;
  }
  setWrappingSettings(fontInfo, wrappingStrategy, wrappingColumn, wrappingIndent) {
    const equalFontInfo = this.fontInfo.equals(fontInfo);
    const equalWrappingStrategy = this.wrappingStrategy === wrappingStrategy;
    const equalWrappingColumn = this.wrappingColumn === wrappingColumn;
    const equalWrappingIndent = this.wrappingIndent === wrappingIndent;
    if (equalFontInfo && equalWrappingStrategy && equalWrappingColumn && equalWrappingIndent) {
      return false;
    }
    const onlyWrappingColumnChanged = equalFontInfo && equalWrappingStrategy && !equalWrappingColumn && equalWrappingIndent;
    this.fontInfo = fontInfo;
    this.wrappingStrategy = wrappingStrategy;
    this.wrappingColumn = wrappingColumn;
    this.wrappingIndent = wrappingIndent;
    let previousLineBreaks = null;
    if (onlyWrappingColumnChanged) {
      previousLineBreaks = [];
      for (let i3 = 0, len2 = this.lines.length; i3 < len2; i3++) {
        previousLineBreaks[i3] = this.lines[i3].getLineBreakData();
      }
    }
    this._constructLines(false, previousLineBreaks);
    return true;
  }
  createLineBreaksComputer() {
    const lineBreaksComputerFactory = this.wrappingStrategy === "advanced" ? this._domLineBreaksComputerFactory : this._monospaceLineBreaksComputerFactory;
    return lineBreaksComputerFactory.createLineBreaksComputer(this.fontInfo, this.tabSize, this.wrappingColumn, this.wrappingIndent);
  }
  onModelFlushed() {
    this._constructLines(true, null);
  }
  onModelLinesDeleted(versionId, fromLineNumber, toLineNumber) {
    if (versionId <= this._validModelVersionId) {
      return null;
    }
    let outputFromLineNumber = fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1;
    let outputToLineNumber = this.prefixSumComputer.getAccumulatedValue(toLineNumber - 1);
    this.lines.splice(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
    this.prefixSumComputer.removeValues(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
    return new ViewLinesDeletedEvent(outputFromLineNumber, outputToLineNumber);
  }
  onModelLinesInserted(versionId, fromLineNumber, _toLineNumber, lineBreaks) {
    if (versionId <= this._validModelVersionId) {
      return null;
    }
    let hiddenAreas = this.getHiddenAreas();
    let isInHiddenArea = false;
    let testPosition = new Position(fromLineNumber, 1);
    for (const hiddenArea of hiddenAreas) {
      if (hiddenArea.containsPosition(testPosition)) {
        isInHiddenArea = true;
        break;
      }
    }
    let outputFromLineNumber = fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1;
    let totalOutputLineCount = 0;
    let insertLines = [];
    let insertPrefixSumValues = [];
    for (let i3 = 0, len2 = lineBreaks.length; i3 < len2; i3++) {
      let line = createSplitLine(lineBreaks[i3], !isInHiddenArea);
      insertLines.push(line);
      let outputLineCount = line.getViewLineCount();
      totalOutputLineCount += outputLineCount;
      insertPrefixSumValues[i3] = outputLineCount;
    }
    this.lines = this.lines.slice(0, fromLineNumber - 1).concat(insertLines).concat(this.lines.slice(fromLineNumber - 1));
    this.prefixSumComputer.insertValues(fromLineNumber - 1, insertPrefixSumValues);
    return new ViewLinesInsertedEvent(outputFromLineNumber, outputFromLineNumber + totalOutputLineCount - 1);
  }
  onModelLineChanged(versionId, lineNumber, lineBreakData) {
    if (versionId <= this._validModelVersionId) {
      return [false, null, null, null];
    }
    let lineIndex = lineNumber - 1;
    let oldOutputLineCount = this.lines[lineIndex].getViewLineCount();
    let isVisible = this.lines[lineIndex].isVisible();
    let line = createSplitLine(lineBreakData, isVisible);
    this.lines[lineIndex] = line;
    let newOutputLineCount = this.lines[lineIndex].getViewLineCount();
    let lineMappingChanged = false;
    let changeFrom = 0;
    let changeTo = -1;
    let insertFrom = 0;
    let insertTo = -1;
    let deleteFrom = 0;
    let deleteTo = -1;
    if (oldOutputLineCount > newOutputLineCount) {
      changeFrom = lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1;
      changeTo = changeFrom + newOutputLineCount - 1;
      deleteFrom = changeTo + 1;
      deleteTo = deleteFrom + (oldOutputLineCount - newOutputLineCount) - 1;
      lineMappingChanged = true;
    } else if (oldOutputLineCount < newOutputLineCount) {
      changeFrom = lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1;
      changeTo = changeFrom + oldOutputLineCount - 1;
      insertFrom = changeTo + 1;
      insertTo = insertFrom + (newOutputLineCount - oldOutputLineCount) - 1;
      lineMappingChanged = true;
    } else {
      changeFrom = lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1;
      changeTo = changeFrom + newOutputLineCount - 1;
    }
    this.prefixSumComputer.changeValue(lineIndex, newOutputLineCount);
    const viewLinesChangedEvent = changeFrom <= changeTo ? new ViewLinesChangedEvent(changeFrom, changeTo) : null;
    const viewLinesInsertedEvent = insertFrom <= insertTo ? new ViewLinesInsertedEvent(insertFrom, insertTo) : null;
    const viewLinesDeletedEvent = deleteFrom <= deleteTo ? new ViewLinesDeletedEvent(deleteFrom, deleteTo) : null;
    return [lineMappingChanged, viewLinesChangedEvent, viewLinesInsertedEvent, viewLinesDeletedEvent];
  }
  acceptVersionId(versionId) {
    this._validModelVersionId = versionId;
    if (this.lines.length === 1 && !this.lines[0].isVisible()) {
      this.setHiddenAreas([]);
    }
  }
  getViewLineCount() {
    return this.prefixSumComputer.getTotalValue();
  }
  _toValidViewLineNumber(viewLineNumber) {
    if (viewLineNumber < 1) {
      return 1;
    }
    const viewLineCount = this.getViewLineCount();
    if (viewLineNumber > viewLineCount) {
      return viewLineCount;
    }
    return viewLineNumber | 0;
  }
  getActiveIndentGuide(viewLineNumber, minLineNumber, maxLineNumber) {
    viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
    minLineNumber = this._toValidViewLineNumber(minLineNumber);
    maxLineNumber = this._toValidViewLineNumber(maxLineNumber);
    const modelPosition = this.convertViewPositionToModelPosition(viewLineNumber, this.getViewLineMinColumn(viewLineNumber));
    const modelMinPosition = this.convertViewPositionToModelPosition(minLineNumber, this.getViewLineMinColumn(minLineNumber));
    const modelMaxPosition = this.convertViewPositionToModelPosition(maxLineNumber, this.getViewLineMinColumn(maxLineNumber));
    const result = this.model.getActiveIndentGuide(modelPosition.lineNumber, modelMinPosition.lineNumber, modelMaxPosition.lineNumber);
    const viewStartPosition = this.convertModelPositionToViewPosition(result.startLineNumber, 1);
    const viewEndPosition = this.convertModelPositionToViewPosition(result.endLineNumber, this.model.getLineMaxColumn(result.endLineNumber));
    return {
      startLineNumber: viewStartPosition.lineNumber,
      endLineNumber: viewEndPosition.lineNumber,
      indent: result.indent
    };
  }
  getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
    viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
    viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
    const modelStart = this.convertViewPositionToModelPosition(viewStartLineNumber, this.getViewLineMinColumn(viewStartLineNumber));
    const modelEnd = this.convertViewPositionToModelPosition(viewEndLineNumber, this.getViewLineMaxColumn(viewEndLineNumber));
    let result = [];
    let resultRepeatCount = [];
    let resultRepeatOption = [];
    const modelStartLineIndex = modelStart.lineNumber - 1;
    const modelEndLineIndex = modelEnd.lineNumber - 1;
    let reqStart = null;
    for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
      const line = this.lines[modelLineIndex];
      if (line.isVisible()) {
        let viewLineStartIndex = line.getViewLineNumberOfModelPosition(0, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
        let viewLineEndIndex = line.getViewLineNumberOfModelPosition(0, this.model.getLineMaxColumn(modelLineIndex + 1));
        let count = viewLineEndIndex - viewLineStartIndex + 1;
        let option = 0;
        if (count > 1 && line.getViewLineMinColumn(this.model, modelLineIndex + 1, viewLineEndIndex) === 1) {
          option = viewLineStartIndex === 0 ? 1 : 2;
        }
        resultRepeatCount.push(count);
        resultRepeatOption.push(option);
        if (reqStart === null) {
          reqStart = new Position(modelLineIndex + 1, 0);
        }
      } else {
        if (reqStart !== null) {
          result = result.concat(this.model.getLinesIndentGuides(reqStart.lineNumber, modelLineIndex));
          reqStart = null;
        }
      }
    }
    if (reqStart !== null) {
      result = result.concat(this.model.getLinesIndentGuides(reqStart.lineNumber, modelEnd.lineNumber));
      reqStart = null;
    }
    const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
    let viewIndents = new Array(viewLineCount);
    let currIndex = 0;
    for (let i3 = 0, len2 = result.length; i3 < len2; i3++) {
      let value = result[i3];
      let count = Math.min(viewLineCount - currIndex, resultRepeatCount[i3]);
      let option = resultRepeatOption[i3];
      let blockAtIndex;
      if (option === 2) {
        blockAtIndex = 0;
      } else if (option === 1) {
        blockAtIndex = 1;
      } else {
        blockAtIndex = count;
      }
      for (let j = 0; j < count; j++) {
        if (j === blockAtIndex) {
          value = 0;
        }
        viewIndents[currIndex++] = value;
      }
    }
    return viewIndents;
  }
  getViewLineContent(viewLineNumber) {
    viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
    let r3 = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
    let lineIndex = r3.index;
    let remainder = r3.remainder;
    return this.lines[lineIndex].getViewLineContent(this.model, lineIndex + 1, remainder);
  }
  getViewLineLength(viewLineNumber) {
    viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
    let r3 = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
    let lineIndex = r3.index;
    let remainder = r3.remainder;
    return this.lines[lineIndex].getViewLineLength(this.model, lineIndex + 1, remainder);
  }
  getViewLineMinColumn(viewLineNumber) {
    viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
    let r3 = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
    let lineIndex = r3.index;
    let remainder = r3.remainder;
    return this.lines[lineIndex].getViewLineMinColumn(this.model, lineIndex + 1, remainder);
  }
  getViewLineMaxColumn(viewLineNumber) {
    viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
    let r3 = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
    let lineIndex = r3.index;
    let remainder = r3.remainder;
    return this.lines[lineIndex].getViewLineMaxColumn(this.model, lineIndex + 1, remainder);
  }
  getViewLineData(viewLineNumber) {
    viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
    let r3 = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
    let lineIndex = r3.index;
    let remainder = r3.remainder;
    return this.lines[lineIndex].getViewLineData(this.model, lineIndex + 1, remainder);
  }
  getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
    viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
    viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
    let start3 = this.prefixSumComputer.getIndexOf(viewStartLineNumber - 1);
    let viewLineNumber = viewStartLineNumber;
    let startModelLineIndex = start3.index;
    let startRemainder = start3.remainder;
    let result = [];
    for (let modelLineIndex = startModelLineIndex, len2 = this.model.getLineCount(); modelLineIndex < len2; modelLineIndex++) {
      let line = this.lines[modelLineIndex];
      if (!line.isVisible()) {
        continue;
      }
      let fromViewLineIndex = modelLineIndex === startModelLineIndex ? startRemainder : 0;
      let remainingViewLineCount = line.getViewLineCount() - fromViewLineIndex;
      let lastLine = false;
      if (viewLineNumber + remainingViewLineCount > viewEndLineNumber) {
        lastLine = true;
        remainingViewLineCount = viewEndLineNumber - viewLineNumber + 1;
      }
      let toViewLineIndex = fromViewLineIndex + remainingViewLineCount;
      line.getViewLinesData(this.model, modelLineIndex + 1, fromViewLineIndex, toViewLineIndex, viewLineNumber - viewStartLineNumber, needed, result);
      viewLineNumber += remainingViewLineCount;
      if (lastLine) {
        break;
      }
    }
    return result;
  }
  validateViewPosition(viewLineNumber, viewColumn, expectedModelPosition) {
    viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
    let r3 = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
    let lineIndex = r3.index;
    let remainder = r3.remainder;
    let line = this.lines[lineIndex];
    let minColumn = line.getViewLineMinColumn(this.model, lineIndex + 1, remainder);
    let maxColumn = line.getViewLineMaxColumn(this.model, lineIndex + 1, remainder);
    if (viewColumn < minColumn) {
      viewColumn = minColumn;
    }
    if (viewColumn > maxColumn) {
      viewColumn = maxColumn;
    }
    let computedModelColumn = line.getModelColumnOfViewPosition(remainder, viewColumn);
    let computedModelPosition = this.model.validatePosition(new Position(lineIndex + 1, computedModelColumn));
    if (computedModelPosition.equals(expectedModelPosition)) {
      return new Position(viewLineNumber, viewColumn);
    }
    return this.convertModelPositionToViewPosition(expectedModelPosition.lineNumber, expectedModelPosition.column);
  }
  validateViewRange(viewRange, expectedModelRange) {
    const validViewStart = this.validateViewPosition(viewRange.startLineNumber, viewRange.startColumn, expectedModelRange.getStartPosition());
    const validViewEnd = this.validateViewPosition(viewRange.endLineNumber, viewRange.endColumn, expectedModelRange.getEndPosition());
    return new Range(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column);
  }
  convertViewPositionToModelPosition(viewLineNumber, viewColumn) {
    viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
    let r3 = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
    let lineIndex = r3.index;
    let remainder = r3.remainder;
    let inputColumn = this.lines[lineIndex].getModelColumnOfViewPosition(remainder, viewColumn);
    return this.model.validatePosition(new Position(lineIndex + 1, inputColumn));
  }
  convertViewRangeToModelRange(viewRange) {
    const start3 = this.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn);
    const end2 = this.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn);
    return new Range(start3.lineNumber, start3.column, end2.lineNumber, end2.column);
  }
  convertModelPositionToViewPosition(_modelLineNumber, _modelColumn) {
    const validPosition = this.model.validatePosition(new Position(_modelLineNumber, _modelColumn));
    const inputLineNumber = validPosition.lineNumber;
    const inputColumn = validPosition.column;
    let lineIndex = inputLineNumber - 1, lineIndexChanged = false;
    while (lineIndex > 0 && !this.lines[lineIndex].isVisible()) {
      lineIndex--;
      lineIndexChanged = true;
    }
    if (lineIndex === 0 && !this.lines[lineIndex].isVisible()) {
      return new Position(1, 1);
    }
    const deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));
    let r3;
    if (lineIndexChanged) {
      r3 = this.lines[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1));
    } else {
      r3 = this.lines[inputLineNumber - 1].getViewPositionOfModelPosition(deltaLineNumber, inputColumn);
    }
    return r3;
  }
  convertModelRangeToViewRange(modelRange) {
    let start3 = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn);
    let end2 = this.convertModelPositionToViewPosition(modelRange.endLineNumber, modelRange.endColumn);
    if (modelRange.startLineNumber === modelRange.endLineNumber && start3.lineNumber !== end2.lineNumber) {
      if (end2.column === this.getViewLineMinColumn(end2.lineNumber)) {
        return new Range(start3.lineNumber, start3.column, end2.lineNumber - 1, this.getViewLineMaxColumn(end2.lineNumber - 1));
      }
    }
    return new Range(start3.lineNumber, start3.column, end2.lineNumber, end2.column);
  }
  _getViewLineNumberForModelPosition(inputLineNumber, inputColumn) {
    let lineIndex = inputLineNumber - 1;
    if (this.lines[lineIndex].isVisible()) {
      const deltaLineNumber2 = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));
      return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber2, inputColumn);
    }
    while (lineIndex > 0 && !this.lines[lineIndex].isVisible()) {
      lineIndex--;
    }
    if (lineIndex === 0 && !this.lines[lineIndex].isVisible()) {
      return 1;
    }
    const deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));
    return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1));
  }
  getAllOverviewRulerDecorations(ownerId, filterOutValidation, theme) {
    const decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation);
    const result = new OverviewRulerDecorations();
    for (const decoration of decorations) {
      const opts = decoration.options.overviewRuler;
      const lane = opts ? opts.position : 0;
      if (lane === 0) {
        continue;
      }
      const color2 = opts.getColor(theme);
      const viewStartLineNumber = this._getViewLineNumberForModelPosition(decoration.range.startLineNumber, decoration.range.startColumn);
      const viewEndLineNumber = this._getViewLineNumberForModelPosition(decoration.range.endLineNumber, decoration.range.endColumn);
      result.accept(color2, viewStartLineNumber, viewEndLineNumber, lane);
    }
    return result.result;
  }
  getDecorationsInRange(range3, ownerId, filterOutValidation) {
    const modelStart = this.convertViewPositionToModelPosition(range3.startLineNumber, range3.startColumn);
    const modelEnd = this.convertViewPositionToModelPosition(range3.endLineNumber, range3.endColumn);
    if (modelEnd.lineNumber - modelStart.lineNumber <= range3.endLineNumber - range3.startLineNumber) {
      return this.model.getDecorationsInRange(new Range(modelStart.lineNumber, 1, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation);
    }
    let result = [];
    const modelStartLineIndex = modelStart.lineNumber - 1;
    const modelEndLineIndex = modelEnd.lineNumber - 1;
    let reqStart = null;
    for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
      const line = this.lines[modelLineIndex];
      if (line.isVisible()) {
        if (reqStart === null) {
          reqStart = new Position(modelLineIndex + 1, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
        }
      } else {
        if (reqStart !== null) {
          const maxLineColumn = this.model.getLineMaxColumn(modelLineIndex);
          result = result.concat(this.model.getDecorationsInRange(new Range(reqStart.lineNumber, reqStart.column, modelLineIndex, maxLineColumn), ownerId, filterOutValidation));
          reqStart = null;
        }
      }
    }
    if (reqStart !== null) {
      result = result.concat(this.model.getDecorationsInRange(new Range(reqStart.lineNumber, reqStart.column, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation));
      reqStart = null;
    }
    result.sort((a2, b2) => {
      const res = Range.compareRangesUsingStarts(a2.range, b2.range);
      if (res === 0) {
        if (a2.id < b2.id) {
          return -1;
        }
        if (a2.id > b2.id) {
          return 1;
        }
        return 0;
      }
      return res;
    });
    let finalResult = [], finalResultLen = 0;
    let prevDecId = null;
    for (const dec of result) {
      const decId = dec.id;
      if (prevDecId === decId) {
        continue;
      }
      prevDecId = decId;
      finalResult[finalResultLen++] = dec;
    }
    return finalResult;
  }
};
var VisibleIdentitySplitLine = class {
  constructor() {
  }
  isVisible() {
    return true;
  }
  setVisible(isVisible) {
    if (isVisible) {
      return this;
    }
    return InvisibleIdentitySplitLine.INSTANCE;
  }
  getLineBreakData() {
    return null;
  }
  getViewLineCount() {
    return 1;
  }
  getViewLineContent(model, modelLineNumber, _outputLineIndex) {
    return model.getLineContent(modelLineNumber);
  }
  getViewLineLength(model, modelLineNumber, _outputLineIndex) {
    return model.getLineLength(modelLineNumber);
  }
  getViewLineMinColumn(model, modelLineNumber, _outputLineIndex) {
    return model.getLineMinColumn(modelLineNumber);
  }
  getViewLineMaxColumn(model, modelLineNumber, _outputLineIndex) {
    return model.getLineMaxColumn(modelLineNumber);
  }
  getViewLineData(model, modelLineNumber, _outputLineIndex) {
    let lineTokens = model.getLineTokens(modelLineNumber);
    let lineContent = lineTokens.getLineContent();
    return new ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate());
  }
  getViewLinesData(model, modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, globalStartIndex, needed, result) {
    if (!needed[globalStartIndex]) {
      result[globalStartIndex] = null;
      return;
    }
    result[globalStartIndex] = this.getViewLineData(model, modelLineNumber, 0);
  }
  getModelColumnOfViewPosition(_outputLineIndex, outputColumn) {
    return outputColumn;
  }
  getViewPositionOfModelPosition(deltaLineNumber, inputColumn) {
    return new Position(deltaLineNumber, inputColumn);
  }
  getViewLineNumberOfModelPosition(deltaLineNumber, _inputColumn) {
    return deltaLineNumber;
  }
};
VisibleIdentitySplitLine.INSTANCE = new VisibleIdentitySplitLine();
var InvisibleIdentitySplitLine = class {
  constructor() {
  }
  isVisible() {
    return false;
  }
  setVisible(isVisible) {
    if (!isVisible) {
      return this;
    }
    return VisibleIdentitySplitLine.INSTANCE;
  }
  getLineBreakData() {
    return null;
  }
  getViewLineCount() {
    return 0;
  }
  getViewLineContent(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineLength(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineMinColumn(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineMaxColumn(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineData(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLinesData(_model, _modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, _globalStartIndex, _needed, _result) {
    throw new Error("Not supported");
  }
  getModelColumnOfViewPosition(_outputLineIndex, _outputColumn) {
    throw new Error("Not supported");
  }
  getViewPositionOfModelPosition(_deltaLineNumber, _inputColumn) {
    throw new Error("Not supported");
  }
  getViewLineNumberOfModelPosition(_deltaLineNumber, _inputColumn) {
    throw new Error("Not supported");
  }
};
InvisibleIdentitySplitLine.INSTANCE = new InvisibleIdentitySplitLine();
var SplitLine = class {
  constructor(lineBreakData, isVisible) {
    this._lineBreakData = lineBreakData;
    this._isVisible = isVisible;
  }
  isVisible() {
    return this._isVisible;
  }
  setVisible(isVisible) {
    this._isVisible = isVisible;
    return this;
  }
  getLineBreakData() {
    return this._lineBreakData;
  }
  getViewLineCount() {
    if (!this._isVisible) {
      return 0;
    }
    return this._lineBreakData.breakOffsets.length;
  }
  getInputStartOffsetOfOutputLineIndex(outputLineIndex) {
    return LineBreakData.getInputOffsetOfOutputPosition(this._lineBreakData.breakOffsets, outputLineIndex, 0);
  }
  getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex) {
    if (outputLineIndex + 1 === this._lineBreakData.breakOffsets.length) {
      return model.getLineMaxColumn(modelLineNumber) - 1;
    }
    return LineBreakData.getInputOffsetOfOutputPosition(this._lineBreakData.breakOffsets, outputLineIndex + 1, 0);
  }
  getViewLineContent(model, modelLineNumber, outputLineIndex) {
    if (!this._isVisible) {
      throw new Error("Not supported");
    }
    let startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex);
    let endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex);
    let r3 = model.getValueInRange({
      startLineNumber: modelLineNumber,
      startColumn: startOffset + 1,
      endLineNumber: modelLineNumber,
      endColumn: endOffset + 1
    });
    if (outputLineIndex > 0) {
      r3 = spaces(this._lineBreakData.wrappedTextIndentLength) + r3;
    }
    return r3;
  }
  getViewLineLength(model, modelLineNumber, outputLineIndex) {
    if (!this._isVisible) {
      throw new Error("Not supported");
    }
    let startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex);
    let endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex);
    let r3 = endOffset - startOffset;
    if (outputLineIndex > 0) {
      r3 = this._lineBreakData.wrappedTextIndentLength + r3;
    }
    return r3;
  }
  getViewLineMinColumn(_model, _modelLineNumber, outputLineIndex) {
    if (!this._isVisible) {
      throw new Error("Not supported");
    }
    if (outputLineIndex > 0) {
      return this._lineBreakData.wrappedTextIndentLength + 1;
    }
    return 1;
  }
  getViewLineMaxColumn(model, modelLineNumber, outputLineIndex) {
    if (!this._isVisible) {
      throw new Error("Not supported");
    }
    return this.getViewLineContent(model, modelLineNumber, outputLineIndex).length + 1;
  }
  getViewLineData(model, modelLineNumber, outputLineIndex) {
    if (!this._isVisible) {
      throw new Error("Not supported");
    }
    let startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex);
    let endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex);
    let lineContent = model.getValueInRange({
      startLineNumber: modelLineNumber,
      startColumn: startOffset + 1,
      endLineNumber: modelLineNumber,
      endColumn: endOffset + 1
    });
    if (outputLineIndex > 0) {
      lineContent = spaces(this._lineBreakData.wrappedTextIndentLength) + lineContent;
    }
    let minColumn = outputLineIndex > 0 ? this._lineBreakData.wrappedTextIndentLength + 1 : 1;
    let maxColumn = lineContent.length + 1;
    let continuesWithWrappedLine = outputLineIndex + 1 < this.getViewLineCount();
    let deltaStartIndex = 0;
    if (outputLineIndex > 0) {
      deltaStartIndex = this._lineBreakData.wrappedTextIndentLength;
    }
    let lineTokens = model.getLineTokens(modelLineNumber);
    const startVisibleColumn = outputLineIndex === 0 ? 0 : this._lineBreakData.breakOffsetsVisibleColumn[outputLineIndex - 1];
    return new ViewLineData(lineContent, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, lineTokens.sliceAndInflate(startOffset, endOffset, deltaStartIndex));
  }
  getViewLinesData(model, modelLineNumber, fromOuputLineIndex, toOutputLineIndex, globalStartIndex, needed, result) {
    if (!this._isVisible) {
      throw new Error("Not supported");
    }
    for (let outputLineIndex = fromOuputLineIndex; outputLineIndex < toOutputLineIndex; outputLineIndex++) {
      let globalIndex = globalStartIndex + outputLineIndex - fromOuputLineIndex;
      if (!needed[globalIndex]) {
        result[globalIndex] = null;
        continue;
      }
      result[globalIndex] = this.getViewLineData(model, modelLineNumber, outputLineIndex);
    }
  }
  getModelColumnOfViewPosition(outputLineIndex, outputColumn) {
    if (!this._isVisible) {
      throw new Error("Not supported");
    }
    let adjustedColumn = outputColumn - 1;
    if (outputLineIndex > 0) {
      if (adjustedColumn < this._lineBreakData.wrappedTextIndentLength) {
        adjustedColumn = 0;
      } else {
        adjustedColumn -= this._lineBreakData.wrappedTextIndentLength;
      }
    }
    return LineBreakData.getInputOffsetOfOutputPosition(this._lineBreakData.breakOffsets, outputLineIndex, adjustedColumn) + 1;
  }
  getViewPositionOfModelPosition(deltaLineNumber, inputColumn) {
    if (!this._isVisible) {
      throw new Error("Not supported");
    }
    let r3 = LineBreakData.getOutputPositionOfInputOffset(this._lineBreakData.breakOffsets, inputColumn - 1);
    let outputLineIndex = r3.outputLineIndex;
    let outputColumn = r3.outputOffset + 1;
    if (outputLineIndex > 0) {
      outputColumn += this._lineBreakData.wrappedTextIndentLength;
    }
    return new Position(deltaLineNumber + outputLineIndex, outputColumn);
  }
  getViewLineNumberOfModelPosition(deltaLineNumber, inputColumn) {
    if (!this._isVisible) {
      throw new Error("Not supported");
    }
    const r3 = LineBreakData.getOutputPositionOfInputOffset(this._lineBreakData.breakOffsets, inputColumn - 1);
    return deltaLineNumber + r3.outputLineIndex;
  }
};
var _spaces = [""];
function spaces(count) {
  if (count >= _spaces.length) {
    for (let i3 = 1; i3 <= count; i3++) {
      _spaces[i3] = _makeSpaces(i3);
    }
  }
  return _spaces[count];
}
function _makeSpaces(count) {
  return new Array(count + 1).join(" ");
}
function createSplitLine(lineBreakData, isVisible) {
  if (lineBreakData === null) {
    if (isVisible) {
      return VisibleIdentitySplitLine.INSTANCE;
    }
    return InvisibleIdentitySplitLine.INSTANCE;
  } else {
    return new SplitLine(lineBreakData, isVisible);
  }
}
var IdentityCoordinatesConverter = class {
  constructor(lines) {
    this._lines = lines;
  }
  _validPosition(pos) {
    return this._lines.model.validatePosition(pos);
  }
  _validRange(range3) {
    return this._lines.model.validateRange(range3);
  }
  convertViewPositionToModelPosition(viewPosition) {
    return this._validPosition(viewPosition);
  }
  convertViewRangeToModelRange(viewRange) {
    return this._validRange(viewRange);
  }
  validateViewPosition(_viewPosition, expectedModelPosition) {
    return this._validPosition(expectedModelPosition);
  }
  validateViewRange(_viewRange, expectedModelRange) {
    return this._validRange(expectedModelRange);
  }
  convertModelPositionToViewPosition(modelPosition) {
    return this._validPosition(modelPosition);
  }
  convertModelRangeToViewRange(modelRange) {
    return this._validRange(modelRange);
  }
  modelPositionIsVisible(modelPosition) {
    const lineCount = this._lines.model.getLineCount();
    if (modelPosition.lineNumber < 1 || modelPosition.lineNumber > lineCount) {
      return false;
    }
    return true;
  }
};
var IdentityLinesCollection = class {
  constructor(model) {
    this.model = model;
  }
  dispose() {
  }
  createCoordinatesConverter() {
    return new IdentityCoordinatesConverter(this);
  }
  getHiddenAreas() {
    return [];
  }
  setHiddenAreas(_ranges) {
    return false;
  }
  setTabSize(_newTabSize) {
    return false;
  }
  setWrappingSettings(_fontInfo, _wrappingStrategy, _wrappingColumn, _wrappingIndent) {
    return false;
  }
  createLineBreaksComputer() {
    let result = [];
    return {
      addRequest: (lineText, previousLineBreakData) => {
        result.push(null);
      },
      finalize: () => {
        return result;
      }
    };
  }
  onModelFlushed() {
  }
  onModelLinesDeleted(_versionId, fromLineNumber, toLineNumber) {
    return new ViewLinesDeletedEvent(fromLineNumber, toLineNumber);
  }
  onModelLinesInserted(_versionId, fromLineNumber, toLineNumber, lineBreaks) {
    return new ViewLinesInsertedEvent(fromLineNumber, toLineNumber);
  }
  onModelLineChanged(_versionId, lineNumber, lineBreakData) {
    return [false, new ViewLinesChangedEvent(lineNumber, lineNumber), null, null];
  }
  acceptVersionId(_versionId) {
  }
  getViewLineCount() {
    return this.model.getLineCount();
  }
  getActiveIndentGuide(viewLineNumber, _minLineNumber, _maxLineNumber) {
    return {
      startLineNumber: viewLineNumber,
      endLineNumber: viewLineNumber,
      indent: 0
    };
  }
  getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
    const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
    let result = new Array(viewLineCount);
    for (let i3 = 0; i3 < viewLineCount; i3++) {
      result[i3] = 0;
    }
    return result;
  }
  getViewLineContent(viewLineNumber) {
    return this.model.getLineContent(viewLineNumber);
  }
  getViewLineLength(viewLineNumber) {
    return this.model.getLineLength(viewLineNumber);
  }
  getViewLineMinColumn(viewLineNumber) {
    return this.model.getLineMinColumn(viewLineNumber);
  }
  getViewLineMaxColumn(viewLineNumber) {
    return this.model.getLineMaxColumn(viewLineNumber);
  }
  getViewLineData(viewLineNumber) {
    let lineTokens = this.model.getLineTokens(viewLineNumber);
    let lineContent = lineTokens.getLineContent();
    return new ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate());
  }
  getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
    const lineCount = this.model.getLineCount();
    viewStartLineNumber = Math.min(Math.max(1, viewStartLineNumber), lineCount);
    viewEndLineNumber = Math.min(Math.max(1, viewEndLineNumber), lineCount);
    let result = [];
    for (let lineNumber = viewStartLineNumber; lineNumber <= viewEndLineNumber; lineNumber++) {
      let idx = lineNumber - viewStartLineNumber;
      if (!needed[idx]) {
        result[idx] = null;
      }
      result[idx] = this.getViewLineData(lineNumber);
    }
    return result;
  }
  getAllOverviewRulerDecorations(ownerId, filterOutValidation, theme) {
    const decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation);
    const result = new OverviewRulerDecorations();
    for (const decoration of decorations) {
      const opts = decoration.options.overviewRuler;
      const lane = opts ? opts.position : 0;
      if (lane === 0) {
        continue;
      }
      const color2 = opts.getColor(theme);
      const viewStartLineNumber = decoration.range.startLineNumber;
      const viewEndLineNumber = decoration.range.endLineNumber;
      result.accept(color2, viewStartLineNumber, viewEndLineNumber, lane);
    }
    return result.result;
  }
  getDecorationsInRange(range3, ownerId, filterOutValidation) {
    return this.model.getDecorationsInRange(range3, ownerId, filterOutValidation);
  }
};
var OverviewRulerDecorations = class {
  constructor() {
    this.result = Object.create(null);
  }
  accept(color2, startLineNumber, endLineNumber, lane) {
    let prev = this.result[color2];
    if (prev) {
      const prevLane = prev[prev.length - 3];
      const prevEndLineNumber = prev[prev.length - 1];
      if (prevLane === lane && prevEndLineNumber + 1 >= startLineNumber) {
        if (endLineNumber > prevEndLineNumber) {
          prev[prev.length - 1] = endLineNumber;
        }
        return;
      }
      prev.push(lane, startLineNumber, endLineNumber);
    } else {
      this.result[color2] = [lane, startLineNumber, endLineNumber];
    }
  }
};
var ViewModelDecorations = class {
  constructor(editorId, model, configuration, linesCollection, coordinatesConverter) {
    this.editorId = editorId;
    this.model = model;
    this.configuration = configuration;
    this._linesCollection = linesCollection;
    this._coordinatesConverter = coordinatesConverter;
    this._decorationsCache = Object.create(null);
    this._cachedModelDecorationsResolver = null;
    this._cachedModelDecorationsResolverViewRange = null;
  }
  _clearCachedModelDecorationsResolver() {
    this._cachedModelDecorationsResolver = null;
    this._cachedModelDecorationsResolverViewRange = null;
  }
  dispose() {
    this._decorationsCache = Object.create(null);
    this._clearCachedModelDecorationsResolver();
  }
  reset() {
    this._decorationsCache = Object.create(null);
    this._clearCachedModelDecorationsResolver();
  }
  onModelDecorationsChanged() {
    this._decorationsCache = Object.create(null);
    this._clearCachedModelDecorationsResolver();
  }
  onLineMappingChanged() {
    this._decorationsCache = Object.create(null);
    this._clearCachedModelDecorationsResolver();
  }
  _getOrCreateViewModelDecoration(modelDecoration) {
    const id3 = modelDecoration.id;
    let r3 = this._decorationsCache[id3];
    if (!r3) {
      const modelRange = modelDecoration.range;
      const options = modelDecoration.options;
      let viewRange;
      if (options.isWholeLine) {
        const start3 = this._coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.startLineNumber, 1));
        const end2 = this._coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber)));
        viewRange = new Range(start3.lineNumber, start3.column, end2.lineNumber, end2.column);
      } else {
        viewRange = this._coordinatesConverter.convertModelRangeToViewRange(modelRange);
      }
      r3 = new ViewModelDecoration(viewRange, options);
      this._decorationsCache[id3] = r3;
    }
    return r3;
  }
  getDecorationsViewportData(viewRange) {
    let cacheIsValid = this._cachedModelDecorationsResolver !== null;
    cacheIsValid = cacheIsValid && viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange);
    if (!cacheIsValid) {
      this._cachedModelDecorationsResolver = this._getDecorationsViewportData(viewRange);
      this._cachedModelDecorationsResolverViewRange = viewRange;
    }
    return this._cachedModelDecorationsResolver;
  }
  _getDecorationsViewportData(viewportRange) {
    const modelDecorations = this._linesCollection.getDecorationsInRange(viewportRange, this.editorId, filterValidationDecorations(this.configuration.options));
    const startLineNumber = viewportRange.startLineNumber;
    const endLineNumber = viewportRange.endLineNumber;
    let decorationsInViewport = [], decorationsInViewportLen = 0;
    let inlineDecorations = [];
    for (let j = startLineNumber; j <= endLineNumber; j++) {
      inlineDecorations[j - startLineNumber] = [];
    }
    for (let i3 = 0, len2 = modelDecorations.length; i3 < len2; i3++) {
      let modelDecoration = modelDecorations[i3];
      let decorationOptions = modelDecoration.options;
      let viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration);
      let viewRange = viewModelDecoration.range;
      decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration;
      if (decorationOptions.inlineClassName) {
        let inlineDecoration = new InlineDecoration(viewRange, decorationOptions.inlineClassName, decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 : 0);
        let intersectedStartLineNumber = Math.max(startLineNumber, viewRange.startLineNumber);
        let intersectedEndLineNumber = Math.min(endLineNumber, viewRange.endLineNumber);
        for (let j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) {
          inlineDecorations[j - startLineNumber].push(inlineDecoration);
        }
      }
      if (decorationOptions.beforeContentClassName) {
        if (startLineNumber <= viewRange.startLineNumber && viewRange.startLineNumber <= endLineNumber) {
          let inlineDecoration = new InlineDecoration(new Range(viewRange.startLineNumber, viewRange.startColumn, viewRange.startLineNumber, viewRange.startColumn), decorationOptions.beforeContentClassName, 1);
          inlineDecorations[viewRange.startLineNumber - startLineNumber].push(inlineDecoration);
        }
      }
      if (decorationOptions.afterContentClassName) {
        if (startLineNumber <= viewRange.endLineNumber && viewRange.endLineNumber <= endLineNumber) {
          let inlineDecoration = new InlineDecoration(new Range(viewRange.endLineNumber, viewRange.endColumn, viewRange.endLineNumber, viewRange.endColumn), decorationOptions.afterContentClassName, 2);
          inlineDecorations[viewRange.endLineNumber - startLineNumber].push(inlineDecoration);
        }
      }
    }
    return {
      decorations: decorationsInViewport,
      inlineDecorations
    };
  }
};
var ViewModel = class extends Disposable {
  constructor(editorId, configuration, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, scheduleAtNextAnimationFrame2) {
    super();
    this._editorId = editorId;
    this._configuration = configuration;
    this.model = model;
    this._eventDispatcher = new ViewModelEventDispatcher();
    this.onEvent = this._eventDispatcher.onEvent;
    this.cursorConfig = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration);
    this._tokenizeViewportSoon = this._register(new RunOnceScheduler(() => this.tokenizeViewport(), 50));
    this._updateConfigurationViewLineCount = this._register(new RunOnceScheduler(() => this._updateConfigurationViewLineCountNow(), 0));
    this._hasFocus = false;
    this._viewportStartLine = -1;
    this._viewportStartLineTrackedRange = null;
    this._viewportStartLineDelta = 0;
    if (this.model.isTooLargeForTokenization()) {
      this._lines = new IdentityLinesCollection(this.model);
    } else {
      const options = this._configuration.options;
      const fontInfo = options.get(36);
      const wrappingStrategy = options.get(112);
      const wrappingInfo = options.get(118);
      const wrappingIndent = options.get(111);
      this._lines = new SplitLinesCollection(this.model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, this.model.getOptions().tabSize, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent);
    }
    this.coordinatesConverter = this._lines.createCoordinatesConverter();
    this._cursor = this._register(new Cursor(model, this, this.coordinatesConverter, this.cursorConfig));
    this.viewLayout = this._register(new ViewLayout(this._configuration, this.getLineCount(), scheduleAtNextAnimationFrame2));
    this._register(this.viewLayout.onDidScroll((e2) => {
      if (e2.scrollTopChanged) {
        this._tokenizeViewportSoon.schedule();
      }
      this._eventDispatcher.emitSingleViewEvent(new ViewScrollChangedEvent(e2));
      this._eventDispatcher.emitOutgoingEvent(new ScrollChangedEvent(e2.oldScrollWidth, e2.oldScrollLeft, e2.oldScrollHeight, e2.oldScrollTop, e2.scrollWidth, e2.scrollLeft, e2.scrollHeight, e2.scrollTop));
    }));
    this._register(this.viewLayout.onDidContentSizeChange((e2) => {
      this._eventDispatcher.emitOutgoingEvent(e2);
    }));
    this._decorations = new ViewModelDecorations(this._editorId, this.model, this._configuration, this._lines, this.coordinatesConverter);
    this._registerModelEvents();
    this._register(this._configuration.onDidChangeFast((e2) => {
      try {
        const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
        this._onConfigurationChanged(eventsCollector, e2);
      } finally {
        this._eventDispatcher.endEmitViewEvents();
      }
    }));
    this._register(MinimapTokensColorTracker.getInstance().onDidChange(() => {
      this._eventDispatcher.emitSingleViewEvent(new ViewTokensColorsChangedEvent());
    }));
    this._updateConfigurationViewLineCountNow();
  }
  dispose() {
    super.dispose();
    this._decorations.dispose();
    this._lines.dispose();
    this.invalidateMinimapColorCache();
    this._viewportStartLineTrackedRange = this.model._setTrackedRange(this._viewportStartLineTrackedRange, null, 1);
    this._eventDispatcher.dispose();
  }
  addViewEventHandler(eventHandler) {
    this._eventDispatcher.addViewEventHandler(eventHandler);
  }
  removeViewEventHandler(eventHandler) {
    this._eventDispatcher.removeViewEventHandler(eventHandler);
  }
  _updateConfigurationViewLineCountNow() {
    this._configuration.setViewLineCount(this._lines.getViewLineCount());
  }
  tokenizeViewport() {
    const linesViewportData = this.viewLayout.getLinesViewportData();
    const startPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(linesViewportData.startLineNumber, 1));
    const endPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(linesViewportData.endLineNumber, 1));
    this.model.tokenizeViewport(startPosition.lineNumber, endPosition.lineNumber);
  }
  setHasFocus(hasFocus) {
    this._hasFocus = hasFocus;
    this._cursor.setHasFocus(hasFocus);
    this._eventDispatcher.emitSingleViewEvent(new ViewFocusChangedEvent(hasFocus));
    this._eventDispatcher.emitOutgoingEvent(new FocusChangedEvent(!hasFocus, hasFocus));
  }
  onDidColorThemeChange() {
    this._eventDispatcher.emitSingleViewEvent(new ViewThemeChangedEvent());
  }
  _onConfigurationChanged(eventsCollector, e2) {
    let previousViewportStartModelPosition = null;
    if (this._viewportStartLine !== -1) {
      let previousViewportStartViewPosition = new Position(this._viewportStartLine, this.getLineMinColumn(this._viewportStartLine));
      previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition);
    }
    let restorePreviousViewportStart = false;
    const options = this._configuration.options;
    const fontInfo = options.get(36);
    const wrappingStrategy = options.get(112);
    const wrappingInfo = options.get(118);
    const wrappingIndent = options.get(111);
    if (this._lines.setWrappingSettings(fontInfo, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent)) {
      eventsCollector.emitViewEvent(new ViewFlushedEvent());
      eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
      eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
      this._cursor.onLineMappingChanged(eventsCollector);
      this._decorations.onLineMappingChanged();
      this.viewLayout.onFlushed(this.getLineCount());
      if (this.viewLayout.getCurrentScrollTop() !== 0) {
        restorePreviousViewportStart = true;
      }
      this._updateConfigurationViewLineCount.schedule();
    }
    if (e2.hasChanged(72)) {
      this._decorations.reset();
      eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
    }
    eventsCollector.emitViewEvent(new ViewConfigurationChangedEvent(e2));
    this.viewLayout.onConfigurationChanged(e2);
    if (restorePreviousViewportStart && previousViewportStartModelPosition) {
      const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(previousViewportStartModelPosition);
      const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
      this.viewLayout.setScrollPosition({scrollTop: viewPositionTop + this._viewportStartLineDelta}, 1);
    }
    if (CursorConfiguration.shouldRecreate(e2)) {
      this.cursorConfig = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration);
      this._cursor.updateConfiguration(this.cursorConfig);
    }
  }
  _registerModelEvents() {
    this._register(this.model.onDidChangeRawContentFast((e2) => {
      try {
        const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
        let hadOtherModelChange = false;
        let hadModelLineChangeThatChangedLineMapping = false;
        const changes = e2.changes;
        const versionId = e2.versionId;
        const lineBreaksComputer = this._lines.createLineBreaksComputer();
        for (const change of changes) {
          switch (change.changeType) {
            case 4: {
              for (const line of change.detail) {
                lineBreaksComputer.addRequest(line, null);
              }
              break;
            }
            case 2: {
              lineBreaksComputer.addRequest(change.detail, null);
              break;
            }
          }
        }
        const lineBreaks = lineBreaksComputer.finalize();
        let lineBreaksOffset = 0;
        for (const change of changes) {
          switch (change.changeType) {
            case 1: {
              this._lines.onModelFlushed();
              eventsCollector.emitViewEvent(new ViewFlushedEvent());
              this._decorations.reset();
              this.viewLayout.onFlushed(this.getLineCount());
              hadOtherModelChange = true;
              break;
            }
            case 3: {
              const linesDeletedEvent = this._lines.onModelLinesDeleted(versionId, change.fromLineNumber, change.toLineNumber);
              if (linesDeletedEvent !== null) {
                eventsCollector.emitViewEvent(linesDeletedEvent);
                this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
              }
              hadOtherModelChange = true;
              break;
            }
            case 4: {
              const insertedLineBreaks = lineBreaks.slice(lineBreaksOffset, lineBreaksOffset + change.detail.length);
              lineBreaksOffset += change.detail.length;
              const linesInsertedEvent = this._lines.onModelLinesInserted(versionId, change.fromLineNumber, change.toLineNumber, insertedLineBreaks);
              if (linesInsertedEvent !== null) {
                eventsCollector.emitViewEvent(linesInsertedEvent);
                this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
              }
              hadOtherModelChange = true;
              break;
            }
            case 2: {
              const changedLineBreakData = lineBreaks[lineBreaksOffset];
              lineBreaksOffset++;
              const [lineMappingChanged, linesChangedEvent, linesInsertedEvent, linesDeletedEvent] = this._lines.onModelLineChanged(versionId, change.lineNumber, changedLineBreakData);
              hadModelLineChangeThatChangedLineMapping = lineMappingChanged;
              if (linesChangedEvent) {
                eventsCollector.emitViewEvent(linesChangedEvent);
              }
              if (linesInsertedEvent) {
                eventsCollector.emitViewEvent(linesInsertedEvent);
                this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
              }
              if (linesDeletedEvent) {
                eventsCollector.emitViewEvent(linesDeletedEvent);
                this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
              }
              break;
            }
            case 5: {
              break;
            }
          }
        }
        this._lines.acceptVersionId(versionId);
        this.viewLayout.onHeightMaybeChanged();
        if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) {
          eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
          eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
          this._cursor.onLineMappingChanged(eventsCollector);
          this._decorations.onLineMappingChanged();
        }
      } finally {
        this._eventDispatcher.endEmitViewEvents();
      }
      this._viewportStartLine = -1;
      this._configuration.setMaxLineNumber(this.model.getLineCount());
      this._updateConfigurationViewLineCountNow();
      if (!this._hasFocus && this.model.getAttachedEditorCount() >= 2 && this._viewportStartLineTrackedRange) {
        const modelRange = this.model._getTrackedRange(this._viewportStartLineTrackedRange);
        if (modelRange) {
          const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition());
          const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
          this.viewLayout.setScrollPosition({scrollTop: viewPositionTop + this._viewportStartLineDelta}, 1);
        }
      }
      try {
        const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
        this._cursor.onModelContentChanged(eventsCollector, e2);
      } finally {
        this._eventDispatcher.endEmitViewEvents();
      }
    }));
    this._register(this.model.onDidChangeTokens((e2) => {
      let viewRanges = [];
      for (let j = 0, lenJ = e2.ranges.length; j < lenJ; j++) {
        const modelRange = e2.ranges[j];
        const viewStartLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.fromLineNumber, 1)).lineNumber;
        const viewEndLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.toLineNumber, this.model.getLineMaxColumn(modelRange.toLineNumber))).lineNumber;
        viewRanges[j] = {
          fromLineNumber: viewStartLineNumber,
          toLineNumber: viewEndLineNumber
        };
      }
      this._eventDispatcher.emitSingleViewEvent(new ViewTokensChangedEvent(viewRanges));
      if (e2.tokenizationSupportChanged) {
        this._tokenizeViewportSoon.schedule();
      }
    }));
    this._register(this.model.onDidChangeLanguageConfiguration((e2) => {
      this._eventDispatcher.emitSingleViewEvent(new ViewLanguageConfigurationEvent());
      this.cursorConfig = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration);
      this._cursor.updateConfiguration(this.cursorConfig);
    }));
    this._register(this.model.onDidChangeLanguage((e2) => {
      this.cursorConfig = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration);
      this._cursor.updateConfiguration(this.cursorConfig);
    }));
    this._register(this.model.onDidChangeOptions((e2) => {
      if (this._lines.setTabSize(this.model.getOptions().tabSize)) {
        try {
          const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
          eventsCollector.emitViewEvent(new ViewFlushedEvent());
          eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
          eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
          this._cursor.onLineMappingChanged(eventsCollector);
          this._decorations.onLineMappingChanged();
          this.viewLayout.onFlushed(this.getLineCount());
        } finally {
          this._eventDispatcher.endEmitViewEvents();
        }
        this._updateConfigurationViewLineCount.schedule();
      }
      this.cursorConfig = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration);
      this._cursor.updateConfiguration(this.cursorConfig);
    }));
    this._register(this.model.onDidChangeDecorations((e2) => {
      this._decorations.onModelDecorationsChanged();
      this._eventDispatcher.emitSingleViewEvent(new ViewDecorationsChangedEvent(e2));
    }));
  }
  setHiddenAreas(ranges) {
    try {
      const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
      let lineMappingChanged = this._lines.setHiddenAreas(ranges);
      if (lineMappingChanged) {
        eventsCollector.emitViewEvent(new ViewFlushedEvent());
        eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
        eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
        this._cursor.onLineMappingChanged(eventsCollector);
        this._decorations.onLineMappingChanged();
        this.viewLayout.onFlushed(this.getLineCount());
        this.viewLayout.onHeightMaybeChanged();
      }
    } finally {
      this._eventDispatcher.endEmitViewEvents();
    }
    this._updateConfigurationViewLineCount.schedule();
  }
  getVisibleRangesPlusViewportAboveBelow() {
    const layoutInfo = this._configuration.options.get(117);
    const lineHeight = this._configuration.options.get(51);
    const linesAround = Math.max(20, Math.round(layoutInfo.height / lineHeight));
    const partialData = this.viewLayout.getLinesViewportData();
    const startViewLineNumber = Math.max(1, partialData.completelyVisibleStartLineNumber - linesAround);
    const endViewLineNumber = Math.min(this.getLineCount(), partialData.completelyVisibleEndLineNumber + linesAround);
    return this._toModelVisibleRanges(new Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber)));
  }
  getVisibleRanges() {
    const visibleViewRange = this.getCompletelyVisibleViewRange();
    return this._toModelVisibleRanges(visibleViewRange);
  }
  _toModelVisibleRanges(visibleViewRange) {
    const visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
    const hiddenAreas = this._lines.getHiddenAreas();
    if (hiddenAreas.length === 0) {
      return [visibleRange];
    }
    let result = [], resultLen = 0;
    let startLineNumber = visibleRange.startLineNumber;
    let startColumn = visibleRange.startColumn;
    let endLineNumber = visibleRange.endLineNumber;
    let endColumn = visibleRange.endColumn;
    for (let i3 = 0, len2 = hiddenAreas.length; i3 < len2; i3++) {
      const hiddenStartLineNumber = hiddenAreas[i3].startLineNumber;
      const hiddenEndLineNumber = hiddenAreas[i3].endLineNumber;
      if (hiddenEndLineNumber < startLineNumber) {
        continue;
      }
      if (hiddenStartLineNumber > endLineNumber) {
        continue;
      }
      if (startLineNumber < hiddenStartLineNumber) {
        result[resultLen++] = new Range(startLineNumber, startColumn, hiddenStartLineNumber - 1, this.model.getLineMaxColumn(hiddenStartLineNumber - 1));
      }
      startLineNumber = hiddenEndLineNumber + 1;
      startColumn = 1;
    }
    if (startLineNumber < endLineNumber || startLineNumber === endLineNumber && startColumn < endColumn) {
      result[resultLen++] = new Range(startLineNumber, startColumn, endLineNumber, endColumn);
    }
    return result;
  }
  getCompletelyVisibleViewRange() {
    const partialData = this.viewLayout.getLinesViewportData();
    const startViewLineNumber = partialData.completelyVisibleStartLineNumber;
    const endViewLineNumber = partialData.completelyVisibleEndLineNumber;
    return new Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
  }
  getCompletelyVisibleViewRangeAtScrollTop(scrollTop) {
    const partialData = this.viewLayout.getLinesViewportDataAtScrollTop(scrollTop);
    const startViewLineNumber = partialData.completelyVisibleStartLineNumber;
    const endViewLineNumber = partialData.completelyVisibleEndLineNumber;
    return new Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
  }
  saveState() {
    const compatViewState = this.viewLayout.saveState();
    const scrollTop = compatViewState.scrollTop;
    const firstViewLineNumber = this.viewLayout.getLineNumberAtVerticalOffset(scrollTop);
    const firstPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(firstViewLineNumber, this.getLineMinColumn(firstViewLineNumber)));
    const firstPositionDeltaTop = this.viewLayout.getVerticalOffsetForLineNumber(firstViewLineNumber) - scrollTop;
    return {
      scrollLeft: compatViewState.scrollLeft,
      firstPosition,
      firstPositionDeltaTop
    };
  }
  reduceRestoreState(state) {
    if (typeof state.firstPosition === "undefined") {
      return this._reduceRestoreStateCompatibility(state);
    }
    const modelPosition = this.model.validatePosition(state.firstPosition);
    const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
    const scrollTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber) - state.firstPositionDeltaTop;
    return {
      scrollLeft: state.scrollLeft,
      scrollTop
    };
  }
  _reduceRestoreStateCompatibility(state) {
    return {
      scrollLeft: state.scrollLeft,
      scrollTop: state.scrollTopWithoutViewZones
    };
  }
  getTabSize() {
    return this.model.getOptions().tabSize;
  }
  getTextModelOptions() {
    return this.model.getOptions();
  }
  getLineCount() {
    return this._lines.getViewLineCount();
  }
  setViewport(startLineNumber, endLineNumber, centeredLineNumber) {
    this._viewportStartLine = startLineNumber;
    let position2 = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(startLineNumber, this.getLineMinColumn(startLineNumber)));
    this._viewportStartLineTrackedRange = this.model._setTrackedRange(this._viewportStartLineTrackedRange, new Range(position2.lineNumber, position2.column, position2.lineNumber, position2.column), 1);
    const viewportStartLineTop = this.viewLayout.getVerticalOffsetForLineNumber(startLineNumber);
    const scrollTop = this.viewLayout.getCurrentScrollTop();
    this._viewportStartLineDelta = scrollTop - viewportStartLineTop;
  }
  getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
    return this._lines.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber);
  }
  getLinesIndentGuides(startLineNumber, endLineNumber) {
    return this._lines.getViewLinesIndentGuides(startLineNumber, endLineNumber);
  }
  getLineContent(lineNumber) {
    return this._lines.getViewLineContent(lineNumber);
  }
  getLineLength(lineNumber) {
    return this._lines.getViewLineLength(lineNumber);
  }
  getLineMinColumn(lineNumber) {
    return this._lines.getViewLineMinColumn(lineNumber);
  }
  getLineMaxColumn(lineNumber) {
    return this._lines.getViewLineMaxColumn(lineNumber);
  }
  getLineFirstNonWhitespaceColumn(lineNumber) {
    const result = firstNonWhitespaceIndex(this.getLineContent(lineNumber));
    if (result === -1) {
      return 0;
    }
    return result + 1;
  }
  getLineLastNonWhitespaceColumn(lineNumber) {
    const result = lastNonWhitespaceIndex(this.getLineContent(lineNumber));
    if (result === -1) {
      return 0;
    }
    return result + 2;
  }
  getDecorationsInViewport(visibleRange) {
    return this._decorations.getDecorationsViewportData(visibleRange).decorations;
  }
  getViewLineRenderingData(visibleRange, lineNumber) {
    let mightContainRTL = this.model.mightContainRTL();
    let mightContainNonBasicASCII = this.model.mightContainNonBasicASCII();
    let tabSize = this.getTabSize();
    let lineData = this._lines.getViewLineData(lineNumber);
    let allInlineDecorations = this._decorations.getDecorationsViewportData(visibleRange).inlineDecorations;
    let inlineDecorations = allInlineDecorations[lineNumber - visibleRange.startLineNumber];
    return new ViewLineRenderingData(lineData.minColumn, lineData.maxColumn, lineData.content, lineData.continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize, lineData.startVisibleColumn);
  }
  getViewLineData(lineNumber) {
    return this._lines.getViewLineData(lineNumber);
  }
  getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
    let result = this._lines.getViewLinesData(startLineNumber, endLineNumber, needed);
    return new MinimapLinesRenderingData(this.getTabSize(), result);
  }
  getAllOverviewRulerDecorations(theme) {
    return this._lines.getAllOverviewRulerDecorations(this._editorId, filterValidationDecorations(this._configuration.options), theme);
  }
  invalidateOverviewRulerColorCache() {
    const decorations = this.model.getOverviewRulerDecorations();
    for (const decoration of decorations) {
      const opts = decoration.options.overviewRuler;
      if (opts) {
        opts.invalidateCachedColor();
      }
    }
  }
  invalidateMinimapColorCache() {
    const decorations = this.model.getAllDecorations();
    for (const decoration of decorations) {
      const opts = decoration.options.minimap;
      if (opts) {
        opts.invalidateCachedColor();
      }
    }
  }
  getValueInRange(range3, eol) {
    const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range3);
    return this.model.getValueInRange(modelRange, eol);
  }
  getModelLineMaxColumn(modelLineNumber) {
    return this.model.getLineMaxColumn(modelLineNumber);
  }
  validateModelPosition(position2) {
    return this.model.validatePosition(position2);
  }
  validateModelRange(range3) {
    return this.model.validateRange(range3);
  }
  deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt) {
    const modelAnchor = this.coordinatesConverter.convertViewPositionToModelPosition(viewAnchorPosition);
    if (this.model.getEOL().length === 2) {
      if (deltaOffset < 0) {
        deltaOffset -= lineFeedCnt;
      } else {
        deltaOffset += lineFeedCnt;
      }
    }
    const modelAnchorOffset = this.model.getOffsetAt(modelAnchor);
    const resultOffset = modelAnchorOffset + deltaOffset;
    return this.model.getPositionAt(resultOffset);
  }
  getEOL() {
    return this.model.getEOL();
  }
  getPlainTextToCopy(modelRanges, emptySelectionClipboard, forceCRLF) {
    const newLineCharacter = forceCRLF ? "\r\n" : this.model.getEOL();
    modelRanges = modelRanges.slice(0);
    modelRanges.sort(Range.compareRangesUsingStarts);
    let hasEmptyRange = false;
    let hasNonEmptyRange = false;
    for (const range3 of modelRanges) {
      if (range3.isEmpty()) {
        hasEmptyRange = true;
      } else {
        hasNonEmptyRange = true;
      }
    }
    if (!hasNonEmptyRange) {
      if (!emptySelectionClipboard) {
        return "";
      }
      const modelLineNumbers = modelRanges.map((r3) => r3.startLineNumber);
      let result2 = "";
      for (let i3 = 0; i3 < modelLineNumbers.length; i3++) {
        if (i3 > 0 && modelLineNumbers[i3 - 1] === modelLineNumbers[i3]) {
          continue;
        }
        result2 += this.model.getLineContent(modelLineNumbers[i3]) + newLineCharacter;
      }
      return result2;
    }
    if (hasEmptyRange && emptySelectionClipboard) {
      let result2 = [];
      let prevModelLineNumber = 0;
      for (const modelRange of modelRanges) {
        const modelLineNumber = modelRange.startLineNumber;
        if (modelRange.isEmpty()) {
          if (modelLineNumber !== prevModelLineNumber) {
            result2.push(this.model.getLineContent(modelLineNumber));
          }
        } else {
          result2.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 : 0));
        }
        prevModelLineNumber = modelLineNumber;
      }
      return result2.length === 1 ? result2[0] : result2;
    }
    let result = [];
    for (const modelRange of modelRanges) {
      if (!modelRange.isEmpty()) {
        result.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 : 0));
      }
    }
    return result.length === 1 ? result[0] : result;
  }
  getRichTextToCopy(modelRanges, emptySelectionClipboard) {
    const languageId = this.model.getLanguageIdentifier();
    if (languageId.id === 1) {
      return null;
    }
    if (modelRanges.length !== 1) {
      return null;
    }
    let range3 = modelRanges[0];
    if (range3.isEmpty()) {
      if (!emptySelectionClipboard) {
        return null;
      }
      const lineNumber = range3.startLineNumber;
      range3 = new Range(lineNumber, this.model.getLineMinColumn(lineNumber), lineNumber, this.model.getLineMaxColumn(lineNumber));
    }
    const fontInfo = this._configuration.options.get(36);
    const colorMap = this._getColorMap();
    const fontFamily = fontInfo.fontFamily === EDITOR_FONT_DEFAULTS.fontFamily ? fontInfo.fontFamily : `'${fontInfo.fontFamily}', ${EDITOR_FONT_DEFAULTS.fontFamily}`;
    return {
      mode: languageId.language,
      html: `<div style="color: ${colorMap[1]};background-color: ${colorMap[2]};font-family: ${fontFamily};font-weight: ${fontInfo.fontWeight};font-size: ${fontInfo.fontSize}px;line-height: ${fontInfo.lineHeight}px;white-space: pre;">` + this._getHTMLToCopy(range3, colorMap) + "</div>"
    };
  }
  _getHTMLToCopy(modelRange, colorMap) {
    const startLineNumber = modelRange.startLineNumber;
    const startColumn = modelRange.startColumn;
    const endLineNumber = modelRange.endLineNumber;
    const endColumn = modelRange.endColumn;
    const tabSize = this.getTabSize();
    let result = "";
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const lineTokens = this.model.getLineTokens(lineNumber);
      const lineContent = lineTokens.getLineContent();
      const startOffset = lineNumber === startLineNumber ? startColumn - 1 : 0;
      const endOffset = lineNumber === endLineNumber ? endColumn - 1 : lineContent.length;
      if (lineContent === "") {
        result += "<br>";
      } else {
        result += tokenizeLineToHTML(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, isWindows);
      }
    }
    return result;
  }
  _getColorMap() {
    let colorMap = TokenizationRegistry.getColorMap();
    let result = ["#000000"];
    if (colorMap) {
      for (let i3 = 1, len2 = colorMap.length; i3 < len2; i3++) {
        result[i3] = Color.Format.CSS.formatHex(colorMap[i3]);
      }
    }
    return result;
  }
  pushStackElement() {
    this.model.pushStackElement();
  }
  getPrimaryCursorState() {
    return this._cursor.getPrimaryCursorState();
  }
  getLastAddedCursorIndex() {
    return this._cursor.getLastAddedCursorIndex();
  }
  getCursorStates() {
    return this._cursor.getCursorStates();
  }
  setCursorStates(source2, reason, states) {
    this._withViewEventsCollector((eventsCollector) => this._cursor.setStates(eventsCollector, source2, reason, states));
  }
  getCursorColumnSelectData() {
    return this._cursor.getCursorColumnSelectData();
  }
  setCursorColumnSelectData(columnSelectData) {
    this._cursor.setCursorColumnSelectData(columnSelectData);
  }
  getPrevEditOperationType() {
    return this._cursor.getPrevEditOperationType();
  }
  setPrevEditOperationType(type) {
    this._cursor.setPrevEditOperationType(type);
  }
  getSelection() {
    return this._cursor.getSelection();
  }
  getSelections() {
    return this._cursor.getSelections();
  }
  getPosition() {
    return this._cursor.getPrimaryCursorState().modelState.position;
  }
  setSelections(source2, selections) {
    this._withViewEventsCollector((eventsCollector) => this._cursor.setSelections(eventsCollector, source2, selections));
  }
  saveCursorState() {
    return this._cursor.saveState();
  }
  restoreCursorState(states) {
    this._withViewEventsCollector((eventsCollector) => this._cursor.restoreState(eventsCollector, states));
  }
  _executeCursorEdit(callback) {
    if (this._cursor.context.cursorConfig.readOnly) {
      this._eventDispatcher.emitOutgoingEvent(new ReadOnlyEditAttemptEvent());
      return;
    }
    this._withViewEventsCollector(callback);
  }
  executeEdits(source2, edits, cursorStateComputer) {
    this._executeCursorEdit((eventsCollector) => this._cursor.executeEdits(eventsCollector, source2, edits, cursorStateComputer));
  }
  startComposition() {
    this._cursor.setIsDoingComposition(true);
    this._executeCursorEdit((eventsCollector) => this._cursor.startComposition(eventsCollector));
  }
  endComposition(source2) {
    this._cursor.setIsDoingComposition(false);
    this._executeCursorEdit((eventsCollector) => this._cursor.endComposition(eventsCollector, source2));
  }
  type(text, source2) {
    this._executeCursorEdit((eventsCollector) => this._cursor.type(eventsCollector, text, source2));
  }
  replacePreviousChar(text, replaceCharCnt, source2) {
    this._executeCursorEdit((eventsCollector) => this._cursor.replacePreviousChar(eventsCollector, text, replaceCharCnt, source2));
  }
  paste(text, pasteOnNewLine, multicursorText, source2) {
    this._executeCursorEdit((eventsCollector) => this._cursor.paste(eventsCollector, text, pasteOnNewLine, multicursorText, source2));
  }
  cut(source2) {
    this._executeCursorEdit((eventsCollector) => this._cursor.cut(eventsCollector, source2));
  }
  executeCommand(command, source2) {
    this._executeCursorEdit((eventsCollector) => this._cursor.executeCommand(eventsCollector, command, source2));
  }
  executeCommands(commands, source2) {
    this._executeCursorEdit((eventsCollector) => this._cursor.executeCommands(eventsCollector, commands, source2));
  }
  revealPrimaryCursor(source2, revealHorizontal) {
    this._withViewEventsCollector((eventsCollector) => this._cursor.revealPrimary(eventsCollector, source2, revealHorizontal, 0));
  }
  revealTopMostCursor(source2) {
    const viewPosition = this._cursor.getTopMostViewPosition();
    const viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
    this._withViewEventsCollector((eventsCollector) => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source2, viewRange, null, 0, true, 0)));
  }
  revealBottomMostCursor(source2) {
    const viewPosition = this._cursor.getBottomMostViewPosition();
    const viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
    this._withViewEventsCollector((eventsCollector) => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source2, viewRange, null, 0, true, 0)));
  }
  revealRange(source2, revealHorizontal, viewRange, verticalType, scrollType) {
    this._withViewEventsCollector((eventsCollector) => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source2, viewRange, null, verticalType, revealHorizontal, scrollType)));
  }
  getVerticalOffsetForLineNumber(viewLineNumber) {
    return this.viewLayout.getVerticalOffsetForLineNumber(viewLineNumber);
  }
  getScrollTop() {
    return this.viewLayout.getCurrentScrollTop();
  }
  setScrollTop(newScrollTop, scrollType) {
    this.viewLayout.setScrollPosition({scrollTop: newScrollTop}, scrollType);
  }
  setScrollPosition(position2, type) {
    this.viewLayout.setScrollPosition(position2, type);
  }
  deltaScrollNow(deltaScrollLeft, deltaScrollTop) {
    this.viewLayout.deltaScrollNow(deltaScrollLeft, deltaScrollTop);
  }
  changeWhitespace(callback) {
    const hadAChange = this.viewLayout.changeWhitespace(callback);
    if (hadAChange) {
      this._eventDispatcher.emitSingleViewEvent(new ViewZonesChangedEvent());
      this._eventDispatcher.emitOutgoingEvent(new ViewZonesChangedEvent$1());
    }
  }
  setMaxLineWidth(maxLineWidth) {
    this.viewLayout.setMaxLineWidth(maxLineWidth);
  }
  _withViewEventsCollector(callback) {
    try {
      const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
      callback(eventsCollector);
    } finally {
      this._eventDispatcher.endEmitViewEvents();
    }
  }
};
var ServiceCollection = class {
  constructor(...entries) {
    this._entries = new Map();
    for (let [id3, service] of entries) {
      this.set(id3, service);
    }
  }
  set(id3, instanceOrDescriptor) {
    const result = this._entries.get(id3);
    this._entries.set(id3, instanceOrDescriptor);
    return result;
  }
  has(id3) {
    return this._entries.has(id3);
  }
  get(id3) {
    return this._entries.get(id3);
  }
};
var IAccessibilityService = createDecorator("accessibilityService");
var CONTEXT_ACCESSIBILITY_MODE_ENABLED = new RawContextKey("accessibilityModeEnabled", false);
var WrappingCharacterClassifier = class extends CharacterClassifier {
  constructor(BREAK_BEFORE, BREAK_AFTER) {
    super(0);
    for (let i3 = 0; i3 < BREAK_BEFORE.length; i3++) {
      this.set(BREAK_BEFORE.charCodeAt(i3), 1);
    }
    for (let i3 = 0; i3 < BREAK_AFTER.length; i3++) {
      this.set(BREAK_AFTER.charCodeAt(i3), 2);
    }
  }
  get(charCode) {
    if (charCode >= 0 && charCode < 256) {
      return this._asciiMap[charCode];
    } else {
      if (charCode >= 12352 && charCode <= 12543 || charCode >= 13312 && charCode <= 19903 || charCode >= 19968 && charCode <= 40959) {
        return 3;
      }
      return this._map.get(charCode) || this._defaultValue;
    }
  }
};
var arrPool1 = [];
var arrPool2 = [];
var MonospaceLineBreaksComputerFactory = class {
  constructor(breakBeforeChars, breakAfterChars) {
    this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars);
  }
  static create(options) {
    return new MonospaceLineBreaksComputerFactory(options.get(108), options.get(107));
  }
  createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent) {
    tabSize = tabSize | 0;
    wrappingColumn = +wrappingColumn;
    let requests = [];
    let previousBreakingData = [];
    return {
      addRequest: (lineText, previousLineBreakData) => {
        requests.push(lineText);
        previousBreakingData.push(previousLineBreakData);
      },
      finalize: () => {
        const columnsForFullWidthChar = fontInfo.typicalFullwidthCharacterWidth / fontInfo.typicalHalfwidthCharacterWidth;
        let result = [];
        for (let i3 = 0, len2 = requests.length; i3 < len2; i3++) {
          const previousLineBreakData = previousBreakingData[i3];
          if (previousLineBreakData) {
            result[i3] = createLineBreaksFromPreviousLineBreaks(this.classifier, previousLineBreakData, requests[i3], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent);
          } else {
            result[i3] = createLineBreaks(this.classifier, requests[i3], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent);
          }
        }
        arrPool1.length = 0;
        arrPool2.length = 0;
        return result;
      }
    };
  }
};
function createLineBreaksFromPreviousLineBreaks(classifier, previousBreakingData, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
  if (firstLineBreakColumn === -1) {
    return null;
  }
  const len2 = lineText.length;
  if (len2 <= 1) {
    return null;
  }
  const prevBreakingOffsets = previousBreakingData.breakOffsets;
  const prevBreakingOffsetsVisibleColumn = previousBreakingData.breakOffsetsVisibleColumn;
  const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
  const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
  let breakingOffsets = arrPool1;
  let breakingOffsetsVisibleColumn = arrPool2;
  let breakingOffsetsCount = 0;
  let lastBreakingOffset = 0;
  let lastBreakingOffsetVisibleColumn = 0;
  let breakingColumn = firstLineBreakColumn;
  const prevLen = prevBreakingOffsets.length;
  let prevIndex = 0;
  if (prevIndex >= 0) {
    let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
    while (prevIndex + 1 < prevLen) {
      const distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
      if (distance >= bestDistance) {
        break;
      }
      bestDistance = distance;
      prevIndex++;
    }
  }
  while (prevIndex < prevLen) {
    let prevBreakOffset = prevIndex < 0 ? 0 : prevBreakingOffsets[prevIndex];
    let prevBreakOffsetVisibleColumn = prevIndex < 0 ? 0 : prevBreakingOffsetsVisibleColumn[prevIndex];
    if (lastBreakingOffset > prevBreakOffset) {
      prevBreakOffset = lastBreakingOffset;
      prevBreakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn;
    }
    let breakOffset = 0;
    let breakOffsetVisibleColumn = 0;
    let forcedBreakOffset = 0;
    let forcedBreakOffsetVisibleColumn = 0;
    if (prevBreakOffsetVisibleColumn <= breakingColumn) {
      let visibleColumn = prevBreakOffsetVisibleColumn;
      let prevCharCode = prevBreakOffset === 0 ? 0 : lineText.charCodeAt(prevBreakOffset - 1);
      let prevCharCodeClass = prevBreakOffset === 0 ? 0 : classifier.get(prevCharCode);
      let entireLineFits = true;
      for (let i3 = prevBreakOffset; i3 < len2; i3++) {
        const charStartOffset = i3;
        const charCode = lineText.charCodeAt(i3);
        let charCodeClass;
        let charWidth;
        if (isHighSurrogate(charCode)) {
          i3++;
          charCodeClass = 0;
          charWidth = 2;
        } else {
          charCodeClass = classifier.get(charCode);
          charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
        }
        if (charStartOffset > lastBreakingOffset && canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass)) {
          breakOffset = charStartOffset;
          breakOffsetVisibleColumn = visibleColumn;
        }
        visibleColumn += charWidth;
        if (visibleColumn > breakingColumn) {
          if (charStartOffset > lastBreakingOffset) {
            forcedBreakOffset = charStartOffset;
            forcedBreakOffsetVisibleColumn = visibleColumn - charWidth;
          } else {
            forcedBreakOffset = i3 + 1;
            forcedBreakOffsetVisibleColumn = visibleColumn;
          }
          if (visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
            breakOffset = 0;
          }
          entireLineFits = false;
          break;
        }
        prevCharCode = charCode;
        prevCharCodeClass = charCodeClass;
      }
      if (entireLineFits) {
        if (breakingOffsetsCount > 0) {
          breakingOffsets[breakingOffsetsCount] = prevBreakingOffsets[prevBreakingOffsets.length - 1];
          breakingOffsetsVisibleColumn[breakingOffsetsCount] = prevBreakingOffsetsVisibleColumn[prevBreakingOffsets.length - 1];
          breakingOffsetsCount++;
        }
        break;
      }
    }
    if (breakOffset === 0) {
      let visibleColumn = prevBreakOffsetVisibleColumn;
      let charCode = lineText.charCodeAt(prevBreakOffset);
      let charCodeClass = classifier.get(charCode);
      let hitATabCharacter = false;
      for (let i3 = prevBreakOffset - 1; i3 >= lastBreakingOffset; i3--) {
        const charStartOffset = i3 + 1;
        const prevCharCode = lineText.charCodeAt(i3);
        if (prevCharCode === 9) {
          hitATabCharacter = true;
          break;
        }
        let prevCharCodeClass;
        let prevCharWidth;
        if (isLowSurrogate(prevCharCode)) {
          i3--;
          prevCharCodeClass = 0;
          prevCharWidth = 2;
        } else {
          prevCharCodeClass = classifier.get(prevCharCode);
          prevCharWidth = isFullWidthCharacter(prevCharCode) ? columnsForFullWidthChar : 1;
        }
        if (visibleColumn <= breakingColumn) {
          if (forcedBreakOffset === 0) {
            forcedBreakOffset = charStartOffset;
            forcedBreakOffsetVisibleColumn = visibleColumn;
          }
          if (visibleColumn <= breakingColumn - wrappedLineBreakColumn) {
            break;
          }
          if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass)) {
            breakOffset = charStartOffset;
            breakOffsetVisibleColumn = visibleColumn;
            break;
          }
        }
        visibleColumn -= prevCharWidth;
        charCode = prevCharCode;
        charCodeClass = prevCharCodeClass;
      }
      if (breakOffset !== 0) {
        const remainingWidthOfNextLine = wrappedLineBreakColumn - (forcedBreakOffsetVisibleColumn - breakOffsetVisibleColumn);
        if (remainingWidthOfNextLine <= tabSize) {
          const charCodeAtForcedBreakOffset = lineText.charCodeAt(forcedBreakOffset);
          let charWidth;
          if (isHighSurrogate(charCodeAtForcedBreakOffset)) {
            charWidth = 2;
          } else {
            charWidth = computeCharWidth(charCodeAtForcedBreakOffset, forcedBreakOffsetVisibleColumn, tabSize, columnsForFullWidthChar);
          }
          if (remainingWidthOfNextLine - charWidth < 0) {
            breakOffset = 0;
          }
        }
      }
      if (hitATabCharacter) {
        prevIndex--;
        continue;
      }
    }
    if (breakOffset === 0) {
      breakOffset = forcedBreakOffset;
      breakOffsetVisibleColumn = forcedBreakOffsetVisibleColumn;
    }
    lastBreakingOffset = breakOffset;
    breakingOffsets[breakingOffsetsCount] = breakOffset;
    lastBreakingOffsetVisibleColumn = breakOffsetVisibleColumn;
    breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
    breakingOffsetsCount++;
    breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
    while (prevIndex < 0 || prevIndex < prevLen && prevBreakingOffsetsVisibleColumn[prevIndex] < breakOffsetVisibleColumn) {
      prevIndex++;
    }
    let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
    while (prevIndex + 1 < prevLen) {
      const distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
      if (distance >= bestDistance) {
        break;
      }
      bestDistance = distance;
      prevIndex++;
    }
  }
  if (breakingOffsetsCount === 0) {
    return null;
  }
  breakingOffsets.length = breakingOffsetsCount;
  breakingOffsetsVisibleColumn.length = breakingOffsetsCount;
  arrPool1 = previousBreakingData.breakOffsets;
  arrPool2 = previousBreakingData.breakOffsetsVisibleColumn;
  previousBreakingData.breakOffsets = breakingOffsets;
  previousBreakingData.breakOffsetsVisibleColumn = breakingOffsetsVisibleColumn;
  previousBreakingData.wrappedTextIndentLength = wrappedTextIndentLength;
  return previousBreakingData;
}
function createLineBreaks(classifier, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
  if (firstLineBreakColumn === -1) {
    return null;
  }
  const len2 = lineText.length;
  if (len2 <= 1) {
    return null;
  }
  const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
  const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
  let breakingOffsets = [];
  let breakingOffsetsVisibleColumn = [];
  let breakingOffsetsCount = 0;
  let breakOffset = 0;
  let breakOffsetVisibleColumn = 0;
  let breakingColumn = firstLineBreakColumn;
  let prevCharCode = lineText.charCodeAt(0);
  let prevCharCodeClass = classifier.get(prevCharCode);
  let visibleColumn = computeCharWidth(prevCharCode, 0, tabSize, columnsForFullWidthChar);
  let startOffset = 1;
  if (isHighSurrogate(prevCharCode)) {
    visibleColumn += 1;
    prevCharCode = lineText.charCodeAt(1);
    prevCharCodeClass = classifier.get(prevCharCode);
    startOffset++;
  }
  for (let i3 = startOffset; i3 < len2; i3++) {
    const charStartOffset = i3;
    const charCode = lineText.charCodeAt(i3);
    let charCodeClass;
    let charWidth;
    if (isHighSurrogate(charCode)) {
      i3++;
      charCodeClass = 0;
      charWidth = 2;
    } else {
      charCodeClass = classifier.get(charCode);
      charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
    }
    if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass)) {
      breakOffset = charStartOffset;
      breakOffsetVisibleColumn = visibleColumn;
    }
    visibleColumn += charWidth;
    if (visibleColumn > breakingColumn) {
      if (breakOffset === 0 || visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
        breakOffset = charStartOffset;
        breakOffsetVisibleColumn = visibleColumn - charWidth;
      }
      breakingOffsets[breakingOffsetsCount] = breakOffset;
      breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
      breakingOffsetsCount++;
      breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
      breakOffset = 0;
    }
    prevCharCode = charCode;
    prevCharCodeClass = charCodeClass;
  }
  if (breakingOffsetsCount === 0) {
    return null;
  }
  breakingOffsets[breakingOffsetsCount] = len2;
  breakingOffsetsVisibleColumn[breakingOffsetsCount] = visibleColumn;
  return new LineBreakData(breakingOffsets, breakingOffsetsVisibleColumn, wrappedTextIndentLength);
}
function computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar) {
  if (charCode === 9) {
    return tabSize - visibleColumn % tabSize;
  }
  if (isFullWidthCharacter(charCode)) {
    return columnsForFullWidthChar;
  }
  return 1;
}
function tabCharacterWidth(visibleColumn, tabSize) {
  return tabSize - visibleColumn % tabSize;
}
function canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass) {
  return charCode !== 32 && (prevCharCodeClass === 2 || prevCharCodeClass === 3 && charCodeClass !== 2 || charCodeClass === 1 || charCodeClass === 3 && prevCharCodeClass !== 1);
}
function computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
  let wrappedTextIndentLength = 0;
  if (wrappingIndent !== 0) {
    const firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineText);
    if (firstNonWhitespaceIndex$1 !== -1) {
      for (let i3 = 0; i3 < firstNonWhitespaceIndex$1; i3++) {
        const charWidth = lineText.charCodeAt(i3) === 9 ? tabCharacterWidth(wrappedTextIndentLength, tabSize) : 1;
        wrappedTextIndentLength += charWidth;
      }
      const numberOfAdditionalTabs = wrappingIndent === 3 ? 2 : wrappingIndent === 2 ? 1 : 0;
      for (let i3 = 0; i3 < numberOfAdditionalTabs; i3++) {
        const charWidth = tabCharacterWidth(wrappedTextIndentLength, tabSize);
        wrappedTextIndentLength += charWidth;
      }
      if (wrappedTextIndentLength + columnsForFullWidthChar > firstLineBreakColumn) {
        wrappedTextIndentLength = 0;
      }
    }
  }
  return wrappedTextIndentLength;
}
var DOMLineBreaksComputerFactory = class {
  static create() {
    return new DOMLineBreaksComputerFactory();
  }
  constructor() {
  }
  createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent) {
    tabSize = tabSize | 0;
    wrappingColumn = +wrappingColumn;
    let requests = [];
    return {
      addRequest: (lineText, previousLineBreakData) => {
        requests.push(lineText);
      },
      finalize: () => {
        return createLineBreaks$1(requests, fontInfo, tabSize, wrappingColumn, wrappingIndent);
      }
    };
  }
};
function createLineBreaks$1(requests, fontInfo, tabSize, firstLineBreakColumn, wrappingIndent) {
  if (firstLineBreakColumn === -1) {
    const result2 = [];
    for (let i3 = 0, len2 = requests.length; i3 < len2; i3++) {
      result2[i3] = null;
    }
    return result2;
  }
  const overallWidth = Math.round(firstLineBreakColumn * fontInfo.typicalHalfwidthCharacterWidth);
  if (wrappingIndent === 2 || wrappingIndent === 3) {
    wrappingIndent = 1;
  }
  const containerDomNode = document.createElement("div");
  Configuration$1.applyFontInfoSlow(containerDomNode, fontInfo);
  const sb2 = createStringBuilder(1e4);
  const firstNonWhitespaceIndices = [];
  const wrappedTextIndentLengths = [];
  const renderLineContents = [];
  const allCharOffsets = [];
  const allVisibleColumns = [];
  for (let i3 = 0; i3 < requests.length; i3++) {
    const lineContent = requests[i3];
    let firstNonWhitespaceIndex$1 = 0;
    let wrappedTextIndentLength = 0;
    let width2 = overallWidth;
    if (wrappingIndent !== 0) {
      firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
      if (firstNonWhitespaceIndex$1 === -1) {
        firstNonWhitespaceIndex$1 = 0;
      } else {
        for (let i4 = 0; i4 < firstNonWhitespaceIndex$1; i4++) {
          const charWidth = lineContent.charCodeAt(i4) === 9 ? tabSize - wrappedTextIndentLength % tabSize : 1;
          wrappedTextIndentLength += charWidth;
        }
        const indentWidth = Math.ceil(fontInfo.spaceWidth * wrappedTextIndentLength);
        if (indentWidth + fontInfo.typicalFullwidthCharacterWidth > overallWidth) {
          firstNonWhitespaceIndex$1 = 0;
          wrappedTextIndentLength = 0;
        } else {
          width2 = overallWidth - indentWidth;
        }
      }
    }
    const renderLineContent = lineContent.substr(firstNonWhitespaceIndex$1);
    const tmp = renderLine(renderLineContent, wrappedTextIndentLength, tabSize, width2, sb2);
    firstNonWhitespaceIndices[i3] = firstNonWhitespaceIndex$1;
    wrappedTextIndentLengths[i3] = wrappedTextIndentLength;
    renderLineContents[i3] = renderLineContent;
    allCharOffsets[i3] = tmp[0];
    allVisibleColumns[i3] = tmp[1];
  }
  containerDomNode.innerHTML = sb2.build();
  containerDomNode.style.position = "absolute";
  containerDomNode.style.top = "10000";
  containerDomNode.style.wordWrap = "break-word";
  document.body.appendChild(containerDomNode);
  let range3 = document.createRange();
  const lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0);
  let result = [];
  for (let i3 = 0; i3 < requests.length; i3++) {
    const lineDomNode = lineDomNodes[i3];
    const breakOffsets = readLineBreaks(range3, lineDomNode, renderLineContents[i3], allCharOffsets[i3]);
    if (breakOffsets === null) {
      result[i3] = null;
      continue;
    }
    const firstNonWhitespaceIndex2 = firstNonWhitespaceIndices[i3];
    const wrappedTextIndentLength = wrappedTextIndentLengths[i3];
    const visibleColumns = allVisibleColumns[i3];
    const breakOffsetsVisibleColumn = [];
    for (let j = 0, len2 = breakOffsets.length; j < len2; j++) {
      breakOffsetsVisibleColumn[j] = visibleColumns[breakOffsets[j]];
    }
    if (firstNonWhitespaceIndex2 !== 0) {
      for (let j = 0, len2 = breakOffsets.length; j < len2; j++) {
        breakOffsets[j] += firstNonWhitespaceIndex2;
      }
    }
    result[i3] = new LineBreakData(breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength);
  }
  document.body.removeChild(containerDomNode);
  return result;
}
function renderLine(lineContent, initialVisibleColumn, tabSize, width2, sb2) {
  sb2.appendASCIIString('<div style="width:');
  sb2.appendASCIIString(String(width2));
  sb2.appendASCIIString('px;">');
  const len2 = lineContent.length;
  let visibleColumn = initialVisibleColumn;
  let charOffset = 0;
  let charOffsets = [];
  let visibleColumns = [];
  let nextCharCode = 0 < len2 ? lineContent.charCodeAt(0) : 0;
  sb2.appendASCIIString("<span>");
  for (let charIndex = 0; charIndex < len2; charIndex++) {
    if (charIndex !== 0 && charIndex % 16384 === 0) {
      sb2.appendASCIIString("</span><span>");
    }
    charOffsets[charIndex] = charOffset;
    visibleColumns[charIndex] = visibleColumn;
    const charCode = nextCharCode;
    nextCharCode = charIndex + 1 < len2 ? lineContent.charCodeAt(charIndex + 1) : 0;
    let producedCharacters = 1;
    let charWidth = 1;
    switch (charCode) {
      case 9:
        producedCharacters = tabSize - visibleColumn % tabSize;
        charWidth = producedCharacters;
        for (let space = 1; space <= producedCharacters; space++) {
          if (space < producedCharacters) {
            sb2.write1(160);
          } else {
            sb2.appendASCII(32);
          }
        }
        break;
      case 32:
        if (nextCharCode === 32) {
          sb2.write1(160);
        } else {
          sb2.appendASCII(32);
        }
        break;
      case 60:
        sb2.appendASCIIString("&lt;");
        break;
      case 62:
        sb2.appendASCIIString("&gt;");
        break;
      case 38:
        sb2.appendASCIIString("&amp;");
        break;
      case 0:
        sb2.appendASCIIString("&#00;");
        break;
      case 65279:
      case 8232:
      case 8233:
      case 133:
        sb2.write1(65533);
        break;
      default:
        if (isFullWidthCharacter(charCode)) {
          charWidth++;
        }
        sb2.write1(charCode);
    }
    charOffset += producedCharacters;
    visibleColumn += charWidth;
  }
  sb2.appendASCIIString("</span>");
  charOffsets[lineContent.length] = charOffset;
  visibleColumns[lineContent.length] = visibleColumn;
  sb2.appendASCIIString("</div>");
  return [charOffsets, visibleColumns];
}
function readLineBreaks(range3, lineDomNode, lineContent, charOffsets) {
  if (lineContent.length <= 1) {
    return null;
  }
  const spans = Array.prototype.slice.call(lineDomNode.children, 0);
  const breakOffsets = [];
  try {
    discoverBreaks(range3, spans, charOffsets, 0, null, lineContent.length - 1, null, breakOffsets);
  } catch (err) {
    console.log(err);
    return null;
  }
  if (breakOffsets.length === 0) {
    return null;
  }
  breakOffsets.push(lineContent.length);
  return breakOffsets;
}
function discoverBreaks(range3, spans, charOffsets, low, lowRects, high, highRects, result) {
  if (low === high) {
    return;
  }
  lowRects = lowRects || readClientRect(range3, spans, charOffsets[low], charOffsets[low + 1]);
  highRects = highRects || readClientRect(range3, spans, charOffsets[high], charOffsets[high + 1]);
  if (Math.abs(lowRects[0].top - highRects[0].top) <= 0.1) {
    return;
  }
  if (low + 1 === high) {
    result.push(high);
    return;
  }
  const mid = low + (high - low) / 2 | 0;
  const midRects = readClientRect(range3, spans, charOffsets[mid], charOffsets[mid + 1]);
  discoverBreaks(range3, spans, charOffsets, low, lowRects, mid, midRects, result);
  discoverBreaks(range3, spans, charOffsets, mid, midRects, high, highRects, result);
}
function readClientRect(range3, spans, startOffset, endOffset) {
  range3.setStart(spans[startOffset / 16384 | 0].firstChild, startOffset % 16384);
  range3.setEnd(spans[endOffset / 16384 | 0].firstChild, endOffset % 16384);
  return range3.getClientRects();
}
var __decorate$5 = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$4 = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var EDITOR_ID = 0;
var ModelData = class {
  constructor(model, viewModel, view, hasRealView, listenersToRemove) {
    this.model = model;
    this.viewModel = viewModel;
    this.view = view;
    this.hasRealView = hasRealView;
    this.listenersToRemove = listenersToRemove;
  }
  dispose() {
    dispose(this.listenersToRemove);
    this.model.onBeforeDetached();
    if (this.hasRealView) {
      this.view.dispose();
    }
    this.viewModel.dispose();
  }
};
var CodeEditorWidget = class CodeEditorWidget2 extends Disposable {
  constructor(domElement, options, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService) {
    super();
    this._onDidDispose = this._register(new Emitter());
    this.onDidDispose = this._onDidDispose.event;
    this._onDidChangeModelContent = this._register(new Emitter());
    this.onDidChangeModelContent = this._onDidChangeModelContent.event;
    this._onDidChangeModelLanguage = this._register(new Emitter());
    this.onDidChangeModelLanguage = this._onDidChangeModelLanguage.event;
    this._onDidChangeModelLanguageConfiguration = this._register(new Emitter());
    this.onDidChangeModelLanguageConfiguration = this._onDidChangeModelLanguageConfiguration.event;
    this._onDidChangeModelOptions = this._register(new Emitter());
    this.onDidChangeModelOptions = this._onDidChangeModelOptions.event;
    this._onDidChangeModelDecorations = this._register(new Emitter());
    this.onDidChangeModelDecorations = this._onDidChangeModelDecorations.event;
    this._onDidChangeConfiguration = this._register(new Emitter());
    this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
    this._onDidChangeModel = this._register(new Emitter());
    this.onDidChangeModel = this._onDidChangeModel.event;
    this._onDidChangeCursorPosition = this._register(new Emitter());
    this.onDidChangeCursorPosition = this._onDidChangeCursorPosition.event;
    this._onDidChangeCursorSelection = this._register(new Emitter());
    this.onDidChangeCursorSelection = this._onDidChangeCursorSelection.event;
    this._onDidAttemptReadOnlyEdit = this._register(new Emitter());
    this.onDidAttemptReadOnlyEdit = this._onDidAttemptReadOnlyEdit.event;
    this._onDidLayoutChange = this._register(new Emitter());
    this.onDidLayoutChange = this._onDidLayoutChange.event;
    this._editorTextFocus = this._register(new BooleanEventEmitter());
    this.onDidFocusEditorText = this._editorTextFocus.onDidChangeToTrue;
    this.onDidBlurEditorText = this._editorTextFocus.onDidChangeToFalse;
    this._editorWidgetFocus = this._register(new BooleanEventEmitter());
    this.onDidFocusEditorWidget = this._editorWidgetFocus.onDidChangeToTrue;
    this.onDidBlurEditorWidget = this._editorWidgetFocus.onDidChangeToFalse;
    this._onWillType = this._register(new Emitter());
    this.onWillType = this._onWillType.event;
    this._onDidType = this._register(new Emitter());
    this.onDidType = this._onDidType.event;
    this._onDidCompositionStart = this._register(new Emitter());
    this.onDidCompositionStart = this._onDidCompositionStart.event;
    this._onDidCompositionEnd = this._register(new Emitter());
    this.onDidCompositionEnd = this._onDidCompositionEnd.event;
    this._onDidPaste = this._register(new Emitter());
    this.onDidPaste = this._onDidPaste.event;
    this._onMouseUp = this._register(new Emitter());
    this.onMouseUp = this._onMouseUp.event;
    this._onMouseDown = this._register(new Emitter());
    this.onMouseDown = this._onMouseDown.event;
    this._onMouseDrag = this._register(new Emitter());
    this.onMouseDrag = this._onMouseDrag.event;
    this._onMouseDrop = this._register(new Emitter());
    this.onMouseDrop = this._onMouseDrop.event;
    this._onContextMenu = this._register(new Emitter());
    this.onContextMenu = this._onContextMenu.event;
    this._onMouseMove = this._register(new Emitter());
    this.onMouseMove = this._onMouseMove.event;
    this._onMouseLeave = this._register(new Emitter());
    this.onMouseLeave = this._onMouseLeave.event;
    this._onMouseWheel = this._register(new Emitter());
    this.onMouseWheel = this._onMouseWheel.event;
    this._onKeyUp = this._register(new Emitter());
    this.onKeyUp = this._onKeyUp.event;
    this._onKeyDown = this._register(new Emitter());
    this.onKeyDown = this._onKeyDown.event;
    this._onDidContentSizeChange = this._register(new Emitter());
    this.onDidContentSizeChange = this._onDidContentSizeChange.event;
    this._onDidScrollChange = this._register(new Emitter());
    this.onDidScrollChange = this._onDidScrollChange.event;
    this._onDidChangeViewZones = this._register(new Emitter());
    this.onDidChangeViewZones = this._onDidChangeViewZones.event;
    options = options || {};
    this._domElement = domElement;
    this._overflowWidgetsDomNode = options.overflowWidgetsDomNode;
    this._id = ++EDITOR_ID;
    this._decorationTypeKeysToIds = {};
    this._decorationTypeSubtypes = {};
    this.isSimpleWidget = codeEditorWidgetOptions.isSimpleWidget || false;
    this._telemetryData = codeEditorWidgetOptions.telemetryData;
    this._configuration = this._register(this._createConfiguration(options, accessibilityService));
    this._register(this._configuration.onDidChange((e2) => {
      this._onDidChangeConfiguration.fire(e2);
      const options2 = this._configuration.options;
      if (e2.hasChanged(117)) {
        const layoutInfo = options2.get(117);
        this._onDidLayoutChange.fire(layoutInfo);
      }
    }));
    this._contextKeyService = this._register(contextKeyService.createScoped(this._domElement));
    this._notificationService = notificationService;
    this._codeEditorService = codeEditorService;
    this._commandService = commandService;
    this._themeService = themeService;
    this._register(new EditorContextKeysManager(this, this._contextKeyService));
    this._register(new EditorModeContext(this, this._contextKeyService));
    this._instantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService]));
    this._modelData = null;
    this._contributions = {};
    this._actions = {};
    this._focusTracker = new CodeEditorWidgetFocusTracker(domElement);
    this._focusTracker.onChange(() => {
      this._editorWidgetFocus.setValue(this._focusTracker.hasFocus());
    });
    this._contentWidgets = {};
    this._overlayWidgets = {};
    let contributions;
    if (Array.isArray(codeEditorWidgetOptions.contributions)) {
      contributions = codeEditorWidgetOptions.contributions;
    } else {
      contributions = EditorExtensionsRegistry.getEditorContributions();
    }
    for (const desc of contributions) {
      try {
        const contribution = this._instantiationService.createInstance(desc.ctor, this);
        this._contributions[desc.id] = contribution;
      } catch (err) {
        onUnexpectedError(err);
      }
    }
    EditorExtensionsRegistry.getEditorActions().forEach((action) => {
      const internalAction = new InternalEditorAction(action.id, action.label, action.alias, withNullAsUndefined(action.precondition), () => {
        return this._instantiationService.invokeFunction((accessor) => {
          return Promise.resolve(action.runEditorCommand(accessor, this, null));
        });
      }, this._contextKeyService);
      this._actions[internalAction.id] = internalAction;
    });
    this._codeEditorService.addCodeEditor(this);
  }
  _createConfiguration(options, accessibilityService) {
    return new Configuration$1(this.isSimpleWidget, options, this._domElement, accessibilityService);
  }
  getId() {
    return this.getEditorType() + ":" + this._id;
  }
  getEditorType() {
    return EditorType.ICodeEditor;
  }
  dispose() {
    this._codeEditorService.removeCodeEditor(this);
    this._focusTracker.dispose();
    const keys2 = Object.keys(this._contributions);
    for (let i3 = 0, len2 = keys2.length; i3 < len2; i3++) {
      const contributionId = keys2[i3];
      this._contributions[contributionId].dispose();
    }
    this._removeDecorationTypes();
    this._postDetachModelCleanup(this._detachModel());
    this._onDidDispose.fire();
    super.dispose();
  }
  invokeWithinContext(fn) {
    return this._instantiationService.invokeFunction(fn);
  }
  updateOptions(newOptions) {
    this._configuration.updateOptions(newOptions);
  }
  getOptions() {
    return this._configuration.options;
  }
  getOption(id3) {
    return this._configuration.options.get(id3);
  }
  getRawOptions() {
    return this._configuration.getRawOptions();
  }
  getOverflowWidgetsDomNode() {
    return this._overflowWidgetsDomNode;
  }
  getConfiguredWordAtPosition(position2) {
    if (!this._modelData) {
      return null;
    }
    return WordOperations.getWordAtPosition(this._modelData.model, this._configuration.options.get(105), position2);
  }
  getValue(options = null) {
    if (!this._modelData) {
      return "";
    }
    const preserveBOM = options && options.preserveBOM ? true : false;
    let eolPreference = 0;
    if (options && options.lineEnding && options.lineEnding === "\n") {
      eolPreference = 1;
    } else if (options && options.lineEnding && options.lineEnding === "\r\n") {
      eolPreference = 2;
    }
    return this._modelData.model.getValue(eolPreference, preserveBOM);
  }
  setValue(newValue) {
    if (!this._modelData) {
      return;
    }
    this._modelData.model.setValue(newValue);
  }
  getModel() {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.model;
  }
  setModel(_model = null) {
    const model = _model;
    if (this._modelData === null && model === null) {
      return;
    }
    if (this._modelData && this._modelData.model === model) {
      return;
    }
    const hasTextFocus = this.hasTextFocus();
    const detachedModel = this._detachModel();
    this._attachModel(model);
    if (hasTextFocus && this.hasModel()) {
      this.focus();
    }
    const e2 = {
      oldModelUrl: detachedModel ? detachedModel.uri : null,
      newModelUrl: model ? model.uri : null
    };
    this._removeDecorationTypes();
    this._onDidChangeModel.fire(e2);
    this._postDetachModelCleanup(detachedModel);
  }
  _removeDecorationTypes() {
    this._decorationTypeKeysToIds = {};
    if (this._decorationTypeSubtypes) {
      for (let decorationType in this._decorationTypeSubtypes) {
        const subTypes = this._decorationTypeSubtypes[decorationType];
        for (let subType in subTypes) {
          this._removeDecorationType(decorationType + "-" + subType);
        }
      }
      this._decorationTypeSubtypes = {};
    }
  }
  getVisibleRanges() {
    if (!this._modelData) {
      return [];
    }
    return this._modelData.viewModel.getVisibleRanges();
  }
  getVisibleRangesPlusViewportAboveBelow() {
    if (!this._modelData) {
      return [];
    }
    return this._modelData.viewModel.getVisibleRangesPlusViewportAboveBelow();
  }
  getWhitespaces() {
    if (!this._modelData) {
      return [];
    }
    return this._modelData.viewModel.viewLayout.getWhitespaces();
  }
  static _getVerticalOffsetForPosition(modelData, modelLineNumber, modelColumn) {
    const modelPosition = modelData.model.validatePosition({
      lineNumber: modelLineNumber,
      column: modelColumn
    });
    const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
    return modelData.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
  }
  getTopForLineNumber(lineNumber) {
    if (!this._modelData) {
      return -1;
    }
    return CodeEditorWidget2._getVerticalOffsetForPosition(this._modelData, lineNumber, 1);
  }
  getTopForPosition(lineNumber, column) {
    if (!this._modelData) {
      return -1;
    }
    return CodeEditorWidget2._getVerticalOffsetForPosition(this._modelData, lineNumber, column);
  }
  setHiddenAreas(ranges) {
    if (this._modelData) {
      this._modelData.viewModel.setHiddenAreas(ranges.map((r3) => Range.lift(r3)));
    }
  }
  getVisibleColumnFromPosition(rawPosition) {
    if (!this._modelData) {
      return rawPosition.column;
    }
    const position2 = this._modelData.model.validatePosition(rawPosition);
    const tabSize = this._modelData.model.getOptions().tabSize;
    return CursorColumns.visibleColumnFromColumn(this._modelData.model.getLineContent(position2.lineNumber), position2.column, tabSize) + 1;
  }
  getPosition() {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.viewModel.getPosition();
  }
  setPosition(position2) {
    if (!this._modelData) {
      return;
    }
    if (!Position.isIPosition(position2)) {
      throw new Error("Invalid arguments");
    }
    this._modelData.viewModel.setSelections("api", [{
      selectionStartLineNumber: position2.lineNumber,
      selectionStartColumn: position2.column,
      positionLineNumber: position2.lineNumber,
      positionColumn: position2.column
    }]);
  }
  _sendRevealRange(modelRange, verticalType, revealHorizontal, scrollType) {
    if (!this._modelData) {
      return;
    }
    if (!Range.isIRange(modelRange)) {
      throw new Error("Invalid arguments");
    }
    const validatedModelRange = this._modelData.model.validateRange(modelRange);
    const viewRange = this._modelData.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange);
    this._modelData.viewModel.revealRange("api", revealHorizontal, viewRange, verticalType, scrollType);
  }
  revealLine(lineNumber, scrollType = 0) {
    this._revealLine(lineNumber, 0, scrollType);
  }
  revealLineInCenter(lineNumber, scrollType = 0) {
    this._revealLine(lineNumber, 1, scrollType);
  }
  revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0) {
    this._revealLine(lineNumber, 2, scrollType);
  }
  revealLineNearTop(lineNumber, scrollType = 0) {
    this._revealLine(lineNumber, 5, scrollType);
  }
  _revealLine(lineNumber, revealType, scrollType) {
    if (typeof lineNumber !== "number") {
      throw new Error("Invalid arguments");
    }
    this._sendRevealRange(new Range(lineNumber, 1, lineNumber, 1), revealType, false, scrollType);
  }
  revealPosition(position2, scrollType = 0) {
    this._revealPosition(position2, 0, true, scrollType);
  }
  revealPositionInCenter(position2, scrollType = 0) {
    this._revealPosition(position2, 1, true, scrollType);
  }
  revealPositionInCenterIfOutsideViewport(position2, scrollType = 0) {
    this._revealPosition(position2, 2, true, scrollType);
  }
  revealPositionNearTop(position2, scrollType = 0) {
    this._revealPosition(position2, 5, true, scrollType);
  }
  _revealPosition(position2, verticalType, revealHorizontal, scrollType) {
    if (!Position.isIPosition(position2)) {
      throw new Error("Invalid arguments");
    }
    this._sendRevealRange(new Range(position2.lineNumber, position2.column, position2.lineNumber, position2.column), verticalType, revealHorizontal, scrollType);
  }
  getSelection() {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.viewModel.getSelection();
  }
  getSelections() {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.viewModel.getSelections();
  }
  setSelection(something) {
    const isSelection = Selection.isISelection(something);
    const isRange = Range.isIRange(something);
    if (!isSelection && !isRange) {
      throw new Error("Invalid arguments");
    }
    if (isSelection) {
      this._setSelectionImpl(something);
    } else if (isRange) {
      const selection2 = {
        selectionStartLineNumber: something.startLineNumber,
        selectionStartColumn: something.startColumn,
        positionLineNumber: something.endLineNumber,
        positionColumn: something.endColumn
      };
      this._setSelectionImpl(selection2);
    }
  }
  _setSelectionImpl(sel) {
    if (!this._modelData) {
      return;
    }
    const selection2 = new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
    this._modelData.viewModel.setSelections("api", [selection2]);
  }
  revealLines(startLineNumber, endLineNumber, scrollType = 0) {
    this._revealLines(startLineNumber, endLineNumber, 0, scrollType);
  }
  revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0) {
    this._revealLines(startLineNumber, endLineNumber, 1, scrollType);
  }
  revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0) {
    this._revealLines(startLineNumber, endLineNumber, 2, scrollType);
  }
  revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0) {
    this._revealLines(startLineNumber, endLineNumber, 5, scrollType);
  }
  _revealLines(startLineNumber, endLineNumber, verticalType, scrollType) {
    if (typeof startLineNumber !== "number" || typeof endLineNumber !== "number") {
      throw new Error("Invalid arguments");
    }
    this._sendRevealRange(new Range(startLineNumber, 1, endLineNumber, 1), verticalType, false, scrollType);
  }
  revealRange(range3, scrollType = 0, revealVerticalInCenter = false, revealHorizontal = true) {
    this._revealRange(range3, revealVerticalInCenter ? 1 : 0, revealHorizontal, scrollType);
  }
  revealRangeInCenter(range3, scrollType = 0) {
    this._revealRange(range3, 1, true, scrollType);
  }
  revealRangeInCenterIfOutsideViewport(range3, scrollType = 0) {
    this._revealRange(range3, 2, true, scrollType);
  }
  revealRangeNearTop(range3, scrollType = 0) {
    this._revealRange(range3, 5, true, scrollType);
  }
  revealRangeNearTopIfOutsideViewport(range3, scrollType = 0) {
    this._revealRange(range3, 6, true, scrollType);
  }
  revealRangeAtTop(range3, scrollType = 0) {
    this._revealRange(range3, 3, true, scrollType);
  }
  _revealRange(range3, verticalType, revealHorizontal, scrollType) {
    if (!Range.isIRange(range3)) {
      throw new Error("Invalid arguments");
    }
    this._sendRevealRange(Range.lift(range3), verticalType, revealHorizontal, scrollType);
  }
  setSelections(ranges, source2 = "api") {
    if (!this._modelData) {
      return;
    }
    if (!ranges || ranges.length === 0) {
      throw new Error("Invalid arguments");
    }
    for (let i3 = 0, len2 = ranges.length; i3 < len2; i3++) {
      if (!Selection.isISelection(ranges[i3])) {
        throw new Error("Invalid arguments");
      }
    }
    this._modelData.viewModel.setSelections(source2, ranges);
  }
  getContentWidth() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getContentWidth();
  }
  getScrollWidth() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getScrollWidth();
  }
  getScrollLeft() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getCurrentScrollLeft();
  }
  getContentHeight() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getContentHeight();
  }
  getScrollHeight() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getScrollHeight();
  }
  getScrollTop() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getCurrentScrollTop();
  }
  setScrollLeft(newScrollLeft, scrollType = 1) {
    if (!this._modelData) {
      return;
    }
    if (typeof newScrollLeft !== "number") {
      throw new Error("Invalid arguments");
    }
    this._modelData.viewModel.setScrollPosition({
      scrollLeft: newScrollLeft
    }, scrollType);
  }
  setScrollTop(newScrollTop, scrollType = 1) {
    if (!this._modelData) {
      return;
    }
    if (typeof newScrollTop !== "number") {
      throw new Error("Invalid arguments");
    }
    this._modelData.viewModel.setScrollPosition({
      scrollTop: newScrollTop
    }, scrollType);
  }
  setScrollPosition(position2, scrollType = 1) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.setScrollPosition(position2, scrollType);
  }
  saveViewState() {
    if (!this._modelData) {
      return null;
    }
    const contributionsState = {};
    const keys2 = Object.keys(this._contributions);
    for (const id3 of keys2) {
      const contribution = this._contributions[id3];
      if (typeof contribution.saveViewState === "function") {
        contributionsState[id3] = contribution.saveViewState();
      }
    }
    const cursorState = this._modelData.viewModel.saveCursorState();
    const viewState = this._modelData.viewModel.saveState();
    return {
      cursorState,
      viewState,
      contributionsState
    };
  }
  restoreViewState(s2) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    const codeEditorState = s2;
    if (codeEditorState && codeEditorState.cursorState && codeEditorState.viewState) {
      const cursorState = codeEditorState.cursorState;
      if (Array.isArray(cursorState)) {
        this._modelData.viewModel.restoreCursorState(cursorState);
      } else {
        this._modelData.viewModel.restoreCursorState([cursorState]);
      }
      const contributionsState = codeEditorState.contributionsState || {};
      const keys2 = Object.keys(this._contributions);
      for (let i3 = 0, len2 = keys2.length; i3 < len2; i3++) {
        const id3 = keys2[i3];
        const contribution = this._contributions[id3];
        if (typeof contribution.restoreViewState === "function") {
          contribution.restoreViewState(contributionsState[id3]);
        }
      }
      const reducedState = this._modelData.viewModel.reduceRestoreState(codeEditorState.viewState);
      this._modelData.view.restoreState(reducedState);
    }
  }
  getContribution(id3) {
    return this._contributions[id3] || null;
  }
  getActions() {
    const result = [];
    const keys2 = Object.keys(this._actions);
    for (let i3 = 0, len2 = keys2.length; i3 < len2; i3++) {
      const id3 = keys2[i3];
      result.push(this._actions[id3]);
    }
    return result;
  }
  getSupportedActions() {
    let result = this.getActions();
    result = result.filter((action) => action.isSupported());
    return result;
  }
  getAction(id3) {
    return this._actions[id3] || null;
  }
  trigger(source2, handlerId, payload) {
    payload = payload || {};
    switch (handlerId) {
      case "compositionStart":
        this._startComposition();
        return;
      case "compositionEnd":
        this._endComposition(source2);
        return;
      case "type": {
        const args = payload;
        this._type(source2, args.text || "");
        return;
      }
      case "replacePreviousChar": {
        const args = payload;
        this._replacePreviousChar(source2, args.text || "", args.replaceCharCnt || 0);
        return;
      }
      case "paste": {
        const args = payload;
        this._paste(source2, args.text || "", args.pasteOnNewLine || false, args.multicursorText || null, args.mode || null);
        return;
      }
      case "cut":
        this._cut(source2);
        return;
    }
    const action = this.getAction(handlerId);
    if (action) {
      Promise.resolve(action.run()).then(void 0, onUnexpectedError);
      return;
    }
    if (!this._modelData) {
      return;
    }
    if (this._triggerEditorCommand(source2, handlerId, payload)) {
      return;
    }
  }
  _startComposition() {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.startComposition();
    this._onDidCompositionStart.fire();
  }
  _endComposition(source2) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.endComposition(source2);
    this._onDidCompositionEnd.fire();
  }
  _type(source2, text) {
    if (!this._modelData || text.length === 0) {
      return;
    }
    if (source2 === "keyboard") {
      this._onWillType.fire(text);
    }
    this._modelData.viewModel.type(text, source2);
    if (source2 === "keyboard") {
      this._onDidType.fire(text);
    }
  }
  _replacePreviousChar(source2, text, replaceCharCnt) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.replacePreviousChar(text, replaceCharCnt, source2);
  }
  _paste(source2, text, pasteOnNewLine, multicursorText, mode) {
    if (!this._modelData || text.length === 0) {
      return;
    }
    const startPosition = this._modelData.viewModel.getSelection().getStartPosition();
    this._modelData.viewModel.paste(text, pasteOnNewLine, multicursorText, source2);
    const endPosition = this._modelData.viewModel.getSelection().getStartPosition();
    if (source2 === "keyboard") {
      this._onDidPaste.fire({
        range: new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column),
        mode
      });
    }
  }
  _cut(source2) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.cut(source2);
  }
  _triggerEditorCommand(source2, handlerId, payload) {
    const command = EditorExtensionsRegistry.getEditorCommand(handlerId);
    if (command) {
      payload = payload || {};
      payload.source = source2;
      this._instantiationService.invokeFunction((accessor) => {
        Promise.resolve(command.runEditorCommand(accessor, this, payload)).then(void 0, onUnexpectedError);
      });
      return true;
    }
    return false;
  }
  _getViewModel() {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.viewModel;
  }
  pushUndoStop() {
    if (!this._modelData) {
      return false;
    }
    if (this._configuration.options.get(72)) {
      return false;
    }
    this._modelData.model.pushStackElement();
    return true;
  }
  executeEdits(source2, edits, endCursorState) {
    if (!this._modelData) {
      return false;
    }
    if (this._configuration.options.get(72)) {
      return false;
    }
    let cursorStateComputer;
    if (!endCursorState) {
      cursorStateComputer = () => null;
    } else if (Array.isArray(endCursorState)) {
      cursorStateComputer = () => endCursorState;
    } else {
      cursorStateComputer = endCursorState;
    }
    this._modelData.viewModel.executeEdits(source2, edits, cursorStateComputer);
    return true;
  }
  executeCommand(source2, command) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.executeCommand(command, source2);
  }
  executeCommands(source2, commands) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.executeCommands(commands, source2);
  }
  changeDecorations(callback) {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.model.changeDecorations(callback, this._id);
  }
  getLineDecorations(lineNumber) {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.model.getLineDecorations(lineNumber, this._id, filterValidationDecorations(this._configuration.options));
  }
  deltaDecorations(oldDecorations, newDecorations) {
    if (!this._modelData) {
      return [];
    }
    if (oldDecorations.length === 0 && newDecorations.length === 0) {
      return oldDecorations;
    }
    return this._modelData.model.deltaDecorations(oldDecorations, newDecorations, this._id);
  }
  removeDecorations(decorationTypeKey) {
    const oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey];
    if (oldDecorationsIds) {
      this.deltaDecorations(oldDecorationsIds, []);
    }
    if (this._decorationTypeKeysToIds.hasOwnProperty(decorationTypeKey)) {
      delete this._decorationTypeKeysToIds[decorationTypeKey];
    }
    if (this._decorationTypeSubtypes.hasOwnProperty(decorationTypeKey)) {
      delete this._decorationTypeSubtypes[decorationTypeKey];
    }
  }
  getLayoutInfo() {
    const options = this._configuration.options;
    const layoutInfo = options.get(117);
    return layoutInfo;
  }
  createOverviewRuler(cssClassName) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return null;
    }
    return this._modelData.view.createOverviewRuler(cssClassName);
  }
  getContainerDomNode() {
    return this._domElement;
  }
  getDomNode() {
    if (!this._modelData || !this._modelData.hasRealView) {
      return null;
    }
    return this._modelData.view.domNode.domNode;
  }
  delegateVerticalScrollbarMouseDown(browserEvent) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    this._modelData.view.delegateVerticalScrollbarMouseDown(browserEvent);
  }
  layout(dimension) {
    this._configuration.observeReferenceElement(dimension);
    this.render();
  }
  focus() {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    this._modelData.view.focus();
  }
  hasTextFocus() {
    if (!this._modelData || !this._modelData.hasRealView) {
      return false;
    }
    return this._modelData.view.isFocused();
  }
  hasWidgetFocus() {
    return this._focusTracker && this._focusTracker.hasFocus();
  }
  addContentWidget(widget) {
    const widgetData = {
      widget,
      position: widget.getPosition()
    };
    if (this._contentWidgets.hasOwnProperty(widget.getId())) {
      console.warn("Overwriting a content widget with the same id.");
    }
    this._contentWidgets[widget.getId()] = widgetData;
    if (this._modelData && this._modelData.hasRealView) {
      this._modelData.view.addContentWidget(widgetData);
    }
  }
  layoutContentWidget(widget) {
    const widgetId = widget.getId();
    if (this._contentWidgets.hasOwnProperty(widgetId)) {
      const widgetData = this._contentWidgets[widgetId];
      widgetData.position = widget.getPosition();
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.layoutContentWidget(widgetData);
      }
    }
  }
  removeContentWidget(widget) {
    const widgetId = widget.getId();
    if (this._contentWidgets.hasOwnProperty(widgetId)) {
      const widgetData = this._contentWidgets[widgetId];
      delete this._contentWidgets[widgetId];
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.removeContentWidget(widgetData);
      }
    }
  }
  addOverlayWidget(widget) {
    const widgetData = {
      widget,
      position: widget.getPosition()
    };
    if (this._overlayWidgets.hasOwnProperty(widget.getId())) {
      console.warn("Overwriting an overlay widget with the same id.");
    }
    this._overlayWidgets[widget.getId()] = widgetData;
    if (this._modelData && this._modelData.hasRealView) {
      this._modelData.view.addOverlayWidget(widgetData);
    }
  }
  layoutOverlayWidget(widget) {
    const widgetId = widget.getId();
    if (this._overlayWidgets.hasOwnProperty(widgetId)) {
      const widgetData = this._overlayWidgets[widgetId];
      widgetData.position = widget.getPosition();
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.layoutOverlayWidget(widgetData);
      }
    }
  }
  removeOverlayWidget(widget) {
    const widgetId = widget.getId();
    if (this._overlayWidgets.hasOwnProperty(widgetId)) {
      const widgetData = this._overlayWidgets[widgetId];
      delete this._overlayWidgets[widgetId];
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.removeOverlayWidget(widgetData);
      }
    }
  }
  changeViewZones(callback) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    this._modelData.view.change(callback);
  }
  getTargetAtClientPoint(clientX, clientY) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return null;
    }
    return this._modelData.view.getTargetAtClientPoint(clientX, clientY);
  }
  getScrolledVisiblePosition(rawPosition) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return null;
    }
    const position2 = this._modelData.model.validatePosition(rawPosition);
    const options = this._configuration.options;
    const layoutInfo = options.get(117);
    const top2 = CodeEditorWidget2._getVerticalOffsetForPosition(this._modelData, position2.lineNumber, position2.column) - this.getScrollTop();
    const left2 = this._modelData.view.getOffsetForColumn(position2.lineNumber, position2.column) + layoutInfo.glyphMarginWidth + layoutInfo.lineNumbersWidth + layoutInfo.decorationsWidth - this.getScrollLeft();
    return {
      top: top2,
      left: left2,
      height: options.get(51)
    };
  }
  getOffsetForColumn(lineNumber, column) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return -1;
    }
    return this._modelData.view.getOffsetForColumn(lineNumber, column);
  }
  render(forceRedraw = false) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    this._modelData.view.render(true, forceRedraw);
  }
  setAriaOptions(options) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    this._modelData.view.setAriaOptions(options);
  }
  applyFontInfo(target) {
    Configuration$1.applyFontInfoSlow(target, this._configuration.options.get(36));
  }
  _attachModel(model) {
    if (!model) {
      this._modelData = null;
      return;
    }
    const listenersToRemove = [];
    this._domElement.setAttribute("data-mode-id", model.getLanguageIdentifier().language);
    this._configuration.setIsDominatedByLongLines(model.isDominatedByLongLines());
    this._configuration.setMaxLineNumber(model.getLineCount());
    model.onBeforeAttached();
    const viewModel = new ViewModel(this._id, this._configuration, model, DOMLineBreaksComputerFactory.create(), MonospaceLineBreaksComputerFactory.create(this._configuration.options), (callback) => scheduleAtNextAnimationFrame(callback));
    listenersToRemove.push(model.onDidChangeDecorations((e2) => this._onDidChangeModelDecorations.fire(e2)));
    listenersToRemove.push(model.onDidChangeLanguage((e2) => {
      this._domElement.setAttribute("data-mode-id", model.getLanguageIdentifier().language);
      this._onDidChangeModelLanguage.fire(e2);
    }));
    listenersToRemove.push(model.onDidChangeLanguageConfiguration((e2) => this._onDidChangeModelLanguageConfiguration.fire(e2)));
    listenersToRemove.push(model.onDidChangeContent((e2) => this._onDidChangeModelContent.fire(e2)));
    listenersToRemove.push(model.onDidChangeOptions((e2) => this._onDidChangeModelOptions.fire(e2)));
    listenersToRemove.push(model.onWillDispose(() => this.setModel(null)));
    listenersToRemove.push(viewModel.onEvent((e2) => {
      switch (e2.kind) {
        case 0:
          this._onDidContentSizeChange.fire(e2);
          break;
        case 1:
          this._editorTextFocus.setValue(e2.hasFocus);
          break;
        case 2:
          this._onDidScrollChange.fire(e2);
          break;
        case 3:
          this._onDidChangeViewZones.fire();
          break;
        case 4:
          this._onDidAttemptReadOnlyEdit.fire();
          break;
        case 5: {
          if (e2.reachedMaxCursorCount) {
            this._notificationService.warn(localize("cursors.maximum", "The number of cursors has been limited to {0}.", Cursor.MAX_CURSOR_COUNT));
          }
          const positions = [];
          for (let i3 = 0, len2 = e2.selections.length; i3 < len2; i3++) {
            positions[i3] = e2.selections[i3].getPosition();
          }
          const e1 = {
            position: positions[0],
            secondaryPositions: positions.slice(1),
            reason: e2.reason,
            source: e2.source
          };
          this._onDidChangeCursorPosition.fire(e1);
          const e22 = {
            selection: e2.selections[0],
            secondarySelections: e2.selections.slice(1),
            modelVersionId: e2.modelVersionId,
            oldSelections: e2.oldSelections,
            oldModelVersionId: e2.oldModelVersionId,
            source: e2.source,
            reason: e2.reason
          };
          this._onDidChangeCursorSelection.fire(e22);
          break;
        }
      }
    }));
    const [view, hasRealView] = this._createView(viewModel);
    if (hasRealView) {
      this._domElement.appendChild(view.domNode.domNode);
      let keys2 = Object.keys(this._contentWidgets);
      for (let i3 = 0, len2 = keys2.length; i3 < len2; i3++) {
        const widgetId = keys2[i3];
        view.addContentWidget(this._contentWidgets[widgetId]);
      }
      keys2 = Object.keys(this._overlayWidgets);
      for (let i3 = 0, len2 = keys2.length; i3 < len2; i3++) {
        const widgetId = keys2[i3];
        view.addOverlayWidget(this._overlayWidgets[widgetId]);
      }
      view.render(false, true);
      view.domNode.domNode.setAttribute("data-uri", model.uri.toString());
    }
    this._modelData = new ModelData(model, viewModel, view, hasRealView, listenersToRemove);
  }
  _createView(viewModel) {
    let commandDelegate;
    if (this.isSimpleWidget) {
      commandDelegate = {
        paste: (text, pasteOnNewLine, multicursorText, mode) => {
          this._paste("keyboard", text, pasteOnNewLine, multicursorText, mode);
        },
        type: (text) => {
          this._type("keyboard", text);
        },
        replacePreviousChar: (text, replaceCharCnt) => {
          this._replacePreviousChar("keyboard", text, replaceCharCnt);
        },
        startComposition: () => {
          this._startComposition();
        },
        endComposition: () => {
          this._endComposition("keyboard");
        },
        cut: () => {
          this._cut("keyboard");
        }
      };
    } else {
      commandDelegate = {
        paste: (text, pasteOnNewLine, multicursorText, mode) => {
          const payload = {text, pasteOnNewLine, multicursorText, mode};
          this._commandService.executeCommand("paste", payload);
        },
        type: (text) => {
          const payload = {text};
          this._commandService.executeCommand("type", payload);
        },
        replacePreviousChar: (text, replaceCharCnt) => {
          const payload = {text, replaceCharCnt};
          this._commandService.executeCommand("replacePreviousChar", payload);
        },
        startComposition: () => {
          this._commandService.executeCommand("compositionStart", {});
        },
        endComposition: () => {
          this._commandService.executeCommand("compositionEnd", {});
        },
        cut: () => {
          this._commandService.executeCommand("cut", {});
        }
      };
    }
    const viewUserInputEvents = new ViewUserInputEvents(viewModel.coordinatesConverter);
    viewUserInputEvents.onKeyDown = (e2) => this._onKeyDown.fire(e2);
    viewUserInputEvents.onKeyUp = (e2) => this._onKeyUp.fire(e2);
    viewUserInputEvents.onContextMenu = (e2) => this._onContextMenu.fire(e2);
    viewUserInputEvents.onMouseMove = (e2) => this._onMouseMove.fire(e2);
    viewUserInputEvents.onMouseLeave = (e2) => this._onMouseLeave.fire(e2);
    viewUserInputEvents.onMouseDown = (e2) => this._onMouseDown.fire(e2);
    viewUserInputEvents.onMouseUp = (e2) => this._onMouseUp.fire(e2);
    viewUserInputEvents.onMouseDrag = (e2) => this._onMouseDrag.fire(e2);
    viewUserInputEvents.onMouseDrop = (e2) => this._onMouseDrop.fire(e2);
    viewUserInputEvents.onMouseWheel = (e2) => this._onMouseWheel.fire(e2);
    const view = new View(commandDelegate, this._configuration, this._themeService, viewModel, viewUserInputEvents, this._overflowWidgetsDomNode);
    return [view, true];
  }
  _postDetachModelCleanup(detachedModel) {
    if (detachedModel) {
      detachedModel.removeAllDecorationsWithOwnerId(this._id);
    }
  }
  _detachModel() {
    if (!this._modelData) {
      return null;
    }
    const model = this._modelData.model;
    const removeDomNode = this._modelData.hasRealView ? this._modelData.view.domNode.domNode : null;
    this._modelData.dispose();
    this._modelData = null;
    this._domElement.removeAttribute("data-mode-id");
    if (removeDomNode && this._domElement.contains(removeDomNode)) {
      this._domElement.removeChild(removeDomNode);
    }
    return model;
  }
  _removeDecorationType(key) {
    this._codeEditorService.removeDecorationType(key);
  }
  hasModel() {
    return this._modelData !== null;
  }
};
CodeEditorWidget = __decorate$5([
  __param$4(3, IInstantiationService),
  __param$4(4, ICodeEditorService),
  __param$4(5, ICommandService),
  __param$4(6, IContextKeyService),
  __param$4(7, IThemeService),
  __param$4(8, INotificationService),
  __param$4(9, IAccessibilityService)
], CodeEditorWidget);
var BooleanEventEmitter = class extends Disposable {
  constructor() {
    super();
    this._onDidChangeToTrue = this._register(new Emitter());
    this.onDidChangeToTrue = this._onDidChangeToTrue.event;
    this._onDidChangeToFalse = this._register(new Emitter());
    this.onDidChangeToFalse = this._onDidChangeToFalse.event;
    this._value = 0;
  }
  setValue(_value) {
    const value = _value ? 2 : 1;
    if (this._value === value) {
      return;
    }
    this._value = value;
    if (this._value === 2) {
      this._onDidChangeToTrue.fire();
    } else if (this._value === 1) {
      this._onDidChangeToFalse.fire();
    }
  }
};
var EditorContextKeysManager = class extends Disposable {
  constructor(editor2, contextKeyService) {
    super();
    this._editor = editor2;
    contextKeyService.createKey("editorId", editor2.getId());
    this._editorSimpleInput = EditorContextKeys.editorSimpleInput.bindTo(contextKeyService);
    this._editorFocus = EditorContextKeys.focus.bindTo(contextKeyService);
    this._textInputFocus = EditorContextKeys.textInputFocus.bindTo(contextKeyService);
    this._editorTextFocus = EditorContextKeys.editorTextFocus.bindTo(contextKeyService);
    this._editorTabMovesFocus = EditorContextKeys.tabMovesFocus.bindTo(contextKeyService);
    this._editorReadonly = EditorContextKeys.readOnly.bindTo(contextKeyService);
    this._editorColumnSelection = EditorContextKeys.columnSelection.bindTo(contextKeyService);
    this._hasMultipleSelections = EditorContextKeys.hasMultipleSelections.bindTo(contextKeyService);
    this._hasNonEmptySelection = EditorContextKeys.hasNonEmptySelection.bindTo(contextKeyService);
    this._canUndo = EditorContextKeys.canUndo.bindTo(contextKeyService);
    this._canRedo = EditorContextKeys.canRedo.bindTo(contextKeyService);
    this._register(this._editor.onDidChangeConfiguration(() => this._updateFromConfig()));
    this._register(this._editor.onDidChangeCursorSelection(() => this._updateFromSelection()));
    this._register(this._editor.onDidFocusEditorWidget(() => this._updateFromFocus()));
    this._register(this._editor.onDidBlurEditorWidget(() => this._updateFromFocus()));
    this._register(this._editor.onDidFocusEditorText(() => this._updateFromFocus()));
    this._register(this._editor.onDidBlurEditorText(() => this._updateFromFocus()));
    this._register(this._editor.onDidChangeModel(() => this._updateFromModel()));
    this._register(this._editor.onDidChangeConfiguration(() => this._updateFromModel()));
    this._updateFromConfig();
    this._updateFromSelection();
    this._updateFromFocus();
    this._updateFromModel();
    this._editorSimpleInput.set(this._editor.isSimpleWidget);
  }
  _updateFromConfig() {
    const options = this._editor.getOptions();
    this._editorTabMovesFocus.set(options.get(116));
    this._editorReadonly.set(options.get(72));
    this._editorColumnSelection.set(options.get(13));
  }
  _updateFromSelection() {
    const selections = this._editor.getSelections();
    if (!selections) {
      this._hasMultipleSelections.reset();
      this._hasNonEmptySelection.reset();
    } else {
      this._hasMultipleSelections.set(selections.length > 1);
      this._hasNonEmptySelection.set(selections.some((s2) => !s2.isEmpty()));
    }
  }
  _updateFromFocus() {
    this._editorFocus.set(this._editor.hasWidgetFocus() && !this._editor.isSimpleWidget);
    this._editorTextFocus.set(this._editor.hasTextFocus() && !this._editor.isSimpleWidget);
    this._textInputFocus.set(this._editor.hasTextFocus());
  }
  _updateFromModel() {
    const model = this._editor.getModel();
    this._canUndo.set(Boolean(model && model.canUndo()));
    this._canRedo.set(Boolean(model && model.canRedo()));
  }
};
var EditorModeContext = class extends Disposable {
  constructor(_editor, _contextKeyService) {
    super();
    this._editor = _editor;
    this._contextKeyService = _contextKeyService;
    this._langId = EditorContextKeys.languageId.bindTo(_contextKeyService);
    this._hasCompletionItemProvider = EditorContextKeys.hasCompletionItemProvider.bindTo(_contextKeyService);
    this._hasCodeActionsProvider = EditorContextKeys.hasCodeActionsProvider.bindTo(_contextKeyService);
    this._hasCodeLensProvider = EditorContextKeys.hasCodeLensProvider.bindTo(_contextKeyService);
    this._hasDefinitionProvider = EditorContextKeys.hasDefinitionProvider.bindTo(_contextKeyService);
    this._hasDeclarationProvider = EditorContextKeys.hasDeclarationProvider.bindTo(_contextKeyService);
    this._hasImplementationProvider = EditorContextKeys.hasImplementationProvider.bindTo(_contextKeyService);
    this._hasTypeDefinitionProvider = EditorContextKeys.hasTypeDefinitionProvider.bindTo(_contextKeyService);
    this._hasHoverProvider = EditorContextKeys.hasHoverProvider.bindTo(_contextKeyService);
    this._hasDocumentHighlightProvider = EditorContextKeys.hasDocumentHighlightProvider.bindTo(_contextKeyService);
    this._hasDocumentSymbolProvider = EditorContextKeys.hasDocumentSymbolProvider.bindTo(_contextKeyService);
    this._hasReferenceProvider = EditorContextKeys.hasReferenceProvider.bindTo(_contextKeyService);
    this._hasRenameProvider = EditorContextKeys.hasRenameProvider.bindTo(_contextKeyService);
    this._hasSignatureHelpProvider = EditorContextKeys.hasSignatureHelpProvider.bindTo(_contextKeyService);
    this._hasDocumentFormattingProvider = EditorContextKeys.hasDocumentFormattingProvider.bindTo(_contextKeyService);
    this._hasDocumentSelectionFormattingProvider = EditorContextKeys.hasDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
    this._hasMultipleDocumentFormattingProvider = EditorContextKeys.hasMultipleDocumentFormattingProvider.bindTo(_contextKeyService);
    this._hasMultipleDocumentSelectionFormattingProvider = EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
    this._isInWalkThrough = EditorContextKeys.isInWalkThroughSnippet.bindTo(_contextKeyService);
    const update = () => this._update();
    this._register(_editor.onDidChangeModel(update));
    this._register(_editor.onDidChangeModelLanguage(update));
    this._register(CompletionProviderRegistry.onDidChange(update));
    this._register(CodeActionProviderRegistry.onDidChange(update));
    this._register(CodeLensProviderRegistry.onDidChange(update));
    this._register(DefinitionProviderRegistry.onDidChange(update));
    this._register(DeclarationProviderRegistry.onDidChange(update));
    this._register(ImplementationProviderRegistry.onDidChange(update));
    this._register(TypeDefinitionProviderRegistry.onDidChange(update));
    this._register(HoverProviderRegistry.onDidChange(update));
    this._register(DocumentHighlightProviderRegistry.onDidChange(update));
    this._register(DocumentSymbolProviderRegistry.onDidChange(update));
    this._register(ReferenceProviderRegistry.onDidChange(update));
    this._register(RenameProviderRegistry.onDidChange(update));
    this._register(DocumentFormattingEditProviderRegistry.onDidChange(update));
    this._register(DocumentRangeFormattingEditProviderRegistry.onDidChange(update));
    this._register(SignatureHelpProviderRegistry.onDidChange(update));
    update();
  }
  dispose() {
    super.dispose();
  }
  reset() {
    this._contextKeyService.bufferChangeEvents(() => {
      this._langId.reset();
      this._hasCompletionItemProvider.reset();
      this._hasCodeActionsProvider.reset();
      this._hasCodeLensProvider.reset();
      this._hasDefinitionProvider.reset();
      this._hasDeclarationProvider.reset();
      this._hasImplementationProvider.reset();
      this._hasTypeDefinitionProvider.reset();
      this._hasHoverProvider.reset();
      this._hasDocumentHighlightProvider.reset();
      this._hasDocumentSymbolProvider.reset();
      this._hasReferenceProvider.reset();
      this._hasRenameProvider.reset();
      this._hasDocumentFormattingProvider.reset();
      this._hasDocumentSelectionFormattingProvider.reset();
      this._hasSignatureHelpProvider.reset();
      this._isInWalkThrough.reset();
    });
  }
  _update() {
    const model = this._editor.getModel();
    if (!model) {
      this.reset();
      return;
    }
    this._contextKeyService.bufferChangeEvents(() => {
      this._langId.set(model.getLanguageIdentifier().language);
      this._hasCompletionItemProvider.set(CompletionProviderRegistry.has(model));
      this._hasCodeActionsProvider.set(CodeActionProviderRegistry.has(model));
      this._hasCodeLensProvider.set(CodeLensProviderRegistry.has(model));
      this._hasDefinitionProvider.set(DefinitionProviderRegistry.has(model));
      this._hasDeclarationProvider.set(DeclarationProviderRegistry.has(model));
      this._hasImplementationProvider.set(ImplementationProviderRegistry.has(model));
      this._hasTypeDefinitionProvider.set(TypeDefinitionProviderRegistry.has(model));
      this._hasHoverProvider.set(HoverProviderRegistry.has(model));
      this._hasDocumentHighlightProvider.set(DocumentHighlightProviderRegistry.has(model));
      this._hasDocumentSymbolProvider.set(DocumentSymbolProviderRegistry.has(model));
      this._hasReferenceProvider.set(ReferenceProviderRegistry.has(model));
      this._hasRenameProvider.set(RenameProviderRegistry.has(model));
      this._hasSignatureHelpProvider.set(SignatureHelpProviderRegistry.has(model));
      this._hasDocumentFormattingProvider.set(DocumentFormattingEditProviderRegistry.has(model) || DocumentRangeFormattingEditProviderRegistry.has(model));
      this._hasDocumentSelectionFormattingProvider.set(DocumentRangeFormattingEditProviderRegistry.has(model));
      this._hasMultipleDocumentFormattingProvider.set(DocumentFormattingEditProviderRegistry.all(model).length + DocumentRangeFormattingEditProviderRegistry.all(model).length > 1);
      this._hasMultipleDocumentSelectionFormattingProvider.set(DocumentRangeFormattingEditProviderRegistry.all(model).length > 1);
      this._isInWalkThrough.set(model.uri.scheme === Schemas.walkThroughSnippet);
    });
  }
};
var CodeEditorWidgetFocusTracker = class extends Disposable {
  constructor(domElement) {
    super();
    this._onChange = this._register(new Emitter());
    this.onChange = this._onChange.event;
    this._hasFocus = false;
    this._domFocusTracker = this._register(trackFocus(domElement));
    this._register(this._domFocusTracker.onDidFocus(() => {
      this._hasFocus = true;
      this._onChange.fire(void 0);
    }));
    this._register(this._domFocusTracker.onDidBlur(() => {
      this._hasFocus = false;
      this._onChange.fire(void 0);
    }));
  }
  hasFocus() {
    return this._hasFocus;
  }
};
var squigglyStart = encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 6 3' enable-background='new 0 0 6 3' height='3' width='6'><g fill='`);
var squigglyEnd = encodeURIComponent(`'><polygon points='5.5,0 2.5,3 1.1,3 4.1,0'/><polygon points='4,0 6,2 6,0.6 5.4,0'/><polygon points='0,2 1,3 2.4,3 0,0.6'/></g></svg>`);
function getSquigglySVGData(color2) {
  return squigglyStart + encodeURIComponent(color2.toString()) + squigglyEnd;
}
var dotdotdotStart = encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" height="3" width="12"><g fill="`);
var dotdotdotEnd = encodeURIComponent(`"><circle cx="1" cy="1" r="1"/><circle cx="5" cy="1" r="1"/><circle cx="9" cy="1" r="1"/></g></svg>`);
function getDotDotDotSVGData(color2) {
  return dotdotdotStart + encodeURIComponent(color2.toString()) + dotdotdotEnd;
}
registerThemingParticipant((theme, collector) => {
  const errorBorderColor = theme.getColor(editorErrorBorder);
  if (errorBorderColor) {
    collector.addRule(`.monaco-editor .${"squiggly-error"} { border-bottom: 4px double ${errorBorderColor}; }`);
  }
  const errorForeground2 = theme.getColor(editorErrorForeground);
  if (errorForeground2) {
    collector.addRule(`.monaco-editor .${"squiggly-error"} { background: url("data:image/svg+xml,${getSquigglySVGData(errorForeground2)}") repeat-x bottom left; }`);
  }
  const warningBorderColor = theme.getColor(editorWarningBorder);
  if (warningBorderColor) {
    collector.addRule(`.monaco-editor .${"squiggly-warning"} { border-bottom: 4px double ${warningBorderColor}; }`);
  }
  const warningForeground = theme.getColor(editorWarningForeground);
  if (warningForeground) {
    collector.addRule(`.monaco-editor .${"squiggly-warning"} { background: url("data:image/svg+xml,${getSquigglySVGData(warningForeground)}") repeat-x bottom left; }`);
  }
  const infoBorderColor = theme.getColor(editorInfoBorder);
  if (infoBorderColor) {
    collector.addRule(`.monaco-editor .${"squiggly-info"} { border-bottom: 4px double ${infoBorderColor}; }`);
  }
  const infoForeground = theme.getColor(editorInfoForeground);
  if (infoForeground) {
    collector.addRule(`.monaco-editor .${"squiggly-info"} { background: url("data:image/svg+xml,${getSquigglySVGData(infoForeground)}") repeat-x bottom left; }`);
  }
  const hintBorderColor = theme.getColor(editorHintBorder);
  if (hintBorderColor) {
    collector.addRule(`.monaco-editor .${"squiggly-hint"} { border-bottom: 2px dotted ${hintBorderColor}; }`);
  }
  const hintForeground = theme.getColor(editorHintForeground);
  if (hintForeground) {
    collector.addRule(`.monaco-editor .${"squiggly-hint"} { background: url("data:image/svg+xml,${getDotDotDotSVGData(hintForeground)}") no-repeat bottom left; }`);
  }
  const unnecessaryForeground = theme.getColor(editorUnnecessaryCodeOpacity);
  if (unnecessaryForeground) {
    collector.addRule(`.monaco-editor.showUnused .${"squiggly-inline-unnecessary"} { opacity: ${unnecessaryForeground.rgba.a}; }`);
  }
  const unnecessaryBorder = theme.getColor(editorUnnecessaryCodeBorder);
  if (unnecessaryBorder) {
    collector.addRule(`.monaco-editor.showUnused .${"squiggly-unnecessary"} { border-bottom: 2px dashed ${unnecessaryBorder}; }`);
  }
  const deprecatedForeground = theme.getColor(editorForeground) || "inherit";
  collector.addRule(`.monaco-editor.showDeprecated .${"squiggly-inline-deprecated"} { text-decoration: line-through; text-decoration-color: ${deprecatedForeground}}`);
});
function __snowpack__injectStyle$k(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$k("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n/* ---------- DiffEditor ---------- */\r\n\r\n.monaco-diff-editor .diffOverview {\r\n	z-index: 9;\r\n}\r\n\r\n.monaco-diff-editor .diffOverview .diffViewport {\r\n	z-index: 10;\r\n}\r\n\r\n/* colors not externalized: using transparancy on background */\r\n.monaco-diff-editor.vs			.diffOverview { background: rgba(0, 0, 0, 0.03); }\r\n.monaco-diff-editor.vs-dark		.diffOverview { background: rgba(255, 255, 255, 0.01); }\r\n\r\n.monaco-scrollable-element.modified-in-monaco-diff-editor.vs		.scrollbar { background: rgba(0,0,0,0); }\r\n.monaco-scrollable-element.modified-in-monaco-diff-editor.vs-dark	.scrollbar { background: rgba(0,0,0,0); }\r\n.monaco-scrollable-element.modified-in-monaco-diff-editor.hc-black	.scrollbar { background: none; }\r\n\r\n.monaco-scrollable-element.modified-in-monaco-diff-editor .slider {\r\n	z-index: 10;\r\n}\r\n.modified-in-monaco-diff-editor				.slider.active { background: rgba(171, 171, 171, .4); }\r\n.modified-in-monaco-diff-editor.hc-black	.slider.active { background: none; }\r\n\r\n/* ---------- Diff ---------- */\r\n\r\n.monaco-editor .insert-sign,\r\n.monaco-diff-editor .insert-sign,\r\n.monaco-editor .delete-sign,\r\n.monaco-diff-editor .delete-sign {\r\n	font-size: 11px !important;\r\n	opacity: 0.7 !important;\r\n	display: flex !important;\r\n	align-items: center;\r\n}\r\n.monaco-editor.hc-black .insert-sign,\r\n.monaco-diff-editor.hc-black .insert-sign,\r\n.monaco-editor.hc-black .delete-sign,\r\n.monaco-diff-editor.hc-black .delete-sign {\r\n	opacity: 1;\r\n}\r\n\r\n.monaco-editor .inline-deleted-margin-view-zone {\r\n	text-align: right;\r\n}\r\n.monaco-editor .inline-added-margin-view-zone {\r\n	text-align: right;\r\n}\r\n\r\n/* ---------- Inline Diff ---------- */\r\n\r\n.monaco-editor .view-zones .view-lines .view-line span {\r\n	display: inline-block;\r\n}\r\n\r\n.monaco-editor .margin-view-zones .lightbulb-glyph:hover {\r\n	cursor: pointer;\r\n}\r\n");
function __snowpack__injectStyle$l(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$l("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-sash {\r\n	position: absolute;\r\n	z-index: 35;\r\n	touch-action: none;\r\n}\r\n\r\n.monaco-sash.disabled {\r\n	pointer-events: none;\r\n}\r\n\r\n.monaco-sash.mac.vertical {\r\n	cursor: col-resize;\r\n}\r\n\r\n.monaco-sash.vertical.minimum {\r\n	cursor: e-resize;\r\n}\r\n\r\n.monaco-sash.vertical.maximum {\r\n	cursor: w-resize;\r\n}\r\n\r\n.monaco-sash.mac.horizontal {\r\n	cursor: row-resize;\r\n}\r\n\r\n.monaco-sash.horizontal.minimum {\r\n	cursor: s-resize;\r\n}\r\n\r\n.monaco-sash.horizontal.maximum {\r\n	cursor: n-resize;\r\n}\r\n\r\n.monaco-sash.disabled {\r\n	cursor: default !important;\r\n	pointer-events: none !important;\r\n}\r\n\r\n/** Debug **/\r\n\r\n.monaco-sash.debug {\r\n	background: cyan;\r\n}\r\n\r\n.monaco-sash.debug.disabled {\r\n	background: rgba(0, 255, 255, 0.2);\r\n}\r\n\r\n.monaco-sash.debug:not(.disabled).orthogonal-start::before,\r\n.monaco-sash.debug:not(.disabled).orthogonal-end::after {\r\n	background: red;\r\n}\r\n");
var DEBUG = false;
var globalSize = 4;
var onDidChangeGlobalSize = new Emitter();
var Sash = class extends Disposable {
  constructor(container, layoutProvider, options) {
    super();
    this._state = 3;
    this._onDidEnablementChange = this._register(new Emitter());
    this.onDidEnablementChange = this._onDidEnablementChange.event;
    this._onDidStart = this._register(new Emitter());
    this.onDidStart = this._onDidStart.event;
    this._onDidChange = this._register(new Emitter());
    this.onDidChange = this._onDidChange.event;
    this._onDidReset = this._register(new Emitter());
    this.onDidReset = this._onDidReset.event;
    this._onDidEnd = this._register(new Emitter());
    this.onDidEnd = this._onDidEnd.event;
    this.linkedSash = void 0;
    this.orthogonalStartSashDisposables = this._register(new DisposableStore());
    this.orthogonalEndSashDisposables = this._register(new DisposableStore());
    this.el = append(container, $(".monaco-sash"));
    if (isMacintosh) {
      addClass(this.el, "mac");
    }
    this._register(domEvent(this.el, "mousedown")(this.onMouseDown, this));
    this._register(domEvent(this.el, "dblclick")(this.onMouseDoubleClick, this));
    this._register(Gesture.addTarget(this.el));
    this._register(domEvent(this.el, EventType$1.Start)(this.onTouchStart, this));
    if (typeof options.size === "number") {
      this.size = options.size;
      if (options.orientation === 0) {
        this.el.style.width = `${this.size}px`;
      } else {
        this.el.style.height = `${this.size}px`;
      }
    } else {
      this.size = globalSize;
      this._register(onDidChangeGlobalSize.event((size2) => {
        this.size = size2;
        this.layout();
      }));
    }
    this.hidden = false;
    this.layoutProvider = layoutProvider;
    this.orthogonalStartSash = options.orthogonalStartSash;
    this.orthogonalEndSash = options.orthogonalEndSash;
    this.orientation = options.orientation || 0;
    if (this.orientation === 1) {
      addClass(this.el, "horizontal");
      removeClass(this.el, "vertical");
    } else {
      removeClass(this.el, "horizontal");
      addClass(this.el, "vertical");
    }
    toggleClass(this.el, "debug", DEBUG);
    this.layout();
  }
  get state() {
    return this._state;
  }
  set state(state) {
    if (this._state === state) {
      return;
    }
    toggleClass(this.el, "disabled", state === 0);
    toggleClass(this.el, "minimum", state === 1);
    toggleClass(this.el, "maximum", state === 2);
    this._state = state;
    this._onDidEnablementChange.fire(state);
  }
  get orthogonalStartSash() {
    return this._orthogonalStartSash;
  }
  set orthogonalStartSash(sash) {
    this.orthogonalStartSashDisposables.clear();
    if (sash) {
      this.orthogonalStartSashDisposables.add(sash.onDidEnablementChange(this.onOrthogonalStartSashEnablementChange, this));
      this.onOrthogonalStartSashEnablementChange(sash.state);
    } else {
      this.onOrthogonalStartSashEnablementChange(0);
    }
    this._orthogonalStartSash = sash;
  }
  get orthogonalEndSash() {
    return this._orthogonalEndSash;
  }
  set orthogonalEndSash(sash) {
    this.orthogonalEndSashDisposables.clear();
    if (sash) {
      this.orthogonalEndSashDisposables.add(sash.onDidEnablementChange(this.onOrthogonalEndSashEnablementChange, this));
      this.onOrthogonalEndSashEnablementChange(sash.state);
    } else {
      this.onOrthogonalEndSashEnablementChange(0);
    }
    this._orthogonalEndSash = sash;
  }
  onMouseDown(e2) {
    EventHelper.stop(e2, false);
    let isMultisashResize = false;
    if (!e2.__orthogonalSashEvent) {
      const orthogonalSash = this.getOrthogonalSash(e2);
      if (orthogonalSash) {
        isMultisashResize = true;
        e2.__orthogonalSashEvent = true;
        orthogonalSash.onMouseDown(e2);
      }
    }
    if (this.linkedSash && !e2.__linkedSashEvent) {
      e2.__linkedSashEvent = true;
      this.linkedSash.onMouseDown(e2);
    }
    if (!this.state) {
      return;
    }
    const iframes = [
      ...getElementsByTagName("iframe"),
      ...getElementsByTagName("webview")
    ];
    for (const iframe of iframes) {
      iframe.style.pointerEvents = "none";
    }
    const mouseDownEvent = new StandardMouseEvent(e2);
    const startX = mouseDownEvent.posx;
    const startY = mouseDownEvent.posy;
    const altKey = mouseDownEvent.altKey;
    const startEvent = {startX, currentX: startX, startY, currentY: startY, altKey};
    addClass(this.el, "active");
    this._onDidStart.fire(startEvent);
    const style = createStyleSheet(this.el);
    const updateStyle = () => {
      let cursor = "";
      if (isMultisashResize) {
        cursor = "all-scroll";
      } else if (this.orientation === 1) {
        if (this.state === 1) {
          cursor = "s-resize";
        } else if (this.state === 2) {
          cursor = "n-resize";
        } else {
          cursor = isMacintosh ? "row-resize" : "ns-resize";
        }
      } else {
        if (this.state === 1) {
          cursor = "e-resize";
        } else if (this.state === 2) {
          cursor = "w-resize";
        } else {
          cursor = isMacintosh ? "col-resize" : "ew-resize";
        }
      }
      style.innerHTML = `* { cursor: ${cursor} !important; }`;
    };
    const disposables = new DisposableStore();
    updateStyle();
    if (!isMultisashResize) {
      this.onDidEnablementChange(updateStyle, null, disposables);
    }
    const onMouseMove = (e3) => {
      EventHelper.stop(e3, false);
      const mouseMoveEvent = new StandardMouseEvent(e3);
      const event = {startX, currentX: mouseMoveEvent.posx, startY, currentY: mouseMoveEvent.posy, altKey};
      this._onDidChange.fire(event);
    };
    const onMouseUp = (e3) => {
      EventHelper.stop(e3, false);
      this.el.removeChild(style);
      removeClass(this.el, "active");
      this._onDidEnd.fire();
      disposables.dispose();
      for (const iframe of iframes) {
        iframe.style.pointerEvents = "auto";
      }
    };
    domEvent(window, "mousemove")(onMouseMove, null, disposables);
    domEvent(window, "mouseup")(onMouseUp, null, disposables);
  }
  onMouseDoubleClick(e2) {
    const orthogonalSash = this.getOrthogonalSash(e2);
    if (orthogonalSash) {
      orthogonalSash._onDidReset.fire();
    }
    if (this.linkedSash) {
      this.linkedSash._onDidReset.fire();
    }
    this._onDidReset.fire();
  }
  onTouchStart(event) {
    EventHelper.stop(event);
    const listeners = [];
    const startX = event.pageX;
    const startY = event.pageY;
    const altKey = event.altKey;
    this._onDidStart.fire({
      startX,
      currentX: startX,
      startY,
      currentY: startY,
      altKey
    });
    listeners.push(addDisposableListener(this.el, EventType$1.Change, (event2) => {
      if (isNumber2(event2.pageX) && isNumber2(event2.pageY)) {
        this._onDidChange.fire({
          startX,
          currentX: event2.pageX,
          startY,
          currentY: event2.pageY,
          altKey
        });
      }
    }));
    listeners.push(addDisposableListener(this.el, EventType$1.End, (event2) => {
      this._onDidEnd.fire();
      dispose(listeners);
    }));
  }
  layout() {
    if (this.orientation === 0) {
      const verticalProvider = this.layoutProvider;
      this.el.style.left = verticalProvider.getVerticalSashLeft(this) - this.size / 2 + "px";
      if (verticalProvider.getVerticalSashTop) {
        this.el.style.top = verticalProvider.getVerticalSashTop(this) + "px";
      }
      if (verticalProvider.getVerticalSashHeight) {
        this.el.style.height = verticalProvider.getVerticalSashHeight(this) + "px";
      }
    } else {
      const horizontalProvider = this.layoutProvider;
      this.el.style.top = horizontalProvider.getHorizontalSashTop(this) - this.size / 2 + "px";
      if (horizontalProvider.getHorizontalSashLeft) {
        this.el.style.left = horizontalProvider.getHorizontalSashLeft(this) + "px";
      }
      if (horizontalProvider.getHorizontalSashWidth) {
        this.el.style.width = horizontalProvider.getHorizontalSashWidth(this) + "px";
      }
    }
  }
  hide() {
    this.hidden = true;
    this.el.style.display = "none";
    this.el.setAttribute("aria-hidden", "true");
  }
  onOrthogonalStartSashEnablementChange(state) {
    toggleClass(this.el, "orthogonal-start", state !== 0);
  }
  onOrthogonalEndSashEnablementChange(state) {
    toggleClass(this.el, "orthogonal-end", state !== 0);
  }
  getOrthogonalSash(e2) {
    if (this.orientation === 0) {
      if (e2.offsetY <= this.size) {
        return this.orthogonalStartSash;
      } else if (e2.offsetY >= this.el.clientHeight - this.size) {
        return this.orthogonalEndSash;
      }
    } else {
      if (e2.offsetX <= this.size) {
        return this.orthogonalStartSash;
      } else if (e2.offsetX >= this.el.clientWidth - this.size) {
        return this.orthogonalEndSash;
      }
    }
    return void 0;
  }
  dispose() {
    super.dispose();
    this.el.remove();
  }
};
var SyncDescriptor = class {
  constructor(ctor, staticArguments = [], supportsDelayedInstantiation = false) {
    this.ctor = ctor;
    this.staticArguments = staticArguments;
    this.supportsDelayedInstantiation = supportsDelayedInstantiation;
  }
};
var _registry$1 = [];
function registerSingleton(id3, ctor, supportsDelayedInstantiation) {
  _registry$1.push([id3, new SyncDescriptor(ctor, [], supportsDelayedInstantiation)]);
}
function getSingletonServiceDescriptors() {
  return _registry$1;
}
var IEditorCancellationTokens = createDecorator("IEditorCancelService");
var ctxCancellableOperation = new RawContextKey("cancellableOperation", false);
registerSingleton(IEditorCancellationTokens, class {
  constructor() {
    this._tokens = new WeakMap();
  }
  add(editor2, cts) {
    let data2 = this._tokens.get(editor2);
    if (!data2) {
      data2 = editor2.invokeWithinContext((accessor) => {
        const key = ctxCancellableOperation.bindTo(accessor.get(IContextKeyService));
        const tokens = new LinkedList();
        return {key, tokens};
      });
      this._tokens.set(editor2, data2);
    }
    let removeFn;
    data2.key.set(true);
    removeFn = data2.tokens.push(cts);
    return () => {
      if (removeFn) {
        removeFn();
        data2.key.set(!data2.tokens.isEmpty());
        removeFn = void 0;
      }
    };
  }
  cancel(editor2) {
    const data2 = this._tokens.get(editor2);
    if (!data2) {
      return;
    }
    const cts = data2.tokens.pop();
    if (cts) {
      cts.cancel();
      data2.key.set(!data2.tokens.isEmpty());
    }
  }
}, true);
registerEditorCommand(new class extends EditorCommand {
  constructor() {
    super({
      id: "editor.cancelOperation",
      kbOpts: {
        weight: 100,
        primary: 9
      },
      precondition: ctxCancellableOperation
    });
  }
  runEditorCommand(accessor, editor2) {
    accessor.get(IEditorCancellationTokens).cancel(editor2);
  }
}());
var StableEditorScrollState = class {
  constructor(_visiblePosition, _visiblePositionScrollDelta, _cursorPosition) {
    this._visiblePosition = _visiblePosition;
    this._visiblePositionScrollDelta = _visiblePositionScrollDelta;
    this._cursorPosition = _cursorPosition;
  }
  static capture(editor2) {
    let visiblePosition = null;
    let visiblePositionScrollDelta = 0;
    if (editor2.getScrollTop() !== 0) {
      const visibleRanges = editor2.getVisibleRanges();
      if (visibleRanges.length > 0) {
        visiblePosition = visibleRanges[0].getStartPosition();
        const visiblePositionScrollTop = editor2.getTopForPosition(visiblePosition.lineNumber, visiblePosition.column);
        visiblePositionScrollDelta = editor2.getScrollTop() - visiblePositionScrollTop;
      }
    }
    return new StableEditorScrollState(visiblePosition, visiblePositionScrollDelta, editor2.getPosition());
  }
  restore(editor2) {
    if (this._visiblePosition) {
      const visiblePositionScrollTop = editor2.getTopForPosition(this._visiblePosition.lineNumber, this._visiblePosition.column);
      editor2.setScrollTop(visiblePositionScrollTop + this._visiblePositionScrollDelta);
    }
  }
  restoreRelativeVerticalPositionOfCursor(editor2) {
    const currentCursorPosition = editor2.getPosition();
    if (!this._cursorPosition || !currentCursorPosition) {
      return;
    }
    const offset2 = editor2.getTopForLineNumber(currentCursorPosition.lineNumber) - editor2.getTopForLineNumber(this._cursorPosition.lineNumber);
    editor2.setScrollTop(editor2.getScrollTop() + offset2);
  }
};
function __snowpack__injectStyle$m(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$m("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-diff-editor .diff-review-line-number {\r\n	text-align: right;\r\n	display: inline-block;\r\n}\r\n\r\n.monaco-diff-editor .diff-review {\r\n	position: absolute;\r\n	user-select: none;\r\n	-webkit-user-select: none;\r\n	-ms-user-select: none;\r\n}\r\n\r\n.monaco-diff-editor .diff-review-summary {\r\n	padding-left: 10px;\r\n}\r\n\r\n.monaco-diff-editor .diff-review-shadow {\r\n	position: absolute;\r\n}\r\n\r\n.monaco-diff-editor .diff-review-row {\r\n	white-space: pre;\r\n}\r\n\r\n.monaco-diff-editor .diff-review-table {\r\n	display: table;\r\n	min-width: 100%;\r\n}\r\n\r\n.monaco-diff-editor .diff-review-row {\r\n	display: table-row;\r\n	width: 100%;\r\n}\r\n\r\n.monaco-diff-editor .diff-review-spacer {\r\n	display: inline-block;\r\n	width: 10px;\r\n	vertical-align: middle;\r\n}\r\n\r\n.monaco-diff-editor .diff-review-spacer > .codicon {\r\n	font-size: 9px !important;\r\n}\r\n\r\n.monaco-diff-editor .diff-review-actions {\r\n	display: inline-block;\r\n	position: absolute;\r\n	right: 10px;\r\n	top: 2px;\r\n}\r\n\r\n.monaco-diff-editor .diff-review-actions .action-label {\r\n	width: 16px;\r\n	height: 16px;\r\n	margin: 2px 0;\r\n}\r\n");
function __snowpack__injectStyle$n(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$n("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-action-bar {\r\n	text-align: right;\r\n	white-space: nowrap;\r\n}\r\n\r\n.monaco-action-bar .actions-container {\r\n	display: flex;\r\n	margin: 0 auto;\r\n	padding: 0;\r\n	width: 100%;\r\n	justify-content: flex-end;\r\n}\r\n\r\n.monaco-action-bar.vertical .actions-container {\r\n	display: inline-block;\r\n}\r\n\r\n.monaco-action-bar.reverse .actions-container {\r\n	flex-direction: row-reverse;\r\n}\r\n\r\n.monaco-action-bar .action-item {\r\n	cursor: pointer;\r\n	display: inline-block;\r\n	transition: transform 50ms ease;\r\n	position: relative;  /* DO NOT REMOVE - this is the key to preventing the ghosting icon bug in Chrome 42 */\r\n}\r\n\r\n.monaco-action-bar .action-item.disabled {\r\n	cursor: default;\r\n}\r\n\r\n.monaco-action-bar.animated .action-item.active {\r\n	transform: scale(1.272019649, 1.272019649); /* 1.272019649 = √φ */\r\n}\r\n\r\n.monaco-action-bar .action-item .icon,\r\n.monaco-action-bar .action-item .codicon {\r\n	display: inline-block;\r\n}\r\n\r\n.monaco-action-bar .action-item .codicon {\r\n	display: flex;\r\n	align-items: center;\r\n}\r\n\r\n.monaco-action-bar .action-label {\r\n	font-size: 11px;\r\n	margin-right: 4px;\r\n}\r\n\r\n.monaco-action-bar .action-item.disabled .action-label,\r\n.monaco-action-bar .action-item.disabled .action-label:hover {\r\n	opacity: 0.4;\r\n}\r\n\r\n/* Vertical actions */\r\n\r\n.monaco-action-bar.vertical {\r\n	text-align: left;\r\n}\r\n\r\n.monaco-action-bar.vertical .action-item {\r\n	display: block;\r\n}\r\n\r\n.monaco-action-bar.vertical .action-label.separator {\r\n	display: block;\r\n	border-bottom: 1px solid #bbb;\r\n	padding-top: 1px;\r\n	margin-left: .8em;\r\n	margin-right: .8em;\r\n}\r\n\r\n.monaco-action-bar.animated.vertical .action-item.active {\r\n	transform: translate(5px, 0);\r\n}\r\n\r\n.secondary-actions .monaco-action-bar .action-label {\r\n	margin-left: 6px;\r\n}\r\n\r\n/* Action Items */\r\n.monaco-action-bar .action-item.select-container {\r\n	overflow: hidden; /* somehow the dropdown overflows its container, we prevent it here to not push */\r\n	flex: 1;\r\n	max-width: 170px;\r\n	min-width: 60px;\r\n	display: flex;\r\n	align-items: center;\r\n	justify-content: center;\r\n	margin-right: 10px;\r\n}\r\n");
var DataTransfers = {
  RESOURCES: "ResourceURLs",
  DOWNLOAD_URL: "DownloadURL",
  FILES: "Files",
  TEXT: "text/plain"
};
var DragAndDropData = class {
  constructor(data2) {
    this.data = data2;
  }
  update() {
  }
  getData() {
    return this.data;
  }
};
var StaticDND = {
  CurrentDragAndDropData: void 0
};
var BaseActionViewItem = class extends Disposable {
  constructor(context2, action, options = {}) {
    super();
    this.options = options;
    this._context = context2 || this;
    this._action = action;
    if (action instanceof Action) {
      this._register(action.onDidChange((event) => {
        if (!this.element) {
          return;
        }
        this.handleActionChangeEvent(event);
      }));
    }
  }
  handleActionChangeEvent(event) {
    if (event.enabled !== void 0) {
      this.updateEnabled();
    }
    if (event.checked !== void 0) {
      this.updateChecked();
    }
    if (event.class !== void 0) {
      this.updateClass();
    }
    if (event.label !== void 0) {
      this.updateLabel();
      this.updateTooltip();
    }
    if (event.tooltip !== void 0) {
      this.updateTooltip();
    }
  }
  get actionRunner() {
    if (!this._actionRunner) {
      this._actionRunner = this._register(new ActionRunner());
    }
    return this._actionRunner;
  }
  set actionRunner(actionRunner) {
    this._actionRunner = actionRunner;
  }
  getAction() {
    return this._action;
  }
  isEnabled() {
    return this._action.enabled;
  }
  setActionContext(newContext) {
    this._context = newContext;
  }
  render(container) {
    const element = this.element = container;
    this._register(Gesture.addTarget(container));
    const enableDragging = this.options && this.options.draggable;
    if (enableDragging) {
      container.draggable = true;
      if (isFirefox) {
        this._register(addDisposableListener(container, EventType.DRAG_START, (e2) => {
          var _a;
          return (_a = e2.dataTransfer) === null || _a === void 0 ? void 0 : _a.setData(DataTransfers.TEXT, this._action.label);
        }));
      }
    }
    this._register(addDisposableListener(element, EventType$1.Tap, (e2) => this.onClick(e2)));
    this._register(addDisposableListener(element, EventType.MOUSE_DOWN, (e2) => {
      if (!enableDragging) {
        EventHelper.stop(e2, true);
      }
      if (this._action.enabled && e2.button === 0) {
        addClass(element, "active");
      }
    }));
    if (isMacintosh) {
      this._register(addDisposableListener(element, EventType.CONTEXT_MENU, (e2) => {
        if (e2.button === 0 && e2.ctrlKey === true) {
          this.onClick(e2);
        }
      }));
    }
    this._register(addDisposableListener(element, EventType.CLICK, (e2) => {
      EventHelper.stop(e2, true);
      if (!(this.options && this.options.isMenu)) {
        setImmediate(() => this.onClick(e2));
      }
    }));
    this._register(addDisposableListener(element, EventType.DBLCLICK, (e2) => {
      EventHelper.stop(e2, true);
    }));
    [EventType.MOUSE_UP, EventType.MOUSE_OUT].forEach((event) => {
      this._register(addDisposableListener(element, event, (e2) => {
        EventHelper.stop(e2);
        removeClass(element, "active");
      }));
    });
  }
  onClick(event) {
    var _a;
    EventHelper.stop(event, true);
    const context2 = isUndefinedOrNull(this._context) ? ((_a = this.options) === null || _a === void 0 ? void 0 : _a.useEventAsContext) ? event : void 0 : this._context;
    this.actionRunner.run(this._action, context2);
  }
  focus() {
    if (this.element) {
      this.element.focus();
      addClass(this.element, "focused");
    }
  }
  blur() {
    if (this.element) {
      this.element.blur();
      removeClass(this.element, "focused");
    }
  }
  updateEnabled() {
  }
  updateLabel() {
  }
  updateTooltip() {
  }
  updateClass() {
  }
  updateChecked() {
  }
  dispose() {
    if (this.element) {
      removeNode(this.element);
      this.element = void 0;
    }
    super.dispose();
  }
};
var ActionViewItem = class extends BaseActionViewItem {
  constructor(context2, action, options = {}) {
    super(context2, action, options);
    this.options = options;
    this.options.icon = options.icon !== void 0 ? options.icon : false;
    this.options.label = options.label !== void 0 ? options.label : true;
    this.cssClass = "";
  }
  render(container) {
    super.render(container);
    if (this.element) {
      this.label = append(this.element, $("a.action-label"));
    }
    if (this.label) {
      if (this._action.id === Separator.ID) {
        this.label.setAttribute("role", "presentation");
      } else {
        if (this.options.isMenu) {
          this.label.setAttribute("role", "menuitem");
        } else {
          this.label.setAttribute("role", "button");
        }
      }
    }
    if (this.options.label && this.options.keybinding && this.element) {
      append(this.element, $("span.keybinding")).textContent = this.options.keybinding;
    }
    this.updateClass();
    this.updateLabel();
    this.updateTooltip();
    this.updateEnabled();
    this.updateChecked();
  }
  focus() {
    super.focus();
    if (this.label) {
      this.label.focus();
    }
  }
  updateLabel() {
    if (this.options.label && this.label) {
      this.label.textContent = this.getAction().label;
    }
  }
  updateTooltip() {
    let title3 = null;
    if (this.getAction().tooltip) {
      title3 = this.getAction().tooltip;
    } else if (!this.options.label && this.getAction().label && this.options.icon) {
      title3 = this.getAction().label;
      if (this.options.keybinding) {
        title3 = localize({key: "titleLabel", comment: ["action title", "action keybinding"]}, "{0} ({1})", title3, this.options.keybinding);
      }
    }
    if (title3 && this.label) {
      this.label.title = title3;
    }
  }
  updateClass() {
    if (this.cssClass && this.label) {
      removeClasses(this.label, this.cssClass);
    }
    if (this.options.icon) {
      this.cssClass = this.getAction().class;
      if (this.label) {
        addClass(this.label, "codicon");
        if (this.cssClass) {
          addClasses(this.label, this.cssClass);
        }
      }
      this.updateEnabled();
    } else {
      if (this.label) {
        removeClass(this.label, "codicon");
      }
    }
  }
  updateEnabled() {
    if (this.getAction().enabled) {
      if (this.label) {
        this.label.removeAttribute("aria-disabled");
        removeClass(this.label, "disabled");
        this.label.tabIndex = 0;
      }
      if (this.element) {
        removeClass(this.element, "disabled");
      }
    } else {
      if (this.label) {
        this.label.setAttribute("aria-disabled", "true");
        addClass(this.label, "disabled");
        removeTabIndexAndUpdateFocus(this.label);
      }
      if (this.element) {
        addClass(this.element, "disabled");
      }
    }
  }
  updateChecked() {
    if (this.label) {
      if (this.getAction().checked) {
        addClass(this.label, "checked");
      } else {
        removeClass(this.label, "checked");
      }
    }
  }
};
var ActionBar = class extends Disposable {
  constructor(container, options = {}) {
    var _a, _b, _c;
    super();
    this._onDidBlur = this._register(new Emitter());
    this.onDidBlur = this._onDidBlur.event;
    this._onDidCancel = this._register(new Emitter());
    this.onDidCancel = this._onDidCancel.event;
    this._onDidRun = this._register(new Emitter());
    this.onDidRun = this._onDidRun.event;
    this._onDidBeforeRun = this._register(new Emitter());
    this.onDidBeforeRun = this._onDidBeforeRun.event;
    this.options = options;
    this._context = (_a = options.context) !== null && _a !== void 0 ? _a : null;
    this._orientation = (_b = this.options.orientation) !== null && _b !== void 0 ? _b : 0;
    this._triggerKeys = (_c = this.options.triggerKeys) !== null && _c !== void 0 ? _c : {
      keys: [3, 10],
      keyDown: false
    };
    if (this.options.actionRunner) {
      this._actionRunner = this.options.actionRunner;
    } else {
      this._actionRunner = new ActionRunner();
      this._register(this._actionRunner);
    }
    this._register(this._actionRunner.onDidRun((e2) => this._onDidRun.fire(e2)));
    this._register(this._actionRunner.onDidBeforeRun((e2) => this._onDidBeforeRun.fire(e2)));
    this.viewItems = [];
    this.focusedItem = void 0;
    this.domNode = document.createElement("div");
    this.domNode.className = "monaco-action-bar";
    if (options.animated !== false) {
      addClass(this.domNode, "animated");
    }
    let previousKey;
    let nextKey;
    switch (this._orientation) {
      case 0:
        previousKey = 15;
        nextKey = 17;
        break;
      case 1:
        previousKey = 17;
        nextKey = 15;
        this.domNode.className += " reverse";
        break;
      case 2:
        previousKey = 16;
        nextKey = 18;
        this.domNode.className += " vertical";
        break;
      case 3:
        previousKey = 18;
        nextKey = 16;
        this.domNode.className += " vertical reverse";
        break;
    }
    this._register(addDisposableListener(this.domNode, EventType.KEY_DOWN, (e2) => {
      const event = new StandardKeyboardEvent(e2);
      let eventHandled = true;
      if (event.equals(previousKey)) {
        eventHandled = this.focusPrevious();
      } else if (event.equals(nextKey)) {
        eventHandled = this.focusNext();
      } else if (event.equals(9)) {
        this._onDidCancel.fire();
      } else if (this.isTriggerKeyEvent(event)) {
        if (this._triggerKeys.keyDown) {
          this.doTrigger(event);
        }
      } else {
        eventHandled = false;
      }
      if (eventHandled) {
        event.preventDefault();
        event.stopPropagation();
      }
    }));
    this._register(addDisposableListener(this.domNode, EventType.KEY_UP, (e2) => {
      const event = new StandardKeyboardEvent(e2);
      if (this.isTriggerKeyEvent(event)) {
        if (!this._triggerKeys.keyDown) {
          this.doTrigger(event);
        }
        event.preventDefault();
        event.stopPropagation();
      } else if (event.equals(2) || event.equals(1024 | 2)) {
        this.updateFocusedItem();
      }
    }));
    this.focusTracker = this._register(trackFocus(this.domNode));
    this._register(this.focusTracker.onDidBlur(() => {
      if (getActiveElement() === this.domNode || !isAncestor(getActiveElement(), this.domNode)) {
        this._onDidBlur.fire();
        this.focusedItem = void 0;
      }
    }));
    this._register(this.focusTracker.onDidFocus(() => this.updateFocusedItem()));
    this.actionsList = document.createElement("ul");
    this.actionsList.className = "actions-container";
    this.actionsList.setAttribute("role", "toolbar");
    if (this.options.ariaLabel) {
      this.actionsList.setAttribute("aria-label", this.options.ariaLabel);
    }
    this.domNode.appendChild(this.actionsList);
    container.appendChild(this.domNode);
  }
  isTriggerKeyEvent(event) {
    let ret = false;
    this._triggerKeys.keys.forEach((keyCode) => {
      ret = ret || event.equals(keyCode);
    });
    return ret;
  }
  updateFocusedItem() {
    for (let i3 = 0; i3 < this.actionsList.children.length; i3++) {
      const elem = this.actionsList.children[i3];
      if (isAncestor(getActiveElement(), elem)) {
        this.focusedItem = i3;
        break;
      }
    }
  }
  get context() {
    return this._context;
  }
  set context(context2) {
    this._context = context2;
    this.viewItems.forEach((i3) => i3.setActionContext(context2));
  }
  get actionRunner() {
    return this._actionRunner;
  }
  set actionRunner(actionRunner) {
    if (actionRunner) {
      this._actionRunner = actionRunner;
      this.viewItems.forEach((item) => item.actionRunner = actionRunner);
    }
  }
  getContainer() {
    return this.domNode;
  }
  push(arg, options = {}) {
    const actions2 = Array.isArray(arg) ? arg : [arg];
    let index3 = isNumber2(options.index) ? options.index : null;
    actions2.forEach((action) => {
      const actionViewItemElement = document.createElement("li");
      actionViewItemElement.className = "action-item";
      actionViewItemElement.setAttribute("role", "presentation");
      if (!this.options.allowContextMenu) {
        this._register(addDisposableListener(actionViewItemElement, EventType.CONTEXT_MENU, (e2) => {
          EventHelper.stop(e2, true);
        }));
      }
      let item;
      if (this.options.actionViewItemProvider) {
        item = this.options.actionViewItemProvider(action);
      }
      if (!item) {
        item = new ActionViewItem(this.context, action, options);
      }
      item.actionRunner = this._actionRunner;
      item.setActionContext(this.context);
      item.render(actionViewItemElement);
      if (index3 === null || index3 < 0 || index3 >= this.actionsList.children.length) {
        this.actionsList.appendChild(actionViewItemElement);
        this.viewItems.push(item);
      } else {
        this.actionsList.insertBefore(actionViewItemElement, this.actionsList.children[index3]);
        this.viewItems.splice(index3, 0, item);
        index3++;
      }
    });
    if (this.focusedItem) {
      this.focus(this.focusedItem);
    }
  }
  clear() {
    dispose(this.viewItems);
    this.viewItems = [];
    clearNode(this.actionsList);
  }
  focus(arg) {
    let selectFirst = false;
    let index3 = void 0;
    if (arg === void 0) {
      selectFirst = true;
    } else if (typeof arg === "number") {
      index3 = arg;
    } else if (typeof arg === "boolean") {
      selectFirst = arg;
    }
    if (selectFirst && typeof this.focusedItem === "undefined") {
      this.focusedItem = -1;
      this.focusNext();
    } else {
      if (index3 !== void 0) {
        this.focusedItem = index3;
      }
      this.updateFocus();
    }
  }
  focusNext() {
    if (typeof this.focusedItem === "undefined") {
      this.focusedItem = this.viewItems.length - 1;
    }
    const startIndex = this.focusedItem;
    let item;
    do {
      if (this.options.preventLoopNavigation && this.focusedItem + 1 >= this.viewItems.length) {
        this.focusedItem = startIndex;
        return false;
      }
      this.focusedItem = (this.focusedItem + 1) % this.viewItems.length;
      item = this.viewItems[this.focusedItem];
    } while (this.focusedItem !== startIndex && !item.isEnabled());
    if (this.focusedItem === startIndex && !item.isEnabled()) {
      this.focusedItem = void 0;
    }
    this.updateFocus();
    return true;
  }
  focusPrevious() {
    if (typeof this.focusedItem === "undefined") {
      this.focusedItem = 0;
    }
    const startIndex = this.focusedItem;
    let item;
    do {
      this.focusedItem = this.focusedItem - 1;
      if (this.focusedItem < 0) {
        if (this.options.preventLoopNavigation) {
          this.focusedItem = startIndex;
          return false;
        }
        this.focusedItem = this.viewItems.length - 1;
      }
      item = this.viewItems[this.focusedItem];
    } while (this.focusedItem !== startIndex && !item.isEnabled());
    if (this.focusedItem === startIndex && !item.isEnabled()) {
      this.focusedItem = void 0;
    }
    this.updateFocus(true);
    return true;
  }
  updateFocus(fromRight, preventScroll) {
    if (typeof this.focusedItem === "undefined") {
      this.actionsList.focus({preventScroll});
    }
    for (let i3 = 0; i3 < this.viewItems.length; i3++) {
      const item = this.viewItems[i3];
      const actionViewItem = item;
      if (i3 === this.focusedItem) {
        if (isFunction3(actionViewItem.isEnabled)) {
          if (actionViewItem.isEnabled() && isFunction3(actionViewItem.focus)) {
            actionViewItem.focus(fromRight);
          } else {
            this.actionsList.focus({preventScroll});
          }
        }
      } else {
        if (isFunction3(actionViewItem.blur)) {
          actionViewItem.blur();
        }
      }
    }
  }
  doTrigger(event) {
    if (typeof this.focusedItem === "undefined") {
      return;
    }
    const actionViewItem = this.viewItems[this.focusedItem];
    if (actionViewItem instanceof BaseActionViewItem) {
      const context2 = actionViewItem._context === null || actionViewItem._context === void 0 ? event : actionViewItem._context;
      this.run(actionViewItem._action, context2);
    }
  }
  run(action, context2) {
    return this._actionRunner.run(action, context2);
  }
  dispose() {
    dispose(this.viewItems);
    this.viewItems = [];
    removeNode(this.getContainer());
    super.dispose();
  }
};
var DIFF_LINES_PADDING = 3;
var DiffEntry = class {
  constructor(originalLineStart, originalLineEnd, modifiedLineStart, modifiedLineEnd) {
    this.originalLineStart = originalLineStart;
    this.originalLineEnd = originalLineEnd;
    this.modifiedLineStart = modifiedLineStart;
    this.modifiedLineEnd = modifiedLineEnd;
  }
  getType() {
    if (this.originalLineStart === 0) {
      return 1;
    }
    if (this.modifiedLineStart === 0) {
      return 2;
    }
    return 0;
  }
};
var Diff = class {
  constructor(entries) {
    this.entries = entries;
  }
};
var diffReviewInsertIcon = registerIcon("diff-review-insert", Codicon.add);
var diffReviewRemoveIcon = registerIcon("diff-review-remove", Codicon.remove);
var diffReviewCloseIcon = registerIcon("diff-review-close", Codicon.close);
var DiffReview = class extends Disposable {
  constructor(diffEditor) {
    super();
    this._width = 0;
    this._diffEditor = diffEditor;
    this._isVisible = false;
    this.shadow = createFastDomNode(document.createElement("div"));
    this.shadow.setClassName("diff-review-shadow");
    this.actionBarContainer = createFastDomNode(document.createElement("div"));
    this.actionBarContainer.setClassName("diff-review-actions");
    this._actionBar = this._register(new ActionBar(this.actionBarContainer.domNode));
    this._actionBar.push(new Action("diffreview.close", localize("label.close", "Close"), "close-diff-review " + diffReviewCloseIcon.classNames, true, () => {
      this.hide();
      return Promise.resolve(null);
    }), {label: false, icon: true});
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setClassName("diff-review monaco-editor-background");
    this._content = createFastDomNode(document.createElement("div"));
    this._content.setClassName("diff-review-content");
    this._content.setAttribute("role", "code");
    this.scrollbar = this._register(new DomScrollableElement(this._content.domNode, {}));
    this.domNode.domNode.appendChild(this.scrollbar.getDomNode());
    this._register(diffEditor.onDidUpdateDiff(() => {
      if (!this._isVisible) {
        return;
      }
      this._diffs = this._compute();
      this._render();
    }));
    this._register(diffEditor.getModifiedEditor().onDidChangeCursorPosition(() => {
      if (!this._isVisible) {
        return;
      }
      this._render();
    }));
    this._register(addStandardDisposableListener(this.domNode.domNode, "click", (e2) => {
      e2.preventDefault();
      let row = findParentWithClass(e2.target, "diff-review-row");
      if (row) {
        this._goToRow(row);
      }
    }));
    this._register(addStandardDisposableListener(this.domNode.domNode, "keydown", (e2) => {
      if (e2.equals(18) || e2.equals(2048 | 18) || e2.equals(512 | 18)) {
        e2.preventDefault();
        this._goToRow(this._getNextRow());
      }
      if (e2.equals(16) || e2.equals(2048 | 16) || e2.equals(512 | 16)) {
        e2.preventDefault();
        this._goToRow(this._getPrevRow());
      }
      if (e2.equals(9) || e2.equals(2048 | 9) || e2.equals(512 | 9) || e2.equals(1024 | 9)) {
        e2.preventDefault();
        this.hide();
      }
      if (e2.equals(10) || e2.equals(3)) {
        e2.preventDefault();
        this.accept();
      }
    }));
    this._diffs = [];
    this._currentDiff = null;
  }
  prev() {
    let index3 = 0;
    if (!this._isVisible) {
      this._diffs = this._compute();
    }
    if (this._isVisible) {
      let currentIndex = -1;
      for (let i3 = 0, len2 = this._diffs.length; i3 < len2; i3++) {
        if (this._diffs[i3] === this._currentDiff) {
          currentIndex = i3;
          break;
        }
      }
      index3 = this._diffs.length + currentIndex - 1;
    } else {
      index3 = this._findDiffIndex(this._diffEditor.getPosition());
    }
    if (this._diffs.length === 0) {
      return;
    }
    index3 = index3 % this._diffs.length;
    const entries = this._diffs[index3].entries;
    this._diffEditor.setPosition(new Position(entries[0].modifiedLineStart, 1));
    this._diffEditor.setSelection({startColumn: 1, startLineNumber: entries[0].modifiedLineStart, endColumn: 1073741824, endLineNumber: entries[entries.length - 1].modifiedLineEnd});
    this._isVisible = true;
    this._diffEditor.doLayout();
    this._render();
    this._goToRow(this._getNextRow());
  }
  next() {
    let index3 = 0;
    if (!this._isVisible) {
      this._diffs = this._compute();
    }
    if (this._isVisible) {
      let currentIndex = -1;
      for (let i3 = 0, len2 = this._diffs.length; i3 < len2; i3++) {
        if (this._diffs[i3] === this._currentDiff) {
          currentIndex = i3;
          break;
        }
      }
      index3 = currentIndex + 1;
    } else {
      index3 = this._findDiffIndex(this._diffEditor.getPosition());
    }
    if (this._diffs.length === 0) {
      return;
    }
    index3 = index3 % this._diffs.length;
    const entries = this._diffs[index3].entries;
    this._diffEditor.setPosition(new Position(entries[0].modifiedLineStart, 1));
    this._diffEditor.setSelection({startColumn: 1, startLineNumber: entries[0].modifiedLineStart, endColumn: 1073741824, endLineNumber: entries[entries.length - 1].modifiedLineEnd});
    this._isVisible = true;
    this._diffEditor.doLayout();
    this._render();
    this._goToRow(this._getNextRow());
  }
  accept() {
    let jumpToLineNumber = -1;
    let current = this._getCurrentFocusedRow();
    if (current) {
      let lineNumber = parseInt(current.getAttribute("data-line"), 10);
      if (!isNaN(lineNumber)) {
        jumpToLineNumber = lineNumber;
      }
    }
    this.hide();
    if (jumpToLineNumber !== -1) {
      this._diffEditor.setPosition(new Position(jumpToLineNumber, 1));
      this._diffEditor.revealPosition(new Position(jumpToLineNumber, 1), 1);
    }
  }
  hide() {
    this._isVisible = false;
    this._diffEditor.updateOptions({readOnly: false});
    this._diffEditor.focus();
    this._diffEditor.doLayout();
    this._render();
  }
  _getPrevRow() {
    let current = this._getCurrentFocusedRow();
    if (!current) {
      return this._getFirstRow();
    }
    if (current.previousElementSibling) {
      return current.previousElementSibling;
    }
    return current;
  }
  _getNextRow() {
    let current = this._getCurrentFocusedRow();
    if (!current) {
      return this._getFirstRow();
    }
    if (current.nextElementSibling) {
      return current.nextElementSibling;
    }
    return current;
  }
  _getFirstRow() {
    return this.domNode.domNode.querySelector(".diff-review-row");
  }
  _getCurrentFocusedRow() {
    let result = document.activeElement;
    if (result && /diff-review-row/.test(result.className)) {
      return result;
    }
    return null;
  }
  _goToRow(row) {
    let prev = this._getCurrentFocusedRow();
    row.tabIndex = 0;
    row.focus();
    if (prev && prev !== row) {
      prev.tabIndex = -1;
    }
    this.scrollbar.scanDomNode();
  }
  isVisible() {
    return this._isVisible;
  }
  layout(top2, width2, height) {
    this._width = width2;
    this.shadow.setTop(top2 - 6);
    this.shadow.setWidth(width2);
    this.shadow.setHeight(this._isVisible ? 6 : 0);
    this.domNode.setTop(top2);
    this.domNode.setWidth(width2);
    this.domNode.setHeight(height);
    this._content.setHeight(height);
    this._content.setWidth(width2);
    if (this._isVisible) {
      this.actionBarContainer.setAttribute("aria-hidden", "false");
      this.actionBarContainer.setDisplay("block");
    } else {
      this.actionBarContainer.setAttribute("aria-hidden", "true");
      this.actionBarContainer.setDisplay("none");
    }
  }
  _compute() {
    const lineChanges = this._diffEditor.getLineChanges();
    if (!lineChanges || lineChanges.length === 0) {
      return [];
    }
    const originalModel = this._diffEditor.getOriginalEditor().getModel();
    const modifiedModel = this._diffEditor.getModifiedEditor().getModel();
    if (!originalModel || !modifiedModel) {
      return [];
    }
    return DiffReview._mergeAdjacent(lineChanges, originalModel.getLineCount(), modifiedModel.getLineCount());
  }
  static _mergeAdjacent(lineChanges, originalLineCount, modifiedLineCount) {
    if (!lineChanges || lineChanges.length === 0) {
      return [];
    }
    let diffs = [], diffsLength = 0;
    for (let i3 = 0, len2 = lineChanges.length; i3 < len2; i3++) {
      const lineChange = lineChanges[i3];
      const originalStart = lineChange.originalStartLineNumber;
      const originalEnd = lineChange.originalEndLineNumber;
      const modifiedStart = lineChange.modifiedStartLineNumber;
      const modifiedEnd = lineChange.modifiedEndLineNumber;
      let r4 = [], rLength2 = 0;
      {
        const originalEqualAbove = originalEnd === 0 ? originalStart : originalStart - 1;
        const modifiedEqualAbove = modifiedEnd === 0 ? modifiedStart : modifiedStart - 1;
        let minOriginal = 1;
        let minModified = 1;
        if (i3 > 0) {
          const prevLineChange = lineChanges[i3 - 1];
          if (prevLineChange.originalEndLineNumber === 0) {
            minOriginal = prevLineChange.originalStartLineNumber + 1;
          } else {
            minOriginal = prevLineChange.originalEndLineNumber + 1;
          }
          if (prevLineChange.modifiedEndLineNumber === 0) {
            minModified = prevLineChange.modifiedStartLineNumber + 1;
          } else {
            minModified = prevLineChange.modifiedEndLineNumber + 1;
          }
        }
        let fromOriginal = originalEqualAbove - DIFF_LINES_PADDING + 1;
        let fromModified = modifiedEqualAbove - DIFF_LINES_PADDING + 1;
        if (fromOriginal < minOriginal) {
          const delta = minOriginal - fromOriginal;
          fromOriginal = fromOriginal + delta;
          fromModified = fromModified + delta;
        }
        if (fromModified < minModified) {
          const delta = minModified - fromModified;
          fromOriginal = fromOriginal + delta;
          fromModified = fromModified + delta;
        }
        r4[rLength2++] = new DiffEntry(fromOriginal, originalEqualAbove, fromModified, modifiedEqualAbove);
      }
      {
        if (originalEnd !== 0) {
          r4[rLength2++] = new DiffEntry(originalStart, originalEnd, 0, 0);
        }
      }
      {
        if (modifiedEnd !== 0) {
          r4[rLength2++] = new DiffEntry(0, 0, modifiedStart, modifiedEnd);
        }
      }
      {
        const originalEqualBelow = originalEnd === 0 ? originalStart + 1 : originalEnd + 1;
        const modifiedEqualBelow = modifiedEnd === 0 ? modifiedStart + 1 : modifiedEnd + 1;
        let maxOriginal = originalLineCount;
        let maxModified = modifiedLineCount;
        if (i3 + 1 < len2) {
          const nextLineChange = lineChanges[i3 + 1];
          if (nextLineChange.originalEndLineNumber === 0) {
            maxOriginal = nextLineChange.originalStartLineNumber;
          } else {
            maxOriginal = nextLineChange.originalStartLineNumber - 1;
          }
          if (nextLineChange.modifiedEndLineNumber === 0) {
            maxModified = nextLineChange.modifiedStartLineNumber;
          } else {
            maxModified = nextLineChange.modifiedStartLineNumber - 1;
          }
        }
        let toOriginal = originalEqualBelow + DIFF_LINES_PADDING - 1;
        let toModified = modifiedEqualBelow + DIFF_LINES_PADDING - 1;
        if (toOriginal > maxOriginal) {
          const delta = maxOriginal - toOriginal;
          toOriginal = toOriginal + delta;
          toModified = toModified + delta;
        }
        if (toModified > maxModified) {
          const delta = maxModified - toModified;
          toOriginal = toOriginal + delta;
          toModified = toModified + delta;
        }
        r4[rLength2++] = new DiffEntry(originalEqualBelow, toOriginal, modifiedEqualBelow, toModified);
      }
      diffs[diffsLength++] = new Diff(r4);
    }
    let curr = diffs[0].entries;
    let r3 = [], rLength = 0;
    for (let i3 = 1, len2 = diffs.length; i3 < len2; i3++) {
      const thisDiff = diffs[i3].entries;
      const currLast = curr[curr.length - 1];
      const thisFirst = thisDiff[0];
      if (currLast.getType() === 0 && thisFirst.getType() === 0 && thisFirst.originalLineStart <= currLast.originalLineEnd) {
        curr[curr.length - 1] = new DiffEntry(currLast.originalLineStart, thisFirst.originalLineEnd, currLast.modifiedLineStart, thisFirst.modifiedLineEnd);
        curr = curr.concat(thisDiff.slice(1));
        continue;
      }
      r3[rLength++] = new Diff(curr);
      curr = thisDiff;
    }
    r3[rLength++] = new Diff(curr);
    return r3;
  }
  _findDiffIndex(pos) {
    const lineNumber = pos.lineNumber;
    for (let i3 = 0, len2 = this._diffs.length; i3 < len2; i3++) {
      const diff = this._diffs[i3].entries;
      const lastModifiedLine = diff[diff.length - 1].modifiedLineEnd;
      if (lineNumber <= lastModifiedLine) {
        return i3;
      }
    }
    return 0;
  }
  _render() {
    const originalOptions = this._diffEditor.getOriginalEditor().getOptions();
    const modifiedOptions = this._diffEditor.getModifiedEditor().getOptions();
    const originalModel = this._diffEditor.getOriginalEditor().getModel();
    const modifiedModel = this._diffEditor.getModifiedEditor().getModel();
    const originalModelOpts = originalModel.getOptions();
    const modifiedModelOpts = modifiedModel.getOptions();
    if (!this._isVisible || !originalModel || !modifiedModel) {
      clearNode(this._content.domNode);
      this._currentDiff = null;
      this.scrollbar.scanDomNode();
      return;
    }
    this._diffEditor.updateOptions({readOnly: true});
    const diffIndex = this._findDiffIndex(this._diffEditor.getPosition());
    if (this._diffs[diffIndex] === this._currentDiff) {
      return;
    }
    this._currentDiff = this._diffs[diffIndex];
    const diffs = this._diffs[diffIndex].entries;
    let container = document.createElement("div");
    container.className = "diff-review-table";
    container.setAttribute("role", "list");
    container.setAttribute("aria-label", 'Difference review. Use "Stage | Unstage | Revert Selected Ranges" commands');
    Configuration$1.applyFontInfoSlow(container, modifiedOptions.get(36));
    let minOriginalLine = 0;
    let maxOriginalLine = 0;
    let minModifiedLine = 0;
    let maxModifiedLine = 0;
    for (let i3 = 0, len2 = diffs.length; i3 < len2; i3++) {
      const diffEntry = diffs[i3];
      const originalLineStart = diffEntry.originalLineStart;
      const originalLineEnd = diffEntry.originalLineEnd;
      const modifiedLineStart = diffEntry.modifiedLineStart;
      const modifiedLineEnd = diffEntry.modifiedLineEnd;
      if (originalLineStart !== 0 && (minOriginalLine === 0 || originalLineStart < minOriginalLine)) {
        minOriginalLine = originalLineStart;
      }
      if (originalLineEnd !== 0 && (maxOriginalLine === 0 || originalLineEnd > maxOriginalLine)) {
        maxOriginalLine = originalLineEnd;
      }
      if (modifiedLineStart !== 0 && (minModifiedLine === 0 || modifiedLineStart < minModifiedLine)) {
        minModifiedLine = modifiedLineStart;
      }
      if (modifiedLineEnd !== 0 && (maxModifiedLine === 0 || modifiedLineEnd > maxModifiedLine)) {
        maxModifiedLine = modifiedLineEnd;
      }
    }
    let header = document.createElement("div");
    header.className = "diff-review-row";
    let cell = document.createElement("div");
    cell.className = "diff-review-cell diff-review-summary";
    const originalChangedLinesCnt = maxOriginalLine - minOriginalLine + 1;
    const modifiedChangedLinesCnt = maxModifiedLine - minModifiedLine + 1;
    cell.appendChild(document.createTextNode(`${diffIndex + 1}/${this._diffs.length}: @@ -${minOriginalLine},${originalChangedLinesCnt} +${minModifiedLine},${modifiedChangedLinesCnt} @@`));
    header.setAttribute("data-line", String(minModifiedLine));
    const getAriaLines = (lines) => {
      if (lines === 0) {
        return localize("no_lines_changed", "no lines changed");
      } else if (lines === 1) {
        return localize("one_line_changed", "1 line changed");
      } else {
        return localize("more_lines_changed", "{0} lines changed", lines);
      }
    };
    const originalChangedLinesCntAria = getAriaLines(originalChangedLinesCnt);
    const modifiedChangedLinesCntAria = getAriaLines(modifiedChangedLinesCnt);
    header.setAttribute("aria-label", localize({
      key: "header",
      comment: [
        "This is the ARIA label for a git diff header.",
        "A git diff header looks like this: @@ -154,12 +159,39 @@.",
        "That encodes that at original line 154 (which is now line 159), 12 lines were removed/changed with 39 lines.",
        "Variables 0 and 1 refer to the diff index out of total number of diffs.",
        "Variables 2 and 4 will be numbers (a line number).",
        'Variables 3 and 5 will be "no lines changed", "1 line changed" or "X lines changed", localized separately.'
      ]
    }, "Difference {0} of {1}: original line {2}, {3}, modified line {4}, {5}", diffIndex + 1, this._diffs.length, minOriginalLine, originalChangedLinesCntAria, minModifiedLine, modifiedChangedLinesCntAria));
    header.appendChild(cell);
    header.setAttribute("role", "listitem");
    container.appendChild(header);
    const lineHeight = modifiedOptions.get(51);
    let modLine = minModifiedLine;
    for (let i3 = 0, len2 = diffs.length; i3 < len2; i3++) {
      const diffEntry = diffs[i3];
      DiffReview._renderSection(container, diffEntry, modLine, lineHeight, this._width, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts);
      if (diffEntry.modifiedLineStart !== 0) {
        modLine = diffEntry.modifiedLineEnd;
      }
    }
    clearNode(this._content.domNode);
    this._content.domNode.appendChild(container);
    this.scrollbar.scanDomNode();
  }
  static _renderSection(dest, diffEntry, modLine, lineHeight, width2, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts) {
    const type = diffEntry.getType();
    let rowClassName = "diff-review-row";
    let lineNumbersExtraClassName = "";
    const spacerClassName = "diff-review-spacer";
    let spacerIcon = null;
    switch (type) {
      case 1:
        rowClassName = "diff-review-row line-insert";
        lineNumbersExtraClassName = " char-insert";
        spacerIcon = diffReviewInsertIcon;
        break;
      case 2:
        rowClassName = "diff-review-row line-delete";
        lineNumbersExtraClassName = " char-delete";
        spacerIcon = diffReviewRemoveIcon;
        break;
    }
    const originalLineStart = diffEntry.originalLineStart;
    const originalLineEnd = diffEntry.originalLineEnd;
    const modifiedLineStart = diffEntry.modifiedLineStart;
    const modifiedLineEnd = diffEntry.modifiedLineEnd;
    const cnt = Math.max(modifiedLineEnd - modifiedLineStart, originalLineEnd - originalLineStart);
    const originalLayoutInfo = originalOptions.get(117);
    const originalLineNumbersWidth = originalLayoutInfo.glyphMarginWidth + originalLayoutInfo.lineNumbersWidth;
    const modifiedLayoutInfo = modifiedOptions.get(117);
    const modifiedLineNumbersWidth = 10 + modifiedLayoutInfo.glyphMarginWidth + modifiedLayoutInfo.lineNumbersWidth;
    for (let i3 = 0; i3 <= cnt; i3++) {
      const originalLine = originalLineStart === 0 ? 0 : originalLineStart + i3;
      const modifiedLine = modifiedLineStart === 0 ? 0 : modifiedLineStart + i3;
      const row = document.createElement("div");
      row.style.minWidth = width2 + "px";
      row.className = rowClassName;
      row.setAttribute("role", "listitem");
      if (modifiedLine !== 0) {
        modLine = modifiedLine;
      }
      row.setAttribute("data-line", String(modLine));
      let cell = document.createElement("div");
      cell.className = "diff-review-cell";
      cell.style.height = `${lineHeight}px`;
      row.appendChild(cell);
      const originalLineNumber = document.createElement("span");
      originalLineNumber.style.width = originalLineNumbersWidth + "px";
      originalLineNumber.style.minWidth = originalLineNumbersWidth + "px";
      originalLineNumber.className = "diff-review-line-number" + lineNumbersExtraClassName;
      if (originalLine !== 0) {
        originalLineNumber.appendChild(document.createTextNode(String(originalLine)));
      } else {
        originalLineNumber.innerText = " ";
      }
      cell.appendChild(originalLineNumber);
      const modifiedLineNumber = document.createElement("span");
      modifiedLineNumber.style.width = modifiedLineNumbersWidth + "px";
      modifiedLineNumber.style.minWidth = modifiedLineNumbersWidth + "px";
      modifiedLineNumber.style.paddingRight = "10px";
      modifiedLineNumber.className = "diff-review-line-number" + lineNumbersExtraClassName;
      if (modifiedLine !== 0) {
        modifiedLineNumber.appendChild(document.createTextNode(String(modifiedLine)));
      } else {
        modifiedLineNumber.innerText = " ";
      }
      cell.appendChild(modifiedLineNumber);
      const spacer = document.createElement("span");
      spacer.className = spacerClassName;
      if (spacerIcon) {
        const spacerCodicon = document.createElement("span");
        spacerCodicon.className = spacerIcon.classNames;
        spacerCodicon.innerText = "  ";
        spacer.appendChild(spacerCodicon);
      } else {
        spacer.innerText = "  ";
      }
      cell.appendChild(spacer);
      let lineContent;
      if (modifiedLine !== 0) {
        cell.insertAdjacentHTML("beforeend", this._renderLine(modifiedModel, modifiedOptions, modifiedModelOpts.tabSize, modifiedLine));
        lineContent = modifiedModel.getLineContent(modifiedLine);
      } else {
        cell.insertAdjacentHTML("beforeend", this._renderLine(originalModel, originalOptions, originalModelOpts.tabSize, originalLine));
        lineContent = originalModel.getLineContent(originalLine);
      }
      if (lineContent.length === 0) {
        lineContent = localize("blankLine", "blank");
      }
      let ariaLabel = "";
      switch (type) {
        case 0:
          if (originalLine === modifiedLine) {
            ariaLabel = localize({key: "unchangedLine", comment: ["The placholders are contents of the line and should not be translated."]}, "{0} unchanged line {1}", lineContent, originalLine);
          } else {
            ariaLabel = localize("equalLine", "{0} original line {1} modified line {2}", lineContent, originalLine, modifiedLine);
          }
          break;
        case 1:
          ariaLabel = localize("insertLine", "+ {0} modified line {1}", lineContent, modifiedLine);
          break;
        case 2:
          ariaLabel = localize("deleteLine", "- {0} original line {1}", lineContent, originalLine);
          break;
      }
      row.setAttribute("aria-label", ariaLabel);
      dest.appendChild(row);
    }
  }
  static _renderLine(model, options, tabSize, lineNumber) {
    const lineContent = model.getLineContent(lineNumber);
    const fontInfo = options.get(36);
    const defaultMetadata = (0 << 11 | 1 << 14 | 2 << 23) >>> 0;
    const tokens = new Uint32Array(2);
    tokens[0] = lineContent.length;
    tokens[1] = defaultMetadata;
    const lineTokens = new LineTokens(tokens, lineContent);
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(lineContent, model.mightContainNonBasicASCII());
    const containsRTL2 = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII2, model.mightContainRTL());
    const r3 = renderViewLine2(new RenderLineInput(fontInfo.isMonospace && !options.get(24), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII2, containsRTL2, 0, lineTokens, [], tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, options.get(95), options.get(80), options.get(74), options.get(37) !== EditorFontLigatures.OFF, null));
    return r3.html;
  }
};
registerThemingParticipant((theme, collector) => {
  const lineNumbers = theme.getColor(editorLineNumbers);
  if (lineNumbers) {
    collector.addRule(`.monaco-diff-editor .diff-review-line-number { color: ${lineNumbers}; }`);
  }
  const shadow = theme.getColor(scrollbarShadow);
  if (shadow) {
    collector.addRule(`.monaco-diff-editor .diff-review-shadow { box-shadow: ${shadow} 0 -6px 6px -6px inset; }`);
  }
});
var DiffReviewNext = class extends EditorAction {
  constructor() {
    super({
      id: "editor.action.diffReview.next",
      label: localize("editor.action.diffReview.next", "Go to Next Difference"),
      alias: "Go to Next Difference",
      precondition: ContextKeyExpr.has("isInDiffEditor"),
      kbOpts: {
        kbExpr: null,
        primary: 65,
        weight: 100
      }
    });
  }
  run(accessor, editor2) {
    const diffEditor = findFocusedDiffEditor(accessor);
    if (diffEditor) {
      diffEditor.diffReviewNext();
    }
  }
};
var DiffReviewPrev = class extends EditorAction {
  constructor() {
    super({
      id: "editor.action.diffReview.prev",
      label: localize("editor.action.diffReview.prev", "Go to Previous Difference"),
      alias: "Go to Previous Difference",
      precondition: ContextKeyExpr.has("isInDiffEditor"),
      kbOpts: {
        kbExpr: null,
        primary: 1024 | 65,
        weight: 100
      }
    });
  }
  run(accessor, editor2) {
    const diffEditor = findFocusedDiffEditor(accessor);
    if (diffEditor) {
      diffEditor.diffReviewPrev();
    }
  }
};
function findFocusedDiffEditor(accessor) {
  const codeEditorService = accessor.get(ICodeEditorService);
  const diffEditors = codeEditorService.listDiffEditors();
  const activeCodeEditor = codeEditorService.getActiveCodeEditor();
  if (!activeCodeEditor) {
    return null;
  }
  for (let i3 = 0, len2 = diffEditors.length; i3 < len2; i3++) {
    const diffEditor = diffEditors[i3];
    if (diffEditor.getModifiedEditor().getId() === activeCodeEditor.getId() || diffEditor.getOriginalEditor().getId() === activeCodeEditor.getId()) {
      return diffEditor;
    }
  }
  return null;
}
registerEditorAction(DiffReviewNext);
registerEditorAction(DiffReviewPrev);
var IContextViewService = createDecorator("contextViewService");
var IContextMenuService = createDecorator("contextMenuService");
var __awaiter$6 = function(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var InlineDiffMargin = class extends Disposable {
  constructor(_viewZoneId, _marginDomNode, editor2, diff, _contextMenuService, _clipboardService) {
    super();
    this._viewZoneId = _viewZoneId;
    this._marginDomNode = _marginDomNode;
    this.editor = editor2;
    this.diff = diff;
    this._contextMenuService = _contextMenuService;
    this._clipboardService = _clipboardService;
    this._visibility = false;
    this._marginDomNode.style.zIndex = "10";
    this._diffActions = document.createElement("div");
    this._diffActions.className = Codicon.lightBulb.classNames + " lightbulb-glyph";
    this._diffActions.style.position = "absolute";
    const lineHeight = editor2.getOption(51);
    const lineFeed = editor2.getModel().getEOL();
    this._diffActions.style.right = "0px";
    this._diffActions.style.visibility = "hidden";
    this._diffActions.style.height = `${lineHeight}px`;
    this._diffActions.style.lineHeight = `${lineHeight}px`;
    this._marginDomNode.appendChild(this._diffActions);
    const actions2 = [];
    actions2.push(new Action("diff.clipboard.copyDeletedContent", diff.originalEndLineNumber > diff.modifiedStartLineNumber ? localize("diff.clipboard.copyDeletedLinesContent.label", "Copy deleted lines") : localize("diff.clipboard.copyDeletedLinesContent.single.label", "Copy deleted line"), void 0, true, () => __awaiter$6(this, void 0, void 0, function* () {
      yield this._clipboardService.writeText(diff.originalContent.join(lineFeed) + lineFeed);
    })));
    let currentLineNumberOffset = 0;
    let copyLineAction = void 0;
    if (diff.originalEndLineNumber > diff.modifiedStartLineNumber) {
      copyLineAction = new Action("diff.clipboard.copyDeletedLineContent", localize("diff.clipboard.copyDeletedLineContent.label", "Copy deleted line ({0})", diff.originalStartLineNumber), void 0, true, () => __awaiter$6(this, void 0, void 0, function* () {
        yield this._clipboardService.writeText(diff.originalContent[currentLineNumberOffset]);
      }));
      actions2.push(copyLineAction);
    }
    const readOnly = editor2.getOption(72);
    if (!readOnly) {
      actions2.push(new Action("diff.inline.revertChange", localize("diff.inline.revertChange.label", "Revert this change"), void 0, true, () => __awaiter$6(this, void 0, void 0, function* () {
        if (diff.modifiedEndLineNumber === 0) {
          const column = editor2.getModel().getLineMaxColumn(diff.modifiedStartLineNumber);
          editor2.executeEdits("diffEditor", [
            {
              range: new Range(diff.modifiedStartLineNumber, column, diff.modifiedStartLineNumber, column),
              text: lineFeed + diff.originalContent.join(lineFeed)
            }
          ]);
        } else {
          const column = editor2.getModel().getLineMaxColumn(diff.modifiedEndLineNumber);
          editor2.executeEdits("diffEditor", [
            {
              range: new Range(diff.modifiedStartLineNumber, 1, diff.modifiedEndLineNumber, column),
              text: diff.originalContent.join(lineFeed)
            }
          ]);
        }
      })));
    }
    const showContextMenu = (x2, y3) => {
      this._contextMenuService.showContextMenu({
        getAnchor: () => {
          return {
            x: x2,
            y: y3
          };
        },
        getActions: () => {
          if (copyLineAction) {
            copyLineAction.label = localize("diff.clipboard.copyDeletedLineContent.label", "Copy deleted line ({0})", diff.originalStartLineNumber + currentLineNumberOffset);
          }
          return actions2;
        },
        autoSelectFirstItem: true
      });
    };
    this._register(addStandardDisposableListener(this._diffActions, "mousedown", (e2) => {
      const {top: top2, height} = getDomNodePagePosition(this._diffActions);
      let pad = Math.floor(lineHeight / 3);
      e2.preventDefault();
      showContextMenu(e2.posx, top2 + height + pad);
    }));
    this._register(editor2.onMouseMove((e2) => {
      if (e2.target.type === 8 || e2.target.type === 5) {
        const viewZoneId = e2.target.detail.viewZoneId;
        if (viewZoneId === this._viewZoneId) {
          this.visibility = true;
          currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e2.event.browserEvent.y, lineHeight);
        } else {
          this.visibility = false;
        }
      } else {
        this.visibility = false;
      }
    }));
    this._register(editor2.onMouseDown((e2) => {
      if (!e2.event.rightButton) {
        return;
      }
      if (e2.target.type === 8 || e2.target.type === 5) {
        const viewZoneId = e2.target.detail.viewZoneId;
        if (viewZoneId === this._viewZoneId) {
          e2.event.preventDefault();
          currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e2.event.browserEvent.y, lineHeight);
          showContextMenu(e2.event.posx, e2.event.posy + lineHeight);
        }
      }
    }));
  }
  get visibility() {
    return this._visibility;
  }
  set visibility(_visibility) {
    if (this._visibility !== _visibility) {
      this._visibility = _visibility;
      if (_visibility) {
        this._diffActions.style.visibility = "visible";
      } else {
        this._diffActions.style.visibility = "hidden";
      }
    }
  }
  _updateLightBulbPosition(marginDomNode, y3, lineHeight) {
    const {top: top2} = getDomNodePagePosition(marginDomNode);
    const offset2 = y3 - top2;
    const lineNumberOffset = Math.floor(offset2 / lineHeight);
    const newTop = lineNumberOffset * lineHeight;
    this._diffActions.style.top = `${newTop}px`;
    return lineNumberOffset;
  }
};
var IClipboardService = createDecorator("clipboardService");
Object.freeze({report() {
}});
var IEditorProgressService = createDecorator("editorProgressService");
var __decorate$6 = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$5 = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var VisualEditorState = class {
  constructor(_contextMenuService, _clipboardService) {
    this._contextMenuService = _contextMenuService;
    this._clipboardService = _clipboardService;
    this._zones = [];
    this.inlineDiffMargins = [];
    this._zonesMap = {};
    this._decorations = [];
  }
  getForeignViewZones(allViewZones) {
    return allViewZones.filter((z2) => !this._zonesMap[String(z2.id)]);
  }
  clean(editor2) {
    if (this._zones.length > 0) {
      editor2.changeViewZones((viewChangeAccessor) => {
        for (let i3 = 0, length = this._zones.length; i3 < length; i3++) {
          viewChangeAccessor.removeZone(this._zones[i3]);
        }
      });
    }
    this._zones = [];
    this._zonesMap = {};
    this._decorations = editor2.deltaDecorations(this._decorations, []);
  }
  apply(editor2, overviewRuler, newDecorations, restoreScrollState) {
    const scrollState = restoreScrollState ? StableEditorScrollState.capture(editor2) : null;
    editor2.changeViewZones((viewChangeAccessor) => {
      for (let i3 = 0, length = this._zones.length; i3 < length; i3++) {
        viewChangeAccessor.removeZone(this._zones[i3]);
      }
      for (let i3 = 0, length = this.inlineDiffMargins.length; i3 < length; i3++) {
        this.inlineDiffMargins[i3].dispose();
      }
      this._zones = [];
      this._zonesMap = {};
      this.inlineDiffMargins = [];
      for (let i3 = 0, length = newDecorations.zones.length; i3 < length; i3++) {
        const viewZone = newDecorations.zones[i3];
        viewZone.suppressMouseDown = true;
        let zoneId = viewChangeAccessor.addZone(viewZone);
        this._zones.push(zoneId);
        this._zonesMap[String(zoneId)] = true;
        if (newDecorations.zones[i3].diff && viewZone.marginDomNode) {
          viewZone.suppressMouseDown = false;
          this.inlineDiffMargins.push(new InlineDiffMargin(zoneId, viewZone.marginDomNode, editor2, newDecorations.zones[i3].diff, this._contextMenuService, this._clipboardService));
        }
      }
    });
    if (scrollState) {
      scrollState.restore(editor2);
    }
    this._decorations = editor2.deltaDecorations(this._decorations, newDecorations.decorations);
    if (overviewRuler) {
      overviewRuler.setZones(newDecorations.overviewZones);
    }
  }
};
var DIFF_EDITOR_ID = 0;
var diffInsertIcon = registerIcon("diff-insert", Codicon.add);
var diffRemoveIcon = registerIcon("diff-remove", Codicon.remove);
var DiffEditorWidget = class DiffEditorWidget2 extends Disposable {
  constructor(domElement, options, clipboardService, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService, contextMenuService, _editorProgressService) {
    super();
    this._editorProgressService = _editorProgressService;
    this._onDidDispose = this._register(new Emitter());
    this.onDidDispose = this._onDidDispose.event;
    this._onDidUpdateDiff = this._register(new Emitter());
    this.onDidUpdateDiff = this._onDidUpdateDiff.event;
    this._onDidContentSizeChange = this._register(new Emitter());
    this._lastOriginalWarning = null;
    this._lastModifiedWarning = null;
    this._editorWorkerService = editorWorkerService;
    this._codeEditorService = codeEditorService;
    this._contextKeyService = this._register(contextKeyService.createScoped(domElement));
    this._contextKeyService.createKey("isInDiffEditor", true);
    this._themeService = themeService;
    this._notificationService = notificationService;
    this.id = ++DIFF_EDITOR_ID;
    this._state = 0;
    this._updatingDiffProgress = null;
    this._domElement = domElement;
    options = options || {};
    this._renderSideBySide = true;
    if (typeof options.renderSideBySide !== "undefined") {
      this._renderSideBySide = options.renderSideBySide;
    }
    this._maxComputationTime = 5e3;
    if (typeof options.maxComputationTime !== "undefined") {
      this._maxComputationTime = options.maxComputationTime;
    }
    this._ignoreTrimWhitespace = true;
    if (typeof options.ignoreTrimWhitespace !== "undefined") {
      this._ignoreTrimWhitespace = options.ignoreTrimWhitespace;
    }
    this._renderIndicators = true;
    if (typeof options.renderIndicators !== "undefined") {
      this._renderIndicators = options.renderIndicators;
    }
    this._originalIsEditable = false;
    if (typeof options.originalEditable !== "undefined") {
      this._originalIsEditable = Boolean(options.originalEditable);
    }
    this._originalCodeLens = false;
    if (typeof options.originalCodeLens !== "undefined") {
      this._originalCodeLens = Boolean(options.originalCodeLens);
    }
    this._modifiedCodeLens = false;
    if (typeof options.modifiedCodeLens !== "undefined") {
      this._modifiedCodeLens = Boolean(options.modifiedCodeLens);
    }
    this._updateDecorationsRunner = this._register(new RunOnceScheduler(() => this._updateDecorations(), 0));
    this._containerDomElement = document.createElement("div");
    this._containerDomElement.className = DiffEditorWidget2._getClassName(this._themeService.getColorTheme(), this._renderSideBySide);
    this._containerDomElement.style.position = "relative";
    this._containerDomElement.style.height = "100%";
    this._domElement.appendChild(this._containerDomElement);
    this._overviewViewportDomElement = createFastDomNode(document.createElement("div"));
    this._overviewViewportDomElement.setClassName("diffViewport");
    this._overviewViewportDomElement.setPosition("absolute");
    this._overviewDomElement = document.createElement("div");
    this._overviewDomElement.className = "diffOverview";
    this._overviewDomElement.style.position = "absolute";
    this._overviewDomElement.appendChild(this._overviewViewportDomElement.domNode);
    this._register(addStandardDisposableListener(this._overviewDomElement, "mousedown", (e2) => {
      this.modifiedEditor.delegateVerticalScrollbarMouseDown(e2);
    }));
    this._containerDomElement.appendChild(this._overviewDomElement);
    this._originalDomNode = document.createElement("div");
    this._originalDomNode.className = "editor original";
    this._originalDomNode.style.position = "absolute";
    this._originalDomNode.style.height = "100%";
    this._containerDomElement.appendChild(this._originalDomNode);
    this._modifiedDomNode = document.createElement("div");
    this._modifiedDomNode.className = "editor modified";
    this._modifiedDomNode.style.position = "absolute";
    this._modifiedDomNode.style.height = "100%";
    this._containerDomElement.appendChild(this._modifiedDomNode);
    this._beginUpdateDecorationsTimeout = -1;
    this._currentlyChangingViewZones = false;
    this._diffComputationToken = 0;
    this._originalEditorState = new VisualEditorState(contextMenuService, clipboardService);
    this._modifiedEditorState = new VisualEditorState(contextMenuService, clipboardService);
    this._isVisible = true;
    this._isHandlingScrollEvent = false;
    this._elementSizeObserver = this._register(new ElementSizeObserver(this._containerDomElement, void 0, () => this._onDidContainerSizeChanged()));
    if (options.automaticLayout) {
      this._elementSizeObserver.startObserving();
    }
    this._diffComputationResult = null;
    const leftContextKeyService = this._contextKeyService.createScoped();
    const leftServices = new ServiceCollection();
    leftServices.set(IContextKeyService, leftContextKeyService);
    const leftScopedInstantiationService = instantiationService.createChild(leftServices);
    const rightContextKeyService = this._contextKeyService.createScoped();
    const rightServices = new ServiceCollection();
    rightServices.set(IContextKeyService, rightContextKeyService);
    const rightScopedInstantiationService = instantiationService.createChild(rightServices);
    this.originalEditor = this._createLeftHandSideEditor(options, leftScopedInstantiationService, leftContextKeyService);
    this.modifiedEditor = this._createRightHandSideEditor(options, rightScopedInstantiationService, rightContextKeyService);
    this._originalOverviewRuler = null;
    this._modifiedOverviewRuler = null;
    this._reviewPane = new DiffReview(this);
    this._containerDomElement.appendChild(this._reviewPane.domNode.domNode);
    this._containerDomElement.appendChild(this._reviewPane.shadow.domNode);
    this._containerDomElement.appendChild(this._reviewPane.actionBarContainer.domNode);
    this._enableSplitViewResizing = true;
    if (typeof options.enableSplitViewResizing !== "undefined") {
      this._enableSplitViewResizing = options.enableSplitViewResizing;
    }
    if (this._renderSideBySide) {
      this._setStrategy(new DiffEditorWidgetSideBySide(this._createDataSource(), this._enableSplitViewResizing));
    } else {
      this._setStrategy(new DiffEditorWidgetInline(this._createDataSource(), this._enableSplitViewResizing));
    }
    this._register(themeService.onDidColorThemeChange((t5) => {
      if (this._strategy && this._strategy.applyColors(t5)) {
        this._updateDecorationsRunner.schedule();
      }
      this._containerDomElement.className = DiffEditorWidget2._getClassName(this._themeService.getColorTheme(), this._renderSideBySide);
    }));
    const contributions = EditorExtensionsRegistry.getDiffEditorContributions();
    for (const desc of contributions) {
      try {
        this._register(instantiationService.createInstance(desc.ctor, this));
      } catch (err) {
        onUnexpectedError(err);
      }
    }
    this._codeEditorService.addDiffEditor(this);
  }
  _setState(newState) {
    if (this._state === newState) {
      return;
    }
    this._state = newState;
    if (this._updatingDiffProgress) {
      this._updatingDiffProgress.done();
      this._updatingDiffProgress = null;
    }
    if (this._state === 1) {
      this._updatingDiffProgress = this._editorProgressService.show(true, 1e3);
    }
  }
  diffReviewNext() {
    this._reviewPane.next();
  }
  diffReviewPrev() {
    this._reviewPane.prev();
  }
  static _getClassName(theme, renderSideBySide) {
    let result = "monaco-diff-editor monaco-editor-background ";
    if (renderSideBySide) {
      result += "side-by-side ";
    }
    result += getThemeTypeSelector(theme.type);
    return result;
  }
  _recreateOverviewRulers() {
    if (this._originalOverviewRuler) {
      this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode());
      this._originalOverviewRuler.dispose();
    }
    if (this.originalEditor.hasModel()) {
      this._originalOverviewRuler = this.originalEditor.createOverviewRuler("original diffOverviewRuler");
      this._overviewDomElement.appendChild(this._originalOverviewRuler.getDomNode());
    }
    if (this._modifiedOverviewRuler) {
      this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode());
      this._modifiedOverviewRuler.dispose();
    }
    if (this.modifiedEditor.hasModel()) {
      this._modifiedOverviewRuler = this.modifiedEditor.createOverviewRuler("modified diffOverviewRuler");
      this._overviewDomElement.appendChild(this._modifiedOverviewRuler.getDomNode());
    }
    this._layoutOverviewRulers();
  }
  _createLeftHandSideEditor(options, instantiationService, contextKeyService) {
    const editor2 = this._createInnerEditor(instantiationService, this._originalDomNode, this._adjustOptionsForLeftHandSide(options, this._originalIsEditable, this._originalCodeLens));
    this._register(editor2.onDidScrollChange((e2) => {
      if (this._isHandlingScrollEvent) {
        return;
      }
      if (!e2.scrollTopChanged && !e2.scrollLeftChanged && !e2.scrollHeightChanged) {
        return;
      }
      this._isHandlingScrollEvent = true;
      this.modifiedEditor.setScrollPosition({
        scrollLeft: e2.scrollLeft,
        scrollTop: e2.scrollTop
      });
      this._isHandlingScrollEvent = false;
      this._layoutOverviewViewport();
    }));
    this._register(editor2.onDidChangeViewZones(() => {
      this._onViewZonesChanged();
    }));
    this._register(editor2.onDidChangeModelContent(() => {
      if (this._isVisible) {
        this._beginUpdateDecorationsSoon();
      }
    }));
    const isInDiffLeftEditorKey = contextKeyService.createKey("isInDiffLeftEditor", void 0);
    this._register(editor2.onDidFocusEditorWidget(() => isInDiffLeftEditorKey.set(true)));
    this._register(editor2.onDidBlurEditorWidget(() => isInDiffLeftEditorKey.set(false)));
    this._register(editor2.onDidContentSizeChange((e2) => {
      const width2 = this.originalEditor.getContentWidth() + this.modifiedEditor.getContentWidth() + DiffEditorWidget2.ONE_OVERVIEW_WIDTH;
      const height = Math.max(this.modifiedEditor.getContentHeight(), this.originalEditor.getContentHeight());
      this._onDidContentSizeChange.fire({
        contentHeight: height,
        contentWidth: width2,
        contentHeightChanged: e2.contentHeightChanged,
        contentWidthChanged: e2.contentWidthChanged
      });
    }));
    return editor2;
  }
  _createRightHandSideEditor(options, instantiationService, contextKeyService) {
    const editor2 = this._createInnerEditor(instantiationService, this._modifiedDomNode, this._adjustOptionsForRightHandSide(options, this._modifiedCodeLens));
    this._register(editor2.onDidScrollChange((e2) => {
      if (this._isHandlingScrollEvent) {
        return;
      }
      if (!e2.scrollTopChanged && !e2.scrollLeftChanged && !e2.scrollHeightChanged) {
        return;
      }
      this._isHandlingScrollEvent = true;
      this.originalEditor.setScrollPosition({
        scrollLeft: e2.scrollLeft,
        scrollTop: e2.scrollTop
      });
      this._isHandlingScrollEvent = false;
      this._layoutOverviewViewport();
    }));
    this._register(editor2.onDidChangeViewZones(() => {
      this._onViewZonesChanged();
    }));
    this._register(editor2.onDidChangeConfiguration((e2) => {
      if (e2.hasChanged(36) && editor2.getModel()) {
        this._onViewZonesChanged();
      }
    }));
    this._register(editor2.onDidChangeModelContent(() => {
      if (this._isVisible) {
        this._beginUpdateDecorationsSoon();
      }
    }));
    this._register(editor2.onDidChangeModelOptions((e2) => {
      if (e2.tabSize) {
        this._updateDecorationsRunner.schedule();
      }
    }));
    const isInDiffRightEditorKey = contextKeyService.createKey("isInDiffRightEditor", void 0);
    this._register(editor2.onDidFocusEditorWidget(() => isInDiffRightEditorKey.set(true)));
    this._register(editor2.onDidBlurEditorWidget(() => isInDiffRightEditorKey.set(false)));
    this._register(editor2.onDidContentSizeChange((e2) => {
      const width2 = this.originalEditor.getContentWidth() + this.modifiedEditor.getContentWidth() + DiffEditorWidget2.ONE_OVERVIEW_WIDTH;
      const height = Math.max(this.modifiedEditor.getContentHeight(), this.originalEditor.getContentHeight());
      this._onDidContentSizeChange.fire({
        contentHeight: height,
        contentWidth: width2,
        contentHeightChanged: e2.contentHeightChanged,
        contentWidthChanged: e2.contentWidthChanged
      });
    }));
    return editor2;
  }
  _createInnerEditor(instantiationService, container, options) {
    return instantiationService.createInstance(CodeEditorWidget, container, options, {});
  }
  dispose() {
    this._codeEditorService.removeDiffEditor(this);
    if (this._beginUpdateDecorationsTimeout !== -1) {
      window.clearTimeout(this._beginUpdateDecorationsTimeout);
      this._beginUpdateDecorationsTimeout = -1;
    }
    this._cleanViewZonesAndDecorations();
    if (this._originalOverviewRuler) {
      this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode());
      this._originalOverviewRuler.dispose();
    }
    if (this._modifiedOverviewRuler) {
      this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode());
      this._modifiedOverviewRuler.dispose();
    }
    this._overviewDomElement.removeChild(this._overviewViewportDomElement.domNode);
    this._containerDomElement.removeChild(this._overviewDomElement);
    this._containerDomElement.removeChild(this._originalDomNode);
    this.originalEditor.dispose();
    this._containerDomElement.removeChild(this._modifiedDomNode);
    this.modifiedEditor.dispose();
    this._strategy.dispose();
    this._containerDomElement.removeChild(this._reviewPane.domNode.domNode);
    this._containerDomElement.removeChild(this._reviewPane.shadow.domNode);
    this._containerDomElement.removeChild(this._reviewPane.actionBarContainer.domNode);
    this._reviewPane.dispose();
    this._domElement.removeChild(this._containerDomElement);
    this._onDidDispose.fire();
    super.dispose();
  }
  getId() {
    return this.getEditorType() + ":" + this.id;
  }
  getEditorType() {
    return EditorType.IDiffEditor;
  }
  getLineChanges() {
    if (!this._diffComputationResult) {
      return null;
    }
    return this._diffComputationResult.changes;
  }
  getOriginalEditor() {
    return this.originalEditor;
  }
  getModifiedEditor() {
    return this.modifiedEditor;
  }
  updateOptions(newOptions) {
    let renderSideBySideChanged = false;
    if (typeof newOptions.renderSideBySide !== "undefined") {
      if (this._renderSideBySide !== newOptions.renderSideBySide) {
        this._renderSideBySide = newOptions.renderSideBySide;
        renderSideBySideChanged = true;
      }
    }
    if (typeof newOptions.maxComputationTime !== "undefined") {
      this._maxComputationTime = newOptions.maxComputationTime;
      if (this._isVisible) {
        this._beginUpdateDecorationsSoon();
      }
    }
    let beginUpdateDecorations = false;
    if (typeof newOptions.ignoreTrimWhitespace !== "undefined") {
      if (this._ignoreTrimWhitespace !== newOptions.ignoreTrimWhitespace) {
        this._ignoreTrimWhitespace = newOptions.ignoreTrimWhitespace;
        beginUpdateDecorations = true;
      }
    }
    if (typeof newOptions.renderIndicators !== "undefined") {
      if (this._renderIndicators !== newOptions.renderIndicators) {
        this._renderIndicators = newOptions.renderIndicators;
        beginUpdateDecorations = true;
      }
    }
    if (beginUpdateDecorations) {
      this._beginUpdateDecorations();
    }
    if (typeof newOptions.originalEditable !== "undefined") {
      this._originalIsEditable = Boolean(newOptions.originalEditable);
    }
    if (typeof newOptions.originalCodeLens !== "undefined") {
      this._originalCodeLens = Boolean(newOptions.originalCodeLens);
    }
    if (typeof newOptions.modifiedCodeLens !== "undefined") {
      this._modifiedCodeLens = Boolean(newOptions.modifiedCodeLens);
    }
    this.modifiedEditor.updateOptions(this._adjustOptionsForRightHandSide(newOptions, this._modifiedCodeLens));
    this.originalEditor.updateOptions(this._adjustOptionsForLeftHandSide(newOptions, this._originalIsEditable, this._originalCodeLens));
    if (typeof newOptions.enableSplitViewResizing !== "undefined") {
      this._enableSplitViewResizing = newOptions.enableSplitViewResizing;
    }
    this._strategy.setEnableSplitViewResizing(this._enableSplitViewResizing);
    if (renderSideBySideChanged) {
      if (this._renderSideBySide) {
        this._setStrategy(new DiffEditorWidgetSideBySide(this._createDataSource(), this._enableSplitViewResizing));
      } else {
        this._setStrategy(new DiffEditorWidgetInline(this._createDataSource(), this._enableSplitViewResizing));
      }
      this._containerDomElement.className = DiffEditorWidget2._getClassName(this._themeService.getColorTheme(), this._renderSideBySide);
    }
  }
  getModel() {
    return {
      original: this.originalEditor.getModel(),
      modified: this.modifiedEditor.getModel()
    };
  }
  setModel(model) {
    if (model && (!model.original || !model.modified)) {
      throw new Error(!model.original ? "DiffEditorWidget.setModel: Original model is null" : "DiffEditorWidget.setModel: Modified model is null");
    }
    this._cleanViewZonesAndDecorations();
    this.originalEditor.setModel(model ? model.original : null);
    this.modifiedEditor.setModel(model ? model.modified : null);
    this._updateDecorationsRunner.cancel();
    if (model) {
      this.originalEditor.setScrollTop(0);
      this.modifiedEditor.setScrollTop(0);
    }
    this._diffComputationResult = null;
    this._diffComputationToken++;
    this._setState(0);
    if (model) {
      this._recreateOverviewRulers();
      this._beginUpdateDecorations();
    }
    this._layoutOverviewViewport();
  }
  getDomNode() {
    return this._domElement;
  }
  getVisibleColumnFromPosition(position2) {
    return this.modifiedEditor.getVisibleColumnFromPosition(position2);
  }
  getPosition() {
    return this.modifiedEditor.getPosition();
  }
  setPosition(position2) {
    this.modifiedEditor.setPosition(position2);
  }
  revealLine(lineNumber, scrollType = 0) {
    this.modifiedEditor.revealLine(lineNumber, scrollType);
  }
  revealLineInCenter(lineNumber, scrollType = 0) {
    this.modifiedEditor.revealLineInCenter(lineNumber, scrollType);
  }
  revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0) {
    this.modifiedEditor.revealLineInCenterIfOutsideViewport(lineNumber, scrollType);
  }
  revealLineNearTop(lineNumber, scrollType = 0) {
    this.modifiedEditor.revealLineNearTop(lineNumber, scrollType);
  }
  revealPosition(position2, scrollType = 0) {
    this.modifiedEditor.revealPosition(position2, scrollType);
  }
  revealPositionInCenter(position2, scrollType = 0) {
    this.modifiedEditor.revealPositionInCenter(position2, scrollType);
  }
  revealPositionInCenterIfOutsideViewport(position2, scrollType = 0) {
    this.modifiedEditor.revealPositionInCenterIfOutsideViewport(position2, scrollType);
  }
  revealPositionNearTop(position2, scrollType = 0) {
    this.modifiedEditor.revealPositionNearTop(position2, scrollType);
  }
  getSelection() {
    return this.modifiedEditor.getSelection();
  }
  getSelections() {
    return this.modifiedEditor.getSelections();
  }
  setSelection(something) {
    this.modifiedEditor.setSelection(something);
  }
  setSelections(ranges) {
    this.modifiedEditor.setSelections(ranges);
  }
  revealLines(startLineNumber, endLineNumber, scrollType = 0) {
    this.modifiedEditor.revealLines(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0) {
    this.modifiedEditor.revealLinesInCenter(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0) {
    this.modifiedEditor.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0) {
    this.modifiedEditor.revealLinesNearTop(startLineNumber, endLineNumber, scrollType);
  }
  revealRange(range3, scrollType = 0, revealVerticalInCenter = false, revealHorizontal = true) {
    this.modifiedEditor.revealRange(range3, scrollType, revealVerticalInCenter, revealHorizontal);
  }
  revealRangeInCenter(range3, scrollType = 0) {
    this.modifiedEditor.revealRangeInCenter(range3, scrollType);
  }
  revealRangeInCenterIfOutsideViewport(range3, scrollType = 0) {
    this.modifiedEditor.revealRangeInCenterIfOutsideViewport(range3, scrollType);
  }
  revealRangeNearTop(range3, scrollType = 0) {
    this.modifiedEditor.revealRangeNearTop(range3, scrollType);
  }
  revealRangeNearTopIfOutsideViewport(range3, scrollType = 0) {
    this.modifiedEditor.revealRangeNearTopIfOutsideViewport(range3, scrollType);
  }
  revealRangeAtTop(range3, scrollType = 0) {
    this.modifiedEditor.revealRangeAtTop(range3, scrollType);
  }
  getSupportedActions() {
    return this.modifiedEditor.getSupportedActions();
  }
  saveViewState() {
    let originalViewState = this.originalEditor.saveViewState();
    let modifiedViewState = this.modifiedEditor.saveViewState();
    return {
      original: originalViewState,
      modified: modifiedViewState
    };
  }
  restoreViewState(s2) {
    if (s2.original && s2.modified) {
      let diffEditorState = s2;
      this.originalEditor.restoreViewState(diffEditorState.original);
      this.modifiedEditor.restoreViewState(diffEditorState.modified);
    }
  }
  layout(dimension) {
    this._elementSizeObserver.observe(dimension);
  }
  focus() {
    this.modifiedEditor.focus();
  }
  hasTextFocus() {
    return this.originalEditor.hasTextFocus() || this.modifiedEditor.hasTextFocus();
  }
  trigger(source2, handlerId, payload) {
    this.modifiedEditor.trigger(source2, handlerId, payload);
  }
  changeDecorations(callback) {
    return this.modifiedEditor.changeDecorations(callback);
  }
  _onDidContainerSizeChanged() {
    this._doLayout();
  }
  _getReviewHeight() {
    return this._reviewPane.isVisible() ? this._elementSizeObserver.getHeight() : 0;
  }
  _layoutOverviewRulers() {
    if (!this._originalOverviewRuler || !this._modifiedOverviewRuler) {
      return;
    }
    const height = this._elementSizeObserver.getHeight();
    const reviewHeight = this._getReviewHeight();
    let freeSpace = DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH - 2 * DiffEditorWidget2.ONE_OVERVIEW_WIDTH;
    let layoutInfo = this.modifiedEditor.getLayoutInfo();
    if (layoutInfo) {
      this._originalOverviewRuler.setLayout({
        top: 0,
        width: DiffEditorWidget2.ONE_OVERVIEW_WIDTH,
        right: freeSpace + DiffEditorWidget2.ONE_OVERVIEW_WIDTH,
        height: height - reviewHeight
      });
      this._modifiedOverviewRuler.setLayout({
        top: 0,
        right: 0,
        width: DiffEditorWidget2.ONE_OVERVIEW_WIDTH,
        height: height - reviewHeight
      });
    }
  }
  _onViewZonesChanged() {
    if (this._currentlyChangingViewZones) {
      return;
    }
    this._updateDecorationsRunner.schedule();
  }
  _beginUpdateDecorationsSoon() {
    if (this._beginUpdateDecorationsTimeout !== -1) {
      window.clearTimeout(this._beginUpdateDecorationsTimeout);
      this._beginUpdateDecorationsTimeout = -1;
    }
    this._beginUpdateDecorationsTimeout = window.setTimeout(() => this._beginUpdateDecorations(), DiffEditorWidget2.UPDATE_DIFF_DECORATIONS_DELAY);
  }
  static _equals(a2, b2) {
    if (!a2 && !b2) {
      return true;
    }
    if (!a2 || !b2) {
      return false;
    }
    return a2.toString() === b2.toString();
  }
  _beginUpdateDecorations() {
    this._beginUpdateDecorationsTimeout = -1;
    const currentOriginalModel = this.originalEditor.getModel();
    const currentModifiedModel = this.modifiedEditor.getModel();
    if (!currentOriginalModel || !currentModifiedModel) {
      return;
    }
    this._diffComputationToken++;
    let currentToken = this._diffComputationToken;
    this._setState(1);
    if (!this._editorWorkerService.canComputeDiff(currentOriginalModel.uri, currentModifiedModel.uri)) {
      if (!DiffEditorWidget2._equals(currentOriginalModel.uri, this._lastOriginalWarning) || !DiffEditorWidget2._equals(currentModifiedModel.uri, this._lastModifiedWarning)) {
        this._lastOriginalWarning = currentOriginalModel.uri;
        this._lastModifiedWarning = currentModifiedModel.uri;
        this._notificationService.warn(localize("diff.tooLarge", "Cannot compare files because one file is too large."));
      }
      return;
    }
    this._editorWorkerService.computeDiff(currentOriginalModel.uri, currentModifiedModel.uri, this._ignoreTrimWhitespace, this._maxComputationTime).then((result) => {
      if (currentToken === this._diffComputationToken && currentOriginalModel === this.originalEditor.getModel() && currentModifiedModel === this.modifiedEditor.getModel()) {
        this._setState(2);
        this._diffComputationResult = result;
        this._updateDecorationsRunner.schedule();
        this._onDidUpdateDiff.fire();
      }
    }, (error2) => {
      if (currentToken === this._diffComputationToken && currentOriginalModel === this.originalEditor.getModel() && currentModifiedModel === this.modifiedEditor.getModel()) {
        this._setState(2);
        this._diffComputationResult = null;
        this._updateDecorationsRunner.schedule();
      }
    });
  }
  _cleanViewZonesAndDecorations() {
    this._originalEditorState.clean(this.originalEditor);
    this._modifiedEditorState.clean(this.modifiedEditor);
  }
  _updateDecorations() {
    if (!this.originalEditor.getModel() || !this.modifiedEditor.getModel() || !this._originalOverviewRuler || !this._modifiedOverviewRuler) {
      return;
    }
    const lineChanges = this._diffComputationResult ? this._diffComputationResult.changes : [];
    let foreignOriginal = this._originalEditorState.getForeignViewZones(this.originalEditor.getWhitespaces());
    let foreignModified = this._modifiedEditorState.getForeignViewZones(this.modifiedEditor.getWhitespaces());
    let diffDecorations = this._strategy.getEditorsDiffDecorations(lineChanges, this._ignoreTrimWhitespace, this._renderIndicators, foreignOriginal, foreignModified, this.originalEditor, this.modifiedEditor);
    try {
      this._currentlyChangingViewZones = true;
      this._originalEditorState.apply(this.originalEditor, this._originalOverviewRuler, diffDecorations.original, false);
      this._modifiedEditorState.apply(this.modifiedEditor, this._modifiedOverviewRuler, diffDecorations.modified, true);
    } finally {
      this._currentlyChangingViewZones = false;
    }
  }
  _adjustOptionsForSubEditor(options) {
    let clonedOptions = deepClone(options || {});
    clonedOptions.inDiffEditor = true;
    clonedOptions.wordWrap = "off";
    clonedOptions.wordWrapMinified = false;
    clonedOptions.automaticLayout = false;
    clonedOptions.scrollbar = clonedOptions.scrollbar || {};
    clonedOptions.scrollbar.vertical = "visible";
    clonedOptions.folding = false;
    clonedOptions.codeLens = false;
    clonedOptions.fixedOverflowWidgets = true;
    clonedOptions.overflowWidgetsDomNode = options.overflowWidgetsDomNode;
    if (!clonedOptions.minimap) {
      clonedOptions.minimap = {};
    }
    clonedOptions.minimap.enabled = false;
    return clonedOptions;
  }
  _adjustOptionsForLeftHandSide(options, isEditable, isCodeLensEnabled) {
    let result = this._adjustOptionsForSubEditor(options);
    if (isCodeLensEnabled) {
      result.codeLens = true;
    }
    result.readOnly = !isEditable;
    result.extraEditorClassName = "original-in-monaco-diff-editor";
    return result;
  }
  _adjustOptionsForRightHandSide(options, isCodeLensEnabled) {
    let result = this._adjustOptionsForSubEditor(options);
    if (isCodeLensEnabled) {
      result.codeLens = true;
    }
    result.revealHorizontalRightPadding = EditorOptions.revealHorizontalRightPadding.defaultValue + DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH;
    result.scrollbar.verticalHasArrows = false;
    result.extraEditorClassName = "modified-in-monaco-diff-editor";
    return result;
  }
  doLayout() {
    this._elementSizeObserver.observe();
    this._doLayout();
  }
  _doLayout() {
    const width2 = this._elementSizeObserver.getWidth();
    const height = this._elementSizeObserver.getHeight();
    const reviewHeight = this._getReviewHeight();
    let splitPoint = this._strategy.layout();
    this._originalDomNode.style.width = splitPoint + "px";
    this._originalDomNode.style.left = "0px";
    this._modifiedDomNode.style.width = width2 - splitPoint + "px";
    this._modifiedDomNode.style.left = splitPoint + "px";
    this._overviewDomElement.style.top = "0px";
    this._overviewDomElement.style.height = height - reviewHeight + "px";
    this._overviewDomElement.style.width = DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH + "px";
    this._overviewDomElement.style.left = width2 - DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH + "px";
    this._overviewViewportDomElement.setWidth(DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH);
    this._overviewViewportDomElement.setHeight(30);
    this.originalEditor.layout({width: splitPoint, height: height - reviewHeight});
    this.modifiedEditor.layout({width: width2 - splitPoint - DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH, height: height - reviewHeight});
    if (this._originalOverviewRuler || this._modifiedOverviewRuler) {
      this._layoutOverviewRulers();
    }
    this._reviewPane.layout(height - reviewHeight, width2, reviewHeight);
    this._layoutOverviewViewport();
  }
  _layoutOverviewViewport() {
    let layout3 = this._computeOverviewViewport();
    if (!layout3) {
      this._overviewViewportDomElement.setTop(0);
      this._overviewViewportDomElement.setHeight(0);
    } else {
      this._overviewViewportDomElement.setTop(layout3.top);
      this._overviewViewportDomElement.setHeight(layout3.height);
    }
  }
  _computeOverviewViewport() {
    let layoutInfo = this.modifiedEditor.getLayoutInfo();
    if (!layoutInfo) {
      return null;
    }
    let scrollTop = this.modifiedEditor.getScrollTop();
    let scrollHeight = this.modifiedEditor.getScrollHeight();
    let computedAvailableSize = Math.max(0, layoutInfo.height);
    let computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * 0);
    let computedRatio = scrollHeight > 0 ? computedRepresentableSize / scrollHeight : 0;
    let computedSliderSize = Math.max(0, Math.floor(layoutInfo.height * computedRatio));
    let computedSliderPosition = Math.floor(scrollTop * computedRatio);
    return {
      height: computedSliderSize,
      top: computedSliderPosition
    };
  }
  _createDataSource() {
    return {
      getWidth: () => {
        return this._elementSizeObserver.getWidth();
      },
      getHeight: () => {
        return this._elementSizeObserver.getHeight() - this._getReviewHeight();
      },
      getContainerDomNode: () => {
        return this._containerDomElement;
      },
      relayoutEditors: () => {
        this._doLayout();
      },
      getOriginalEditor: () => {
        return this.originalEditor;
      },
      getModifiedEditor: () => {
        return this.modifiedEditor;
      }
    };
  }
  _setStrategy(newStrategy) {
    if (this._strategy) {
      this._strategy.dispose();
    }
    this._strategy = newStrategy;
    newStrategy.applyColors(this._themeService.getColorTheme());
    if (this._diffComputationResult) {
      this._updateDecorations();
    }
    this._doLayout();
  }
  _getLineChangeAtOrBeforeLineNumber(lineNumber, startLineNumberExtractor) {
    const lineChanges = this._diffComputationResult ? this._diffComputationResult.changes : [];
    if (lineChanges.length === 0 || lineNumber < startLineNumberExtractor(lineChanges[0])) {
      return null;
    }
    let min2 = 0, max2 = lineChanges.length - 1;
    while (min2 < max2) {
      let mid = Math.floor((min2 + max2) / 2);
      let midStart = startLineNumberExtractor(lineChanges[mid]);
      let midEnd = mid + 1 <= max2 ? startLineNumberExtractor(lineChanges[mid + 1]) : 1073741824;
      if (lineNumber < midStart) {
        max2 = mid - 1;
      } else if (lineNumber >= midEnd) {
        min2 = mid + 1;
      } else {
        min2 = mid;
        max2 = mid;
      }
    }
    return lineChanges[min2];
  }
  _getEquivalentLineForOriginalLineNumber(lineNumber) {
    let lineChange = this._getLineChangeAtOrBeforeLineNumber(lineNumber, (lineChange2) => lineChange2.originalStartLineNumber);
    if (!lineChange) {
      return lineNumber;
    }
    let originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
    let modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
    let lineChangeOriginalLength = lineChange.originalEndLineNumber > 0 ? lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1 : 0;
    let lineChangeModifiedLength = lineChange.modifiedEndLineNumber > 0 ? lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1 : 0;
    let delta = lineNumber - originalEquivalentLineNumber;
    if (delta <= lineChangeOriginalLength) {
      return modifiedEquivalentLineNumber + Math.min(delta, lineChangeModifiedLength);
    }
    return modifiedEquivalentLineNumber + lineChangeModifiedLength - lineChangeOriginalLength + delta;
  }
  _getEquivalentLineForModifiedLineNumber(lineNumber) {
    let lineChange = this._getLineChangeAtOrBeforeLineNumber(lineNumber, (lineChange2) => lineChange2.modifiedStartLineNumber);
    if (!lineChange) {
      return lineNumber;
    }
    let originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
    let modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
    let lineChangeOriginalLength = lineChange.originalEndLineNumber > 0 ? lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1 : 0;
    let lineChangeModifiedLength = lineChange.modifiedEndLineNumber > 0 ? lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1 : 0;
    let delta = lineNumber - modifiedEquivalentLineNumber;
    if (delta <= lineChangeModifiedLength) {
      return originalEquivalentLineNumber + Math.min(delta, lineChangeOriginalLength);
    }
    return originalEquivalentLineNumber + lineChangeOriginalLength - lineChangeModifiedLength + delta;
  }
  getDiffLineInformationForOriginal(lineNumber) {
    if (!this._diffComputationResult) {
      return null;
    }
    return {
      equivalentLineNumber: this._getEquivalentLineForOriginalLineNumber(lineNumber)
    };
  }
  getDiffLineInformationForModified(lineNumber) {
    if (!this._diffComputationResult) {
      return null;
    }
    return {
      equivalentLineNumber: this._getEquivalentLineForModifiedLineNumber(lineNumber)
    };
  }
};
DiffEditorWidget.ONE_OVERVIEW_WIDTH = 15;
DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH = 30;
DiffEditorWidget.UPDATE_DIFF_DECORATIONS_DELAY = 200;
DiffEditorWidget = __decorate$6([
  __param$5(2, IClipboardService),
  __param$5(3, IEditorWorkerService),
  __param$5(4, IContextKeyService),
  __param$5(5, IInstantiationService),
  __param$5(6, ICodeEditorService),
  __param$5(7, IThemeService),
  __param$5(8, INotificationService),
  __param$5(9, IContextMenuService),
  __param$5(10, IEditorProgressService)
], DiffEditorWidget);
var DiffEditorWidgetStyle = class extends Disposable {
  constructor(dataSource) {
    super();
    this._dataSource = dataSource;
    this._insertColor = null;
    this._removeColor = null;
  }
  applyColors(theme) {
    let newInsertColor = (theme.getColor(diffInserted) || defaultInsertColor).transparent(2);
    let newRemoveColor = (theme.getColor(diffRemoved) || defaultRemoveColor).transparent(2);
    let hasChanges = !newInsertColor.equals(this._insertColor) || !newRemoveColor.equals(this._removeColor);
    this._insertColor = newInsertColor;
    this._removeColor = newRemoveColor;
    return hasChanges;
  }
  getEditorsDiffDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, originalWhitespaces, modifiedWhitespaces, originalEditor, modifiedEditor) {
    modifiedWhitespaces = modifiedWhitespaces.sort((a2, b2) => {
      return a2.afterLineNumber - b2.afterLineNumber;
    });
    originalWhitespaces = originalWhitespaces.sort((a2, b2) => {
      return a2.afterLineNumber - b2.afterLineNumber;
    });
    let zones = this._getViewZones(lineChanges, originalWhitespaces, modifiedWhitespaces, originalEditor, modifiedEditor, renderIndicators);
    let originalDecorations = this._getOriginalEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor);
    let modifiedDecorations = this._getModifiedEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor);
    return {
      original: {
        decorations: originalDecorations.decorations,
        overviewZones: originalDecorations.overviewZones,
        zones: zones.original
      },
      modified: {
        decorations: modifiedDecorations.decorations,
        overviewZones: modifiedDecorations.overviewZones,
        zones: zones.modified
      }
    };
  }
};
var ForeignViewZonesIterator = class {
  constructor(source2) {
    this._source = source2;
    this._index = -1;
    this.current = null;
    this.advance();
  }
  advance() {
    this._index++;
    if (this._index < this._source.length) {
      this.current = this._source[this._index];
    } else {
      this.current = null;
    }
  }
};
var ViewZonesComputer = class {
  constructor(lineChanges, originalForeignVZ, originalLineHeight, modifiedForeignVZ, modifiedLineHeight) {
    this.lineChanges = lineChanges;
    this.originalForeignVZ = originalForeignVZ;
    this.originalLineHeight = originalLineHeight;
    this.modifiedForeignVZ = modifiedForeignVZ;
    this.modifiedLineHeight = modifiedLineHeight;
  }
  getViewZones() {
    let result = {
      original: [],
      modified: []
    };
    let lineChangeModifiedLength = 0;
    let lineChangeOriginalLength = 0;
    let originalEquivalentLineNumber = 0;
    let modifiedEquivalentLineNumber = 0;
    let originalEndEquivalentLineNumber = 0;
    let modifiedEndEquivalentLineNumber = 0;
    let sortMyViewZones = (a2, b2) => {
      return a2.afterLineNumber - b2.afterLineNumber;
    };
    let addAndCombineIfPossible = (destination, item) => {
      if (item.domNode === null && destination.length > 0) {
        let lastItem = destination[destination.length - 1];
        if (lastItem.afterLineNumber === item.afterLineNumber && lastItem.domNode === null) {
          lastItem.heightInLines += item.heightInLines;
          return;
        }
      }
      destination.push(item);
    };
    let modifiedForeignVZ = new ForeignViewZonesIterator(this.modifiedForeignVZ);
    let originalForeignVZ = new ForeignViewZonesIterator(this.originalForeignVZ);
    for (let i3 = 0, length = this.lineChanges.length; i3 <= length; i3++) {
      let lineChange = i3 < length ? this.lineChanges[i3] : null;
      if (lineChange !== null) {
        originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
        modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
        lineChangeOriginalLength = lineChange.originalEndLineNumber > 0 ? lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1 : 0;
        lineChangeModifiedLength = lineChange.modifiedEndLineNumber > 0 ? lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1 : 0;
        originalEndEquivalentLineNumber = Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
        modifiedEndEquivalentLineNumber = Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
      } else {
        originalEquivalentLineNumber += 1e7 + lineChangeOriginalLength;
        modifiedEquivalentLineNumber += 1e7 + lineChangeModifiedLength;
        originalEndEquivalentLineNumber = originalEquivalentLineNumber;
        modifiedEndEquivalentLineNumber = modifiedEquivalentLineNumber;
      }
      let stepOriginal = [];
      let stepModified = [];
      while (modifiedForeignVZ.current && modifiedForeignVZ.current.afterLineNumber <= modifiedEndEquivalentLineNumber) {
        let viewZoneLineNumber;
        if (modifiedForeignVZ.current.afterLineNumber <= modifiedEquivalentLineNumber) {
          viewZoneLineNumber = originalEquivalentLineNumber - modifiedEquivalentLineNumber + modifiedForeignVZ.current.afterLineNumber;
        } else {
          viewZoneLineNumber = originalEndEquivalentLineNumber;
        }
        let marginDomNode = null;
        if (lineChange && lineChange.modifiedStartLineNumber <= modifiedForeignVZ.current.afterLineNumber && modifiedForeignVZ.current.afterLineNumber <= lineChange.modifiedEndLineNumber) {
          marginDomNode = this._createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion();
        }
        stepOriginal.push({
          afterLineNumber: viewZoneLineNumber,
          heightInLines: modifiedForeignVZ.current.height / this.modifiedLineHeight,
          domNode: null,
          marginDomNode
        });
        modifiedForeignVZ.advance();
      }
      while (originalForeignVZ.current && originalForeignVZ.current.afterLineNumber <= originalEndEquivalentLineNumber) {
        let viewZoneLineNumber;
        if (originalForeignVZ.current.afterLineNumber <= originalEquivalentLineNumber) {
          viewZoneLineNumber = modifiedEquivalentLineNumber - originalEquivalentLineNumber + originalForeignVZ.current.afterLineNumber;
        } else {
          viewZoneLineNumber = modifiedEndEquivalentLineNumber;
        }
        stepModified.push({
          afterLineNumber: viewZoneLineNumber,
          heightInLines: originalForeignVZ.current.height / this.originalLineHeight,
          domNode: null
        });
        originalForeignVZ.advance();
      }
      if (lineChange !== null && isChangeOrInsert(lineChange)) {
        let r3 = this._produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength);
        if (r3) {
          stepOriginal.push(r3);
        }
      }
      if (lineChange !== null && isChangeOrDelete(lineChange)) {
        let r3 = this._produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength);
        if (r3) {
          stepModified.push(r3);
        }
      }
      let stepOriginalIndex = 0;
      let stepModifiedIndex = 0;
      stepOriginal = stepOriginal.sort(sortMyViewZones);
      stepModified = stepModified.sort(sortMyViewZones);
      while (stepOriginalIndex < stepOriginal.length && stepModifiedIndex < stepModified.length) {
        let original = stepOriginal[stepOriginalIndex];
        let modified = stepModified[stepModifiedIndex];
        let originalDelta = original.afterLineNumber - originalEquivalentLineNumber;
        let modifiedDelta = modified.afterLineNumber - modifiedEquivalentLineNumber;
        if (originalDelta < modifiedDelta) {
          addAndCombineIfPossible(result.original, original);
          stepOriginalIndex++;
        } else if (modifiedDelta < originalDelta) {
          addAndCombineIfPossible(result.modified, modified);
          stepModifiedIndex++;
        } else if (original.shouldNotShrink) {
          addAndCombineIfPossible(result.original, original);
          stepOriginalIndex++;
        } else if (modified.shouldNotShrink) {
          addAndCombineIfPossible(result.modified, modified);
          stepModifiedIndex++;
        } else {
          if (original.heightInLines >= modified.heightInLines) {
            original.heightInLines -= modified.heightInLines;
            stepModifiedIndex++;
          } else {
            modified.heightInLines -= original.heightInLines;
            stepOriginalIndex++;
          }
        }
      }
      while (stepOriginalIndex < stepOriginal.length) {
        addAndCombineIfPossible(result.original, stepOriginal[stepOriginalIndex]);
        stepOriginalIndex++;
      }
      while (stepModifiedIndex < stepModified.length) {
        addAndCombineIfPossible(result.modified, stepModified[stepModifiedIndex]);
        stepModifiedIndex++;
      }
    }
    return {
      original: ViewZonesComputer._ensureDomNodes(result.original),
      modified: ViewZonesComputer._ensureDomNodes(result.modified)
    };
  }
  static _ensureDomNodes(zones) {
    return zones.map((z2) => {
      if (!z2.domNode) {
        z2.domNode = createFakeLinesDiv();
      }
      return z2;
    });
  }
};
function createDecoration(startLineNumber, startColumn, endLineNumber, endColumn, options) {
  return {
    range: new Range(startLineNumber, startColumn, endLineNumber, endColumn),
    options
  };
}
var DECORATIONS = {
  charDelete: ModelDecorationOptions.register({
    className: "char-delete"
  }),
  charDeleteWholeLine: ModelDecorationOptions.register({
    className: "char-delete",
    isWholeLine: true
  }),
  charInsert: ModelDecorationOptions.register({
    className: "char-insert"
  }),
  charInsertWholeLine: ModelDecorationOptions.register({
    className: "char-insert",
    isWholeLine: true
  }),
  lineInsert: ModelDecorationOptions.register({
    className: "line-insert",
    marginClassName: "line-insert",
    isWholeLine: true
  }),
  lineInsertWithSign: ModelDecorationOptions.register({
    className: "line-insert",
    linesDecorationsClassName: "insert-sign " + diffInsertIcon.classNames,
    marginClassName: "line-insert",
    isWholeLine: true
  }),
  lineDelete: ModelDecorationOptions.register({
    className: "line-delete",
    marginClassName: "line-delete",
    isWholeLine: true
  }),
  lineDeleteWithSign: ModelDecorationOptions.register({
    className: "line-delete",
    linesDecorationsClassName: "delete-sign " + diffRemoveIcon.classNames,
    marginClassName: "line-delete",
    isWholeLine: true
  }),
  lineDeleteMargin: ModelDecorationOptions.register({
    marginClassName: "line-delete"
  })
};
var DiffEditorWidgetSideBySide = class extends DiffEditorWidgetStyle {
  constructor(dataSource, enableSplitViewResizing) {
    super(dataSource);
    this._disableSash = enableSplitViewResizing === false;
    this._sashRatio = null;
    this._sashPosition = null;
    this._startSashPosition = null;
    this._sash = this._register(new Sash(this._dataSource.getContainerDomNode(), this, {orientation: 0}));
    if (this._disableSash) {
      this._sash.state = 0;
    }
    this._sash.onDidStart(() => this.onSashDragStart());
    this._sash.onDidChange((e2) => this.onSashDrag(e2));
    this._sash.onDidEnd(() => this.onSashDragEnd());
    this._sash.onDidReset(() => this.onSashReset());
  }
  setEnableSplitViewResizing(enableSplitViewResizing) {
    let newDisableSash = enableSplitViewResizing === false;
    if (this._disableSash !== newDisableSash) {
      this._disableSash = newDisableSash;
      this._sash.state = this._disableSash ? 0 : 3;
    }
  }
  layout(sashRatio = this._sashRatio) {
    let w2 = this._dataSource.getWidth();
    let contentWidth = w2 - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH;
    let sashPosition = Math.floor((sashRatio || 0.5) * contentWidth);
    let midPoint = Math.floor(0.5 * contentWidth);
    sashPosition = this._disableSash ? midPoint : sashPosition || midPoint;
    if (contentWidth > DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH * 2) {
      if (sashPosition < DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) {
        sashPosition = DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH;
      }
      if (sashPosition > contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) {
        sashPosition = contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH;
      }
    } else {
      sashPosition = midPoint;
    }
    if (this._sashPosition !== sashPosition) {
      this._sashPosition = sashPosition;
      this._sash.layout();
    }
    return this._sashPosition;
  }
  onSashDragStart() {
    this._startSashPosition = this._sashPosition;
  }
  onSashDrag(e2) {
    let w2 = this._dataSource.getWidth();
    let contentWidth = w2 - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH;
    let sashPosition = this.layout((this._startSashPosition + (e2.currentX - e2.startX)) / contentWidth);
    this._sashRatio = sashPosition / contentWidth;
    this._dataSource.relayoutEditors();
  }
  onSashDragEnd() {
    this._sash.layout();
  }
  onSashReset() {
    this._sashRatio = 0.5;
    this._dataSource.relayoutEditors();
    this._sash.layout();
  }
  getVerticalSashTop(sash) {
    return 0;
  }
  getVerticalSashLeft(sash) {
    return this._sashPosition;
  }
  getVerticalSashHeight(sash) {
    return this._dataSource.getHeight();
  }
  _getViewZones(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor) {
    let c3 = new SideBySideViewZonesComputer(lineChanges, originalForeignVZ, originalEditor.getOption(51), modifiedForeignVZ, modifiedEditor.getOption(51));
    return c3.getViewZones();
  }
  _getOriginalEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) {
    const overviewZoneColor = String(this._removeColor);
    let result = {
      decorations: [],
      overviewZones: []
    };
    let originalModel = originalEditor.getModel();
    for (let i3 = 0, length = lineChanges.length; i3 < length; i3++) {
      let lineChange = lineChanges[i3];
      if (isChangeOrDelete(lineChange)) {
        result.decorations.push({
          range: new Range(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824),
          options: renderIndicators ? DECORATIONS.lineDeleteWithSign : DECORATIONS.lineDelete
        });
        if (!isChangeOrInsert(lineChange) || !lineChange.charChanges) {
          result.decorations.push(createDecoration(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824, DECORATIONS.charDeleteWholeLine));
        }
        result.overviewZones.push(new OverviewRulerZone(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber, overviewZoneColor));
        if (lineChange.charChanges) {
          for (let j = 0, lengthJ = lineChange.charChanges.length; j < lengthJ; j++) {
            let charChange = lineChange.charChanges[j];
            if (isChangeOrDelete(charChange)) {
              if (ignoreTrimWhitespace) {
                for (let lineNumber = charChange.originalStartLineNumber; lineNumber <= charChange.originalEndLineNumber; lineNumber++) {
                  let startColumn;
                  let endColumn;
                  if (lineNumber === charChange.originalStartLineNumber) {
                    startColumn = charChange.originalStartColumn;
                  } else {
                    startColumn = originalModel.getLineFirstNonWhitespaceColumn(lineNumber);
                  }
                  if (lineNumber === charChange.originalEndLineNumber) {
                    endColumn = charChange.originalEndColumn;
                  } else {
                    endColumn = originalModel.getLineLastNonWhitespaceColumn(lineNumber);
                  }
                  result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charDelete));
                }
              } else {
                result.decorations.push(createDecoration(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn, DECORATIONS.charDelete));
              }
            }
          }
        }
      }
    }
    return result;
  }
  _getModifiedEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) {
    const overviewZoneColor = String(this._insertColor);
    let result = {
      decorations: [],
      overviewZones: []
    };
    let modifiedModel = modifiedEditor.getModel();
    for (let i3 = 0, length = lineChanges.length; i3 < length; i3++) {
      let lineChange = lineChanges[i3];
      if (isChangeOrInsert(lineChange)) {
        result.decorations.push({
          range: new Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824),
          options: renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert
        });
        if (!isChangeOrDelete(lineChange) || !lineChange.charChanges) {
          result.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824, DECORATIONS.charInsertWholeLine));
        }
        result.overviewZones.push(new OverviewRulerZone(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber, overviewZoneColor));
        if (lineChange.charChanges) {
          for (let j = 0, lengthJ = lineChange.charChanges.length; j < lengthJ; j++) {
            let charChange = lineChange.charChanges[j];
            if (isChangeOrInsert(charChange)) {
              if (ignoreTrimWhitespace) {
                for (let lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) {
                  let startColumn;
                  let endColumn;
                  if (lineNumber === charChange.modifiedStartLineNumber) {
                    startColumn = charChange.modifiedStartColumn;
                  } else {
                    startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber);
                  }
                  if (lineNumber === charChange.modifiedEndLineNumber) {
                    endColumn = charChange.modifiedEndColumn;
                  } else {
                    endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber);
                  }
                  result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert));
                }
              } else {
                result.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert));
              }
            }
          }
        }
      }
    }
    return result;
  }
};
DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH = 100;
var SideBySideViewZonesComputer = class extends ViewZonesComputer {
  constructor(lineChanges, originalForeignVZ, originalLineHeight, modifiedForeignVZ, modifiedLineHeight) {
    super(lineChanges, originalForeignVZ, originalLineHeight, modifiedForeignVZ, modifiedLineHeight);
  }
  _createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion() {
    return null;
  }
  _produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
    if (lineChangeModifiedLength > lineChangeOriginalLength) {
      return {
        afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber),
        heightInLines: lineChangeModifiedLength - lineChangeOriginalLength,
        domNode: null
      };
    }
    return null;
  }
  _produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
    if (lineChangeOriginalLength > lineChangeModifiedLength) {
      return {
        afterLineNumber: Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber),
        heightInLines: lineChangeOriginalLength - lineChangeModifiedLength,
        domNode: null
      };
    }
    return null;
  }
};
var DiffEditorWidgetInline = class extends DiffEditorWidgetStyle {
  constructor(dataSource, enableSplitViewResizing) {
    super(dataSource);
    this.decorationsLeft = dataSource.getOriginalEditor().getLayoutInfo().decorationsLeft;
    this._register(dataSource.getOriginalEditor().onDidLayoutChange((layoutInfo) => {
      if (this.decorationsLeft !== layoutInfo.decorationsLeft) {
        this.decorationsLeft = layoutInfo.decorationsLeft;
        dataSource.relayoutEditors();
      }
    }));
  }
  setEnableSplitViewResizing(enableSplitViewResizing) {
  }
  _getViewZones(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators) {
    let computer = new InlineViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators);
    return computer.getViewZones();
  }
  _getOriginalEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) {
    const overviewZoneColor = String(this._removeColor);
    let result = {
      decorations: [],
      overviewZones: []
    };
    for (let i3 = 0, length = lineChanges.length; i3 < length; i3++) {
      let lineChange = lineChanges[i3];
      if (isChangeOrDelete(lineChange)) {
        result.decorations.push({
          range: new Range(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824),
          options: DECORATIONS.lineDeleteMargin
        });
        result.overviewZones.push(new OverviewRulerZone(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber, overviewZoneColor));
      }
    }
    return result;
  }
  _getModifiedEditorDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, originalEditor, modifiedEditor) {
    const overviewZoneColor = String(this._insertColor);
    let result = {
      decorations: [],
      overviewZones: []
    };
    let modifiedModel = modifiedEditor.getModel();
    for (let i3 = 0, length = lineChanges.length; i3 < length; i3++) {
      let lineChange = lineChanges[i3];
      if (isChangeOrInsert(lineChange)) {
        result.decorations.push({
          range: new Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824),
          options: renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert
        });
        result.overviewZones.push(new OverviewRulerZone(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber, overviewZoneColor));
        if (lineChange.charChanges) {
          for (let j = 0, lengthJ = lineChange.charChanges.length; j < lengthJ; j++) {
            let charChange = lineChange.charChanges[j];
            if (isChangeOrInsert(charChange)) {
              if (ignoreTrimWhitespace) {
                for (let lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) {
                  let startColumn;
                  let endColumn;
                  if (lineNumber === charChange.modifiedStartLineNumber) {
                    startColumn = charChange.modifiedStartColumn;
                  } else {
                    startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber);
                  }
                  if (lineNumber === charChange.modifiedEndLineNumber) {
                    endColumn = charChange.modifiedEndColumn;
                  } else {
                    endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber);
                  }
                  result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert));
                }
              } else {
                result.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert));
              }
            }
          }
        } else {
          result.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824, DECORATIONS.charInsertWholeLine));
        }
      }
    }
    return result;
  }
  layout() {
    return Math.max(5, this.decorationsLeft);
  }
};
var InlineViewZonesComputer = class extends ViewZonesComputer {
  constructor(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators) {
    super(lineChanges, originalForeignVZ, originalEditor.getOption(51), modifiedForeignVZ, modifiedEditor.getOption(51));
    this.originalModel = originalEditor.getModel();
    this.modifiedEditorOptions = modifiedEditor.getOptions();
    this.modifiedEditorTabSize = modifiedEditor.getModel().getOptions().tabSize;
    this.renderIndicators = renderIndicators;
  }
  _createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion() {
    let result = document.createElement("div");
    result.className = "inline-added-margin-view-zone";
    return result;
  }
  _produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
    let marginDomNode = document.createElement("div");
    marginDomNode.className = "inline-added-margin-view-zone";
    return {
      afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber),
      heightInLines: lineChangeModifiedLength,
      domNode: document.createElement("div"),
      marginDomNode
    };
  }
  _produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
    let decorations = [];
    if (lineChange.charChanges) {
      for (let j = 0, lengthJ = lineChange.charChanges.length; j < lengthJ; j++) {
        let charChange = lineChange.charChanges[j];
        if (isChangeOrDelete(charChange)) {
          decorations.push(new InlineDecoration(new Range(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn), "char-delete", 0));
        }
      }
    }
    let sb2 = createStringBuilder(1e4);
    let marginHTML = [];
    const layoutInfo = this.modifiedEditorOptions.get(117);
    const fontInfo = this.modifiedEditorOptions.get(36);
    const lineDecorationsWidth = layoutInfo.decorationsWidth;
    let lineHeight = this.modifiedEditorOptions.get(51);
    const typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    let maxCharsPerLine = 0;
    const originalContent = [];
    for (let lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) {
      maxCharsPerLine = Math.max(maxCharsPerLine, this._renderOriginalLine(lineNumber - lineChange.originalStartLineNumber, this.originalModel, this.modifiedEditorOptions, this.modifiedEditorTabSize, lineNumber, decorations, sb2));
      originalContent.push(this.originalModel.getLineContent(lineNumber));
      if (this.renderIndicators) {
        let index3 = lineNumber - lineChange.originalStartLineNumber;
        marginHTML = marginHTML.concat([
          `<div class="delete-sign ${diffRemoveIcon.classNames}" style="position:absolute;top:${index3 * lineHeight}px;width:${lineDecorationsWidth}px;height:${lineHeight}px;right:0;"></div>`
        ]);
      }
    }
    maxCharsPerLine += this.modifiedEditorOptions.get(85);
    let domNode = document.createElement("div");
    domNode.className = `view-lines line-delete ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`;
    domNode.innerHTML = sb2.build();
    Configuration$1.applyFontInfoSlow(domNode, fontInfo);
    let marginDomNode = document.createElement("div");
    marginDomNode.className = "inline-deleted-margin-view-zone";
    marginDomNode.innerHTML = marginHTML.join("");
    Configuration$1.applyFontInfoSlow(marginDomNode, fontInfo);
    return {
      shouldNotShrink: true,
      afterLineNumber: lineChange.modifiedEndLineNumber === 0 ? lineChange.modifiedStartLineNumber : lineChange.modifiedStartLineNumber - 1,
      heightInLines: lineChangeOriginalLength,
      minWidthInPx: maxCharsPerLine * typicalHalfwidthCharacterWidth,
      domNode,
      marginDomNode,
      diff: {
        originalStartLineNumber: lineChange.originalStartLineNumber,
        originalEndLineNumber: lineChange.originalEndLineNumber,
        modifiedStartLineNumber: lineChange.modifiedStartLineNumber,
        modifiedEndLineNumber: lineChange.modifiedEndLineNumber,
        originalContent
      }
    };
  }
  _renderOriginalLine(count, originalModel, options, tabSize, lineNumber, decorations, sb2) {
    const lineTokens = originalModel.getLineTokens(lineNumber);
    const lineContent = lineTokens.getLineContent();
    const fontInfo = options.get(36);
    const actualDecorations = LineDecoration.filter(decorations, lineNumber, 1, lineContent.length + 1);
    sb2.appendASCIIString('<div class="view-line');
    if (decorations.length === 0) {
      sb2.appendASCIIString(" char-delete");
    }
    sb2.appendASCIIString('" style="top:');
    sb2.appendASCIIString(String(count * options.get(51)));
    sb2.appendASCIIString('px;width:1000000px;">');
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(lineContent, originalModel.mightContainNonBasicASCII());
    const containsRTL2 = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII2, originalModel.mightContainRTL());
    const output2 = renderViewLine(new RenderLineInput(fontInfo.isMonospace && !options.get(24), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII2, containsRTL2, 0, lineTokens, actualDecorations, tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, options.get(95), options.get(80), options.get(74), options.get(37) !== EditorFontLigatures.OFF, null), sb2);
    sb2.appendASCIIString("</div>");
    const absoluteOffsets = output2.characterMapping.getAbsoluteOffsets();
    return absoluteOffsets.length > 0 ? absoluteOffsets[absoluteOffsets.length - 1] : 0;
  }
};
function isChangeOrInsert(lineChange) {
  return lineChange.modifiedEndLineNumber > 0;
}
function isChangeOrDelete(lineChange) {
  return lineChange.originalEndLineNumber > 0;
}
function createFakeLinesDiv() {
  let r3 = document.createElement("div");
  r3.className = "diagonal-fill";
  return r3;
}
registerThemingParticipant((theme, collector) => {
  const added = theme.getColor(diffInserted);
  if (added) {
    collector.addRule(`.monaco-editor .line-insert, .monaco-editor .char-insert { background-color: ${added}; }`);
    collector.addRule(`.monaco-diff-editor .line-insert, .monaco-diff-editor .char-insert { background-color: ${added}; }`);
    collector.addRule(`.monaco-editor .inline-added-margin-view-zone { background-color: ${added}; }`);
  }
  const removed = theme.getColor(diffRemoved);
  if (removed) {
    collector.addRule(`.monaco-editor .line-delete, .monaco-editor .char-delete { background-color: ${removed}; }`);
    collector.addRule(`.monaco-diff-editor .line-delete, .monaco-diff-editor .char-delete { background-color: ${removed}; }`);
    collector.addRule(`.monaco-editor .inline-deleted-margin-view-zone { background-color: ${removed}; }`);
  }
  const addedOutline = theme.getColor(diffInsertedOutline);
  if (addedOutline) {
    collector.addRule(`.monaco-editor .line-insert, .monaco-editor .char-insert { border: 1px ${theme.type === "hc" ? "dashed" : "solid"} ${addedOutline}; }`);
  }
  const removedOutline = theme.getColor(diffRemovedOutline);
  if (removedOutline) {
    collector.addRule(`.monaco-editor .line-delete, .monaco-editor .char-delete { border: 1px ${theme.type === "hc" ? "dashed" : "solid"} ${removedOutline}; }`);
  }
  const shadow = theme.getColor(scrollbarShadow);
  if (shadow) {
    collector.addRule(`.monaco-diff-editor.side-by-side .editor.modified { box-shadow: -6px 0 5px -5px ${shadow}; }`);
  }
  const border = theme.getColor(diffBorder);
  if (border) {
    collector.addRule(`.monaco-diff-editor.side-by-side .editor.modified { border-left: 1px solid ${border}; }`);
  }
  const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground);
  if (scrollbarSliderBackgroundColor) {
    collector.addRule(`
			.monaco-diff-editor .diffViewport {
				background: ${scrollbarSliderBackgroundColor};
			}
		`);
  }
  const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground);
  if (scrollbarSliderHoverBackgroundColor) {
    collector.addRule(`
			.monaco-diff-editor .diffViewport:hover {
				background: ${scrollbarSliderHoverBackgroundColor};
			}
		`);
  }
  const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground);
  if (scrollbarSliderActiveBackgroundColor) {
    collector.addRule(`
			.monaco-diff-editor .diffViewport:active {
				background: ${scrollbarSliderActiveBackgroundColor};
			}
		`);
  }
  const diffDiagonalFillColor = theme.getColor(diffDiagonalFill);
  collector.addRule(`
	.monaco-editor .diagonal-fill {
		background-image: linear-gradient(
			-45deg,
			${diffDiagonalFillColor} 12.5%,
			#0000 12.5%, #0000 50%,
			${diffDiagonalFillColor} 50%, ${diffDiagonalFillColor} 62.5%,
			#0000 62.5%, #0000 100%
		);
		background-size: 8px 8px;
	}
	`);
});
var IStandaloneThemeService = createDecorator("themeService");
var IKeybindingService = createDecorator("keybindingService");
var __decorate$7 = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$6 = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var LAST_GENERATED_COMMAND_ID = 0;
var ariaDomNodeCreated = false;
function createAriaDomNode() {
  if (ariaDomNodeCreated) {
    return;
  }
  ariaDomNodeCreated = true;
  setARIAContainer(document.body);
}
var StandaloneCodeEditor = class StandaloneCodeEditor2 extends CodeEditorWidget {
  constructor(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, accessibilityService) {
    options = options || {};
    options.ariaLabel = options.ariaLabel || StandaloneCodeEditorNLS.editorViewAccessibleLabel;
    options.ariaLabel = options.ariaLabel + ";" + StandaloneCodeEditorNLS.accessibilityHelpMessage;
    super(domElement, options, {}, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService);
    if (keybindingService instanceof StandaloneKeybindingService) {
      this._standaloneKeybindingService = keybindingService;
    } else {
      this._standaloneKeybindingService = null;
    }
    createAriaDomNode();
  }
  addCommand(keybinding, handler, context2) {
    if (!this._standaloneKeybindingService) {
      console.warn("Cannot add command because the editor is configured with an unrecognized KeybindingService");
      return null;
    }
    let commandId = "DYNAMIC_" + ++LAST_GENERATED_COMMAND_ID;
    let whenExpression = ContextKeyExpr.deserialize(context2);
    this._standaloneKeybindingService.addDynamicKeybinding(commandId, keybinding, handler, whenExpression);
    return commandId;
  }
  createContextKey(key, defaultValue) {
    return this._contextKeyService.createKey(key, defaultValue);
  }
  addAction(_descriptor) {
    if (typeof _descriptor.id !== "string" || typeof _descriptor.label !== "string" || typeof _descriptor.run !== "function") {
      throw new Error("Invalid action descriptor, `id`, `label` and `run` are required properties!");
    }
    if (!this._standaloneKeybindingService) {
      console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService");
      return Disposable.None;
    }
    const id3 = _descriptor.id;
    const label2 = _descriptor.label;
    const precondition = ContextKeyExpr.and(ContextKeyExpr.equals("editorId", this.getId()), ContextKeyExpr.deserialize(_descriptor.precondition));
    const keybindings = _descriptor.keybindings;
    const keybindingsWhen = ContextKeyExpr.and(precondition, ContextKeyExpr.deserialize(_descriptor.keybindingContext));
    const contextMenuGroupId = _descriptor.contextMenuGroupId || null;
    const contextMenuOrder = _descriptor.contextMenuOrder || 0;
    const run2 = (accessor, ...args) => {
      return Promise.resolve(_descriptor.run(this, ...args));
    };
    const toDispose = new DisposableStore();
    const uniqueId2 = this.getId() + ":" + id3;
    toDispose.add(CommandsRegistry.registerCommand(uniqueId2, run2));
    if (contextMenuGroupId) {
      let menuItem = {
        command: {
          id: uniqueId2,
          title: label2
        },
        when: precondition,
        group: contextMenuGroupId,
        order: contextMenuOrder
      };
      toDispose.add(MenuRegistry.appendMenuItem(MenuId.EditorContext, menuItem));
    }
    if (Array.isArray(keybindings)) {
      for (const kb2 of keybindings) {
        toDispose.add(this._standaloneKeybindingService.addDynamicKeybinding(uniqueId2, kb2, run2, keybindingsWhen));
      }
    }
    let internalAction = new InternalEditorAction(uniqueId2, label2, label2, precondition, run2, this._contextKeyService);
    this._actions[id3] = internalAction;
    toDispose.add(toDisposable(() => {
      delete this._actions[id3];
    }));
    return toDispose;
  }
};
StandaloneCodeEditor = __decorate$7([
  __param$6(2, IInstantiationService),
  __param$6(3, ICodeEditorService),
  __param$6(4, ICommandService),
  __param$6(5, IContextKeyService),
  __param$6(6, IKeybindingService),
  __param$6(7, IThemeService),
  __param$6(8, INotificationService),
  __param$6(9, IAccessibilityService)
], StandaloneCodeEditor);
var StandaloneEditor = class StandaloneEditor2 extends StandaloneCodeEditor {
  constructor(domElement, options, toDispose, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, contextViewService, themeService, notificationService, configurationService, accessibilityService) {
    applyConfigurationValues(configurationService, options, false);
    const themeDomRegistration = themeService.registerEditorContainer(domElement);
    options = options || {};
    if (typeof options.theme === "string") {
      themeService.setTheme(options.theme);
    }
    let _model = options.model;
    delete options.model;
    super(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, accessibilityService);
    this._contextViewService = contextViewService;
    this._configurationService = configurationService;
    this._standaloneThemeService = themeService;
    this._register(toDispose);
    this._register(themeDomRegistration);
    let model;
    if (typeof _model === "undefined") {
      model = self.monaco.editor.createModel(options.value || "", options.language || "text/plain");
      this._ownsModel = true;
    } else {
      model = _model;
      this._ownsModel = false;
    }
    this._attachModel(model);
    if (model) {
      let e2 = {
        oldModelUrl: null,
        newModelUrl: model.uri
      };
      this._onDidChangeModel.fire(e2);
    }
  }
  dispose() {
    super.dispose();
  }
  updateOptions(newOptions) {
    applyConfigurationValues(this._configurationService, newOptions, false);
    if (typeof newOptions.theme === "string") {
      this._standaloneThemeService.setTheme(newOptions.theme);
    }
    super.updateOptions(newOptions);
  }
  _attachModel(model) {
    super._attachModel(model);
    if (this._modelData) {
      this._contextViewService.setContainer(this._modelData.view.domNode.domNode);
    }
  }
  _postDetachModelCleanup(detachedModel) {
    super._postDetachModelCleanup(detachedModel);
    if (detachedModel && this._ownsModel) {
      detachedModel.dispose();
      this._ownsModel = false;
    }
  }
};
StandaloneEditor = __decorate$7([
  __param$6(3, IInstantiationService),
  __param$6(4, ICodeEditorService),
  __param$6(5, ICommandService),
  __param$6(6, IContextKeyService),
  __param$6(7, IKeybindingService),
  __param$6(8, IContextViewService),
  __param$6(9, IStandaloneThemeService),
  __param$6(10, INotificationService),
  __param$6(11, IConfigurationService),
  __param$6(12, IAccessibilityService)
], StandaloneEditor);
var StandaloneDiffEditor = class StandaloneDiffEditor2 extends DiffEditorWidget {
  constructor(domElement, options, toDispose, instantiationService, contextKeyService, keybindingService, contextViewService, editorWorkerService, codeEditorService, themeService, notificationService, configurationService, contextMenuService, editorProgressService, clipboardService) {
    applyConfigurationValues(configurationService, options, true);
    const themeDomRegistration = themeService.registerEditorContainer(domElement);
    options = options || {};
    if (typeof options.theme === "string") {
      options.theme = themeService.setTheme(options.theme);
    }
    super(domElement, options, clipboardService, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService, contextMenuService, editorProgressService);
    this._contextViewService = contextViewService;
    this._configurationService = configurationService;
    this._standaloneThemeService = themeService;
    this._register(toDispose);
    this._register(themeDomRegistration);
    this._contextViewService.setContainer(this._containerDomElement);
  }
  dispose() {
    super.dispose();
  }
  updateOptions(newOptions) {
    applyConfigurationValues(this._configurationService, newOptions, true);
    if (typeof newOptions.theme === "string") {
      this._standaloneThemeService.setTheme(newOptions.theme);
    }
    super.updateOptions(newOptions);
  }
  _createInnerEditor(instantiationService, container, options) {
    return instantiationService.createInstance(StandaloneCodeEditor, container, options);
  }
  getOriginalEditor() {
    return super.getOriginalEditor();
  }
  getModifiedEditor() {
    return super.getModifiedEditor();
  }
  addCommand(keybinding, handler, context2) {
    return this.getModifiedEditor().addCommand(keybinding, handler, context2);
  }
  createContextKey(key, defaultValue) {
    return this.getModifiedEditor().createContextKey(key, defaultValue);
  }
  addAction(descriptor) {
    return this.getModifiedEditor().addAction(descriptor);
  }
};
StandaloneDiffEditor = __decorate$7([
  __param$6(3, IInstantiationService),
  __param$6(4, IContextKeyService),
  __param$6(5, IKeybindingService),
  __param$6(6, IContextViewService),
  __param$6(7, IEditorWorkerService),
  __param$6(8, ICodeEditorService),
  __param$6(9, IStandaloneThemeService),
  __param$6(10, INotificationService),
  __param$6(11, IConfigurationService),
  __param$6(12, IContextMenuService),
  __param$6(13, IEditorProgressService),
  __param$6(14, IClipboardService)
], StandaloneDiffEditor);
var IModeService = createDecorator("modeService");
var FrankensteinMode = class {
  constructor(languageIdentifier) {
    this._languageIdentifier = languageIdentifier;
  }
  getId() {
    return this._languageIdentifier.language;
  }
};
var MIME_TEXT = "text/plain";
var MIME_UNKNOWN = "application/unknown";
var registeredAssociations = [];
var nonUserRegisteredAssociations = [];
var userRegisteredAssociations = [];
function registerTextMime(association, warnOnOverwrite = false) {
  const associationItem = toTextMimeAssociationItem(association);
  registeredAssociations.push(associationItem);
  if (!associationItem.userConfigured) {
    nonUserRegisteredAssociations.push(associationItem);
  } else {
    userRegisteredAssociations.push(associationItem);
  }
  if (warnOnOverwrite && !associationItem.userConfigured) {
    registeredAssociations.forEach((a2) => {
      if (a2.mime === associationItem.mime || a2.userConfigured) {
        return;
      }
      if (associationItem.extension && a2.extension === associationItem.extension) {
        console.warn(`Overwriting extension <<${associationItem.extension}>> to now point to mime <<${associationItem.mime}>>`);
      }
      if (associationItem.filename && a2.filename === associationItem.filename) {
        console.warn(`Overwriting filename <<${associationItem.filename}>> to now point to mime <<${associationItem.mime}>>`);
      }
      if (associationItem.filepattern && a2.filepattern === associationItem.filepattern) {
        console.warn(`Overwriting filepattern <<${associationItem.filepattern}>> to now point to mime <<${associationItem.mime}>>`);
      }
      if (associationItem.firstline && a2.firstline === associationItem.firstline) {
        console.warn(`Overwriting firstline <<${associationItem.firstline}>> to now point to mime <<${associationItem.mime}>>`);
      }
    });
  }
}
function toTextMimeAssociationItem(association) {
  return {
    id: association.id,
    mime: association.mime,
    filename: association.filename,
    extension: association.extension,
    filepattern: association.filepattern,
    firstline: association.firstline,
    userConfigured: association.userConfigured,
    filenameLowercase: association.filename ? association.filename.toLowerCase() : void 0,
    extensionLowercase: association.extension ? association.extension.toLowerCase() : void 0,
    filepatternLowercase: association.filepattern ? association.filepattern.toLowerCase() : void 0,
    filepatternOnPath: association.filepattern ? association.filepattern.indexOf(posix.sep) >= 0 : false
  };
}
function guessMimeTypes(resource2, firstLine) {
  let path;
  if (resource2) {
    switch (resource2.scheme) {
      case Schemas.file:
        path = resource2.fsPath;
        break;
      case Schemas.data:
        const metadata = DataUri.parseMetaData(resource2);
        path = metadata.get(DataUri.META_DATA_LABEL);
        break;
      default:
        path = resource2.path;
    }
  }
  if (!path) {
    return [MIME_UNKNOWN];
  }
  path = path.toLowerCase();
  const filename = basename(path);
  const configuredMime = guessMimeTypeByPath(path, filename, userRegisteredAssociations);
  if (configuredMime) {
    return [configuredMime, MIME_TEXT];
  }
  const registeredMime = guessMimeTypeByPath(path, filename, nonUserRegisteredAssociations);
  if (registeredMime) {
    return [registeredMime, MIME_TEXT];
  }
  if (firstLine) {
    const firstlineMime = guessMimeTypeByFirstline(firstLine);
    if (firstlineMime) {
      return [firstlineMime, MIME_TEXT];
    }
  }
  return [MIME_UNKNOWN];
}
function guessMimeTypeByPath(path, filename, associations) {
  let filenameMatch = null;
  let patternMatch = null;
  let extensionMatch = null;
  for (let i3 = associations.length - 1; i3 >= 0; i3--) {
    const association = associations[i3];
    if (filename === association.filenameLowercase) {
      filenameMatch = association;
      break;
    }
    if (association.filepattern) {
      if (!patternMatch || association.filepattern.length > patternMatch.filepattern.length) {
        const target = association.filepatternOnPath ? path : filename;
        if (match(association.filepatternLowercase, target)) {
          patternMatch = association;
        }
      }
    }
    if (association.extension) {
      if (!extensionMatch || association.extension.length > extensionMatch.extension.length) {
        if (filename.endsWith(association.extensionLowercase)) {
          extensionMatch = association;
        }
      }
    }
  }
  if (filenameMatch) {
    return filenameMatch.mime;
  }
  if (patternMatch) {
    return patternMatch.mime;
  }
  if (extensionMatch) {
    return extensionMatch.mime;
  }
  return null;
}
function guessMimeTypeByFirstline(firstLine) {
  if (startsWithUTF8BOM(firstLine)) {
    firstLine = firstLine.substr(1);
  }
  if (firstLine.length > 0) {
    for (let i3 = registeredAssociations.length - 1; i3 >= 0; i3--) {
      const association = registeredAssociations[i3];
      if (!association.firstline) {
        continue;
      }
      const matches2 = firstLine.match(association.firstline);
      if (matches2 && matches2.length > 0) {
        return association.mime;
      }
    }
  }
  return null;
}
var Extensions$6 = {
  ModesRegistry: "editor.modesRegistry"
};
var EditorModesRegistry = class {
  constructor() {
    this._onDidChangeLanguages = new Emitter();
    this.onDidChangeLanguages = this._onDidChangeLanguages.event;
    this._languages = [];
    this._dynamicLanguages = [];
  }
  registerLanguage(def) {
    this._languages.push(def);
    this._onDidChangeLanguages.fire(void 0);
    return {
      dispose: () => {
        for (let i3 = 0, len2 = this._languages.length; i3 < len2; i3++) {
          if (this._languages[i3] === def) {
            this._languages.splice(i3, 1);
            return;
          }
        }
      }
    };
  }
  getLanguages() {
    return [].concat(this._languages).concat(this._dynamicLanguages);
  }
};
var ModesRegistry = new EditorModesRegistry();
Registry$1.add(Extensions$6.ModesRegistry, ModesRegistry);
var PLAINTEXT_MODE_ID = "plaintext";
var PLAINTEXT_LANGUAGE_IDENTIFIER = new LanguageIdentifier(PLAINTEXT_MODE_ID, 1);
ModesRegistry.registerLanguage({
  id: PLAINTEXT_MODE_ID,
  extensions: [".txt"],
  aliases: [localize("plainText.alias", "Plain Text"), "text"],
  mimetypes: ["text/plain"]
});
LanguageConfigurationRegistry.register(PLAINTEXT_LANGUAGE_IDENTIFIER, {
  brackets: [
    ["(", ")"],
    ["[", "]"],
    ["{", "}"]
  ],
  surroundingPairs: [
    {open: "{", close: "}"},
    {open: "[", close: "]"},
    {open: "(", close: ")"},
    {open: "<", close: ">"},
    {open: '"', close: '"'},
    {open: "'", close: "'"},
    {open: "`", close: "`"}
  ],
  folding: {
    offSide: true
  }
});
var hasOwnProperty$3 = Object.prototype.hasOwnProperty;
var LanguagesRegistry = class extends Disposable {
  constructor(useModesRegistry = true, warnOnOverwrite = false) {
    super();
    this._onDidChange = this._register(new Emitter());
    this.onDidChange = this._onDidChange.event;
    this._warnOnOverwrite = warnOnOverwrite;
    this._nextLanguageId2 = 1;
    this._languageIdToLanguage = [];
    this._languageToLanguageId = Object.create(null);
    this._languages = {};
    this._mimeTypesMap = {};
    this._nameMap = {};
    this._lowercaseNameMap = {};
    if (useModesRegistry) {
      this._initializeFromRegistry();
      this._register(ModesRegistry.onDidChangeLanguages((m2) => this._initializeFromRegistry()));
    }
  }
  _initializeFromRegistry() {
    this._languages = {};
    this._mimeTypesMap = {};
    this._nameMap = {};
    this._lowercaseNameMap = {};
    const desc = ModesRegistry.getLanguages();
    this._registerLanguages(desc);
  }
  _registerLanguages(desc) {
    for (const d2 of desc) {
      this._registerLanguage(d2);
    }
    this._mimeTypesMap = {};
    this._nameMap = {};
    this._lowercaseNameMap = {};
    Object.keys(this._languages).forEach((langId) => {
      let language = this._languages[langId];
      if (language.name) {
        this._nameMap[language.name] = language.identifier;
      }
      language.aliases.forEach((alias) => {
        this._lowercaseNameMap[alias.toLowerCase()] = language.identifier;
      });
      language.mimetypes.forEach((mimetype) => {
        this._mimeTypesMap[mimetype] = language.identifier;
      });
    });
    Registry$1.as(Extensions$1.Configuration).registerOverrideIdentifiers(ModesRegistry.getLanguages().map((language) => language.id));
    this._onDidChange.fire();
  }
  _getLanguageId(language) {
    if (this._languageToLanguageId[language]) {
      return this._languageToLanguageId[language];
    }
    const languageId = this._nextLanguageId2++;
    this._languageIdToLanguage[languageId] = language;
    this._languageToLanguageId[language] = languageId;
    return languageId;
  }
  _registerLanguage(lang) {
    const langId = lang.id;
    let resolvedLanguage;
    if (hasOwnProperty$3.call(this._languages, langId)) {
      resolvedLanguage = this._languages[langId];
    } else {
      const languageId = this._getLanguageId(langId);
      resolvedLanguage = {
        identifier: new LanguageIdentifier(langId, languageId),
        name: null,
        mimetypes: [],
        aliases: [],
        extensions: [],
        filenames: [],
        configurationFiles: []
      };
      this._languages[langId] = resolvedLanguage;
    }
    this._mergeLanguage(resolvedLanguage, lang);
  }
  _mergeLanguage(resolvedLanguage, lang) {
    const langId = lang.id;
    let primaryMime = null;
    if (Array.isArray(lang.mimetypes) && lang.mimetypes.length > 0) {
      resolvedLanguage.mimetypes.push(...lang.mimetypes);
      primaryMime = lang.mimetypes[0];
    }
    if (!primaryMime) {
      primaryMime = `text/x-${langId}`;
      resolvedLanguage.mimetypes.push(primaryMime);
    }
    if (Array.isArray(lang.extensions)) {
      if (lang.configuration) {
        resolvedLanguage.extensions = lang.extensions.concat(resolvedLanguage.extensions);
      } else {
        resolvedLanguage.extensions = resolvedLanguage.extensions.concat(lang.extensions);
      }
      for (let extension of lang.extensions) {
        registerTextMime({id: langId, mime: primaryMime, extension}, this._warnOnOverwrite);
      }
    }
    if (Array.isArray(lang.filenames)) {
      for (let filename of lang.filenames) {
        registerTextMime({id: langId, mime: primaryMime, filename}, this._warnOnOverwrite);
        resolvedLanguage.filenames.push(filename);
      }
    }
    if (Array.isArray(lang.filenamePatterns)) {
      for (let filenamePattern of lang.filenamePatterns) {
        registerTextMime({id: langId, mime: primaryMime, filepattern: filenamePattern}, this._warnOnOverwrite);
      }
    }
    if (typeof lang.firstLine === "string" && lang.firstLine.length > 0) {
      let firstLineRegexStr = lang.firstLine;
      if (firstLineRegexStr.charAt(0) !== "^") {
        firstLineRegexStr = "^" + firstLineRegexStr;
      }
      try {
        let firstLineRegex = new RegExp(firstLineRegexStr);
        if (!regExpLeadsToEndlessLoop(firstLineRegex)) {
          registerTextMime({id: langId, mime: primaryMime, firstline: firstLineRegex}, this._warnOnOverwrite);
        }
      } catch (err) {
        onUnexpectedError(err);
      }
    }
    resolvedLanguage.aliases.push(langId);
    let langAliases = null;
    if (typeof lang.aliases !== "undefined" && Array.isArray(lang.aliases)) {
      if (lang.aliases.length === 0) {
        langAliases = [null];
      } else {
        langAliases = lang.aliases;
      }
    }
    if (langAliases !== null) {
      for (const langAlias of langAliases) {
        if (!langAlias || langAlias.length === 0) {
          continue;
        }
        resolvedLanguage.aliases.push(langAlias);
      }
    }
    let containsAliases = langAliases !== null && langAliases.length > 0;
    if (containsAliases && langAliases[0] === null)
      ;
    else {
      let bestName = (containsAliases ? langAliases[0] : null) || langId;
      if (containsAliases || !resolvedLanguage.name) {
        resolvedLanguage.name = bestName;
      }
    }
    if (lang.configuration) {
      resolvedLanguage.configurationFiles.push(lang.configuration);
    }
  }
  isRegisteredMode(mimetypeOrModeId) {
    if (hasOwnProperty$3.call(this._mimeTypesMap, mimetypeOrModeId)) {
      return true;
    }
    return hasOwnProperty$3.call(this._languages, mimetypeOrModeId);
  }
  getModeIdForLanguageNameLowercase(languageNameLower) {
    if (!hasOwnProperty$3.call(this._lowercaseNameMap, languageNameLower)) {
      return null;
    }
    return this._lowercaseNameMap[languageNameLower].language;
  }
  extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds) {
    if (!commaSeparatedMimetypesOrCommaSeparatedIds) {
      return [];
    }
    return commaSeparatedMimetypesOrCommaSeparatedIds.split(",").map((mimeTypeOrId) => mimeTypeOrId.trim()).map((mimeTypeOrId) => {
      if (hasOwnProperty$3.call(this._mimeTypesMap, mimeTypeOrId)) {
        return this._mimeTypesMap[mimeTypeOrId].language;
      }
      return mimeTypeOrId;
    }).filter((modeId) => {
      return hasOwnProperty$3.call(this._languages, modeId);
    });
  }
  getLanguageIdentifier(_modeId) {
    if (_modeId === NULL_MODE_ID || _modeId === 0) {
      return NULL_LANGUAGE_IDENTIFIER;
    }
    let modeId;
    if (typeof _modeId === "string") {
      modeId = _modeId;
    } else {
      modeId = this._languageIdToLanguage[_modeId];
      if (!modeId) {
        return null;
      }
    }
    if (!hasOwnProperty$3.call(this._languages, modeId)) {
      return null;
    }
    return this._languages[modeId].identifier;
  }
  getModeIdsFromFilepathOrFirstLine(resource2, firstLine) {
    if (!resource2 && !firstLine) {
      return [];
    }
    let mimeTypes = guessMimeTypes(resource2, firstLine);
    return this.extractModeIds(mimeTypes.join(","));
  }
};
var LanguageSelection = class extends Disposable {
  constructor(onLanguagesMaybeChanged, selector2) {
    super();
    this._onDidChange = this._register(new Emitter());
    this.onDidChange = this._onDidChange.event;
    this._selector = selector2;
    this.languageIdentifier = this._selector();
    this._register(onLanguagesMaybeChanged(() => this._evaluate()));
  }
  _evaluate() {
    let languageIdentifier = this._selector();
    if (languageIdentifier.id === this.languageIdentifier.id) {
      return;
    }
    this.languageIdentifier = languageIdentifier;
    this._onDidChange.fire(this.languageIdentifier);
  }
};
var ModeServiceImpl = class {
  constructor(warnOnOverwrite = false) {
    this._onDidCreateMode = new Emitter();
    this.onDidCreateMode = this._onDidCreateMode.event;
    this._onLanguagesMaybeChanged = new Emitter();
    this.onLanguagesMaybeChanged = this._onLanguagesMaybeChanged.event;
    this._instantiatedModes = {};
    this._registry = new LanguagesRegistry(true, warnOnOverwrite);
    this._registry.onDidChange(() => this._onLanguagesMaybeChanged.fire());
  }
  isRegisteredMode(mimetypeOrModeId) {
    return this._registry.isRegisteredMode(mimetypeOrModeId);
  }
  getModeIdForLanguageName(alias) {
    return this._registry.getModeIdForLanguageNameLowercase(alias);
  }
  getModeIdByFilepathOrFirstLine(resource2, firstLine) {
    const modeIds = this._registry.getModeIdsFromFilepathOrFirstLine(resource2, firstLine);
    return firstOrDefault(modeIds, null);
  }
  getModeId(commaSeparatedMimetypesOrCommaSeparatedIds) {
    const modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds);
    return firstOrDefault(modeIds, null);
  }
  getLanguageIdentifier(modeId) {
    return this._registry.getLanguageIdentifier(modeId);
  }
  create(commaSeparatedMimetypesOrCommaSeparatedIds) {
    return new LanguageSelection(this.onLanguagesMaybeChanged, () => {
      const modeId = this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds);
      return this._createModeAndGetLanguageIdentifier(modeId);
    });
  }
  createByFilepathOrFirstLine(resource2, firstLine) {
    return new LanguageSelection(this.onLanguagesMaybeChanged, () => {
      const modeId = this.getModeIdByFilepathOrFirstLine(resource2, firstLine);
      return this._createModeAndGetLanguageIdentifier(modeId);
    });
  }
  _createModeAndGetLanguageIdentifier(modeId) {
    const languageIdentifier = this.getLanguageIdentifier(modeId || "plaintext") || NULL_LANGUAGE_IDENTIFIER;
    this._getOrCreateMode(languageIdentifier.language);
    return languageIdentifier;
  }
  triggerMode(commaSeparatedMimetypesOrCommaSeparatedIds) {
    const modeId = this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds);
    this._getOrCreateMode(modeId || "plaintext");
  }
  _getOrCreateMode(modeId) {
    if (!this._instantiatedModes.hasOwnProperty(modeId)) {
      let languageIdentifier = this.getLanguageIdentifier(modeId) || NULL_LANGUAGE_IDENTIFIER;
      this._instantiatedModes[modeId] = new FrankensteinMode(languageIdentifier);
      this._onDidCreateMode.fire(this._instantiatedModes[modeId]);
    }
    return this._instantiatedModes[modeId];
  }
};
var IUndoRedoService = createDecorator("undoRedoService");
var ResourceEditStackSnapshot = class {
  constructor(resource2, elements) {
    this.resource = resource2;
    this.elements = elements;
  }
};
var SemanticTokensProviderStyling = class {
  constructor(_legend, _themeService, _logService) {
    this._legend = _legend;
    this._themeService = _themeService;
    this._logService = _logService;
    this._hashTable = new HashTable();
  }
  getMetadata(tokenTypeIndex, tokenModifierSet, languageId) {
    const entry = this._hashTable.get(tokenTypeIndex, tokenModifierSet, languageId.id);
    let metadata;
    if (entry) {
      metadata = entry.metadata;
      if (this._logService.getLevel() === LogLevel.Trace) {
        this._logService.trace(`SemanticTokensProviderStyling [CACHED] ${tokenTypeIndex} / ${tokenModifierSet}: foreground ${TokenMetadata.getForeground(metadata)}, fontStyle ${TokenMetadata.getFontStyle(metadata).toString(2)}`);
      }
    } else {
      let tokenType = this._legend.tokenTypes[tokenTypeIndex];
      const tokenModifiers = [];
      if (tokenType) {
        let modifierSet = tokenModifierSet;
        for (let modifierIndex = 0; modifierSet > 0 && modifierIndex < this._legend.tokenModifiers.length; modifierIndex++) {
          if (modifierSet & 1) {
            tokenModifiers.push(this._legend.tokenModifiers[modifierIndex]);
          }
          modifierSet = modifierSet >> 1;
        }
        if (modifierSet > 0 && this._logService.getLevel() === LogLevel.Trace) {
          this._logService.trace(`SemanticTokensProviderStyling: unknown token modifier index: ${tokenModifierSet.toString(2)} for legend: ${JSON.stringify(this._legend.tokenModifiers)}`);
          tokenModifiers.push("not-in-legend");
        }
        const tokenStyle = this._themeService.getColorTheme().getTokenStyleMetadata(tokenType, tokenModifiers, languageId.language);
        if (typeof tokenStyle === "undefined") {
          metadata = 2147483647;
        } else {
          metadata = 0;
          if (typeof tokenStyle.italic !== "undefined") {
            const italicBit = (tokenStyle.italic ? 1 : 0) << 11;
            metadata |= italicBit | 1;
          }
          if (typeof tokenStyle.bold !== "undefined") {
            const boldBit = (tokenStyle.bold ? 2 : 0) << 11;
            metadata |= boldBit | 2;
          }
          if (typeof tokenStyle.underline !== "undefined") {
            const underlineBit = (tokenStyle.underline ? 4 : 0) << 11;
            metadata |= underlineBit | 4;
          }
          if (tokenStyle.foreground) {
            const foregroundBits = tokenStyle.foreground << 14;
            metadata |= foregroundBits | 8;
          }
          if (metadata === 0) {
            metadata = 2147483647;
          }
        }
      } else {
        if (this._logService.getLevel() === LogLevel.Trace) {
          this._logService.trace(`SemanticTokensProviderStyling: unknown token type index: ${tokenTypeIndex} for legend: ${JSON.stringify(this._legend.tokenTypes)}`);
        }
        metadata = 2147483647;
        tokenType = "not-in-legend";
      }
      this._hashTable.add(tokenTypeIndex, tokenModifierSet, languageId.id, metadata);
      if (this._logService.getLevel() === LogLevel.Trace) {
        this._logService.trace(`SemanticTokensProviderStyling ${tokenTypeIndex} (${tokenType}) / ${tokenModifierSet} (${tokenModifiers.join(" ")}): foreground ${TokenMetadata.getForeground(metadata)}, fontStyle ${TokenMetadata.getFontStyle(metadata).toString(2)}`);
      }
    }
    return metadata;
  }
};
function toMultilineTokens2(tokens, styling, languageId) {
  const srcData = tokens.data;
  const tokenCount = tokens.data.length / 5 | 0;
  const tokensPerArea = Math.max(Math.ceil(tokenCount / 1024), 400);
  const result = [];
  let tokenIndex = 0;
  let lastLineNumber = 1;
  let lastStartCharacter = 0;
  while (tokenIndex < tokenCount) {
    const tokenStartIndex = tokenIndex;
    let tokenEndIndex = Math.min(tokenStartIndex + tokensPerArea, tokenCount);
    if (tokenEndIndex < tokenCount) {
      let smallTokenEndIndex = tokenEndIndex;
      while (smallTokenEndIndex - 1 > tokenStartIndex && srcData[5 * smallTokenEndIndex] === 0) {
        smallTokenEndIndex--;
      }
      if (smallTokenEndIndex - 1 === tokenStartIndex) {
        let bigTokenEndIndex = tokenEndIndex;
        while (bigTokenEndIndex + 1 < tokenCount && srcData[5 * bigTokenEndIndex] === 0) {
          bigTokenEndIndex++;
        }
        tokenEndIndex = bigTokenEndIndex;
      } else {
        tokenEndIndex = smallTokenEndIndex;
      }
    }
    let destData = new Uint32Array((tokenEndIndex - tokenStartIndex) * 4);
    let destOffset = 0;
    let areaLine = 0;
    while (tokenIndex < tokenEndIndex) {
      const srcOffset = 5 * tokenIndex;
      const deltaLine = srcData[srcOffset];
      const deltaCharacter = srcData[srcOffset + 1];
      const lineNumber = lastLineNumber + deltaLine;
      const startCharacter = deltaLine === 0 ? lastStartCharacter + deltaCharacter : deltaCharacter;
      const length = srcData[srcOffset + 2];
      const tokenTypeIndex = srcData[srcOffset + 3];
      const tokenModifierSet = srcData[srcOffset + 4];
      const metadata = styling.getMetadata(tokenTypeIndex, tokenModifierSet, languageId);
      if (metadata !== 2147483647) {
        if (areaLine === 0) {
          areaLine = lineNumber;
        }
        destData[destOffset] = lineNumber - areaLine;
        destData[destOffset + 1] = startCharacter;
        destData[destOffset + 2] = startCharacter + length;
        destData[destOffset + 3] = metadata;
        destOffset += 4;
      }
      lastLineNumber = lineNumber;
      lastStartCharacter = startCharacter;
      tokenIndex++;
    }
    if (destOffset !== destData.length) {
      destData = destData.subarray(0, destOffset);
    }
    const tokens2 = new MultilineTokens2(areaLine, new SparseEncodedTokens(destData));
    result.push(tokens2);
  }
  return result;
}
var HashTableEntry = class {
  constructor(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
    this.tokenTypeIndex = tokenTypeIndex;
    this.tokenModifierSet = tokenModifierSet;
    this.languageId = languageId;
    this.metadata = metadata;
    this.next = null;
  }
};
var HashTable = class {
  constructor() {
    this._elementsCount = 0;
    this._currentLengthIndex = 0;
    this._currentLength = HashTable._SIZES[this._currentLengthIndex];
    this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
    this._elements = [];
    HashTable._nullOutEntries(this._elements, this._currentLength);
  }
  static _nullOutEntries(entries, length) {
    for (let i3 = 0; i3 < length; i3++) {
      entries[i3] = null;
    }
  }
  _hash2(n1, n22) {
    return (n1 << 5) - n1 + n22 | 0;
  }
  _hashFunc(tokenTypeIndex, tokenModifierSet, languageId) {
    return this._hash2(this._hash2(tokenTypeIndex, tokenModifierSet), languageId) % this._currentLength;
  }
  get(tokenTypeIndex, tokenModifierSet, languageId) {
    const hash2 = this._hashFunc(tokenTypeIndex, tokenModifierSet, languageId);
    let p2 = this._elements[hash2];
    while (p2) {
      if (p2.tokenTypeIndex === tokenTypeIndex && p2.tokenModifierSet === tokenModifierSet && p2.languageId === languageId) {
        return p2;
      }
      p2 = p2.next;
    }
    return null;
  }
  add(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
    this._elementsCount++;
    if (this._growCount !== 0 && this._elementsCount >= this._growCount) {
      const oldElements = this._elements;
      this._currentLengthIndex++;
      this._currentLength = HashTable._SIZES[this._currentLengthIndex];
      this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
      this._elements = [];
      HashTable._nullOutEntries(this._elements, this._currentLength);
      for (const first2 of oldElements) {
        let p2 = first2;
        while (p2) {
          const oldNext = p2.next;
          p2.next = null;
          this._add(p2);
          p2 = oldNext;
        }
      }
    }
    this._add(new HashTableEntry(tokenTypeIndex, tokenModifierSet, languageId, metadata));
  }
  _add(element) {
    const hash2 = this._hashFunc(element.tokenTypeIndex, element.tokenModifierSet, element.languageId);
    element.next = this._elements[hash2];
    this._elements[hash2] = element;
  }
};
HashTable._SIZES = [3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143];
var __decorate$8 = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$7 = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
function MODEL_ID$1(resource2) {
  return resource2.toString();
}
function computeModelSha1(model) {
  const shaComputer = new StringSHA1();
  const snapshot = model.createSnapshot();
  let text;
  while (text = snapshot.read()) {
    shaComputer.update(text);
  }
  return shaComputer.digest();
}
var ModelData$1 = class {
  constructor(model, onWillDispose, onDidChangeLanguage) {
    this._modelEventListeners = new DisposableStore();
    this.model = model;
    this._languageSelection = null;
    this._languageSelectionListener = null;
    this._modelEventListeners.add(model.onWillDispose(() => onWillDispose(model)));
    this._modelEventListeners.add(model.onDidChangeLanguage((e2) => onDidChangeLanguage(model, e2)));
  }
  _disposeLanguageSelection() {
    if (this._languageSelectionListener) {
      this._languageSelectionListener.dispose();
      this._languageSelectionListener = null;
    }
    if (this._languageSelection) {
      this._languageSelection.dispose();
      this._languageSelection = null;
    }
  }
  dispose() {
    this._modelEventListeners.dispose();
    this._disposeLanguageSelection();
  }
  setLanguage(languageSelection) {
    this._disposeLanguageSelection();
    this._languageSelection = languageSelection;
    this._languageSelectionListener = this._languageSelection.onDidChange(() => this.model.setMode(languageSelection.languageIdentifier));
    this.model.setMode(languageSelection.languageIdentifier);
  }
};
var DEFAULT_EOL = isLinux || isMacintosh ? 1 : 2;
var ModelServiceImpl = class ModelServiceImpl2 extends Disposable {
  constructor(_configurationService, _resourcePropertiesService, _themeService, _logService, _undoRedoService) {
    super();
    this._configurationService = _configurationService;
    this._resourcePropertiesService = _resourcePropertiesService;
    this._themeService = _themeService;
    this._logService = _logService;
    this._undoRedoService = _undoRedoService;
    this._onModelAdded = this._register(new Emitter());
    this.onModelAdded = this._onModelAdded.event;
    this._onModelRemoved = this._register(new Emitter());
    this.onModelRemoved = this._onModelRemoved.event;
    this._onModelModeChanged = this._register(new Emitter());
    this.onModelModeChanged = this._onModelModeChanged.event;
    this._modelCreationOptionsByLanguageAndResource = Object.create(null);
    this._models = {};
    this._disposedModels = new Map();
    this._disposedModelsHeapSize = 0;
    this._semanticStyling = this._register(new SemanticStyling(this._themeService, this._logService));
    this._register(this._configurationService.onDidChangeConfiguration(() => this._updateModelOptions()));
    this._updateModelOptions();
    this._register(new SemanticColoringFeature(this, this._themeService, this._configurationService, this._semanticStyling));
  }
  static _readModelOptions(config2, isForSimpleWidget) {
    let tabSize = EDITOR_MODEL_DEFAULTS.tabSize;
    if (config2.editor && typeof config2.editor.tabSize !== "undefined") {
      const parsedTabSize = parseInt(config2.editor.tabSize, 10);
      if (!isNaN(parsedTabSize)) {
        tabSize = parsedTabSize;
      }
      if (tabSize < 1) {
        tabSize = 1;
      }
    }
    let indentSize = tabSize;
    if (config2.editor && typeof config2.editor.indentSize !== "undefined" && config2.editor.indentSize !== "tabSize") {
      const parsedIndentSize = parseInt(config2.editor.indentSize, 10);
      if (!isNaN(parsedIndentSize)) {
        indentSize = parsedIndentSize;
      }
      if (indentSize < 1) {
        indentSize = 1;
      }
    }
    let insertSpaces = EDITOR_MODEL_DEFAULTS.insertSpaces;
    if (config2.editor && typeof config2.editor.insertSpaces !== "undefined") {
      insertSpaces = config2.editor.insertSpaces === "false" ? false : Boolean(config2.editor.insertSpaces);
    }
    let newDefaultEOL = DEFAULT_EOL;
    const eol = config2.eol;
    if (eol === "\r\n") {
      newDefaultEOL = 2;
    } else if (eol === "\n") {
      newDefaultEOL = 1;
    }
    let trimAutoWhitespace = EDITOR_MODEL_DEFAULTS.trimAutoWhitespace;
    if (config2.editor && typeof config2.editor.trimAutoWhitespace !== "undefined") {
      trimAutoWhitespace = config2.editor.trimAutoWhitespace === "false" ? false : Boolean(config2.editor.trimAutoWhitespace);
    }
    let detectIndentation = EDITOR_MODEL_DEFAULTS.detectIndentation;
    if (config2.editor && typeof config2.editor.detectIndentation !== "undefined") {
      detectIndentation = config2.editor.detectIndentation === "false" ? false : Boolean(config2.editor.detectIndentation);
    }
    let largeFileOptimizations = EDITOR_MODEL_DEFAULTS.largeFileOptimizations;
    if (config2.editor && typeof config2.editor.largeFileOptimizations !== "undefined") {
      largeFileOptimizations = config2.editor.largeFileOptimizations === "false" ? false : Boolean(config2.editor.largeFileOptimizations);
    }
    return {
      isForSimpleWidget,
      tabSize,
      indentSize,
      insertSpaces,
      detectIndentation,
      defaultEOL: newDefaultEOL,
      trimAutoWhitespace,
      largeFileOptimizations
    };
  }
  _getEOL(resource2, language) {
    if (resource2) {
      return this._resourcePropertiesService.getEOL(resource2, language);
    }
    const eol = this._configurationService.getValue("files.eol", {overrideIdentifier: language});
    if (eol && eol !== "auto") {
      return eol;
    }
    return OS === 3 || OS === 2 ? "\n" : "\r\n";
  }
  getCreationOptions(language, resource2, isForSimpleWidget) {
    let creationOptions = this._modelCreationOptionsByLanguageAndResource[language + resource2];
    if (!creationOptions) {
      const editor2 = this._configurationService.getValue("editor", {overrideIdentifier: language, resource: resource2});
      const eol = this._getEOL(resource2, language);
      creationOptions = ModelServiceImpl2._readModelOptions({editor: editor2, eol}, isForSimpleWidget);
      this._modelCreationOptionsByLanguageAndResource[language + resource2] = creationOptions;
    }
    return creationOptions;
  }
  _updateModelOptions() {
    const oldOptionsByLanguageAndResource = this._modelCreationOptionsByLanguageAndResource;
    this._modelCreationOptionsByLanguageAndResource = Object.create(null);
    const keys2 = Object.keys(this._models);
    for (let i3 = 0, len2 = keys2.length; i3 < len2; i3++) {
      const modelId = keys2[i3];
      const modelData = this._models[modelId];
      const language = modelData.model.getLanguageIdentifier().language;
      const uri = modelData.model.uri;
      const oldOptions = oldOptionsByLanguageAndResource[language + uri];
      const newOptions = this.getCreationOptions(language, uri, modelData.model.isForSimpleWidget);
      ModelServiceImpl2._setModelOptionsForModel(modelData.model, newOptions, oldOptions);
    }
  }
  static _setModelOptionsForModel(model, newOptions, currentOptions) {
    if (currentOptions && currentOptions.defaultEOL !== newOptions.defaultEOL && model.getLineCount() === 1) {
      model.setEOL(newOptions.defaultEOL === 1 ? 0 : 1);
    }
    if (currentOptions && currentOptions.detectIndentation === newOptions.detectIndentation && currentOptions.insertSpaces === newOptions.insertSpaces && currentOptions.tabSize === newOptions.tabSize && currentOptions.indentSize === newOptions.indentSize && currentOptions.trimAutoWhitespace === newOptions.trimAutoWhitespace) {
      return;
    }
    if (newOptions.detectIndentation) {
      model.detectIndentation(newOptions.insertSpaces, newOptions.tabSize);
      model.updateOptions({
        trimAutoWhitespace: newOptions.trimAutoWhitespace
      });
    } else {
      model.updateOptions({
        insertSpaces: newOptions.insertSpaces,
        tabSize: newOptions.tabSize,
        indentSize: newOptions.indentSize,
        trimAutoWhitespace: newOptions.trimAutoWhitespace
      });
    }
  }
  _removeDisposedModel(resource2) {
    const disposedModelData = this._disposedModels.get(MODEL_ID$1(resource2));
    if (disposedModelData) {
      this._disposedModelsHeapSize -= disposedModelData.heapSize;
    }
    this._disposedModels.delete(MODEL_ID$1(resource2));
    return disposedModelData;
  }
  _createModelData(value, languageIdentifier, resource2, isForSimpleWidget) {
    const options = this.getCreationOptions(languageIdentifier.language, resource2, isForSimpleWidget);
    const model = new TextModel(value, options, languageIdentifier, resource2, this._undoRedoService);
    if (resource2 && this._disposedModels.has(MODEL_ID$1(resource2))) {
      const disposedModelData = this._removeDisposedModel(resource2);
      const elements = this._undoRedoService.getElements(resource2);
      const sha1IsEqual = computeModelSha1(model) === disposedModelData.sha1;
      if (sha1IsEqual || disposedModelData.sharesUndoRedoStack) {
        for (const element of elements.past) {
          if (isEditStackElement(element) && element.matchesResource(resource2)) {
            element.setModel(model);
          }
        }
        for (const element of elements.future) {
          if (isEditStackElement(element) && element.matchesResource(resource2)) {
            element.setModel(model);
          }
        }
        this._undoRedoService.setElementsValidFlag(resource2, true, (element) => isEditStackElement(element) && element.matchesResource(resource2));
        if (sha1IsEqual) {
          model._overwriteVersionId(disposedModelData.versionId);
          model._overwriteAlternativeVersionId(disposedModelData.alternativeVersionId);
          model._overwriteInitialUndoRedoSnapshot(disposedModelData.initialUndoRedoSnapshot);
        }
      } else {
        if (disposedModelData.initialUndoRedoSnapshot !== null) {
          this._undoRedoService.restoreSnapshot(disposedModelData.initialUndoRedoSnapshot);
        }
      }
    }
    const modelId = MODEL_ID$1(model.uri);
    if (this._models[modelId]) {
      throw new Error("ModelService: Cannot add model because it already exists!");
    }
    const modelData = new ModelData$1(model, (model2) => this._onWillDispose(model2), (model2, e2) => this._onDidChangeLanguage(model2, e2));
    this._models[modelId] = modelData;
    return modelData;
  }
  createModel(value, languageSelection, resource2, isForSimpleWidget = false) {
    let modelData;
    if (languageSelection) {
      modelData = this._createModelData(value, languageSelection.languageIdentifier, resource2, isForSimpleWidget);
      this.setMode(modelData.model, languageSelection);
    } else {
      modelData = this._createModelData(value, PLAINTEXT_LANGUAGE_IDENTIFIER, resource2, isForSimpleWidget);
    }
    this._onModelAdded.fire(modelData.model);
    return modelData.model;
  }
  setMode(model, languageSelection) {
    if (!languageSelection) {
      return;
    }
    const modelData = this._models[MODEL_ID$1(model.uri)];
    if (!modelData) {
      return;
    }
    modelData.setLanguage(languageSelection);
  }
  getModels() {
    const ret = [];
    const keys2 = Object.keys(this._models);
    for (let i3 = 0, len2 = keys2.length; i3 < len2; i3++) {
      const modelId = keys2[i3];
      ret.push(this._models[modelId].model);
    }
    return ret;
  }
  getModel(resource2) {
    const modelId = MODEL_ID$1(resource2);
    const modelData = this._models[modelId];
    if (!modelData) {
      return null;
    }
    return modelData.model;
  }
  getSemanticTokensProviderStyling(provider) {
    return this._semanticStyling.get(provider);
  }
  _onWillDispose(model) {
    const modelId = MODEL_ID$1(model.uri);
    const modelData = this._models[modelId];
    delete this._models[modelId];
    modelData.dispose();
    delete this._modelCreationOptionsByLanguageAndResource[model.getLanguageIdentifier().language + model.uri];
    this._onModelRemoved.fire(model);
  }
  _onDidChangeLanguage(model, e2) {
    const oldModeId = e2.oldLanguage;
    const newModeId = model.getLanguageIdentifier().language;
    const oldOptions = this.getCreationOptions(oldModeId, model.uri, model.isForSimpleWidget);
    const newOptions = this.getCreationOptions(newModeId, model.uri, model.isForSimpleWidget);
    ModelServiceImpl2._setModelOptionsForModel(model, newOptions, oldOptions);
    this._onModelModeChanged.fire({model, oldModeId});
  }
};
ModelServiceImpl = __decorate$8([
  __param$7(0, IConfigurationService),
  __param$7(1, ITextResourcePropertiesService),
  __param$7(2, IThemeService),
  __param$7(3, ILogService),
  __param$7(4, IUndoRedoService)
], ModelServiceImpl);
var SEMANTIC_HIGHLIGHTING_SETTING_ID = "editor.semanticHighlighting";
function isSemanticColoringEnabled(model, themeService, configurationService) {
  var _a;
  const setting = (_a = configurationService.getValue(SEMANTIC_HIGHLIGHTING_SETTING_ID, {overrideIdentifier: model.getLanguageIdentifier().language, resource: model.uri})) === null || _a === void 0 ? void 0 : _a.enabled;
  if (typeof setting === "boolean") {
    return setting;
  }
  return themeService.getColorTheme().semanticHighlighting;
}
var SemanticColoringFeature = class extends Disposable {
  constructor(modelService, themeService, configurationService, semanticStyling) {
    super();
    this._watchers = Object.create(null);
    this._semanticStyling = semanticStyling;
    const register2 = (model) => {
      this._watchers[model.uri.toString()] = new ModelSemanticColoring(model, themeService, this._semanticStyling);
    };
    const deregister = (model, modelSemanticColoring) => {
      modelSemanticColoring.dispose();
      delete this._watchers[model.uri.toString()];
    };
    const handleSettingOrThemeChange = () => {
      for (let model of modelService.getModels()) {
        const curr = this._watchers[model.uri.toString()];
        if (isSemanticColoringEnabled(model, themeService, configurationService)) {
          if (!curr) {
            register2(model);
          }
        } else {
          if (curr) {
            deregister(model, curr);
          }
        }
      }
    };
    this._register(modelService.onModelAdded((model) => {
      if (isSemanticColoringEnabled(model, themeService, configurationService)) {
        register2(model);
      }
    }));
    this._register(modelService.onModelRemoved((model) => {
      const curr = this._watchers[model.uri.toString()];
      if (curr) {
        deregister(model, curr);
      }
    }));
    this._register(configurationService.onDidChangeConfiguration((e2) => {
      if (e2.affectsConfiguration(SEMANTIC_HIGHLIGHTING_SETTING_ID)) {
        handleSettingOrThemeChange();
      }
    }));
    this._register(themeService.onDidColorThemeChange(handleSettingOrThemeChange));
  }
};
var SemanticStyling = class extends Disposable {
  constructor(_themeService, _logService) {
    super();
    this._themeService = _themeService;
    this._logService = _logService;
    this._caches = new WeakMap();
    this._register(this._themeService.onDidColorThemeChange(() => {
      this._caches = new WeakMap();
    }));
  }
  get(provider) {
    if (!this._caches.has(provider)) {
      this._caches.set(provider, new SemanticTokensProviderStyling(provider.getLegend(), this._themeService, this._logService));
    }
    return this._caches.get(provider);
  }
};
var SemanticTokensResponse = class {
  constructor(_provider, resultId, data2) {
    this._provider = _provider;
    this.resultId = resultId;
    this.data = data2;
  }
  dispose() {
    this._provider.releaseDocumentSemanticTokens(this.resultId);
  }
};
var ModelSemanticColoring = class extends Disposable {
  constructor(model, themeService, stylingProvider) {
    super();
    this._isDisposed = false;
    this._model = model;
    this._semanticStyling = stylingProvider;
    this._fetchDocumentSemanticTokens = this._register(new RunOnceScheduler(() => this._fetchDocumentSemanticTokensNow(), 300));
    this._currentDocumentResponse = null;
    this._currentDocumentRequestCancellationTokenSource = null;
    this._documentProvidersChangeListeners = [];
    this._register(this._model.onDidChangeContent(() => {
      if (!this._fetchDocumentSemanticTokens.isScheduled()) {
        this._fetchDocumentSemanticTokens.schedule();
      }
    }));
    const bindDocumentChangeListeners = () => {
      dispose(this._documentProvidersChangeListeners);
      this._documentProvidersChangeListeners = [];
      for (const provider of DocumentSemanticTokensProviderRegistry.all(model)) {
        if (typeof provider.onDidChange === "function") {
          this._documentProvidersChangeListeners.push(provider.onDidChange(() => this._fetchDocumentSemanticTokens.schedule(0)));
        }
      }
    };
    bindDocumentChangeListeners();
    this._register(DocumentSemanticTokensProviderRegistry.onDidChange(() => {
      bindDocumentChangeListeners();
      this._fetchDocumentSemanticTokens.schedule();
    }));
    this._register(themeService.onDidColorThemeChange((_23) => {
      this._setDocumentSemanticTokens(null, null, null, []);
      this._fetchDocumentSemanticTokens.schedule();
    }));
    this._fetchDocumentSemanticTokens.schedule(0);
  }
  dispose() {
    if (this._currentDocumentResponse) {
      this._currentDocumentResponse.dispose();
      this._currentDocumentResponse = null;
    }
    if (this._currentDocumentRequestCancellationTokenSource) {
      this._currentDocumentRequestCancellationTokenSource.cancel();
      this._currentDocumentRequestCancellationTokenSource = null;
    }
    this._setDocumentSemanticTokens(null, null, null, []);
    this._isDisposed = true;
    super.dispose();
  }
  _fetchDocumentSemanticTokensNow() {
    if (this._currentDocumentRequestCancellationTokenSource) {
      return;
    }
    const provider = this._getSemanticColoringProvider();
    if (!provider) {
      return;
    }
    this._currentDocumentRequestCancellationTokenSource = new CancellationTokenSource();
    const pendingChanges = [];
    const contentChangeListener = this._model.onDidChangeContent((e2) => {
      pendingChanges.push(e2);
    });
    const styling = this._semanticStyling.get(provider);
    const lastResultId = this._currentDocumentResponse ? this._currentDocumentResponse.resultId || null : null;
    const request2 = Promise.resolve(provider.provideDocumentSemanticTokens(this._model, lastResultId, this._currentDocumentRequestCancellationTokenSource.token));
    request2.then((res) => {
      this._currentDocumentRequestCancellationTokenSource = null;
      contentChangeListener.dispose();
      this._setDocumentSemanticTokens(provider, res || null, styling, pendingChanges);
    }, (err) => {
      if (!err || typeof err.message !== "string" || err.message.indexOf("busy") === -1) {
        onUnexpectedError(err);
      }
      this._currentDocumentRequestCancellationTokenSource = null;
      contentChangeListener.dispose();
      if (pendingChanges.length > 0) {
        if (!this._fetchDocumentSemanticTokens.isScheduled()) {
          this._fetchDocumentSemanticTokens.schedule();
        }
      }
    });
  }
  static _isSemanticTokens(v2) {
    return v2 && !!v2.data;
  }
  static _isSemanticTokensEdits(v2) {
    return v2 && Array.isArray(v2.edits);
  }
  static _copy(src, srcOffset, dest, destOffset, length) {
    for (let i3 = 0; i3 < length; i3++) {
      dest[destOffset + i3] = src[srcOffset + i3];
    }
  }
  _setDocumentSemanticTokens(provider, tokens, styling, pendingChanges) {
    const currentResponse = this._currentDocumentResponse;
    if (this._currentDocumentResponse) {
      this._currentDocumentResponse.dispose();
      this._currentDocumentResponse = null;
    }
    if (this._isDisposed) {
      if (provider && tokens) {
        provider.releaseDocumentSemanticTokens(tokens.resultId);
      }
      return;
    }
    if (!provider || !styling) {
      this._model.setSemanticTokens(null, false);
      return;
    }
    if (!tokens) {
      this._model.setSemanticTokens(null, true);
      return;
    }
    if (ModelSemanticColoring._isSemanticTokensEdits(tokens)) {
      if (!currentResponse) {
        this._model.setSemanticTokens(null, true);
        return;
      }
      if (tokens.edits.length === 0) {
        tokens = {
          resultId: tokens.resultId,
          data: currentResponse.data
        };
      } else {
        let deltaLength = 0;
        for (const edit of tokens.edits) {
          deltaLength += (edit.data ? edit.data.length : 0) - edit.deleteCount;
        }
        const srcData = currentResponse.data;
        const destData = new Uint32Array(srcData.length + deltaLength);
        let srcLastStart = srcData.length;
        let destLastStart = destData.length;
        for (let i3 = tokens.edits.length - 1; i3 >= 0; i3--) {
          const edit = tokens.edits[i3];
          const copyCount = srcLastStart - (edit.start + edit.deleteCount);
          if (copyCount > 0) {
            ModelSemanticColoring._copy(srcData, srcLastStart - copyCount, destData, destLastStart - copyCount, copyCount);
            destLastStart -= copyCount;
          }
          if (edit.data) {
            ModelSemanticColoring._copy(edit.data, 0, destData, destLastStart - edit.data.length, edit.data.length);
            destLastStart -= edit.data.length;
          }
          srcLastStart = edit.start;
        }
        if (srcLastStart > 0) {
          ModelSemanticColoring._copy(srcData, 0, destData, 0, srcLastStart);
        }
        tokens = {
          resultId: tokens.resultId,
          data: destData
        };
      }
    }
    if (ModelSemanticColoring._isSemanticTokens(tokens)) {
      this._currentDocumentResponse = new SemanticTokensResponse(provider, tokens.resultId, tokens.data);
      const result = toMultilineTokens2(tokens, styling, this._model.getLanguageIdentifier());
      if (pendingChanges.length > 0) {
        for (const change of pendingChanges) {
          for (const area of result) {
            for (const singleChange of change.changes) {
              area.applyEdit(singleChange.range, singleChange.text);
            }
          }
        }
        if (!this._fetchDocumentSemanticTokens.isScheduled()) {
          this._fetchDocumentSemanticTokens.schedule();
        }
      }
      this._model.setSemanticTokens(result, true);
      return;
    }
    this._model.setSemanticTokens(null, true);
  }
  _getSemanticColoringProvider() {
    const result = DocumentSemanticTokensProviderRegistry.ordered(this._model);
    return result.length > 0 ? result[0] : null;
  }
};
var AbstractCodeEditorService = class extends Disposable {
  constructor() {
    super();
    this._onCodeEditorAdd = this._register(new Emitter());
    this.onCodeEditorAdd = this._onCodeEditorAdd.event;
    this._onCodeEditorRemove = this._register(new Emitter());
    this.onCodeEditorRemove = this._onCodeEditorRemove.event;
    this._onDiffEditorAdd = this._register(new Emitter());
    this._onDiffEditorRemove = this._register(new Emitter());
    this._modelProperties = new Map();
    this._codeEditors = Object.create(null);
    this._diffEditors = Object.create(null);
  }
  addCodeEditor(editor2) {
    this._codeEditors[editor2.getId()] = editor2;
    this._onCodeEditorAdd.fire(editor2);
  }
  removeCodeEditor(editor2) {
    if (delete this._codeEditors[editor2.getId()]) {
      this._onCodeEditorRemove.fire(editor2);
    }
  }
  listCodeEditors() {
    return Object.keys(this._codeEditors).map((id3) => this._codeEditors[id3]);
  }
  addDiffEditor(editor2) {
    this._diffEditors[editor2.getId()] = editor2;
    this._onDiffEditorAdd.fire(editor2);
  }
  removeDiffEditor(editor2) {
    if (delete this._diffEditors[editor2.getId()]) {
      this._onDiffEditorRemove.fire(editor2);
    }
  }
  listDiffEditors() {
    return Object.keys(this._diffEditors).map((id3) => this._diffEditors[id3]);
  }
  getFocusedCodeEditor() {
    let editorWithWidgetFocus = null;
    const editors = this.listCodeEditors();
    for (const editor2 of editors) {
      if (editor2.hasTextFocus()) {
        return editor2;
      }
      if (editor2.hasWidgetFocus()) {
        editorWithWidgetFocus = editor2;
      }
    }
    return editorWithWidgetFocus;
  }
  setModelProperty(resource2, key, value) {
    const key1 = resource2.toString();
    let dest;
    if (this._modelProperties.has(key1)) {
      dest = this._modelProperties.get(key1);
    } else {
      dest = new Map();
      this._modelProperties.set(key1, dest);
    }
    dest.set(key, value);
  }
  getModelProperty(resource2, key) {
    const key1 = resource2.toString();
    if (this._modelProperties.has(key1)) {
      const innerMap = this._modelProperties.get(key1);
      return innerMap.get(key);
    }
    return void 0;
  }
};
var __decorate$9 = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$8 = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var RefCountedStyleSheet = class {
  constructor(parent, editorId, styleSheet) {
    this._parent = parent;
    this._editorId = editorId;
    this._styleSheet = styleSheet;
    this._refCount = 0;
  }
  ref() {
    this._refCount++;
  }
  unref() {
    var _a;
    this._refCount--;
    if (this._refCount === 0) {
      (_a = this._styleSheet.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this._styleSheet);
      this._parent._removeEditorStyleSheets(this._editorId);
    }
  }
  insertRule(rule, index3) {
    const sheet = this._styleSheet.sheet;
    sheet.insertRule(rule, index3);
  }
  removeRulesContainingSelector(ruleName) {
    removeCSSRulesContainingSelector(ruleName, this._styleSheet);
  }
};
var GlobalStyleSheet = class {
  constructor(styleSheet) {
    this._styleSheet = styleSheet;
  }
  ref() {
  }
  unref() {
  }
  insertRule(rule, index3) {
    const sheet = this._styleSheet.sheet;
    sheet.insertRule(rule, index3);
  }
  removeRulesContainingSelector(ruleName) {
    removeCSSRulesContainingSelector(ruleName, this._styleSheet);
  }
};
var CodeEditorServiceImpl = class CodeEditorServiceImpl2 extends AbstractCodeEditorService {
  constructor(themeService, styleSheet = null) {
    super();
    this._decorationOptionProviders = new Map();
    this._editorStyleSheets = new Map();
    this._globalStyleSheet = styleSheet ? styleSheet : null;
    this._themeService = themeService;
  }
  _getOrCreateGlobalStyleSheet() {
    if (!this._globalStyleSheet) {
      this._globalStyleSheet = new GlobalStyleSheet(createStyleSheet());
    }
    return this._globalStyleSheet;
  }
  _getOrCreateStyleSheet(editor2) {
    if (!editor2) {
      return this._getOrCreateGlobalStyleSheet();
    }
    const domNode = editor2.getContainerDomNode();
    if (!isInShadowDOM(domNode)) {
      return this._getOrCreateGlobalStyleSheet();
    }
    const editorId = editor2.getId();
    if (!this._editorStyleSheets.has(editorId)) {
      const refCountedStyleSheet = new RefCountedStyleSheet(this, editorId, createStyleSheet(domNode));
      this._editorStyleSheets.set(editorId, refCountedStyleSheet);
    }
    return this._editorStyleSheets.get(editorId);
  }
  _removeEditorStyleSheets(editorId) {
    this._editorStyleSheets.delete(editorId);
  }
  registerDecorationType(key, options, parentTypeKey, editor2) {
    let provider = this._decorationOptionProviders.get(key);
    if (!provider) {
      const styleSheet = this._getOrCreateStyleSheet(editor2);
      const providerArgs = {
        styleSheet,
        key,
        parentTypeKey,
        options: options || Object.create(null)
      };
      if (!parentTypeKey) {
        provider = new DecorationTypeOptionsProvider(this._themeService, styleSheet, providerArgs);
      } else {
        provider = new DecorationSubTypeOptionsProvider(this._themeService, styleSheet, providerArgs);
      }
      this._decorationOptionProviders.set(key, provider);
    }
    provider.refCount++;
  }
  removeDecorationType(key) {
    const provider = this._decorationOptionProviders.get(key);
    if (provider) {
      provider.refCount--;
      if (provider.refCount <= 0) {
        this._decorationOptionProviders.delete(key);
        provider.dispose();
        this.listCodeEditors().forEach((ed2) => ed2.removeDecorations(key));
      }
    }
  }
  resolveDecorationOptions(decorationTypeKey, writable) {
    const provider = this._decorationOptionProviders.get(decorationTypeKey);
    if (!provider) {
      throw new Error("Unknown decoration type key: " + decorationTypeKey);
    }
    return provider.getOptions(this, writable);
  }
};
CodeEditorServiceImpl = __decorate$9([
  __param$8(0, IThemeService)
], CodeEditorServiceImpl);
var DecorationSubTypeOptionsProvider = class {
  constructor(themeService, styleSheet, providerArgs) {
    this._styleSheet = styleSheet;
    this._styleSheet.ref();
    this._parentTypeKey = providerArgs.parentTypeKey;
    this.refCount = 0;
    this._beforeContentRules = new DecorationCSSRules(3, providerArgs, themeService);
    this._afterContentRules = new DecorationCSSRules(4, providerArgs, themeService);
  }
  getOptions(codeEditorService, writable) {
    const options = codeEditorService.resolveDecorationOptions(this._parentTypeKey, true);
    if (this._beforeContentRules) {
      options.beforeContentClassName = this._beforeContentRules.className;
    }
    if (this._afterContentRules) {
      options.afterContentClassName = this._afterContentRules.className;
    }
    return options;
  }
  dispose() {
    if (this._beforeContentRules) {
      this._beforeContentRules.dispose();
      this._beforeContentRules = null;
    }
    if (this._afterContentRules) {
      this._afterContentRules.dispose();
      this._afterContentRules = null;
    }
    this._styleSheet.unref();
  }
};
var DecorationTypeOptionsProvider = class {
  constructor(themeService, styleSheet, providerArgs) {
    this._disposables = new DisposableStore();
    this._styleSheet = styleSheet;
    this._styleSheet.ref();
    this.refCount = 0;
    const createCSSRules = (type) => {
      const rules = new DecorationCSSRules(type, providerArgs, themeService);
      this._disposables.add(rules);
      if (rules.hasContent) {
        return rules.className;
      }
      return void 0;
    };
    const createInlineCSSRules = (type) => {
      const rules = new DecorationCSSRules(type, providerArgs, themeService);
      this._disposables.add(rules);
      if (rules.hasContent) {
        return {className: rules.className, hasLetterSpacing: rules.hasLetterSpacing};
      }
      return null;
    };
    this.className = createCSSRules(0);
    const inlineData = createInlineCSSRules(1);
    if (inlineData) {
      this.inlineClassName = inlineData.className;
      this.inlineClassNameAffectsLetterSpacing = inlineData.hasLetterSpacing;
    }
    this.beforeContentClassName = createCSSRules(3);
    this.afterContentClassName = createCSSRules(4);
    this.glyphMarginClassName = createCSSRules(2);
    const options = providerArgs.options;
    this.isWholeLine = Boolean(options.isWholeLine);
    this.stickiness = options.rangeBehavior;
    const lightOverviewRulerColor = options.light && options.light.overviewRulerColor || options.overviewRulerColor;
    const darkOverviewRulerColor = options.dark && options.dark.overviewRulerColor || options.overviewRulerColor;
    if (typeof lightOverviewRulerColor !== "undefined" || typeof darkOverviewRulerColor !== "undefined") {
      this.overviewRuler = {
        color: lightOverviewRulerColor || darkOverviewRulerColor,
        darkColor: darkOverviewRulerColor || lightOverviewRulerColor,
        position: options.overviewRulerLane || OverviewRulerLane$1.Center
      };
    }
  }
  getOptions(codeEditorService, writable) {
    if (!writable) {
      return this;
    }
    return {
      inlineClassName: this.inlineClassName,
      beforeContentClassName: this.beforeContentClassName,
      afterContentClassName: this.afterContentClassName,
      className: this.className,
      glyphMarginClassName: this.glyphMarginClassName,
      isWholeLine: this.isWholeLine,
      overviewRuler: this.overviewRuler,
      stickiness: this.stickiness
    };
  }
  dispose() {
    this._disposables.dispose();
    this._styleSheet.unref();
  }
};
var _CSS_MAP = {
  color: "color:{0} !important;",
  opacity: "opacity:{0};",
  backgroundColor: "background-color:{0};",
  outline: "outline:{0};",
  outlineColor: "outline-color:{0};",
  outlineStyle: "outline-style:{0};",
  outlineWidth: "outline-width:{0};",
  border: "border:{0};",
  borderColor: "border-color:{0};",
  borderRadius: "border-radius:{0};",
  borderSpacing: "border-spacing:{0};",
  borderStyle: "border-style:{0};",
  borderWidth: "border-width:{0};",
  fontStyle: "font-style:{0};",
  fontWeight: "font-weight:{0};",
  textDecoration: "text-decoration:{0};",
  cursor: "cursor:{0};",
  letterSpacing: "letter-spacing:{0};",
  gutterIconPath: "background:{0} center center no-repeat;",
  gutterIconSize: "background-size:{0};",
  contentText: "content:'{0}';",
  contentIconPath: "content:{0};",
  margin: "margin:{0};",
  width: "width:{0};",
  height: "height:{0};"
};
var DecorationCSSRules = class {
  constructor(ruleType, providerArgs, themeService) {
    this._theme = themeService.getColorTheme();
    this._ruleType = ruleType;
    this._providerArgs = providerArgs;
    this._usesThemeColors = false;
    this._hasContent = false;
    this._hasLetterSpacing = false;
    let className = CSSNameHelper.getClassName(this._providerArgs.key, ruleType);
    if (this._providerArgs.parentTypeKey) {
      className = className + " " + CSSNameHelper.getClassName(this._providerArgs.parentTypeKey, ruleType);
    }
    this._className = className;
    this._unThemedSelector = CSSNameHelper.getSelector(this._providerArgs.key, this._providerArgs.parentTypeKey, ruleType);
    this._buildCSS();
    if (this._usesThemeColors) {
      this._themeListener = themeService.onDidColorThemeChange((theme) => {
        this._theme = themeService.getColorTheme();
        this._removeCSS();
        this._buildCSS();
      });
    } else {
      this._themeListener = null;
    }
  }
  dispose() {
    if (this._hasContent) {
      this._removeCSS();
      this._hasContent = false;
    }
    if (this._themeListener) {
      this._themeListener.dispose();
      this._themeListener = null;
    }
  }
  get hasContent() {
    return this._hasContent;
  }
  get hasLetterSpacing() {
    return this._hasLetterSpacing;
  }
  get className() {
    return this._className;
  }
  _buildCSS() {
    const options = this._providerArgs.options;
    let unthemedCSS, lightCSS, darkCSS;
    switch (this._ruleType) {
      case 0:
        unthemedCSS = this.getCSSTextForModelDecorationClassName(options);
        lightCSS = this.getCSSTextForModelDecorationClassName(options.light);
        darkCSS = this.getCSSTextForModelDecorationClassName(options.dark);
        break;
      case 1:
        unthemedCSS = this.getCSSTextForModelDecorationInlineClassName(options);
        lightCSS = this.getCSSTextForModelDecorationInlineClassName(options.light);
        darkCSS = this.getCSSTextForModelDecorationInlineClassName(options.dark);
        break;
      case 2:
        unthemedCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options);
        lightCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options.light);
        darkCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options.dark);
        break;
      case 3:
        unthemedCSS = this.getCSSTextForModelDecorationContentClassName(options.before);
        lightCSS = this.getCSSTextForModelDecorationContentClassName(options.light && options.light.before);
        darkCSS = this.getCSSTextForModelDecorationContentClassName(options.dark && options.dark.before);
        break;
      case 4:
        unthemedCSS = this.getCSSTextForModelDecorationContentClassName(options.after);
        lightCSS = this.getCSSTextForModelDecorationContentClassName(options.light && options.light.after);
        darkCSS = this.getCSSTextForModelDecorationContentClassName(options.dark && options.dark.after);
        break;
      default:
        throw new Error("Unknown rule type: " + this._ruleType);
    }
    const sheet = this._providerArgs.styleSheet;
    let hasContent = false;
    if (unthemedCSS.length > 0) {
      sheet.insertRule(`${this._unThemedSelector} {${unthemedCSS}}`, 0);
      hasContent = true;
    }
    if (lightCSS.length > 0) {
      sheet.insertRule(`.vs${this._unThemedSelector} {${lightCSS}}`, 0);
      hasContent = true;
    }
    if (darkCSS.length > 0) {
      sheet.insertRule(`.vs-dark${this._unThemedSelector}, .hc-black${this._unThemedSelector} {${darkCSS}}`, 0);
      hasContent = true;
    }
    this._hasContent = hasContent;
  }
  _removeCSS() {
    this._providerArgs.styleSheet.removeRulesContainingSelector(this._unThemedSelector);
  }
  getCSSTextForModelDecorationClassName(opts) {
    if (!opts) {
      return "";
    }
    const cssTextArr = [];
    this.collectCSSText(opts, ["backgroundColor"], cssTextArr);
    this.collectCSSText(opts, ["outline", "outlineColor", "outlineStyle", "outlineWidth"], cssTextArr);
    this.collectBorderSettingsCSSText(opts, cssTextArr);
    return cssTextArr.join("");
  }
  getCSSTextForModelDecorationInlineClassName(opts) {
    if (!opts) {
      return "";
    }
    const cssTextArr = [];
    this.collectCSSText(opts, ["fontStyle", "fontWeight", "textDecoration", "cursor", "color", "opacity", "letterSpacing"], cssTextArr);
    if (opts.letterSpacing) {
      this._hasLetterSpacing = true;
    }
    return cssTextArr.join("");
  }
  getCSSTextForModelDecorationContentClassName(opts) {
    if (!opts) {
      return "";
    }
    const cssTextArr = [];
    if (typeof opts !== "undefined") {
      this.collectBorderSettingsCSSText(opts, cssTextArr);
      if (typeof opts.contentIconPath !== "undefined") {
        cssTextArr.push(format(_CSS_MAP.contentIconPath, asCSSUrl(URI.revive(opts.contentIconPath))));
      }
      if (typeof opts.contentText === "string") {
        const truncated = opts.contentText.match(/^.*$/m)[0];
        const escaped = truncated.replace(/['\\]/g, "\\$&");
        cssTextArr.push(format(_CSS_MAP.contentText, escaped));
      }
      this.collectCSSText(opts, ["fontStyle", "fontWeight", "textDecoration", "color", "opacity", "backgroundColor", "margin"], cssTextArr);
      if (this.collectCSSText(opts, ["width", "height"], cssTextArr)) {
        cssTextArr.push("display:inline-block;");
      }
    }
    return cssTextArr.join("");
  }
  getCSSTextForModelDecorationGlyphMarginClassName(opts) {
    if (!opts) {
      return "";
    }
    const cssTextArr = [];
    if (typeof opts.gutterIconPath !== "undefined") {
      cssTextArr.push(format(_CSS_MAP.gutterIconPath, asCSSUrl(URI.revive(opts.gutterIconPath))));
      if (typeof opts.gutterIconSize !== "undefined") {
        cssTextArr.push(format(_CSS_MAP.gutterIconSize, opts.gutterIconSize));
      }
    }
    return cssTextArr.join("");
  }
  collectBorderSettingsCSSText(opts, cssTextArr) {
    if (this.collectCSSText(opts, ["border", "borderColor", "borderRadius", "borderSpacing", "borderStyle", "borderWidth"], cssTextArr)) {
      cssTextArr.push(format("box-sizing: border-box;"));
      return true;
    }
    return false;
  }
  collectCSSText(opts, properties, cssTextArr) {
    const lenBefore = cssTextArr.length;
    for (let property2 of properties) {
      const value = this.resolveValue(opts[property2]);
      if (typeof value === "string") {
        cssTextArr.push(format(_CSS_MAP[property2], value));
      }
    }
    return cssTextArr.length !== lenBefore;
  }
  resolveValue(value) {
    if (isThemeColor(value)) {
      this._usesThemeColors = true;
      const color2 = this._theme.getColor(value.id);
      if (color2) {
        return color2.toString();
      }
      return "transparent";
    }
    return value;
  }
};
var CSSNameHelper = class {
  static getClassName(key, type) {
    return "ced-" + key + "-" + type;
  }
  static getSelector(key, parentKey, ruleType) {
    let selector2 = ".monaco-editor ." + this.getClassName(key, ruleType);
    if (parentKey) {
      selector2 = selector2 + "." + this.getClassName(parentKey, ruleType);
    }
    if (ruleType === 3) {
      selector2 += "::before";
    } else if (ruleType === 4) {
      selector2 += "::after";
    }
    return selector2;
  }
};
var StandaloneCodeEditorServiceImpl = class extends CodeEditorServiceImpl {
  getActiveCodeEditor() {
    return null;
  }
  openCodeEditor(input, source2, sideBySide) {
    if (!source2) {
      return Promise.resolve(null);
    }
    return Promise.resolve(this.doOpenEditor(source2, input));
  }
  doOpenEditor(editor2, input) {
    const model = this.findModel(editor2, input.resource);
    if (!model) {
      if (input.resource) {
        const schema = input.resource.scheme;
        if (schema === Schemas.http || schema === Schemas.https) {
          windowOpenNoOpener(input.resource.toString());
          return editor2;
        }
      }
      return null;
    }
    const selection2 = input.options ? input.options.selection : null;
    if (selection2) {
      if (typeof selection2.endLineNumber === "number" && typeof selection2.endColumn === "number") {
        editor2.setSelection(selection2);
        editor2.revealRangeInCenter(selection2, 1);
      } else {
        const pos = {
          lineNumber: selection2.startLineNumber,
          column: selection2.startColumn
        };
        editor2.setPosition(pos);
        editor2.revealPositionInCenter(pos, 1);
      }
    }
    return editor2;
  }
  findModel(editor2, resource2) {
    const model = editor2.getModel();
    if (model && model.uri.toString() !== resource2.toString()) {
      return null;
    }
    return model;
  }
};
var ParsedTokenThemeRule = class {
  constructor(token2, index3, fontStyle, foreground2, background) {
    this.token = token2;
    this.index = index3;
    this.fontStyle = fontStyle;
    this.foreground = foreground2;
    this.background = background;
  }
};
function parseTokenTheme(source2) {
  if (!source2 || !Array.isArray(source2)) {
    return [];
  }
  let result = [], resultLen = 0;
  for (let i3 = 0, len2 = source2.length; i3 < len2; i3++) {
    let entry = source2[i3];
    let fontStyle = -1;
    if (typeof entry.fontStyle === "string") {
      fontStyle = 0;
      let segments = entry.fontStyle.split(" ");
      for (let j = 0, lenJ = segments.length; j < lenJ; j++) {
        let segment = segments[j];
        switch (segment) {
          case "italic":
            fontStyle = fontStyle | 1;
            break;
          case "bold":
            fontStyle = fontStyle | 2;
            break;
          case "underline":
            fontStyle = fontStyle | 4;
            break;
        }
      }
    }
    let foreground2 = null;
    if (typeof entry.foreground === "string") {
      foreground2 = entry.foreground;
    }
    let background = null;
    if (typeof entry.background === "string") {
      background = entry.background;
    }
    result[resultLen++] = new ParsedTokenThemeRule(entry.token || "", i3, fontStyle, foreground2, background);
  }
  return result;
}
function resolveParsedTokenThemeRules(parsedThemeRules, customTokenColors) {
  parsedThemeRules.sort((a2, b2) => {
    let r3 = strcmp(a2.token, b2.token);
    if (r3 !== 0) {
      return r3;
    }
    return a2.index - b2.index;
  });
  let defaultFontStyle = 0;
  let defaultForeground = "000000";
  let defaultBackground = "ffffff";
  while (parsedThemeRules.length >= 1 && parsedThemeRules[0].token === "") {
    let incomingDefaults = parsedThemeRules.shift();
    if (incomingDefaults.fontStyle !== -1) {
      defaultFontStyle = incomingDefaults.fontStyle;
    }
    if (incomingDefaults.foreground !== null) {
      defaultForeground = incomingDefaults.foreground;
    }
    if (incomingDefaults.background !== null) {
      defaultBackground = incomingDefaults.background;
    }
  }
  let colorMap = new ColorMap();
  for (let color2 of customTokenColors) {
    colorMap.getId(color2);
  }
  let foregroundColorId = colorMap.getId(defaultForeground);
  let backgroundColorId = colorMap.getId(defaultBackground);
  let defaults3 = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId);
  let root4 = new ThemeTrieElement(defaults3);
  for (let i3 = 0, len2 = parsedThemeRules.length; i3 < len2; i3++) {
    let rule = parsedThemeRules[i3];
    root4.insert(rule.token, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));
  }
  return new TokenTheme(colorMap, root4);
}
var colorRegExp = /^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/;
var ColorMap = class {
  constructor() {
    this._lastColorId = 0;
    this._id2color = [];
    this._color2id = new Map();
  }
  getId(color2) {
    if (color2 === null) {
      return 0;
    }
    const match2 = color2.match(colorRegExp);
    if (!match2) {
      throw new Error("Illegal value for token color: " + color2);
    }
    color2 = match2[1].toUpperCase();
    let value = this._color2id.get(color2);
    if (value) {
      return value;
    }
    value = ++this._lastColorId;
    this._color2id.set(color2, value);
    this._id2color[value] = Color.fromHex("#" + color2);
    return value;
  }
  getColorMap() {
    return this._id2color.slice(0);
  }
};
var TokenTheme = class {
  constructor(colorMap, root4) {
    this._colorMap = colorMap;
    this._root = root4;
    this._cache = new Map();
  }
  static createFromRawTokenTheme(source2, customTokenColors) {
    return this.createFromParsedTokenTheme(parseTokenTheme(source2), customTokenColors);
  }
  static createFromParsedTokenTheme(source2, customTokenColors) {
    return resolveParsedTokenThemeRules(source2, customTokenColors);
  }
  getColorMap() {
    return this._colorMap.getColorMap();
  }
  _match(token2) {
    return this._root.match(token2);
  }
  match(languageId, token2) {
    let result = this._cache.get(token2);
    if (typeof result === "undefined") {
      let rule = this._match(token2);
      let standardToken = toStandardTokenType(token2);
      result = (rule.metadata | standardToken << 8) >>> 0;
      this._cache.set(token2, result);
    }
    return (result | languageId << 0) >>> 0;
  }
};
var STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|regexp)\b/;
function toStandardTokenType(tokenType) {
  let m2 = tokenType.match(STANDARD_TOKEN_TYPE_REGEXP);
  if (!m2) {
    return 0;
  }
  switch (m2[1]) {
    case "comment":
      return 1;
    case "string":
      return 2;
    case "regex":
      return 4;
    case "regexp":
      return 4;
  }
  throw new Error("Unexpected match for standard token type!");
}
function strcmp(a2, b2) {
  if (a2 < b2) {
    return -1;
  }
  if (a2 > b2) {
    return 1;
  }
  return 0;
}
var ThemeTrieElementRule = class {
  constructor(fontStyle, foreground2, background) {
    this._fontStyle = fontStyle;
    this._foreground = foreground2;
    this._background = background;
    this.metadata = (this._fontStyle << 11 | this._foreground << 14 | this._background << 23) >>> 0;
  }
  clone() {
    return new ThemeTrieElementRule(this._fontStyle, this._foreground, this._background);
  }
  acceptOverwrite(fontStyle, foreground2, background) {
    if (fontStyle !== -1) {
      this._fontStyle = fontStyle;
    }
    if (foreground2 !== 0) {
      this._foreground = foreground2;
    }
    if (background !== 0) {
      this._background = background;
    }
    this.metadata = (this._fontStyle << 11 | this._foreground << 14 | this._background << 23) >>> 0;
  }
};
var ThemeTrieElement = class {
  constructor(mainRule) {
    this._mainRule = mainRule;
    this._children = new Map();
  }
  match(token2) {
    if (token2 === "") {
      return this._mainRule;
    }
    let dotIndex = token2.indexOf(".");
    let head;
    let tail3;
    if (dotIndex === -1) {
      head = token2;
      tail3 = "";
    } else {
      head = token2.substring(0, dotIndex);
      tail3 = token2.substring(dotIndex + 1);
    }
    let child = this._children.get(head);
    if (typeof child !== "undefined") {
      return child.match(tail3);
    }
    return this._mainRule;
  }
  insert(token2, fontStyle, foreground2, background) {
    if (token2 === "") {
      this._mainRule.acceptOverwrite(fontStyle, foreground2, background);
      return;
    }
    let dotIndex = token2.indexOf(".");
    let head;
    let tail3;
    if (dotIndex === -1) {
      head = token2;
      tail3 = "";
    } else {
      head = token2.substring(0, dotIndex);
      tail3 = token2.substring(dotIndex + 1);
    }
    let child = this._children.get(head);
    if (typeof child === "undefined") {
      child = new ThemeTrieElement(this._mainRule.clone());
      this._children.set(head, child);
    }
    child.insert(tail3, fontStyle, foreground2, background);
  }
};
function generateTokensCSSForColorMap(colorMap) {
  let rules = [];
  for (let i3 = 1, len2 = colorMap.length; i3 < len2; i3++) {
    let color2 = colorMap[i3];
    rules[i3] = `.mtk${i3} { color: ${color2}; }`;
  }
  rules.push(".mtki { font-style: italic; }");
  rules.push(".mtkb { font-weight: bold; }");
  rules.push(".mtku { text-decoration: underline; text-underline-position: under; }");
  return rules.join("\n");
}
var vs = {
  base: "vs",
  inherit: false,
  rules: [
    {token: "", foreground: "000000", background: "fffffe"},
    {token: "invalid", foreground: "cd3131"},
    {token: "emphasis", fontStyle: "italic"},
    {token: "strong", fontStyle: "bold"},
    {token: "variable", foreground: "001188"},
    {token: "variable.predefined", foreground: "4864AA"},
    {token: "constant", foreground: "dd0000"},
    {token: "comment", foreground: "008000"},
    {token: "number", foreground: "098658"},
    {token: "number.hex", foreground: "3030c0"},
    {token: "regexp", foreground: "800000"},
    {token: "annotation", foreground: "808080"},
    {token: "type", foreground: "008080"},
    {token: "delimiter", foreground: "000000"},
    {token: "delimiter.html", foreground: "383838"},
    {token: "delimiter.xml", foreground: "0000FF"},
    {token: "tag", foreground: "800000"},
    {token: "tag.id.pug", foreground: "4F76AC"},
    {token: "tag.class.pug", foreground: "4F76AC"},
    {token: "meta.scss", foreground: "800000"},
    {token: "metatag", foreground: "e00000"},
    {token: "metatag.content.html", foreground: "FF0000"},
    {token: "metatag.html", foreground: "808080"},
    {token: "metatag.xml", foreground: "808080"},
    {token: "metatag.php", fontStyle: "bold"},
    {token: "key", foreground: "863B00"},
    {token: "string.key.json", foreground: "A31515"},
    {token: "string.value.json", foreground: "0451A5"},
    {token: "attribute.name", foreground: "FF0000"},
    {token: "attribute.value", foreground: "0451A5"},
    {token: "attribute.value.number", foreground: "098658"},
    {token: "attribute.value.unit", foreground: "098658"},
    {token: "attribute.value.html", foreground: "0000FF"},
    {token: "attribute.value.xml", foreground: "0000FF"},
    {token: "string", foreground: "A31515"},
    {token: "string.html", foreground: "0000FF"},
    {token: "string.sql", foreground: "FF0000"},
    {token: "string.yaml", foreground: "0451A5"},
    {token: "keyword", foreground: "0000FF"},
    {token: "keyword.json", foreground: "0451A5"},
    {token: "keyword.flow", foreground: "AF00DB"},
    {token: "keyword.flow.scss", foreground: "0000FF"},
    {token: "operator.scss", foreground: "666666"},
    {token: "operator.sql", foreground: "778899"},
    {token: "operator.swift", foreground: "666666"},
    {token: "predefined.sql", foreground: "FF00FF"}
  ],
  colors: {
    [editorBackground]: "#FFFFFE",
    [editorForeground]: "#000000",
    [editorInactiveSelection]: "#E5EBF1",
    [editorIndentGuides]: "#D3D3D3",
    [editorActiveIndentGuides]: "#939393",
    [editorSelectionHighlight]: "#ADD6FF4D"
  }
};
var vs_dark = {
  base: "vs-dark",
  inherit: false,
  rules: [
    {token: "", foreground: "D4D4D4", background: "1E1E1E"},
    {token: "invalid", foreground: "f44747"},
    {token: "emphasis", fontStyle: "italic"},
    {token: "strong", fontStyle: "bold"},
    {token: "variable", foreground: "74B0DF"},
    {token: "variable.predefined", foreground: "4864AA"},
    {token: "variable.parameter", foreground: "9CDCFE"},
    {token: "constant", foreground: "569CD6"},
    {token: "comment", foreground: "608B4E"},
    {token: "number", foreground: "B5CEA8"},
    {token: "number.hex", foreground: "5BB498"},
    {token: "regexp", foreground: "B46695"},
    {token: "annotation", foreground: "cc6666"},
    {token: "type", foreground: "3DC9B0"},
    {token: "delimiter", foreground: "DCDCDC"},
    {token: "delimiter.html", foreground: "808080"},
    {token: "delimiter.xml", foreground: "808080"},
    {token: "tag", foreground: "569CD6"},
    {token: "tag.id.pug", foreground: "4F76AC"},
    {token: "tag.class.pug", foreground: "4F76AC"},
    {token: "meta.scss", foreground: "A79873"},
    {token: "meta.tag", foreground: "CE9178"},
    {token: "metatag", foreground: "DD6A6F"},
    {token: "metatag.content.html", foreground: "9CDCFE"},
    {token: "metatag.html", foreground: "569CD6"},
    {token: "metatag.xml", foreground: "569CD6"},
    {token: "metatag.php", fontStyle: "bold"},
    {token: "key", foreground: "9CDCFE"},
    {token: "string.key.json", foreground: "9CDCFE"},
    {token: "string.value.json", foreground: "CE9178"},
    {token: "attribute.name", foreground: "9CDCFE"},
    {token: "attribute.value", foreground: "CE9178"},
    {token: "attribute.value.number.css", foreground: "B5CEA8"},
    {token: "attribute.value.unit.css", foreground: "B5CEA8"},
    {token: "attribute.value.hex.css", foreground: "D4D4D4"},
    {token: "string", foreground: "CE9178"},
    {token: "string.sql", foreground: "FF0000"},
    {token: "keyword", foreground: "569CD6"},
    {token: "keyword.flow", foreground: "C586C0"},
    {token: "keyword.json", foreground: "CE9178"},
    {token: "keyword.flow.scss", foreground: "569CD6"},
    {token: "operator.scss", foreground: "909090"},
    {token: "operator.sql", foreground: "778899"},
    {token: "operator.swift", foreground: "909090"},
    {token: "predefined.sql", foreground: "FF00FF"}
  ],
  colors: {
    [editorBackground]: "#1E1E1E",
    [editorForeground]: "#D4D4D4",
    [editorInactiveSelection]: "#3A3D41",
    [editorIndentGuides]: "#404040",
    [editorActiveIndentGuides]: "#707070",
    [editorSelectionHighlight]: "#ADD6FF26"
  }
};
var hc_black = {
  base: "hc-black",
  inherit: false,
  rules: [
    {token: "", foreground: "FFFFFF", background: "000000"},
    {token: "invalid", foreground: "f44747"},
    {token: "emphasis", fontStyle: "italic"},
    {token: "strong", fontStyle: "bold"},
    {token: "variable", foreground: "1AEBFF"},
    {token: "variable.parameter", foreground: "9CDCFE"},
    {token: "constant", foreground: "569CD6"},
    {token: "comment", foreground: "608B4E"},
    {token: "number", foreground: "FFFFFF"},
    {token: "regexp", foreground: "C0C0C0"},
    {token: "annotation", foreground: "569CD6"},
    {token: "type", foreground: "3DC9B0"},
    {token: "delimiter", foreground: "FFFF00"},
    {token: "delimiter.html", foreground: "FFFF00"},
    {token: "tag", foreground: "569CD6"},
    {token: "tag.id.pug", foreground: "4F76AC"},
    {token: "tag.class.pug", foreground: "4F76AC"},
    {token: "meta", foreground: "D4D4D4"},
    {token: "meta.tag", foreground: "CE9178"},
    {token: "metatag", foreground: "569CD6"},
    {token: "metatag.content.html", foreground: "1AEBFF"},
    {token: "metatag.html", foreground: "569CD6"},
    {token: "metatag.xml", foreground: "569CD6"},
    {token: "metatag.php", fontStyle: "bold"},
    {token: "key", foreground: "9CDCFE"},
    {token: "string.key", foreground: "9CDCFE"},
    {token: "string.value", foreground: "CE9178"},
    {token: "attribute.name", foreground: "569CD6"},
    {token: "attribute.value", foreground: "3FF23F"},
    {token: "string", foreground: "CE9178"},
    {token: "string.sql", foreground: "FF0000"},
    {token: "keyword", foreground: "569CD6"},
    {token: "keyword.flow", foreground: "C586C0"},
    {token: "operator.sql", foreground: "778899"},
    {token: "operator.swift", foreground: "909090"},
    {token: "predefined.sql", foreground: "FF00FF"}
  ],
  colors: {
    [editorBackground]: "#000000",
    [editorForeground]: "#FFFFFF",
    [editorIndentGuides]: "#FFFFFF",
    [editorActiveIndentGuides]: "#FFFFFF"
  }
};
function __snowpack__injectStyle$o(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$o(`/*---------------------------------------------------------------------------------------------\r
 *  Copyright (c) Microsoft Corporation. All rights reserved.\r
 *  Licensed under the MIT License. See License.txt in the project root for license information.\r
 *--------------------------------------------------------------------------------------------*/\r
\r
@font-face {\r
	font-family: "codicon";\r
	src: url(./codicon.ttf) format("truetype");\r
}\r
\r
.codicon[class*='codicon-'] {\r
	font: normal normal normal 16px/1 codicon;\r
	display: inline-block;\r
	text-decoration: none;\r
	text-rendering: auto;\r
	text-align: center;\r
	-webkit-font-smoothing: antialiased;\r
	-moz-osx-font-smoothing: grayscale;\r
	user-select: none;\r
	-webkit-user-select: none;\r
	-ms-user-select: none;\r
}\r
\r
/* icon rules are dynamically created in codiconStyles */\r
`);
function __snowpack__injectStyle$p(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$p("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.codicon-wrench-subaction {\r\n	opacity: 0.5;\r\n}\r\n");
function __snowpack__injectStyle$q(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$q("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n@keyframes codicon-spin {\r\n	100% {\r\n		transform:rotate(360deg);\r\n	}\r\n}\r\n\r\n.codicon-animation-spin {\r\n	/* Use steps to throttle FPS to reduce CPU usage */\r\n	animation: codicon-spin 1.5s steps(30) infinite;\r\n}\r\n");
var CodiconStyles = new class {
  constructor() {
    this.onDidChange = iconRegistry.onDidRegister;
  }
  getCSS() {
    const rules = [];
    for (let c3 of iconRegistry.all) {
      rules.push(formatRule(c3));
    }
    return rules.join("\n");
  }
}();
function formatRule(c3) {
  let def = c3.definition;
  while (def instanceof Codicon) {
    def = def.definition;
  }
  return `.codicon-${c3.id}:before { content: '${def.character}'; }`;
}
var VS_THEME_NAME = "vs";
var VS_DARK_THEME_NAME = "vs-dark";
var HC_BLACK_THEME_NAME = "hc-black";
var colorRegistry$1 = Registry$1.as(Extensions$5.ColorContribution);
var themingRegistry$1 = Registry$1.as(Extensions$4.ThemingContribution);
var StandaloneTheme = class {
  constructor(name, standaloneThemeData) {
    this.semanticHighlighting = false;
    this.themeData = standaloneThemeData;
    let base = standaloneThemeData.base;
    if (name.length > 0) {
      this.id = base + " " + name;
      this.themeName = name;
    } else {
      this.id = base;
      this.themeName = base;
    }
    this.colors = null;
    this.defaultColors = Object.create(null);
    this._tokenTheme = null;
  }
  get base() {
    return this.themeData.base;
  }
  notifyBaseUpdated() {
    if (this.themeData.inherit) {
      this.colors = null;
      this._tokenTheme = null;
    }
  }
  getColors() {
    if (!this.colors) {
      const colors = new Map();
      for (let id3 in this.themeData.colors) {
        colors.set(id3, Color.fromHex(this.themeData.colors[id3]));
      }
      if (this.themeData.inherit) {
        let baseData = getBuiltinRules(this.themeData.base);
        for (let id3 in baseData.colors) {
          if (!colors.has(id3)) {
            colors.set(id3, Color.fromHex(baseData.colors[id3]));
          }
        }
      }
      this.colors = colors;
    }
    return this.colors;
  }
  getColor(colorId, useDefault) {
    const color2 = this.getColors().get(colorId);
    if (color2) {
      return color2;
    }
    if (useDefault !== false) {
      return this.getDefault(colorId);
    }
    return void 0;
  }
  getDefault(colorId) {
    let color2 = this.defaultColors[colorId];
    if (color2) {
      return color2;
    }
    color2 = colorRegistry$1.resolveDefaultColor(colorId, this);
    this.defaultColors[colorId] = color2;
    return color2;
  }
  defines(colorId) {
    return Object.prototype.hasOwnProperty.call(this.getColors(), colorId);
  }
  get type() {
    switch (this.base) {
      case VS_THEME_NAME:
        return "light";
      case HC_BLACK_THEME_NAME:
        return "hc";
      default:
        return "dark";
    }
  }
  get tokenTheme() {
    if (!this._tokenTheme) {
      let rules = [];
      let encodedTokensColors = [];
      if (this.themeData.inherit) {
        let baseData = getBuiltinRules(this.themeData.base);
        rules = baseData.rules;
        if (baseData.encodedTokensColors) {
          encodedTokensColors = baseData.encodedTokensColors;
        }
      }
      rules = rules.concat(this.themeData.rules);
      if (this.themeData.encodedTokensColors) {
        encodedTokensColors = this.themeData.encodedTokensColors;
      }
      this._tokenTheme = TokenTheme.createFromRawTokenTheme(rules, encodedTokensColors);
    }
    return this._tokenTheme;
  }
  getTokenStyleMetadata(type, modifiers, modelLanguage) {
    const style = this.tokenTheme._match([type].concat(modifiers).join("."));
    const metadata = style.metadata;
    const foreground2 = TokenMetadata.getForeground(metadata);
    const fontStyle = TokenMetadata.getFontStyle(metadata);
    return {
      foreground: foreground2,
      italic: Boolean(fontStyle & 1),
      bold: Boolean(fontStyle & 2),
      underline: Boolean(fontStyle & 4)
    };
  }
};
function isBuiltinTheme(themeName) {
  return themeName === VS_THEME_NAME || themeName === VS_DARK_THEME_NAME || themeName === HC_BLACK_THEME_NAME;
}
function getBuiltinRules(builtinTheme) {
  switch (builtinTheme) {
    case VS_THEME_NAME:
      return vs;
    case VS_DARK_THEME_NAME:
      return vs_dark;
    case HC_BLACK_THEME_NAME:
      return hc_black;
  }
}
function newBuiltInTheme(builtinTheme) {
  let themeData = getBuiltinRules(builtinTheme);
  return new StandaloneTheme(builtinTheme, themeData);
}
var StandaloneThemeServiceImpl = class extends Disposable {
  constructor() {
    super();
    this._onColorThemeChange = this._register(new Emitter());
    this.onDidColorThemeChange = this._onColorThemeChange.event;
    this._environment = Object.create(null);
    this._knownThemes = new Map();
    this._knownThemes.set(VS_THEME_NAME, newBuiltInTheme(VS_THEME_NAME));
    this._knownThemes.set(VS_DARK_THEME_NAME, newBuiltInTheme(VS_DARK_THEME_NAME));
    this._knownThemes.set(HC_BLACK_THEME_NAME, newBuiltInTheme(HC_BLACK_THEME_NAME));
    this._codiconCSS = CodiconStyles.getCSS();
    this._themeCSS = "";
    this._allCSS = `${this._codiconCSS}
${this._themeCSS}`;
    this._globalStyleElement = null;
    this._styleElements = [];
    this.setTheme(VS_THEME_NAME);
    CodiconStyles.onDidChange(() => {
      this._codiconCSS = CodiconStyles.getCSS();
      this._updateCSS();
    });
  }
  registerEditorContainer(domNode) {
    if (isInShadowDOM(domNode)) {
      return this._registerShadowDomContainer(domNode);
    }
    return this._registerRegularEditorContainer();
  }
  _registerRegularEditorContainer() {
    if (!this._globalStyleElement) {
      this._globalStyleElement = createStyleSheet();
      this._globalStyleElement.className = "monaco-colors";
      this._globalStyleElement.innerHTML = this._allCSS;
      this._styleElements.push(this._globalStyleElement);
    }
    return Disposable.None;
  }
  _registerShadowDomContainer(domNode) {
    const styleElement = createStyleSheet(domNode);
    styleElement.className = "monaco-colors";
    styleElement.innerHTML = this._allCSS;
    this._styleElements.push(styleElement);
    return {
      dispose: () => {
        for (let i3 = 0; i3 < this._styleElements.length; i3++) {
          if (this._styleElements[i3] === styleElement) {
            this._styleElements.splice(i3, 1);
            return;
          }
        }
      }
    };
  }
  defineTheme(themeName, themeData) {
    if (!/^[a-z0-9\-]+$/i.test(themeName)) {
      throw new Error("Illegal theme name!");
    }
    if (!isBuiltinTheme(themeData.base) && !isBuiltinTheme(themeName)) {
      throw new Error("Illegal theme base!");
    }
    this._knownThemes.set(themeName, new StandaloneTheme(themeName, themeData));
    if (isBuiltinTheme(themeName)) {
      this._knownThemes.forEach((theme) => {
        if (theme.base === themeName) {
          theme.notifyBaseUpdated();
        }
      });
    }
    if (this._theme && this._theme.themeName === themeName) {
      this.setTheme(themeName);
    }
  }
  getColorTheme() {
    return this._theme;
  }
  setTheme(themeName) {
    let theme;
    if (this._knownThemes.has(themeName)) {
      theme = this._knownThemes.get(themeName);
    } else {
      theme = this._knownThemes.get(VS_THEME_NAME);
    }
    if (this._theme === theme) {
      return theme.id;
    }
    this._theme = theme;
    let cssRules = [];
    let hasRule = {};
    let ruleCollector = {
      addRule: (rule) => {
        if (!hasRule[rule]) {
          cssRules.push(rule);
          hasRule[rule] = true;
        }
      }
    };
    themingRegistry$1.getThemingParticipants().forEach((p2) => p2(theme, ruleCollector, this._environment));
    let tokenTheme = theme.tokenTheme;
    let colorMap = tokenTheme.getColorMap();
    ruleCollector.addRule(generateTokensCSSForColorMap(colorMap));
    this._themeCSS = cssRules.join("\n");
    this._updateCSS();
    TokenizationRegistry.setColorMap(colorMap);
    this._onColorThemeChange.fire(theme);
    return theme.id;
  }
  _updateCSS() {
    this._allCSS = `${this._codiconCSS}
${this._themeCSS}`;
    this._styleElements.forEach((styleElement) => styleElement.innerHTML = this._allCSS);
  }
  getFileIconTheme() {
    return {
      hasFileIcons: false,
      hasFolderIcons: false,
      hidesExplorerArrows: false
    };
  }
};
var __decorate$a = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$9 = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var KEYBINDING_CONTEXT_ATTR = "data-keybinding-context";
var Context = class {
  constructor(id3, parent) {
    this._id = id3;
    this._parent = parent;
    this._value = Object.create(null);
    this._value["_contextId"] = id3;
  }
  setValue(key, value) {
    if (this._value[key] !== value) {
      this._value[key] = value;
      return true;
    }
    return false;
  }
  removeValue(key) {
    if (key in this._value) {
      delete this._value[key];
      return true;
    }
    return false;
  }
  getValue(key) {
    const ret = this._value[key];
    if (typeof ret === "undefined" && this._parent) {
      return this._parent.getValue(key);
    }
    return ret;
  }
};
var NullContext = class extends Context {
  constructor() {
    super(-1, null);
  }
  setValue(key, value) {
    return false;
  }
  removeValue(key) {
    return false;
  }
  getValue(key) {
    return void 0;
  }
};
NullContext.INSTANCE = new NullContext();
var ConfigAwareContextValuesContainer = class extends Context {
  constructor(id3, _configurationService, emitter) {
    super(id3, null);
    this._configurationService = _configurationService;
    this._values = new Map();
    this._listener = this._configurationService.onDidChangeConfiguration((event) => {
      if (event.source === 6) {
        const allKeys = Array.from(this._values.keys());
        this._values.clear();
        emitter.fire(new ArrayContextKeyChangeEvent(allKeys));
      } else {
        const changedKeys = [];
        for (const configKey of event.affectedKeys) {
          const contextKey = `config.${configKey}`;
          if (this._values.has(contextKey)) {
            this._values.delete(contextKey);
            changedKeys.push(contextKey);
          }
        }
        emitter.fire(new ArrayContextKeyChangeEvent(changedKeys));
      }
    });
  }
  dispose() {
    this._listener.dispose();
  }
  getValue(key) {
    if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) {
      return super.getValue(key);
    }
    if (this._values.has(key)) {
      return this._values.get(key);
    }
    const configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length);
    const configValue = this._configurationService.getValue(configKey);
    let value = void 0;
    switch (typeof configValue) {
      case "number":
      case "boolean":
      case "string":
        value = configValue;
        break;
      default:
        if (Array.isArray(configValue)) {
          value = JSON.stringify(configValue);
        }
    }
    this._values.set(key, value);
    return value;
  }
  setValue(key, value) {
    return super.setValue(key, value);
  }
  removeValue(key) {
    return super.removeValue(key);
  }
};
ConfigAwareContextValuesContainer._keyPrefix = "config.";
var ContextKey = class {
  constructor(service, key, defaultValue) {
    this._service = service;
    this._key = key;
    this._defaultValue = defaultValue;
    this.reset();
  }
  set(value) {
    this._service.setContext(this._key, value);
  }
  reset() {
    if (typeof this._defaultValue === "undefined") {
      this._service.removeContext(this._key);
    } else {
      this._service.setContext(this._key, this._defaultValue);
    }
  }
  get() {
    return this._service.getContextKeyValue(this._key);
  }
};
var SimpleContextKeyChangeEvent = class {
  constructor(key) {
    this.key = key;
  }
  affectsSome(keys2) {
    return keys2.has(this.key);
  }
};
var ArrayContextKeyChangeEvent = class {
  constructor(keys2) {
    this.keys = keys2;
  }
  affectsSome(keys2) {
    for (const key of this.keys) {
      if (keys2.has(key)) {
        return true;
      }
    }
    return false;
  }
};
var CompositeContextKeyChangeEvent = class {
  constructor(events) {
    this.events = events;
  }
  affectsSome(keys2) {
    for (const e2 of this.events) {
      if (e2.affectsSome(keys2)) {
        return true;
      }
    }
    return false;
  }
};
var AbstractContextKeyService = class {
  constructor(myContextId) {
    this._onDidChangeContext = new PauseableEmitter({merge: (input) => new CompositeContextKeyChangeEvent(input)});
    this._isDisposed = false;
    this._myContextId = myContextId;
  }
  createKey(key, defaultValue) {
    if (this._isDisposed) {
      throw new Error(`AbstractContextKeyService has been disposed`);
    }
    return new ContextKey(this, key, defaultValue);
  }
  get onDidChangeContext() {
    return this._onDidChangeContext.event;
  }
  bufferChangeEvents(callback) {
    this._onDidChangeContext.pause();
    try {
      callback();
    } finally {
      this._onDidChangeContext.resume();
    }
  }
  createScoped(domNode) {
    if (this._isDisposed) {
      throw new Error(`AbstractContextKeyService has been disposed`);
    }
    return new ScopedContextKeyService(this, domNode);
  }
  contextMatchesRules(rules) {
    if (this._isDisposed) {
      throw new Error(`AbstractContextKeyService has been disposed`);
    }
    const context2 = this.getContextValuesContainer(this._myContextId);
    const result = KeybindingResolver.contextMatchesRules(context2, rules);
    return result;
  }
  getContextKeyValue(key) {
    if (this._isDisposed) {
      return void 0;
    }
    return this.getContextValuesContainer(this._myContextId).getValue(key);
  }
  setContext(key, value) {
    if (this._isDisposed) {
      return;
    }
    const myContext = this.getContextValuesContainer(this._myContextId);
    if (!myContext) {
      return;
    }
    if (myContext.setValue(key, value)) {
      this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
    }
  }
  removeContext(key) {
    if (this._isDisposed) {
      return;
    }
    if (this.getContextValuesContainer(this._myContextId).removeValue(key)) {
      this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
    }
  }
  getContext(target) {
    if (this._isDisposed) {
      return NullContext.INSTANCE;
    }
    return this.getContextValuesContainer(findContextAttr(target));
  }
};
var ContextKeyService = class ContextKeyService2 extends AbstractContextKeyService {
  constructor(configurationService) {
    super(0);
    this._contexts = new Map();
    this._toDispose = new DisposableStore();
    this._lastContextId = 0;
    const myContext = new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext);
    this._contexts.set(this._myContextId, myContext);
    this._toDispose.add(myContext);
  }
  dispose() {
    this._isDisposed = true;
    this._toDispose.dispose();
  }
  getContextValuesContainer(contextId) {
    if (this._isDisposed) {
      return NullContext.INSTANCE;
    }
    return this._contexts.get(contextId) || NullContext.INSTANCE;
  }
  createChildContext(parentContextId = this._myContextId) {
    if (this._isDisposed) {
      throw new Error(`ContextKeyService has been disposed`);
    }
    let id3 = ++this._lastContextId;
    this._contexts.set(id3, new Context(id3, this.getContextValuesContainer(parentContextId)));
    return id3;
  }
  disposeContext(contextId) {
    if (!this._isDisposed) {
      this._contexts.delete(contextId);
    }
  }
};
ContextKeyService = __decorate$a([
  __param$9(0, IConfigurationService)
], ContextKeyService);
var ScopedContextKeyService = class extends AbstractContextKeyService {
  constructor(parent, domNode) {
    super(parent.createChildContext());
    this._parent = parent;
    if (domNode) {
      this._domNode = domNode;
      this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId));
    }
  }
  dispose() {
    this._isDisposed = true;
    this._parent.disposeContext(this._myContextId);
    if (this._domNode) {
      this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR);
      this._domNode = void 0;
    }
  }
  get onDidChangeContext() {
    return Event.any(this._parent.onDidChangeContext, this._onDidChangeContext.event);
  }
  getContextValuesContainer(contextId) {
    if (this._isDisposed) {
      return NullContext.INSTANCE;
    }
    return this._parent.getContextValuesContainer(contextId);
  }
  createChildContext(parentContextId = this._myContextId) {
    if (this._isDisposed) {
      throw new Error(`ScopedContextKeyService has been disposed`);
    }
    return this._parent.createChildContext(parentContextId);
  }
  disposeContext(contextId) {
    if (this._isDisposed) {
      return;
    }
    this._parent.disposeContext(contextId);
  }
};
function findContextAttr(domNode) {
  while (domNode) {
    if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
      const attr2 = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR);
      if (attr2) {
        return parseInt(attr2, 10);
      }
      return NaN;
    }
    domNode = domNode.parentElement;
  }
  return 0;
}
CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, function(accessor, contextKey, contextValue) {
  accessor.get(IContextKeyService).createKey(String(contextKey), contextValue);
});
function __snowpack__injectStyle$r(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$r("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.context-view .monaco-menu {\r\n	min-width: 130px;\r\n}\r\n\r\n");
function __snowpack__injectStyle$s(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$s("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.context-view {\r\n	position: absolute;\r\n	z-index: 2500;\r\n}\r\n\r\n.context-view.fixed {\r\n	all: initial;\r\n	font-family: inherit;\r\n	font-size: 13px;\r\n	position: fixed;\r\n	z-index: 2500;\r\n	color: inherit;\r\n}\r\n");
var Range$1;
(function(Range2) {
  function intersect(one2, other) {
    if (one2.start >= other.end || other.start >= one2.end) {
      return {start: 0, end: 0};
    }
    const start3 = Math.max(one2.start, other.start);
    const end2 = Math.min(one2.end, other.end);
    if (end2 - start3 <= 0) {
      return {start: 0, end: 0};
    }
    return {start: start3, end: end2};
  }
  Range2.intersect = intersect;
  function isEmpty3(range3) {
    return range3.end - range3.start <= 0;
  }
  Range2.isEmpty = isEmpty3;
  function intersects2(one2, other) {
    return !isEmpty3(intersect(one2, other));
  }
  Range2.intersects = intersects2;
  function relativeComplement2(one2, other) {
    const result = [];
    const first2 = {start: one2.start, end: Math.min(other.start, one2.end)};
    const second = {start: Math.max(other.end, one2.start), end: one2.end};
    if (!isEmpty3(first2)) {
      result.push(first2);
    }
    if (!isEmpty3(second)) {
      result.push(second);
    }
    return result;
  }
  Range2.relativeComplement = relativeComplement2;
})(Range$1 || (Range$1 = {}));
function layout(viewportSize, viewSize, anchor) {
  const anchorEnd = anchor.offset + anchor.size;
  if (anchor.position === 0) {
    if (viewSize <= viewportSize - anchorEnd) {
      return anchorEnd;
    }
    if (viewSize <= anchor.offset) {
      return anchor.offset - viewSize;
    }
    return Math.max(viewportSize - viewSize, 0);
  } else {
    if (viewSize <= anchor.offset) {
      return anchor.offset - viewSize;
    }
    if (viewSize <= viewportSize - anchorEnd) {
      return anchorEnd;
    }
    return 0;
  }
}
var ContextView = class extends Disposable {
  constructor(container, domPosition) {
    super();
    this.container = null;
    this.delegate = null;
    this.toDisposeOnClean = Disposable.None;
    this.toDisposeOnSetContainer = Disposable.None;
    this.shadowRoot = null;
    this.shadowRootHostElement = null;
    this.view = $(".context-view");
    this.useFixedPosition = false;
    this.useShadowDOM = false;
    hide2(this.view);
    this.setContainer(container, domPosition);
    this._register(toDisposable(() => this.setContainer(null, 1)));
  }
  setContainer(container, domPosition) {
    if (this.container) {
      this.toDisposeOnSetContainer.dispose();
      if (this.shadowRoot) {
        this.shadowRoot.removeChild(this.view);
        this.shadowRoot = null;
        removeNode(this.shadowRootHostElement);
        this.shadowRootHostElement = null;
      } else {
        this.container.removeChild(this.view);
      }
      this.container = null;
    }
    if (container) {
      this.container = container;
      this.useFixedPosition = domPosition !== 1;
      this.useShadowDOM = domPosition === 3;
      if (this.useShadowDOM) {
        this.shadowRootHostElement = $(".shadow-root-host");
        this.container.appendChild(this.shadowRootHostElement);
        this.shadowRoot = this.shadowRootHostElement.attachShadow({mode: "open"});
        this.shadowRoot.innerHTML = `
					<style>
						${SHADOW_ROOT_CSS}
					</style>
				`;
        this.shadowRoot.appendChild(this.view);
        this.shadowRoot.appendChild($("slot"));
      } else {
        this.container.appendChild(this.view);
      }
      const toDisposeOnSetContainer = new DisposableStore();
      ContextView.BUBBLE_UP_EVENTS.forEach((event) => {
        toDisposeOnSetContainer.add(addStandardDisposableListener(this.container, event, (e2) => {
          this.onDOMEvent(e2, false);
        }));
      });
      ContextView.BUBBLE_DOWN_EVENTS.forEach((event) => {
        toDisposeOnSetContainer.add(addStandardDisposableListener(this.container, event, (e2) => {
          this.onDOMEvent(e2, true);
        }, true));
      });
      this.toDisposeOnSetContainer = toDisposeOnSetContainer;
    }
  }
  show(delegate) {
    if (this.isVisible()) {
      this.hide();
    }
    clearNode(this.view);
    this.view.className = "context-view";
    this.view.style.top = "0px";
    this.view.style.left = "0px";
    this.view.style.zIndex = "2500";
    this.view.style.position = this.useFixedPosition ? "fixed" : "absolute";
    show(this.view);
    this.toDisposeOnClean = delegate.render(this.view) || Disposable.None;
    this.delegate = delegate;
    this.doLayout();
    if (this.delegate.focus) {
      this.delegate.focus();
    }
  }
  getViewElement() {
    return this.view;
  }
  layout() {
    if (!this.isVisible()) {
      return;
    }
    if (this.delegate.canRelayout === false && !(isIOS && BrowserFeatures.pointerEvents)) {
      this.hide();
      return;
    }
    if (this.delegate.layout) {
      this.delegate.layout();
    }
    this.doLayout();
  }
  doLayout() {
    if (!this.isVisible()) {
      return;
    }
    let anchor = this.delegate.getAnchor();
    let around;
    if (isHTMLElement3(anchor)) {
      let elementPosition = getDomNodePagePosition(anchor);
      around = {
        top: elementPosition.top,
        left: elementPosition.left,
        width: elementPosition.width,
        height: elementPosition.height
      };
    } else {
      around = {
        top: anchor.y,
        left: anchor.x,
        width: anchor.width || 1,
        height: anchor.height || 2
      };
    }
    const viewSizeWidth = getTotalWidth(this.view);
    const viewSizeHeight = getTotalHeight(this.view);
    const anchorPosition = this.delegate.anchorPosition || 0;
    const anchorAlignment = this.delegate.anchorAlignment || 0;
    const verticalAnchor = {offset: around.top - window.pageYOffset, size: around.height, position: anchorPosition === 0 ? 0 : 1};
    let horizontalAnchor;
    if (anchorAlignment === 0) {
      horizontalAnchor = {offset: around.left, size: 0, position: 0};
    } else {
      horizontalAnchor = {offset: around.left + around.width, size: 0, position: 1};
    }
    const top2 = layout(window.innerHeight, viewSizeHeight, verticalAnchor) + window.pageYOffset;
    if (Range$1.intersects({start: top2, end: top2 + viewSizeHeight}, {start: verticalAnchor.offset, end: verticalAnchor.offset + verticalAnchor.size})) {
      horizontalAnchor.size = around.width;
      if (anchorAlignment === 1) {
        horizontalAnchor.offset = around.left;
      }
    }
    const left2 = layout(window.innerWidth, viewSizeWidth, horizontalAnchor);
    removeClasses(this.view, "top", "bottom", "left", "right");
    addClass(this.view, anchorPosition === 0 ? "bottom" : "top");
    addClass(this.view, anchorAlignment === 0 ? "left" : "right");
    toggleClass(this.view, "fixed", this.useFixedPosition);
    const containerPosition = getDomNodePagePosition(this.container);
    this.view.style.top = `${top2 - (this.useFixedPosition ? getDomNodePagePosition(this.view).top : containerPosition.top)}px`;
    this.view.style.left = `${left2 - (this.useFixedPosition ? getDomNodePagePosition(this.view).left : containerPosition.left)}px`;
    this.view.style.width = "initial";
  }
  hide(data2) {
    const delegate = this.delegate;
    this.delegate = null;
    if (delegate === null || delegate === void 0 ? void 0 : delegate.onHide) {
      delegate.onHide(data2);
    }
    this.toDisposeOnClean.dispose();
    hide2(this.view);
  }
  isVisible() {
    return !!this.delegate;
  }
  onDOMEvent(e2, onCapture) {
    if (this.delegate) {
      if (this.delegate.onDOMEvent) {
        this.delegate.onDOMEvent(e2, document.activeElement);
      } else if (onCapture && !isAncestor(e2.target, this.container)) {
        this.hide();
      }
    }
  }
  dispose() {
    this.hide();
    super.dispose();
  }
};
ContextView.BUBBLE_UP_EVENTS = ["click", "keydown", "focus", "blur"];
ContextView.BUBBLE_DOWN_EVENTS = ["click"];
var SHADOW_ROOT_CSS = `
	:host {
		all: initial; /* 1st rule so subsequent properties are reset. */
	}

	@font-face {
		font-family: "codicon";
		src: url("./codicon.ttf?5d4d76ab2ce5108968ad644d591a16a6") format("truetype");
	}

	.codicon[class*='codicon-'] {
		font: normal normal normal 16px/1 codicon;
		display: inline-block;
		text-decoration: none;
		text-rendering: auto;
		text-align: center;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		user-select: none;
		-webkit-user-select: none;
		-ms-user-select: none;
	}

	:host {
		font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", system-ui, "Ubuntu", "Droid Sans", sans-serif;
	}

	:host-context(.mac) { font-family: -apple-system, BlinkMacSystemFont, sans-serif; }
	:host-context(.mac:lang(zh-Hans)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", sans-serif; }
	:host-context(.mac:lang(zh-Hant)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang TC", sans-serif; }
	:host-context(.mac:lang(ja)) { font-family: -apple-system, BlinkMacSystemFont, "Hiragino Kaku Gothic Pro", sans-serif; }
	:host-context(.mac:lang(ko)) { font-family: -apple-system, BlinkMacSystemFont, "Nanum Gothic", "Apple SD Gothic Neo", "AppleGothic", sans-serif; }

	:host-context(.windows) { font-family: "Segoe WPC", "Segoe UI", sans-serif; }
	:host-context(.windows:lang(zh-Hans)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft YaHei", sans-serif; }
	:host-context(.windows:lang(zh-Hant)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft Jhenghei", sans-serif; }
	:host-context(.windows:lang(ja)) { font-family: "Segoe WPC", "Segoe UI", "Yu Gothic UI", "Meiryo UI", sans-serif; }
	:host-context(.windows:lang(ko)) { font-family: "Segoe WPC", "Segoe UI", "Malgun Gothic", "Dotom", sans-serif; }

	:host-context(.linux) { font-family: system-ui, "Ubuntu", "Droid Sans", sans-serif; }
	:host-context(.linux:lang(zh-Hans)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(zh-Hant)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans TC", "Source Han Sans TW", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(ja)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(ko)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; }
`;
var MENU_MNEMONIC_REGEX = /\(&([^\s&])\)|(^|[^&])&([^\s&])/;
var MENU_ESCAPED_MNEMONIC_REGEX = /(&amp;)?(&amp;)([^\s&])/g;
var menuSelectionIcon = registerIcon("menu-selection", Codicon.check);
var menuSubmenuIcon = registerIcon("menu-submenu", Codicon.chevronRight);
var Direction;
(function(Direction2) {
  Direction2[Direction2["Right"] = 0] = "Right";
  Direction2[Direction2["Left"] = 1] = "Left";
})(Direction || (Direction = {}));
var Menu = class extends ActionBar {
  constructor(container, actions2, options = {}) {
    addClass(container, "monaco-menu-container");
    container.setAttribute("role", "presentation");
    const menuElement = document.createElement("div");
    addClass(menuElement, "monaco-menu");
    menuElement.setAttribute("role", "presentation");
    super(menuElement, {
      orientation: 2,
      actionViewItemProvider: (action) => this.doGetActionViewItem(action, options, parentData),
      context: options.context,
      actionRunner: options.actionRunner,
      ariaLabel: options.ariaLabel,
      triggerKeys: {keys: [3, ...isMacintosh || isLinux ? [10] : []], keyDown: true}
    });
    this.menuElement = menuElement;
    this.actionsList.setAttribute("role", "menu");
    this.actionsList.tabIndex = 0;
    this.menuDisposables = this._register(new DisposableStore());
    this.initializeStyleSheet(container);
    addDisposableListener(menuElement, EventType.KEY_DOWN, (e2) => {
      const event = new StandardKeyboardEvent(e2);
      if (event.equals(2)) {
        e2.preventDefault();
      }
    });
    if (options.enableMnemonics) {
      this.menuDisposables.add(addDisposableListener(menuElement, EventType.KEY_DOWN, (e2) => {
        const key = e2.key.toLocaleLowerCase();
        if (this.mnemonics.has(key)) {
          EventHelper.stop(e2, true);
          const actions3 = this.mnemonics.get(key);
          if (actions3.length === 1) {
            if (actions3[0] instanceof SubmenuMenuActionViewItem && actions3[0].container) {
              this.focusItemByElement(actions3[0].container);
            }
            actions3[0].onClick(e2);
          }
          if (actions3.length > 1) {
            const action = actions3.shift();
            if (action && action.container) {
              this.focusItemByElement(action.container);
              actions3.push(action);
            }
            this.mnemonics.set(key, actions3);
          }
        }
      }));
    }
    if (isLinux) {
      this._register(addDisposableListener(menuElement, EventType.KEY_DOWN, (e2) => {
        const event = new StandardKeyboardEvent(e2);
        if (event.equals(14) || event.equals(11)) {
          this.focusedItem = this.viewItems.length - 1;
          this.focusNext();
          EventHelper.stop(e2, true);
        } else if (event.equals(13) || event.equals(12)) {
          this.focusedItem = 0;
          this.focusPrevious();
          EventHelper.stop(e2, true);
        }
      }));
    }
    this._register(addDisposableListener(this.domNode, EventType.MOUSE_OUT, (e2) => {
      let relatedTarget = e2.relatedTarget;
      if (!isAncestor(relatedTarget, this.domNode)) {
        this.focusedItem = void 0;
        this.updateFocus();
        e2.stopPropagation();
      }
    }));
    this._register(addDisposableListener(this.actionsList, EventType.MOUSE_OVER, (e2) => {
      let target = e2.target;
      if (!target || !isAncestor(target, this.actionsList) || target === this.actionsList) {
        return;
      }
      while (target.parentElement !== this.actionsList && target.parentElement !== null) {
        target = target.parentElement;
      }
      if (hasClass(target, "action-item")) {
        const lastFocusedItem = this.focusedItem;
        this.setFocusedItem(target);
        if (lastFocusedItem !== this.focusedItem) {
          this.updateFocus();
        }
      }
    }));
    let parentData = {
      parent: this
    };
    this.mnemonics = new Map();
    this.scrollableElement = this._register(new DomScrollableElement(menuElement, {
      alwaysConsumeMouseWheel: true,
      horizontal: 2,
      vertical: 3,
      verticalScrollbarSize: 7,
      handleMouseWheel: true,
      useShadows: true
    }));
    const scrollElement = this.scrollableElement.getDomNode();
    scrollElement.style.position = "";
    this._register(addDisposableListener(scrollElement, EventType.MOUSE_UP, (e2) => {
      e2.preventDefault();
    }));
    menuElement.style.maxHeight = `${Math.max(10, window.innerHeight - container.getBoundingClientRect().top - 35)}px`;
    actions2 = actions2.filter((a2) => {
      var _a;
      if ((_a = options.submenuIds) === null || _a === void 0 ? void 0 : _a.has(a2.id)) {
        console.warn(`Found submenu cycle: ${a2.id}`);
        return false;
      }
      return true;
    });
    this.push(actions2, {icon: true, label: true, isMenu: true});
    container.appendChild(this.scrollableElement.getDomNode());
    this.scrollableElement.scanDomNode();
    this.viewItems.filter((item) => !(item instanceof MenuSeparatorActionViewItem)).forEach((item, index3, array2) => {
      item.updatePositionInSet(index3 + 1, array2.length);
    });
  }
  initializeStyleSheet(container) {
    if (isInShadowDOM(container)) {
      this.styleSheet = createStyleSheet(container);
      this.styleSheet.innerHTML = MENU_WIDGET_CSS;
    } else {
      if (!Menu.globalStyleSheet) {
        Menu.globalStyleSheet = createStyleSheet();
        Menu.globalStyleSheet.innerHTML = MENU_WIDGET_CSS;
      }
      this.styleSheet = Menu.globalStyleSheet;
    }
  }
  style(style) {
    const container = this.getContainer();
    const fgColor = style.foregroundColor ? `${style.foregroundColor}` : "";
    const bgColor = style.backgroundColor ? `${style.backgroundColor}` : "";
    const border = style.borderColor ? `1px solid ${style.borderColor}` : "";
    const shadow = style.shadowColor ? `0 2px 4px ${style.shadowColor}` : "";
    container.style.border = border;
    this.domNode.style.color = fgColor;
    this.domNode.style.backgroundColor = bgColor;
    container.style.boxShadow = shadow;
    if (this.viewItems) {
      this.viewItems.forEach((item) => {
        if (item instanceof BaseMenuActionViewItem || item instanceof MenuSeparatorActionViewItem) {
          item.style(style);
        }
      });
    }
  }
  getContainer() {
    return this.scrollableElement.getDomNode();
  }
  get onScroll() {
    return this.scrollableElement.onScroll;
  }
  focusItemByElement(element) {
    const lastFocusedItem = this.focusedItem;
    this.setFocusedItem(element);
    if (lastFocusedItem !== this.focusedItem) {
      this.updateFocus();
    }
  }
  setFocusedItem(element) {
    for (let i3 = 0; i3 < this.actionsList.children.length; i3++) {
      let elem = this.actionsList.children[i3];
      if (element === elem) {
        this.focusedItem = i3;
        break;
      }
    }
  }
  updateFocus(fromRight) {
    super.updateFocus(fromRight, true);
    if (typeof this.focusedItem !== "undefined") {
      this.scrollableElement.setScrollPosition({
        scrollTop: Math.round(this.menuElement.scrollTop)
      });
    }
  }
  doGetActionViewItem(action, options, parentData) {
    if (action instanceof Separator) {
      return new MenuSeparatorActionViewItem(options.context, action, {icon: true});
    } else if (action instanceof SubmenuAction) {
      const menuActionViewItem = new SubmenuMenuActionViewItem(action, action.actions, parentData, Object.assign(Object.assign({}, options), {submenuIds: new Set([...options.submenuIds || [], action.id])}));
      if (options.enableMnemonics) {
        const mnemonic = menuActionViewItem.getMnemonic();
        if (mnemonic && menuActionViewItem.isEnabled()) {
          let actionViewItems = [];
          if (this.mnemonics.has(mnemonic)) {
            actionViewItems = this.mnemonics.get(mnemonic);
          }
          actionViewItems.push(menuActionViewItem);
          this.mnemonics.set(mnemonic, actionViewItems);
        }
      }
      return menuActionViewItem;
    } else {
      const menuItemOptions = {enableMnemonics: options.enableMnemonics, useEventAsContext: options.useEventAsContext};
      if (options.getKeyBinding) {
        const keybinding = options.getKeyBinding(action);
        if (keybinding) {
          const keybindingLabel = keybinding.getLabel();
          if (keybindingLabel) {
            menuItemOptions.keybinding = keybindingLabel;
          }
        }
      }
      const menuActionViewItem = new BaseMenuActionViewItem(options.context, action, menuItemOptions);
      if (options.enableMnemonics) {
        const mnemonic = menuActionViewItem.getMnemonic();
        if (mnemonic && menuActionViewItem.isEnabled()) {
          let actionViewItems = [];
          if (this.mnemonics.has(mnemonic)) {
            actionViewItems = this.mnemonics.get(mnemonic);
          }
          actionViewItems.push(menuActionViewItem);
          this.mnemonics.set(mnemonic, actionViewItems);
        }
      }
      return menuActionViewItem;
    }
  }
};
var BaseMenuActionViewItem = class extends BaseActionViewItem {
  constructor(ctx, action, options = {}) {
    options.isMenu = true;
    super(action, action, options);
    this.options = options;
    this.options.icon = options.icon !== void 0 ? options.icon : false;
    this.options.label = options.label !== void 0 ? options.label : true;
    this.cssClass = "";
    if (this.options.label && options.enableMnemonics) {
      let label2 = this.getAction().label;
      if (label2) {
        let matches2 = MENU_MNEMONIC_REGEX.exec(label2);
        if (matches2) {
          this.mnemonic = (!!matches2[1] ? matches2[1] : matches2[3]).toLocaleLowerCase();
        }
      }
    }
    this.runOnceToEnableMouseUp = new RunOnceScheduler(() => {
      if (!this.element) {
        return;
      }
      this._register(addDisposableListener(this.element, EventType.MOUSE_UP, (e2) => {
        EventHelper.stop(e2, true);
        if (isFirefox) {
          const mouseEvent = new StandardMouseEvent(e2);
          if (mouseEvent.rightButton) {
            return;
          }
          this.onClick(e2);
        }
        setTimeout(() => {
          this.onClick(e2);
        }, 0);
      }));
      this._register(addDisposableListener(this.element, EventType.CONTEXT_MENU, (e2) => {
        EventHelper.stop(e2, true);
      }));
    }, 100);
    this._register(this.runOnceToEnableMouseUp);
  }
  render(container) {
    super.render(container);
    if (!this.element) {
      return;
    }
    this.container = container;
    this.item = append(this.element, $("a.action-menu-item"));
    if (this._action.id === Separator.ID) {
      this.item.setAttribute("role", "presentation");
    } else {
      this.item.setAttribute("role", "menuitem");
      if (this.mnemonic) {
        this.item.setAttribute("aria-keyshortcuts", `${this.mnemonic}`);
      }
    }
    this.check = append(this.item, $("span.menu-item-check" + menuSelectionIcon.cssSelector));
    this.check.setAttribute("role", "none");
    this.label = append(this.item, $("span.action-label"));
    if (this.options.label && this.options.keybinding) {
      append(this.item, $("span.keybinding")).textContent = this.options.keybinding;
    }
    this.runOnceToEnableMouseUp.schedule();
    this.updateClass();
    this.updateLabel();
    this.updateTooltip();
    this.updateEnabled();
    this.updateChecked();
  }
  blur() {
    super.blur();
    this.applyStyle();
  }
  focus() {
    super.focus();
    if (this.item) {
      this.item.focus();
    }
    this.applyStyle();
  }
  updatePositionInSet(pos, setSize) {
    if (this.item) {
      this.item.setAttribute("aria-posinset", `${pos}`);
      this.item.setAttribute("aria-setsize", `${setSize}`);
    }
  }
  updateLabel() {
    if (!this.label) {
      return;
    }
    if (this.options.label) {
      clearNode(this.label);
      let label2 = stripCodicons(this.getAction().label);
      if (label2) {
        const cleanLabel = cleanMnemonic(label2);
        if (!this.options.enableMnemonics) {
          label2 = cleanLabel;
        }
        this.label.setAttribute("aria-label", cleanLabel.replace(/&&/g, "&"));
        const matches2 = MENU_MNEMONIC_REGEX.exec(label2);
        if (matches2) {
          label2 = escape3(label2);
          MENU_ESCAPED_MNEMONIC_REGEX.lastIndex = 0;
          let escMatch = MENU_ESCAPED_MNEMONIC_REGEX.exec(label2);
          while (escMatch && escMatch[1]) {
            escMatch = MENU_ESCAPED_MNEMONIC_REGEX.exec(label2);
          }
          const replaceDoubleEscapes = (str) => str.replace(/&amp;&amp;/g, "&amp;");
          if (escMatch) {
            this.label.append(ltrim(replaceDoubleEscapes(label2.substr(0, escMatch.index)), " "), $("u", {"aria-hidden": "true"}, escMatch[3]), rtrim(replaceDoubleEscapes(label2.substr(escMatch.index + escMatch[0].length)), " "));
          } else {
            this.label.innerText = replaceDoubleEscapes(label2).trim();
          }
          if (this.item) {
            this.item.setAttribute("aria-keyshortcuts", (!!matches2[1] ? matches2[1] : matches2[3]).toLocaleLowerCase());
          }
        } else {
          this.label.innerText = label2.replace(/&&/g, "&").trim();
        }
      }
    }
  }
  updateTooltip() {
    let title3 = null;
    if (this.getAction().tooltip) {
      title3 = this.getAction().tooltip;
    } else if (!this.options.label && this.getAction().label && this.options.icon) {
      title3 = this.getAction().label;
      if (this.options.keybinding) {
        title3 = localize({key: "titleLabel", comment: ["action title", "action keybinding"]}, "{0} ({1})", title3, this.options.keybinding);
      }
    }
    if (title3 && this.item) {
      this.item.title = title3;
    }
  }
  updateClass() {
    if (this.cssClass && this.item) {
      removeClasses(this.item, this.cssClass);
    }
    if (this.options.icon && this.label) {
      this.cssClass = this.getAction().class || "";
      addClass(this.label, "icon");
      if (this.cssClass) {
        addClasses(this.label, this.cssClass);
      }
      this.updateEnabled();
    } else if (this.label) {
      removeClass(this.label, "icon");
    }
  }
  updateEnabled() {
    if (this.getAction().enabled) {
      if (this.element) {
        removeClass(this.element, "disabled");
      }
      if (this.item) {
        removeClass(this.item, "disabled");
        this.item.tabIndex = 0;
      }
    } else {
      if (this.element) {
        addClass(this.element, "disabled");
      }
      if (this.item) {
        addClass(this.item, "disabled");
        removeTabIndexAndUpdateFocus(this.item);
      }
    }
  }
  updateChecked() {
    if (!this.item) {
      return;
    }
    if (this.getAction().checked) {
      addClass(this.item, "checked");
      this.item.setAttribute("role", "menuitemcheckbox");
      this.item.setAttribute("aria-checked", "true");
    } else {
      removeClass(this.item, "checked");
      this.item.setAttribute("role", "menuitem");
      this.item.setAttribute("aria-checked", "false");
    }
  }
  getMnemonic() {
    return this.mnemonic;
  }
  applyStyle() {
    if (!this.menuStyle) {
      return;
    }
    const isSelected = this.element && hasClass(this.element, "focused");
    const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
    const bgColor = isSelected && this.menuStyle.selectionBackgroundColor ? this.menuStyle.selectionBackgroundColor : void 0;
    const border = isSelected && this.menuStyle.selectionBorderColor ? `thin solid ${this.menuStyle.selectionBorderColor}` : "";
    if (this.item) {
      this.item.style.color = fgColor ? fgColor.toString() : "";
      this.item.style.backgroundColor = bgColor ? bgColor.toString() : "";
    }
    if (this.check) {
      this.check.style.color = fgColor ? fgColor.toString() : "";
    }
    if (this.container) {
      this.container.style.border = border;
    }
  }
  style(style) {
    this.menuStyle = style;
    this.applyStyle();
  }
};
var SubmenuMenuActionViewItem = class extends BaseMenuActionViewItem {
  constructor(action, submenuActions, parentData, submenuOptions) {
    super(action, action, submenuOptions);
    this.submenuActions = submenuActions;
    this.parentData = parentData;
    this.submenuOptions = submenuOptions;
    this.mysubmenu = null;
    this.submenuDisposables = this._register(new DisposableStore());
    this.mouseOver = false;
    this.expandDirection = submenuOptions && submenuOptions.expandDirection !== void 0 ? submenuOptions.expandDirection : Direction.Right;
    this.showScheduler = new RunOnceScheduler(() => {
      if (this.mouseOver) {
        this.cleanupExistingSubmenu(false);
        this.createSubmenu(false);
      }
    }, 250);
    this.hideScheduler = new RunOnceScheduler(() => {
      if (this.element && (!isAncestor(getActiveElement(), this.element) && this.parentData.submenu === this.mysubmenu)) {
        this.parentData.parent.focus(false);
        this.cleanupExistingSubmenu(true);
      }
    }, 750);
  }
  render(container) {
    super.render(container);
    if (!this.element) {
      return;
    }
    if (this.item) {
      addClass(this.item, "monaco-submenu-item");
      this.item.setAttribute("aria-haspopup", "true");
      this.updateAriaExpanded("false");
      this.submenuIndicator = append(this.item, $("span.submenu-indicator" + menuSubmenuIcon.cssSelector));
      this.submenuIndicator.setAttribute("aria-hidden", "true");
    }
    this._register(addDisposableListener(this.element, EventType.KEY_UP, (e2) => {
      let event = new StandardKeyboardEvent(e2);
      if (event.equals(17) || event.equals(3)) {
        EventHelper.stop(e2, true);
        this.createSubmenu(true);
      }
    }));
    this._register(addDisposableListener(this.element, EventType.KEY_DOWN, (e2) => {
      let event = new StandardKeyboardEvent(e2);
      if (getActiveElement() === this.item) {
        if (event.equals(17) || event.equals(3)) {
          EventHelper.stop(e2, true);
        }
      }
    }));
    this._register(addDisposableListener(this.element, EventType.MOUSE_OVER, (e2) => {
      if (!this.mouseOver) {
        this.mouseOver = true;
        this.showScheduler.schedule();
      }
    }));
    this._register(addDisposableListener(this.element, EventType.MOUSE_LEAVE, (e2) => {
      this.mouseOver = false;
    }));
    this._register(addDisposableListener(this.element, EventType.FOCUS_OUT, (e2) => {
      if (this.element && !isAncestor(getActiveElement(), this.element)) {
        this.hideScheduler.schedule();
      }
    }));
    this._register(this.parentData.parent.onScroll(() => {
      this.parentData.parent.focus(false);
      this.cleanupExistingSubmenu(false);
    }));
  }
  onClick(e2) {
    EventHelper.stop(e2, true);
    this.cleanupExistingSubmenu(false);
    this.createSubmenu(true);
  }
  cleanupExistingSubmenu(force) {
    if (this.parentData.submenu && (force || this.parentData.submenu !== this.mysubmenu)) {
      try {
        this.parentData.submenu.dispose();
      } catch (_a) {
      }
      this.parentData.submenu = void 0;
      this.updateAriaExpanded("false");
      if (this.submenuContainer) {
        this.submenuDisposables.clear();
        this.submenuContainer = void 0;
      }
    }
  }
  calculateSubmenuMenuLayout(windowDimensions, submenu, entry, expandDirection) {
    const ret = {top: 0, left: 0};
    ret.left = layout(windowDimensions.width, submenu.width, {position: expandDirection === Direction.Right ? 0 : 1, offset: entry.left, size: entry.width});
    if (ret.left >= entry.left && ret.left < entry.left + entry.width) {
      if (entry.left + 10 + submenu.width <= windowDimensions.width) {
        ret.left = entry.left + 10;
      }
      entry.top += 10;
      entry.height = 0;
    }
    ret.top = layout(windowDimensions.height, submenu.height, {position: 0, offset: entry.top, size: 0});
    if (ret.top + submenu.height === entry.top && ret.top + entry.height + submenu.height <= windowDimensions.height) {
      ret.top += entry.height;
    }
    return ret;
  }
  createSubmenu(selectFirstItem = true) {
    if (!this.element) {
      return;
    }
    if (!this.parentData.submenu) {
      this.updateAriaExpanded("true");
      this.submenuContainer = append(this.element, $("div.monaco-submenu"));
      addClasses(this.submenuContainer, "menubar-menu-items-holder", "context-view");
      const computedStyles = getComputedStyle(this.parentData.parent.domNode);
      const paddingTop = parseFloat(computedStyles.paddingTop || "0") || 0;
      this.submenuContainer.style.zIndex = "1";
      this.submenuContainer.style.position = "fixed";
      this.submenuContainer.style.top = "0";
      this.submenuContainer.style.left = "0";
      this.parentData.submenu = new Menu(this.submenuContainer, this.submenuActions, this.submenuOptions);
      if (this.menuStyle) {
        this.parentData.submenu.style(this.menuStyle);
      }
      const entryBox = this.element.getBoundingClientRect();
      const entryBoxUpdated = {
        top: entryBox.top - paddingTop,
        left: entryBox.left,
        height: entryBox.height + 2 * paddingTop,
        width: entryBox.width
      };
      const viewBox = this.submenuContainer.getBoundingClientRect();
      const {top: top2, left: left2} = this.calculateSubmenuMenuLayout({height: window.innerHeight, width: window.innerWidth}, viewBox, entryBoxUpdated, this.expandDirection);
      this.submenuContainer.style.left = `${left2}px`;
      this.submenuContainer.style.top = `${top2}px`;
      this.submenuDisposables.add(addDisposableListener(this.submenuContainer, EventType.KEY_UP, (e2) => {
        let event = new StandardKeyboardEvent(e2);
        if (event.equals(15)) {
          EventHelper.stop(e2, true);
          this.parentData.parent.focus();
          this.cleanupExistingSubmenu(true);
        }
      }));
      this.submenuDisposables.add(addDisposableListener(this.submenuContainer, EventType.KEY_DOWN, (e2) => {
        let event = new StandardKeyboardEvent(e2);
        if (event.equals(15)) {
          EventHelper.stop(e2, true);
        }
      }));
      this.submenuDisposables.add(this.parentData.submenu.onDidCancel(() => {
        this.parentData.parent.focus();
        this.cleanupExistingSubmenu(true);
      }));
      this.parentData.submenu.focus(selectFirstItem);
      this.mysubmenu = this.parentData.submenu;
    } else {
      this.parentData.submenu.focus(false);
    }
  }
  updateAriaExpanded(value) {
    var _a;
    if (this.item) {
      (_a = this.item) === null || _a === void 0 ? void 0 : _a.setAttribute("aria-expanded", value);
    }
  }
  applyStyle() {
    super.applyStyle();
    if (!this.menuStyle) {
      return;
    }
    const isSelected = this.element && hasClass(this.element, "focused");
    const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
    if (this.submenuIndicator) {
      this.submenuIndicator.style.color = fgColor ? `${fgColor}` : "";
    }
    if (this.parentData.submenu) {
      this.parentData.submenu.style(this.menuStyle);
    }
  }
  dispose() {
    super.dispose();
    this.hideScheduler.dispose();
    if (this.mysubmenu) {
      this.mysubmenu.dispose();
      this.mysubmenu = null;
    }
    if (this.submenuContainer) {
      this.submenuContainer = void 0;
    }
  }
};
var MenuSeparatorActionViewItem = class extends ActionViewItem {
  style(style) {
    if (this.label) {
      this.label.style.borderBottomColor = style.separatorColor ? `${style.separatorColor}` : "";
    }
  }
};
function cleanMnemonic(label2) {
  const regex = MENU_MNEMONIC_REGEX;
  const matches2 = regex.exec(label2);
  if (!matches2) {
    return label2;
  }
  const mnemonicInText = !matches2[1];
  return label2.replace(regex, mnemonicInText ? "$2$3" : "").trim();
}
var MENU_WIDGET_CSS = `
.monaco-menu {
	font-size: 13px;

}

${formatRule(menuSelectionIcon)}
${formatRule(menuSubmenuIcon)}

.monaco-menu .monaco-action-bar {
	text-align: right;
	overflow: hidden;
	white-space: nowrap;
}

.monaco-menu .monaco-action-bar .actions-container {
	display: flex;
	margin: 0 auto;
	padding: 0;
	width: 100%;
	justify-content: flex-end;
}

.monaco-menu .monaco-action-bar.vertical .actions-container {
	display: inline-block;
}

.monaco-menu .monaco-action-bar.reverse .actions-container {
	flex-direction: row-reverse;
}

.monaco-menu .monaco-action-bar .action-item {
	cursor: pointer;
	display: inline-block;
	transition: transform 50ms ease;
	position: relative;  /* DO NOT REMOVE - this is the key to preventing the ghosting icon bug in Chrome 42 */
}

.monaco-menu .monaco-action-bar .action-item.disabled {
	cursor: default;
}

.monaco-menu .monaco-action-bar.animated .action-item.active {
	transform: scale(1.272019649, 1.272019649); /* 1.272019649 = √φ */
}

.monaco-menu .monaco-action-bar .action-item .icon,
.monaco-menu .monaco-action-bar .action-item .codicon {
	display: inline-block;
}

.monaco-menu .monaco-action-bar .action-item .codicon {
	display: flex;
	align-items: center;
}

.monaco-menu .monaco-action-bar .action-label {
	font-size: 11px;
	margin-right: 4px;
}

.monaco-menu .monaco-action-bar .action-item.disabled .action-label,
.monaco-menu .monaco-action-bar .action-item.disabled .action-label:hover {
	opacity: 0.4;
}

/* Vertical actions */

.monaco-menu .monaco-action-bar.vertical {
	text-align: left;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	display: block;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	display: block;
	border-bottom: 1px solid #bbb;
	padding-top: 1px;
	margin-left: .8em;
	margin-right: .8em;
}

.monaco-menu .secondary-actions .monaco-action-bar .action-label {
	margin-left: 6px;
}

/* Action Items */
.monaco-menu .monaco-action-bar .action-item.select-container {
	overflow: hidden; /* somehow the dropdown overflows its container, we prevent it here to not push */
	flex: 1;
	max-width: 170px;
	min-width: 60px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 10px;
}

.monaco-menu .monaco-action-bar.vertical {
	margin-left: 0;
	overflow: visible;
}

.monaco-menu .monaco-action-bar.vertical .actions-container {
	display: block;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	padding: 0;
	transform: none;
	display: flex;
}

.monaco-menu .monaco-action-bar.vertical .action-item.active {
	transform: none;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item {
	flex: 1 1 auto;
	display: flex;
	height: 2em;
	align-items: center;
	position: relative;
}

.monaco-menu .monaco-action-bar.vertical .action-label {
	flex: 1 1 auto;
	text-decoration: none;
	padding: 0 1em;
	background: none;
	font-size: 12px;
	line-height: 1;
}

.monaco-menu .monaco-action-bar.vertical .keybinding,
.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	display: inline-block;
	flex: 2 1 auto;
	padding: 0 1em;
	text-align: right;
	font-size: 12px;
	line-height: 1;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon {
	font-size: 16px !important;
	display: flex;
	align-items: center;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon::before {
	margin-left: auto;
	margin-right: -20px;
}

.monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding,
.monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator {
	opacity: 0.4;
}

.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator) {
	display: inline-block;
	box-sizing: border-box;
	margin: 0;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	position: static;
	overflow: visible;
}

.monaco-menu .monaco-action-bar.vertical .action-item .monaco-submenu {
	position: absolute;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	padding: 0.5em 0 0 0;
	margin-bottom: 0.5em;
	width: 100%;
	height: 0px !important;
	margin-left: .8em !important;
	margin-right: .8em !important;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator.text {
	padding: 0.7em 1em 0.1em 1em;
	font-weight: bold;
	opacity: 1;
}

.monaco-menu .monaco-action-bar.vertical .action-label:hover {
	color: inherit;
}

.monaco-menu .monaco-action-bar.vertical .menu-item-check {
	position: absolute;
	visibility: hidden;
	width: 1em;
	height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item.checked .menu-item-check {
	visibility: visible;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* Context Menu */

.context-view.monaco-menu-container {
	outline: 0;
	border: none;
	animation: fadeIn 0.083s linear;
}

.context-view.monaco-menu-container :focus,
.context-view.monaco-menu-container .monaco-action-bar.vertical:focus,
.context-view.monaco-menu-container .monaco-action-bar.vertical :focus {
	outline: 0;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	border: thin solid transparent; /* prevents jumping behaviour on hover or focus */
}


/* High Contrast Theming */
:host-context(.hc-black) .context-view.monaco-menu-container {
	box-shadow: none;
}

:host-context(.hc-black) .monaco-menu .monaco-action-bar.vertical .action-item.focused {
	background: none;
}

/* Vertical Action Bar Styles */

.monaco-menu .monaco-action-bar.vertical {
	padding: .5em 0;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item {
	height: 1.8em;
}

.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),
.monaco-menu .monaco-action-bar.vertical .keybinding {
	font-size: inherit;
	padding: 0 2em;
}

.monaco-menu .monaco-action-bar.vertical .menu-item-check {
	font-size: inherit;
	width: 2em;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	font-size: inherit;
	padding: 0.2em 0 0 0;
	margin-bottom: 0.2em;
}

:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .action-label.separator {
	margin-left: 0;
	margin-right: 0;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	font-size: 60%;
	padding: 0 1.8em;
}

:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	height: 100%;
	mask-size: 10px 10px;
	-webkit-mask-size: 10px 10px;
}

.monaco-menu .action-item {
	cursor: default;
}

/* Arrows */
.monaco-scrollable-element > .scrollbar > .scra {
	cursor: pointer;
	font-size: 11px !important;
}

.monaco-scrollable-element > .visible {
	opacity: 1;

	/* Background rule added for IE9 - to allow clicks on dom node */
	background:rgba(0,0,0,0);

	transition: opacity 100ms linear;
}
.monaco-scrollable-element > .invisible {
	opacity: 0;
	pointer-events: none;
}
.monaco-scrollable-element > .invisible.fade {
	transition: opacity 800ms linear;
}

/* Scrollable Content Inset Shadow */
.monaco-scrollable-element > .shadow {
	position: absolute;
	display: none;
}
.monaco-scrollable-element > .shadow.top {
	display: block;
	top: 0;
	left: 3px;
	height: 3px;
	width: 100%;
	box-shadow: #DDD 0 6px 6px -6px inset;
}
.monaco-scrollable-element > .shadow.left {
	display: block;
	top: 3px;
	left: 0;
	height: 100%;
	width: 3px;
	box-shadow: #DDD 6px 0 6px -6px inset;
}
.monaco-scrollable-element > .shadow.top-left-corner {
	display: block;
	top: 0;
	left: 0;
	height: 3px;
	width: 3px;
}
.monaco-scrollable-element > .shadow.top.left {
	box-shadow: #DDD 6px 6px 6px -6px inset;
}

/* ---------- Default Style ---------- */

:host-context(.vs) .monaco-scrollable-element > .scrollbar > .slider {
	background: rgba(100, 100, 100, .4);
}
:host-context(.vs-dark) .monaco-scrollable-element > .scrollbar > .slider {
	background: rgba(121, 121, 121, .4);
}
:host-context(.hc-black) .monaco-scrollable-element > .scrollbar > .slider {
	background: rgba(111, 195, 223, .6);
}

.monaco-scrollable-element > .scrollbar > .slider:hover {
	background: rgba(100, 100, 100, .7);
}
:host-context(.hc-black) .monaco-scrollable-element > .scrollbar > .slider:hover {
	background: rgba(111, 195, 223, .8);
}

.monaco-scrollable-element > .scrollbar > .slider.active {
	background: rgba(0, 0, 0, .6);
}
:host-context(.vs-dark) .monaco-scrollable-element > .scrollbar > .slider.active {
	background: rgba(191, 191, 191, .4);
}
:host-context(.hc-black) .monaco-scrollable-element > .scrollbar > .slider.active {
	background: rgba(111, 195, 223, 1);
}

:host-context(.vs-dark) .monaco-scrollable-element .shadow.top {
	box-shadow: none;
}

:host-context(.vs-dark) .monaco-scrollable-element .shadow.left {
	box-shadow: #000 6px 0 6px -6px inset;
}

:host-context(.vs-dark) .monaco-scrollable-element .shadow.top.left {
	box-shadow: #000 6px 6px 6px -6px inset;
}

:host-context(.hc-black) .monaco-scrollable-element .shadow.top {
	box-shadow: none;
}

:host-context(.hc-black) .monaco-scrollable-element .shadow.left {
	box-shadow: none;
}

:host-context(.hc-black) .monaco-scrollable-element .shadow.top.left {
	box-shadow: none;
}
`;
function computeStyles2(theme, styleMap) {
  const styles6 = Object.create(null);
  for (let key in styleMap) {
    const value = styleMap[key];
    if (value) {
      styles6[key] = resolveColorValue(value, theme);
    }
  }
  return styles6;
}
function attachStyler(themeService, styleMap, widgetOrCallback) {
  function applyStyles2(theme) {
    const styles6 = computeStyles2(themeService.getColorTheme(), styleMap);
    if (typeof widgetOrCallback === "function") {
      widgetOrCallback(styles6);
    } else {
      widgetOrCallback.style(styles6);
    }
  }
  applyStyles2(themeService.getColorTheme());
  return themeService.onDidColorThemeChange(applyStyles2);
}
function attachListStyler(widget, themeService, overrides) {
  return attachStyler(themeService, Object.assign(Object.assign({}, defaultListStyles), overrides || {}), widget);
}
var defaultListStyles = {
  listFocusBackground,
  listFocusForeground,
  listActiveSelectionBackground: darken(listActiveSelectionBackground, 0.1),
  listActiveSelectionForeground,
  listFocusAndSelectionBackground: listActiveSelectionBackground,
  listFocusAndSelectionForeground: listActiveSelectionForeground,
  listInactiveSelectionBackground,
  listInactiveSelectionForeground,
  listInactiveFocusBackground,
  listHoverBackground,
  listHoverForeground,
  listDropBackground,
  listFocusOutline: activeContrastBorder,
  listSelectionOutline: activeContrastBorder,
  listHoverOutline: activeContrastBorder,
  listFilterWidgetBackground,
  listFilterWidgetOutline,
  listFilterWidgetNoMatchesOutline,
  listMatchesShadow: widgetShadow,
  treeIndentGuidesStroke
};
var defaultMenuStyles = {
  shadowColor: widgetShadow,
  borderColor: menuBorder,
  foregroundColor: menuForeground,
  backgroundColor: menuBackground,
  selectionForegroundColor: menuSelectionForeground,
  selectionBackgroundColor: menuSelectionBackground,
  selectionBorderColor: menuSelectionBorder,
  separatorColor: menuSeparatorBackground
};
function attachMenuStyler(widget, themeService, style) {
  return attachStyler(themeService, Object.assign(Object.assign({}, defaultMenuStyles), style), widget);
}
var ContextMenuHandler = class {
  constructor(contextViewService, telemetryService, notificationService, keybindingService, themeService) {
    this.contextViewService = contextViewService;
    this.telemetryService = telemetryService;
    this.notificationService = notificationService;
    this.keybindingService = keybindingService;
    this.themeService = themeService;
    this.focusToReturn = null;
    this.block = null;
    this.options = {blockMouse: true};
  }
  configure(options) {
    this.options = options;
  }
  showContextMenu(delegate) {
    const actions2 = delegate.getActions();
    if (!actions2.length) {
      return;
    }
    this.focusToReturn = document.activeElement;
    let menu;
    let shadowRootElement = isHTMLElement3(delegate.domForShadowRoot) ? delegate.domForShadowRoot : void 0;
    this.contextViewService.showContextView({
      getAnchor: () => delegate.getAnchor(),
      canRelayout: false,
      anchorAlignment: delegate.anchorAlignment,
      render: (container) => {
        let className = delegate.getMenuClassName ? delegate.getMenuClassName() : "";
        if (className) {
          container.className += " " + className;
        }
        if (this.options.blockMouse) {
          this.block = container.appendChild($(".context-view-block"));
          this.block.style.position = "fixed";
          this.block.style.cursor = "initial";
          this.block.style.left = "0";
          this.block.style.top = "0";
          this.block.style.width = "100%";
          this.block.style.height = "100%";
          this.block.style.zIndex = "-1";
          domEvent(this.block, EventType.MOUSE_DOWN)((e2) => e2.stopPropagation());
        }
        const menuDisposables = new DisposableStore();
        const actionRunner = delegate.actionRunner || new ActionRunner();
        actionRunner.onDidBeforeRun(this.onActionRun, this, menuDisposables);
        actionRunner.onDidRun(this.onDidActionRun, this, menuDisposables);
        menu = new Menu(container, actions2, {
          actionViewItemProvider: delegate.getActionViewItem,
          context: delegate.getActionsContext ? delegate.getActionsContext() : null,
          actionRunner,
          getKeyBinding: delegate.getKeyBinding ? delegate.getKeyBinding : (action) => this.keybindingService.lookupKeybinding(action.id)
        });
        menuDisposables.add(attachMenuStyler(menu, this.themeService));
        menu.onDidCancel(() => this.contextViewService.hideContextView(true), null, menuDisposables);
        menu.onDidBlur(() => this.contextViewService.hideContextView(true), null, menuDisposables);
        domEvent(window, EventType.BLUR)(() => {
          this.contextViewService.hideContextView(true);
        }, null, menuDisposables);
        domEvent(window, EventType.MOUSE_DOWN)((e2) => {
          if (e2.defaultPrevented) {
            return;
          }
          let event = new StandardMouseEvent(e2);
          let element = event.target;
          if (event.rightButton) {
            return;
          }
          while (element) {
            if (element === container) {
              return;
            }
            element = element.parentElement;
          }
          this.contextViewService.hideContextView(true);
        }, null, menuDisposables);
        return combinedDisposable(menuDisposables, menu);
      },
      focus: () => {
        if (menu) {
          menu.focus(!!delegate.autoSelectFirstItem);
        }
      },
      onHide: (didCancel) => {
        if (delegate.onHide) {
          delegate.onHide(!!didCancel);
        }
        if (this.block) {
          removeNode(this.block);
          this.block = null;
        }
        if (this.focusToReturn) {
          this.focusToReturn.focus();
        }
      }
    }, shadowRootElement, !!shadowRootElement);
  }
  onActionRun(e2) {
    if (this.telemetryService) {
      this.telemetryService.publicLog2("workbenchActionExecuted", {id: e2.action.id, from: "contextMenu"});
    }
    this.contextViewService.hideContextView(false);
    if (this.focusToReturn) {
      this.focusToReturn.focus();
    }
  }
  onDidActionRun(e2) {
    if (e2.error && this.notificationService) {
      this.notificationService.error(e2.error);
    }
  }
};
var __decorate$b = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$a = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var ContextMenuService = class ContextMenuService2 extends Disposable {
  constructor(telemetryService, notificationService, contextViewService, keybindingService, themeService) {
    super();
    this._onDidContextMenu = this._register(new Emitter());
    this.onDidContextMenu = this._onDidContextMenu.event;
    this.contextMenuHandler = new ContextMenuHandler(contextViewService, telemetryService, notificationService, keybindingService, themeService);
  }
  configure(options) {
    this.contextMenuHandler.configure(options);
  }
  showContextMenu(delegate) {
    this.contextMenuHandler.showContextMenu(delegate);
    this._onDidContextMenu.fire();
  }
};
ContextMenuService = __decorate$b([
  __param$a(0, ITelemetryService),
  __param$a(1, INotificationService),
  __param$a(2, IContextViewService),
  __param$a(3, IKeybindingService),
  __param$a(4, IThemeService)
], ContextMenuService);
var ILayoutService = createDecorator("layoutService");
var __decorate$c = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$b = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var ContextViewService = class ContextViewService2 extends Disposable {
  constructor(layoutService) {
    super();
    this.layoutService = layoutService;
    this.currentViewDisposable = Disposable.None;
    this.container = layoutService.container;
    this.contextView = this._register(new ContextView(this.container, 1));
    this.layout();
    this._register(layoutService.onLayout(() => this.layout()));
  }
  setContainer(container, domPosition) {
    this.contextView.setContainer(container, domPosition || 1);
  }
  showContextView(delegate, container, shadowRoot) {
    if (container) {
      if (container !== this.container) {
        this.container = container;
        this.setContainer(container, shadowRoot ? 3 : 2);
      }
    } else {
      if (this.container !== this.layoutService.container) {
        this.container = this.layoutService.container;
        this.setContainer(this.container, 1);
      }
    }
    this.contextView.show(delegate);
    const disposable = toDisposable(() => {
      if (this.currentViewDisposable === disposable) {
        this.hideContextView();
      }
    });
    this.currentViewDisposable = disposable;
    return disposable;
  }
  getContextViewElement() {
    return this.contextView.getViewElement();
  }
  layout() {
    this.contextView.layout();
  }
  hideContextView(data2) {
    this.contextView.hide(data2);
  }
};
ContextViewService = __decorate$c([
  __param$b(0, ILayoutService)
], ContextViewService);
var IDialogService = createDecorator("dialogService");
var Node$2 = class {
  constructor(data2) {
    this.incoming = new Map();
    this.outgoing = new Map();
    this.data = data2;
  }
};
var Graph = class {
  constructor(_hashFn) {
    this._hashFn = _hashFn;
    this._nodes = new Map();
  }
  roots() {
    const ret = [];
    for (let node of this._nodes.values()) {
      if (node.outgoing.size === 0) {
        ret.push(node);
      }
    }
    return ret;
  }
  insertEdge(from, to) {
    const fromNode = this.lookupOrInsertNode(from);
    const toNode = this.lookupOrInsertNode(to);
    fromNode.outgoing.set(this._hashFn(to), toNode);
    toNode.incoming.set(this._hashFn(from), fromNode);
  }
  removeNode(data2) {
    const key = this._hashFn(data2);
    this._nodes.delete(key);
    for (let node of this._nodes.values()) {
      node.outgoing.delete(key);
      node.incoming.delete(key);
    }
  }
  lookupOrInsertNode(data2) {
    const key = this._hashFn(data2);
    let node = this._nodes.get(key);
    if (!node) {
      node = new Node$2(data2);
      this._nodes.set(key, node);
    }
    return node;
  }
  isEmpty() {
    return this._nodes.size === 0;
  }
  toString() {
    let data2 = [];
    for (let [key, value] of this._nodes) {
      data2.push(`${key}, (incoming)[${[...value.incoming.keys()].join(", ")}], (outgoing)[${[...value.outgoing.keys()].join(",")}]`);
    }
    return data2.join("\n");
  }
};
var CyclicDependencyError = class extends Error {
  constructor(graph2) {
    super("cyclic dependency between services");
    this.message = graph2.toString();
  }
};
var InstantiationService = class {
  constructor(services = new ServiceCollection(), strict = false, parent) {
    this._services = services;
    this._strict = strict;
    this._parent = parent;
    this._services.set(IInstantiationService, this);
  }
  createChild(services) {
    return new InstantiationService(services, this._strict, this);
  }
  invokeFunction(fn, ...args) {
    let _trace = Trace.traceInvocation(fn);
    let _done = false;
    try {
      const accessor = {
        get: (id3, isOptional) => {
          if (_done) {
            throw illegalState("service accessor is only valid during the invocation of its target method");
          }
          const result = this._getOrCreateServiceInstance(id3, _trace);
          if (!result && isOptional !== optional) {
            throw new Error(`[invokeFunction] unknown service '${id3}'`);
          }
          return result;
        }
      };
      return fn(accessor, ...args);
    } finally {
      _done = true;
      _trace.stop();
    }
  }
  createInstance(ctorOrDescriptor, ...rest) {
    let _trace;
    let result;
    if (ctorOrDescriptor instanceof SyncDescriptor) {
      _trace = Trace.traceCreation(ctorOrDescriptor.ctor);
      result = this._createInstance(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
    } else {
      _trace = Trace.traceCreation(ctorOrDescriptor);
      result = this._createInstance(ctorOrDescriptor, rest, _trace);
    }
    _trace.stop();
    return result;
  }
  _createInstance(ctor, args = [], _trace) {
    let serviceDependencies = _util.getServiceDependencies(ctor).sort((a2, b2) => a2.index - b2.index);
    let serviceArgs = [];
    for (const dependency of serviceDependencies) {
      let service = this._getOrCreateServiceInstance(dependency.id, _trace);
      if (!service && this._strict && !dependency.optional) {
        throw new Error(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`);
      }
      serviceArgs.push(service);
    }
    let firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
    if (args.length !== firstServiceArgPos) {
      console.warn(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);
      let delta = firstServiceArgPos - args.length;
      if (delta > 0) {
        args = args.concat(new Array(delta));
      } else {
        args = args.slice(0, firstServiceArgPos);
      }
    }
    return new ctor(...[...args, ...serviceArgs]);
  }
  _setServiceInstance(id3, instance2) {
    if (this._services.get(id3) instanceof SyncDescriptor) {
      this._services.set(id3, instance2);
    } else if (this._parent) {
      this._parent._setServiceInstance(id3, instance2);
    } else {
      throw new Error("illegalState - setting UNKNOWN service instance");
    }
  }
  _getServiceInstanceOrDescriptor(id3) {
    let instanceOrDesc = this._services.get(id3);
    if (!instanceOrDesc && this._parent) {
      return this._parent._getServiceInstanceOrDescriptor(id3);
    } else {
      return instanceOrDesc;
    }
  }
  _getOrCreateServiceInstance(id3, _trace) {
    let thing = this._getServiceInstanceOrDescriptor(id3);
    if (thing instanceof SyncDescriptor) {
      return this._createAndCacheServiceInstance(id3, thing, _trace.branch(id3, true));
    } else {
      _trace.branch(id3, false);
      return thing;
    }
  }
  _createAndCacheServiceInstance(id3, desc, _trace) {
    const graph2 = new Graph((data2) => data2.id.toString());
    let cycleCount = 0;
    const stack2 = [{id: id3, desc, _trace}];
    while (stack2.length) {
      const item = stack2.pop();
      graph2.lookupOrInsertNode(item);
      if (cycleCount++ > 1e3) {
        throw new CyclicDependencyError(graph2);
      }
      for (let dependency of _util.getServiceDependencies(item.desc.ctor)) {
        let instanceOrDesc = this._getServiceInstanceOrDescriptor(dependency.id);
        if (!instanceOrDesc && !dependency.optional) {
          console.warn(`[createInstance] ${id3} depends on ${dependency.id} which is NOT registered.`);
        }
        if (instanceOrDesc instanceof SyncDescriptor) {
          const d2 = {id: dependency.id, desc: instanceOrDesc, _trace: item._trace.branch(dependency.id, true)};
          graph2.insertEdge(item, d2);
          stack2.push(d2);
        }
      }
    }
    while (true) {
      const roots = graph2.roots();
      if (roots.length === 0) {
        if (!graph2.isEmpty()) {
          throw new CyclicDependencyError(graph2);
        }
        break;
      }
      for (const {data: data2} of roots) {
        const instance2 = this._createServiceInstanceWithOwner(data2.id, data2.desc.ctor, data2.desc.staticArguments, data2.desc.supportsDelayedInstantiation, data2._trace);
        this._setServiceInstance(data2.id, instance2);
        graph2.removeNode(data2);
      }
    }
    return this._getServiceInstanceOrDescriptor(id3);
  }
  _createServiceInstanceWithOwner(id3, ctor, args = [], supportsDelayedInstantiation, _trace) {
    if (this._services.get(id3) instanceof SyncDescriptor) {
      return this._createServiceInstance(ctor, args, supportsDelayedInstantiation, _trace);
    } else if (this._parent) {
      return this._parent._createServiceInstanceWithOwner(id3, ctor, args, supportsDelayedInstantiation, _trace);
    } else {
      throw new Error(`illegalState - creating UNKNOWN service instance ${ctor.name}`);
    }
  }
  _createServiceInstance(ctor, args = [], _supportsDelayedInstantiation, _trace) {
    if (!_supportsDelayedInstantiation) {
      return this._createInstance(ctor, args, _trace);
    } else {
      const idle = new IdleValue(() => this._createInstance(ctor, args, _trace));
      return new Proxy(Object.create(null), {
        get(target, key) {
          if (key in target) {
            return target[key];
          }
          let obj = idle.value;
          let prop = obj[key];
          if (typeof prop !== "function") {
            return prop;
          }
          prop = prop.bind(obj);
          target[key] = prop;
          return prop;
        },
        set(_target, p2, value) {
          idle.value[p2] = value;
          return true;
        }
      });
    }
  }
};
var Trace = class {
  constructor(type, name) {
    this.type = type;
    this.name = name;
    this._start = Date.now();
    this._dep = [];
  }
  static traceInvocation(ctor) {
    return Trace._None;
  }
  static traceCreation(ctor) {
    return Trace._None;
  }
  branch(id3, first2) {
    let child = new Trace(2, id3.toString());
    this._dep.push([id3, first2, child]);
    return child;
  }
  stop() {
    let dur = Date.now() - this._start;
    Trace._totals += dur;
    let causedCreation = false;
    function printChild(n3, trace) {
      let res = [];
      let prefix2 = new Array(n3 + 1).join("	");
      for (const [id3, first2, child] of trace._dep) {
        if (first2 && child) {
          causedCreation = true;
          res.push(`${prefix2}CREATES -> ${id3}`);
          let nested = printChild(n3 + 1, child);
          if (nested) {
            res.push(nested);
          }
        } else {
          res.push(`${prefix2}uses -> ${id3}`);
        }
      }
      return res.join("\n");
    }
    let lines = [
      `${this.type === 0 ? "CREATE" : "CALL"} ${this.name}`,
      `${printChild(1, this)}`,
      `DONE, took ${dur.toFixed(2)}ms (grand total ${Trace._totals.toFixed(2)}ms)`
    ];
    if (dur > 2 || causedCreation) {
      console.log(lines.join("\n"));
    }
  }
};
Trace._None = new class extends Trace {
  constructor() {
    super(-1, null);
  }
  stop() {
  }
  branch() {
    return this;
  }
}();
Trace._totals = 0;
var ILabelService = createDecorator("labelService");
function __snowpack__injectStyle$t(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$t("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-list {\r\n	position: relative;\r\n	height: 100%;\r\n	width: 100%;\r\n	white-space: nowrap;\r\n}\r\n\r\n.monaco-list.mouse-support {\r\n	user-select: none;\r\n	-webkit-user-select: none;\r\n	-ms-user-select: none;\r\n}\r\n\r\n.monaco-list > .monaco-scrollable-element {\r\n	height: 100%;\r\n}\r\n\r\n.monaco-list-rows {\r\n	position: relative;\r\n	width: 100%;\r\n	height: 100%;\r\n}\r\n\r\n.monaco-list.horizontal-scrolling .monaco-list-rows {\r\n	width: auto;\r\n	min-width: 100%;\r\n}\r\n\r\n.monaco-list-row {\r\n	position: absolute;\r\n	box-sizing:	border-box;\r\n	overflow: hidden;\r\n	width: 100%;\r\n}\r\n\r\n.monaco-list.mouse-support .monaco-list-row {\r\n	cursor: pointer;\r\n	touch-action: none;\r\n}\r\n\r\n/* for OS X ballistic scrolling */\r\n.monaco-list-row.scrolling {\r\n	display: none !important;\r\n}\r\n\r\n/* Focus */\r\n.monaco-list.element-focused, .monaco-list.selection-single, .monaco-list.selection-multiple {\r\n	outline: 0 !important;\r\n}\r\n\r\n.monaco-list:focus .monaco-list-row.selected .codicon {\r\n	color: inherit;\r\n}\r\n\r\n/* Dnd */\r\n.monaco-drag-image {\r\n	display: inline-block;\r\n	padding: 1px 7px;\r\n	border-radius: 10px;\r\n	font-size: 12px;\r\n	position: absolute;\r\n}\r\n\r\n/* Type filter */\r\n\r\n.monaco-list-type-filter {\r\n	display: flex;\r\n	align-items: center;\r\n	position: absolute;\r\n	border-radius: 2px;\r\n	padding: 0px 3px;\r\n	max-width: calc(100% - 10px);\r\n	text-overflow: ellipsis;\r\n	overflow: hidden;\r\n	text-align: right;\r\n	box-sizing: border-box;\r\n	cursor: all-scroll;\r\n	font-size: 13px;\r\n	line-height: 18px;\r\n	height: 20px;\r\n	z-index: 1;\r\n	top: 4px;\r\n}\r\n\r\n.monaco-list-type-filter.dragging {\r\n	transition: top 0.2s, left 0.2s;\r\n}\r\n\r\n.monaco-list-type-filter.ne {\r\n	right: 4px;\r\n}\r\n\r\n.monaco-list-type-filter.nw {\r\n	left: 4px;\r\n}\r\n\r\n.monaco-list-type-filter > .controls {\r\n	display: flex;\r\n	align-items: center;\r\n	box-sizing: border-box;\r\n	transition: width 0.2s;\r\n	width: 0;\r\n}\r\n\r\n.monaco-list-type-filter.dragging > .controls,\r\n.monaco-list-type-filter:hover > .controls {\r\n	width: 36px;\r\n}\r\n\r\n.monaco-list-type-filter > .controls > * {\r\n	border: none;\r\n	box-sizing: border-box;\r\n	-webkit-appearance: none;\r\n	-moz-appearance: none;\r\n	background: none;\r\n	width: 16px;\r\n	height: 16px;\r\n	flex-shrink: 0;\r\n	margin: 0;\r\n	padding: 0;\r\n	display: flex;\r\n	align-items: center;\r\n	justify-content: center;\r\n	cursor: pointer;\r\n}\r\n\r\n.monaco-list-type-filter > .controls > .filter {\r\n	margin-left: 4px;\r\n}\r\n\r\n.monaco-list-type-filter-message {\r\n	position: absolute;\r\n	box-sizing: border-box;\r\n	width: 100%;\r\n	height: 100%;\r\n	top: 0;\r\n	left: 0;\r\n	padding: 40px 1em 1em 1em;\r\n	text-align: center;\r\n	white-space: normal;\r\n	opacity: 0.7;\r\n	pointer-events: none;\r\n}\r\n\r\n.monaco-list-type-filter-message:empty {\r\n	display: none;\r\n}\r\n\r\n/* Electron */\r\n\r\n.monaco-list-type-filter {\r\n	cursor: grab;\r\n}\r\n\r\n.monaco-list-type-filter.dragging {\r\n	cursor: grabbing;\r\n}\r\n");
var ListError = class extends Error {
  constructor(user, message) {
    super(`ListError [${user}] ${message}`);
  }
};
function groupIntersect(range3, groups2) {
  const result = [];
  for (let r3 of groups2) {
    if (range3.start >= r3.range.end) {
      continue;
    }
    if (range3.end < r3.range.start) {
      break;
    }
    const intersection = Range$1.intersect(range3, r3.range);
    if (Range$1.isEmpty(intersection)) {
      continue;
    }
    result.push({
      range: intersection,
      size: r3.size
    });
  }
  return result;
}
function shift({start: start3, end: end2}, much) {
  return {start: start3 + much, end: end2 + much};
}
function consolidate(groups2) {
  const result = [];
  let previousGroup = null;
  for (let group of groups2) {
    const start3 = group.range.start;
    const end2 = group.range.end;
    const size2 = group.size;
    if (previousGroup && size2 === previousGroup.size) {
      previousGroup.range.end = end2;
      continue;
    }
    previousGroup = {range: {start: start3, end: end2}, size: size2};
    result.push(previousGroup);
  }
  return result;
}
function concat(...groups2) {
  return consolidate(groups2.reduce((r3, g2) => r3.concat(g2), []));
}
var RangeMap = class {
  constructor() {
    this.groups = [];
    this._size = 0;
  }
  splice(index3, deleteCount, items = []) {
    const diff = items.length - deleteCount;
    const before = groupIntersect({start: 0, end: index3}, this.groups);
    const after = groupIntersect({start: index3 + deleteCount, end: Number.POSITIVE_INFINITY}, this.groups).map((g2) => ({range: shift(g2.range, diff), size: g2.size}));
    const middle = items.map((item, i3) => ({
      range: {start: index3 + i3, end: index3 + i3 + 1},
      size: item.size
    }));
    this.groups = concat(before, middle, after);
    this._size = this.groups.reduce((t5, g2) => t5 + g2.size * (g2.range.end - g2.range.start), 0);
  }
  get count() {
    const len2 = this.groups.length;
    if (!len2) {
      return 0;
    }
    return this.groups[len2 - 1].range.end;
  }
  get size() {
    return this._size;
  }
  indexAt(position2) {
    if (position2 < 0) {
      return -1;
    }
    let index3 = 0;
    let size2 = 0;
    for (let group of this.groups) {
      const count = group.range.end - group.range.start;
      const newSize2 = size2 + count * group.size;
      if (position2 < newSize2) {
        return index3 + Math.floor((position2 - size2) / group.size);
      }
      index3 += count;
      size2 = newSize2;
    }
    return index3;
  }
  indexAfter(position2) {
    return Math.min(this.indexAt(position2) + 1, this.count);
  }
  positionAt(index3) {
    if (index3 < 0) {
      return -1;
    }
    let position2 = 0;
    let count = 0;
    for (let group of this.groups) {
      const groupCount = group.range.end - group.range.start;
      const newCount = count + groupCount;
      if (index3 < newCount) {
        return position2 + (index3 - count) * group.size;
      }
      position2 += groupCount * group.size;
      count = newCount;
    }
    return -1;
  }
};
function removeFromParent(element) {
  try {
    if (element.parentElement) {
      element.parentElement.removeChild(element);
    }
  } catch (e2) {
  }
}
var RowCache = class {
  constructor(renderers) {
    this.renderers = renderers;
    this.cache = new Map();
  }
  alloc(templateId) {
    let result = this.getTemplateCache(templateId).pop();
    if (!result) {
      const domNode = $(".monaco-list-row");
      const renderer = this.getRenderer(templateId);
      const templateData = renderer.renderTemplate(domNode);
      result = {domNode, templateId, templateData};
    }
    return result;
  }
  release(row) {
    if (!row) {
      return;
    }
    this.releaseRow(row);
  }
  releaseRow(row) {
    const {domNode, templateId} = row;
    if (domNode) {
      removeClass(domNode, "scrolling");
      removeFromParent(domNode);
    }
    const cache3 = this.getTemplateCache(templateId);
    cache3.push(row);
  }
  getTemplateCache(templateId) {
    let result = this.cache.get(templateId);
    if (!result) {
      result = [];
      this.cache.set(templateId, result);
    }
    return result;
  }
  dispose() {
    this.cache.forEach((cachedRows, templateId) => {
      for (const cachedRow of cachedRows) {
        const renderer = this.getRenderer(templateId);
        renderer.disposeTemplate(cachedRow.templateData);
        cachedRow.domNode = null;
        cachedRow.templateData = null;
      }
    });
    this.cache.clear();
  }
  getRenderer(templateId) {
    const renderer = this.renderers.get(templateId);
    if (!renderer) {
      throw new Error(`No renderer found for ${templateId}`);
    }
    return renderer;
  }
};
var __decorate$d = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var DefaultOptions = {
  useShadows: true,
  verticalScrollMode: 1,
  setRowLineHeight: true,
  setRowHeight: true,
  supportDynamicHeights: false,
  dnd: {
    getDragElements(e2) {
      return [e2];
    },
    getDragURI() {
      return null;
    },
    onDragStart() {
    },
    onDragOver() {
      return false;
    },
    drop() {
    }
  },
  horizontalScrolling: false,
  transformOptimization: true
};
var ElementsDragAndDropData = class {
  constructor(elements) {
    this.elements = elements;
  }
  update() {
  }
  getData() {
    return this.elements;
  }
};
var ExternalElementsDragAndDropData = class {
  constructor(elements) {
    this.elements = elements;
  }
  update() {
  }
  getData() {
    return this.elements;
  }
};
var NativeDragAndDropData = class {
  constructor() {
    this.types = [];
    this.files = [];
  }
  update(dataTransfer) {
    if (dataTransfer.types) {
      this.types.splice(0, this.types.length, ...dataTransfer.types);
    }
    if (dataTransfer.files) {
      this.files.splice(0, this.files.length);
      for (let i3 = 0; i3 < dataTransfer.files.length; i3++) {
        const file = dataTransfer.files.item(i3);
        if (file && (file.size || file.type)) {
          this.files.push(file);
        }
      }
    }
  }
  getData() {
    return {
      types: this.types,
      files: this.files
    };
  }
};
function equalsDragFeedback(f1, f2) {
  if (Array.isArray(f1) && Array.isArray(f2)) {
    return equals(f1, f2);
  }
  return f1 === f2;
}
var ListViewAccessibilityProvider = class {
  constructor(accessibilityProvider) {
    if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getSetSize) {
      this.getSetSize = accessibilityProvider.getSetSize.bind(accessibilityProvider);
    } else {
      this.getSetSize = (e2, i3, l2) => l2;
    }
    if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getPosInSet) {
      this.getPosInSet = accessibilityProvider.getPosInSet.bind(accessibilityProvider);
    } else {
      this.getPosInSet = (e2, i3) => i3 + 1;
    }
    if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getRole) {
      this.getRole = accessibilityProvider.getRole.bind(accessibilityProvider);
    } else {
      this.getRole = (_23) => "listitem";
    }
    if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.isChecked) {
      this.isChecked = accessibilityProvider.isChecked.bind(accessibilityProvider);
    } else {
      this.isChecked = (_23) => void 0;
    }
  }
};
var ListView = class {
  constructor(container, virtualDelegate, renderers, options = DefaultOptions) {
    this.virtualDelegate = virtualDelegate;
    this.domId = `list_id_${++ListView.InstanceCount}`;
    this.renderers = new Map();
    this.renderWidth = 0;
    this._scrollHeight = 0;
    this.scrollableElementUpdateDisposable = null;
    this.scrollableElementWidthDelayer = new Delayer(50);
    this.splicing = false;
    this.dragOverAnimationStopDisposable = Disposable.None;
    this.dragOverMouseY = 0;
    this.canDrop = false;
    this.currentDragFeedbackDisposable = Disposable.None;
    this.onDragLeaveTimeout = Disposable.None;
    this.disposables = new DisposableStore();
    this._onDidChangeContentHeight = new Emitter();
    this._horizontalScrolling = false;
    if (options.horizontalScrolling && options.supportDynamicHeights) {
      throw new Error("Horizontal scrolling and dynamic heights not supported simultaneously");
    }
    this.items = [];
    this.itemId = 0;
    this.rangeMap = new RangeMap();
    for (const renderer of renderers) {
      this.renderers.set(renderer.templateId, renderer);
    }
    this.cache = this.disposables.add(new RowCache(this.renderers));
    this.lastRenderTop = 0;
    this.lastRenderHeight = 0;
    this.domNode = document.createElement("div");
    this.domNode.className = "monaco-list";
    addClass(this.domNode, this.domId);
    this.domNode.tabIndex = 0;
    toggleClass(this.domNode, "mouse-support", typeof options.mouseSupport === "boolean" ? options.mouseSupport : true);
    this._horizontalScrolling = getOrDefault(options, (o) => o.horizontalScrolling, DefaultOptions.horizontalScrolling);
    toggleClass(this.domNode, "horizontal-scrolling", this._horizontalScrolling);
    this.additionalScrollHeight = typeof options.additionalScrollHeight === "undefined" ? 0 : options.additionalScrollHeight;
    this.accessibilityProvider = new ListViewAccessibilityProvider(options.accessibilityProvider);
    this.rowsContainer = document.createElement("div");
    this.rowsContainer.className = "monaco-list-rows";
    const transformOptimization = getOrDefault(options, (o) => o.transformOptimization, DefaultOptions.transformOptimization);
    if (transformOptimization) {
      this.rowsContainer.style.transform = "translate3d(0px, 0px, 0px)";
    }
    this.disposables.add(Gesture.addTarget(this.rowsContainer));
    this.scrollable = new Scrollable(getOrDefault(options, (o) => o.smoothScrolling, false) ? 125 : 0, (cb2) => scheduleAtNextAnimationFrame(cb2));
    this.scrollableElement = this.disposables.add(new SmoothScrollableElement(this.rowsContainer, {
      alwaysConsumeMouseWheel: true,
      horizontal: 1,
      vertical: getOrDefault(options, (o) => o.verticalScrollMode, DefaultOptions.verticalScrollMode),
      useShadows: getOrDefault(options, (o) => o.useShadows, DefaultOptions.useShadows)
    }, this.scrollable));
    this.domNode.appendChild(this.scrollableElement.getDomNode());
    container.appendChild(this.domNode);
    this.scrollableElement.onScroll(this.onScroll, this, this.disposables);
    domEvent(this.rowsContainer, EventType$1.Change)(this.onTouchChange, this, this.disposables);
    domEvent(this.scrollableElement.getDomNode(), "scroll")((e2) => e2.target.scrollTop = 0, null, this.disposables);
    Event.map(domEvent(this.domNode, "dragover"), (e2) => this.toDragEvent(e2))(this.onDragOver, this, this.disposables);
    Event.map(domEvent(this.domNode, "drop"), (e2) => this.toDragEvent(e2))(this.onDrop, this, this.disposables);
    domEvent(this.domNode, "dragleave")(this.onDragLeave, this, this.disposables);
    domEvent(window, "dragend")(this.onDragEnd, this, this.disposables);
    this.setRowLineHeight = getOrDefault(options, (o) => o.setRowLineHeight, DefaultOptions.setRowLineHeight);
    this.setRowHeight = getOrDefault(options, (o) => o.setRowHeight, DefaultOptions.setRowHeight);
    this.supportDynamicHeights = getOrDefault(options, (o) => o.supportDynamicHeights, DefaultOptions.supportDynamicHeights);
    this.dnd = getOrDefault(options, (o) => o.dnd, DefaultOptions.dnd);
    this.layout();
  }
  get contentHeight() {
    return this.rangeMap.size;
  }
  get horizontalScrolling() {
    return this._horizontalScrolling;
  }
  set horizontalScrolling(value) {
    if (value === this._horizontalScrolling) {
      return;
    }
    if (value && this.supportDynamicHeights) {
      throw new Error("Horizontal scrolling and dynamic heights not supported simultaneously");
    }
    this._horizontalScrolling = value;
    toggleClass(this.domNode, "horizontal-scrolling", this._horizontalScrolling);
    if (this._horizontalScrolling) {
      for (const item of this.items) {
        this.measureItemWidth(item);
      }
      this.updateScrollWidth();
      this.scrollableElement.setScrollDimensions({width: getContentWidth(this.domNode)});
      this.rowsContainer.style.width = `${Math.max(this.scrollWidth || 0, this.renderWidth)}px`;
    } else {
      this.scrollableElementWidthDelayer.cancel();
      this.scrollableElement.setScrollDimensions({width: this.renderWidth, scrollWidth: this.renderWidth});
      this.rowsContainer.style.width = "";
    }
  }
  updateOptions(options) {
    if (options.additionalScrollHeight !== void 0) {
      this.additionalScrollHeight = options.additionalScrollHeight;
    }
    if (options.smoothScrolling !== void 0) {
      this.scrollable.setSmoothScrollDuration(options.smoothScrolling ? 125 : 0);
    }
    if (options.horizontalScrolling !== void 0) {
      this.horizontalScrolling = options.horizontalScrolling;
    }
  }
  splice(start3, deleteCount, elements = []) {
    if (this.splicing) {
      throw new Error("Can't run recursive splices.");
    }
    this.splicing = true;
    try {
      return this._splice(start3, deleteCount, elements);
    } finally {
      this.splicing = false;
      this._onDidChangeContentHeight.fire(this.contentHeight);
    }
  }
  _splice(start3, deleteCount, elements = []) {
    const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
    const deleteRange = {start: start3, end: start3 + deleteCount};
    const removeRange = Range$1.intersect(previousRenderRange, deleteRange);
    for (let i3 = removeRange.start; i3 < removeRange.end; i3++) {
      this.removeItemFromDOM(i3);
    }
    const previousRestRange = {start: start3 + deleteCount, end: this.items.length};
    const previousRenderedRestRange = Range$1.intersect(previousRestRange, previousRenderRange);
    const previousUnrenderedRestRanges = Range$1.relativeComplement(previousRestRange, previousRenderRange);
    const inserted = elements.map((element) => ({
      id: String(this.itemId++),
      element,
      templateId: this.virtualDelegate.getTemplateId(element),
      size: this.virtualDelegate.getHeight(element),
      width: void 0,
      hasDynamicHeight: !!this.virtualDelegate.hasDynamicHeight && this.virtualDelegate.hasDynamicHeight(element),
      lastDynamicHeightWidth: void 0,
      row: null,
      uri: void 0,
      dropTarget: false,
      dragStartDisposable: Disposable.None
    }));
    let deleted;
    if (start3 === 0 && deleteCount >= this.items.length) {
      this.rangeMap = new RangeMap();
      this.rangeMap.splice(0, 0, inserted);
      this.items = inserted;
      deleted = [];
    } else {
      this.rangeMap.splice(start3, deleteCount, inserted);
      deleted = this.items.splice(start3, deleteCount, ...inserted);
    }
    const delta = elements.length - deleteCount;
    const renderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
    const renderedRestRange = shift(previousRenderedRestRange, delta);
    const updateRange = Range$1.intersect(renderRange, renderedRestRange);
    for (let i3 = updateRange.start; i3 < updateRange.end; i3++) {
      this.updateItemInDOM(this.items[i3], i3);
    }
    const removeRanges = Range$1.relativeComplement(renderedRestRange, renderRange);
    for (const range3 of removeRanges) {
      for (let i3 = range3.start; i3 < range3.end; i3++) {
        this.removeItemFromDOM(i3);
      }
    }
    const unrenderedRestRanges = previousUnrenderedRestRanges.map((r3) => shift(r3, delta));
    const elementsRange = {start: start3, end: start3 + elements.length};
    const insertRanges = [elementsRange, ...unrenderedRestRanges].map((r3) => Range$1.intersect(renderRange, r3));
    const beforeElement = this.getNextToLastElement(insertRanges);
    for (const range3 of insertRanges) {
      for (let i3 = range3.start; i3 < range3.end; i3++) {
        this.insertItemInDOM(i3, beforeElement);
      }
    }
    this.eventuallyUpdateScrollDimensions();
    if (this.supportDynamicHeights) {
      this._rerender(this.scrollTop, this.renderHeight);
    }
    return deleted.map((i3) => i3.element);
  }
  eventuallyUpdateScrollDimensions() {
    this._scrollHeight = this.contentHeight;
    this.rowsContainer.style.height = `${this._scrollHeight}px`;
    if (!this.scrollableElementUpdateDisposable) {
      this.scrollableElementUpdateDisposable = scheduleAtNextAnimationFrame(() => {
        this.scrollableElement.setScrollDimensions({scrollHeight: this.scrollHeight});
        this.updateScrollWidth();
        this.scrollableElementUpdateDisposable = null;
      });
    }
  }
  eventuallyUpdateScrollWidth() {
    if (!this.horizontalScrolling) {
      this.scrollableElementWidthDelayer.cancel();
      return;
    }
    this.scrollableElementWidthDelayer.trigger(() => this.updateScrollWidth());
  }
  updateScrollWidth() {
    if (!this.horizontalScrolling) {
      return;
    }
    let scrollWidth = 0;
    for (const item of this.items) {
      if (typeof item.width !== "undefined") {
        scrollWidth = Math.max(scrollWidth, item.width);
      }
    }
    this.scrollWidth = scrollWidth;
    this.scrollableElement.setScrollDimensions({scrollWidth: scrollWidth === 0 ? 0 : scrollWidth + 10});
  }
  rerender() {
    if (!this.supportDynamicHeights) {
      return;
    }
    for (const item of this.items) {
      item.lastDynamicHeightWidth = void 0;
    }
    this._rerender(this.lastRenderTop, this.lastRenderHeight);
  }
  get length() {
    return this.items.length;
  }
  get renderHeight() {
    const scrollDimensions = this.scrollableElement.getScrollDimensions();
    return scrollDimensions.height;
  }
  element(index3) {
    return this.items[index3].element;
  }
  domElement(index3) {
    const row = this.items[index3].row;
    return row && row.domNode;
  }
  elementHeight(index3) {
    return this.items[index3].size;
  }
  elementTop(index3) {
    return this.rangeMap.positionAt(index3);
  }
  indexAt(position2) {
    return this.rangeMap.indexAt(position2);
  }
  indexAfter(position2) {
    return this.rangeMap.indexAfter(position2);
  }
  layout(height, width2) {
    let scrollDimensions = {
      height: typeof height === "number" ? height : getContentHeight(this.domNode)
    };
    if (this.scrollableElementUpdateDisposable) {
      this.scrollableElementUpdateDisposable.dispose();
      this.scrollableElementUpdateDisposable = null;
      scrollDimensions.scrollHeight = this.scrollHeight;
    }
    this.scrollableElement.setScrollDimensions(scrollDimensions);
    if (typeof width2 !== "undefined") {
      this.renderWidth = width2;
      if (this.supportDynamicHeights) {
        this._rerender(this.scrollTop, this.renderHeight);
      }
      if (this.horizontalScrolling) {
        this.scrollableElement.setScrollDimensions({
          width: typeof width2 === "number" ? width2 : getContentWidth(this.domNode)
        });
      }
    }
  }
  render(previousRenderRange, renderTop, renderHeight, renderLeft, scrollWidth, updateItemsInDOM = false) {
    const renderRange = this.getRenderRange(renderTop, renderHeight);
    const rangesToInsert = Range$1.relativeComplement(renderRange, previousRenderRange);
    const rangesToRemove = Range$1.relativeComplement(previousRenderRange, renderRange);
    const beforeElement = this.getNextToLastElement(rangesToInsert);
    if (updateItemsInDOM) {
      const rangesToUpdate = Range$1.intersect(previousRenderRange, renderRange);
      for (let i3 = rangesToUpdate.start; i3 < rangesToUpdate.end; i3++) {
        this.updateItemInDOM(this.items[i3], i3);
      }
    }
    for (const range3 of rangesToInsert) {
      for (let i3 = range3.start; i3 < range3.end; i3++) {
        this.insertItemInDOM(i3, beforeElement);
      }
    }
    for (const range3 of rangesToRemove) {
      for (let i3 = range3.start; i3 < range3.end; i3++) {
        this.removeItemFromDOM(i3);
      }
    }
    if (renderLeft !== void 0) {
      this.rowsContainer.style.left = `-${renderLeft}px`;
    }
    this.rowsContainer.style.top = `-${renderTop}px`;
    if (this.horizontalScrolling && scrollWidth !== void 0) {
      this.rowsContainer.style.width = `${Math.max(scrollWidth, this.renderWidth)}px`;
    }
    this.lastRenderTop = renderTop;
    this.lastRenderHeight = renderHeight;
  }
  insertItemInDOM(index3, beforeElement) {
    const item = this.items[index3];
    if (!item.row) {
      item.row = this.cache.alloc(item.templateId);
      const role = this.accessibilityProvider.getRole(item.element) || "listitem";
      item.row.domNode.setAttribute("role", role);
      const checked = this.accessibilityProvider.isChecked(item.element);
      if (typeof checked !== "undefined") {
        item.row.domNode.setAttribute("aria-checked", String(!!checked));
      }
    }
    if (!item.row.domNode.parentElement) {
      if (beforeElement) {
        this.rowsContainer.insertBefore(item.row.domNode, beforeElement);
      } else {
        this.rowsContainer.appendChild(item.row.domNode);
      }
    }
    this.updateItemInDOM(item, index3);
    const renderer = this.renderers.get(item.templateId);
    if (!renderer) {
      throw new Error(`No renderer found for template id ${item.templateId}`);
    }
    if (renderer) {
      renderer.renderElement(item.element, index3, item.row.templateData, item.size);
    }
    const uri = this.dnd.getDragURI(item.element);
    item.dragStartDisposable.dispose();
    item.row.domNode.draggable = !!uri;
    if (uri) {
      const onDragStart = domEvent(item.row.domNode, "dragstart");
      item.dragStartDisposable = onDragStart((event) => this.onDragStart(item.element, uri, event));
    }
    if (this.horizontalScrolling) {
      this.measureItemWidth(item);
      this.eventuallyUpdateScrollWidth();
    }
  }
  measureItemWidth(item) {
    if (!item.row || !item.row.domNode) {
      return;
    }
    item.row.domNode.style.width = isFirefox ? "-moz-fit-content" : "fit-content";
    item.width = getContentWidth(item.row.domNode);
    const style = window.getComputedStyle(item.row.domNode);
    if (style.paddingLeft) {
      item.width += parseFloat(style.paddingLeft);
    }
    if (style.paddingRight) {
      item.width += parseFloat(style.paddingRight);
    }
    item.row.domNode.style.width = "";
  }
  updateItemInDOM(item, index3) {
    item.row.domNode.style.top = `${this.elementTop(index3)}px`;
    if (this.setRowHeight) {
      item.row.domNode.style.height = `${item.size}px`;
    }
    if (this.setRowLineHeight) {
      item.row.domNode.style.lineHeight = `${item.size}px`;
    }
    item.row.domNode.setAttribute("data-index", `${index3}`);
    item.row.domNode.setAttribute("data-last-element", index3 === this.length - 1 ? "true" : "false");
    item.row.domNode.setAttribute("aria-setsize", String(this.accessibilityProvider.getSetSize(item.element, index3, this.length)));
    item.row.domNode.setAttribute("aria-posinset", String(this.accessibilityProvider.getPosInSet(item.element, index3)));
    item.row.domNode.setAttribute("id", this.getElementDomId(index3));
    toggleClass(item.row.domNode, "drop-target", item.dropTarget);
  }
  removeItemFromDOM(index3) {
    const item = this.items[index3];
    item.dragStartDisposable.dispose();
    const renderer = this.renderers.get(item.templateId);
    if (item.row && renderer && renderer.disposeElement) {
      renderer.disposeElement(item.element, index3, item.row.templateData, item.size);
    }
    this.cache.release(item.row);
    item.row = null;
    if (this.horizontalScrolling) {
      this.eventuallyUpdateScrollWidth();
    }
  }
  getScrollTop() {
    const scrollPosition = this.scrollableElement.getScrollPosition();
    return scrollPosition.scrollTop;
  }
  setScrollTop(scrollTop) {
    if (this.scrollableElementUpdateDisposable) {
      this.scrollableElementUpdateDisposable.dispose();
      this.scrollableElementUpdateDisposable = null;
      this.scrollableElement.setScrollDimensions({scrollHeight: this.scrollHeight});
    }
    this.scrollableElement.setScrollPosition({scrollTop});
  }
  get scrollTop() {
    return this.getScrollTop();
  }
  set scrollTop(scrollTop) {
    this.setScrollTop(scrollTop);
  }
  get scrollHeight() {
    return this._scrollHeight + (this.horizontalScrolling ? 10 : 0) + this.additionalScrollHeight;
  }
  get onMouseClick() {
    return Event.map(domEvent(this.domNode, "click"), (e2) => this.toMouseEvent(e2));
  }
  get onMouseDblClick() {
    return Event.map(domEvent(this.domNode, "dblclick"), (e2) => this.toMouseEvent(e2));
  }
  get onMouseMiddleClick() {
    return Event.filter(Event.map(domEvent(this.domNode, "auxclick"), (e2) => this.toMouseEvent(e2)), (e2) => e2.browserEvent.button === 1);
  }
  get onMouseDown() {
    return Event.map(domEvent(this.domNode, "mousedown"), (e2) => this.toMouseEvent(e2));
  }
  get onContextMenu() {
    return Event.map(domEvent(this.domNode, "contextmenu"), (e2) => this.toMouseEvent(e2));
  }
  get onTouchStart() {
    return Event.map(domEvent(this.domNode, "touchstart"), (e2) => this.toTouchEvent(e2));
  }
  get onTap() {
    return Event.map(domEvent(this.rowsContainer, EventType$1.Tap), (e2) => this.toGestureEvent(e2));
  }
  toMouseEvent(browserEvent) {
    const index3 = this.getItemIndexFromEventTarget(browserEvent.target || null);
    const item = typeof index3 === "undefined" ? void 0 : this.items[index3];
    const element = item && item.element;
    return {browserEvent, index: index3, element};
  }
  toTouchEvent(browserEvent) {
    const index3 = this.getItemIndexFromEventTarget(browserEvent.target || null);
    const item = typeof index3 === "undefined" ? void 0 : this.items[index3];
    const element = item && item.element;
    return {browserEvent, index: index3, element};
  }
  toGestureEvent(browserEvent) {
    const index3 = this.getItemIndexFromEventTarget(browserEvent.initialTarget || null);
    const item = typeof index3 === "undefined" ? void 0 : this.items[index3];
    const element = item && item.element;
    return {browserEvent, index: index3, element};
  }
  toDragEvent(browserEvent) {
    const index3 = this.getItemIndexFromEventTarget(browserEvent.target || null);
    const item = typeof index3 === "undefined" ? void 0 : this.items[index3];
    const element = item && item.element;
    return {browserEvent, index: index3, element};
  }
  onScroll(e2) {
    try {
      const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
      this.render(previousRenderRange, e2.scrollTop, e2.height, e2.scrollLeft, e2.scrollWidth);
      if (this.supportDynamicHeights) {
        this._rerender(e2.scrollTop, e2.height);
      }
    } catch (err) {
      console.error("Got bad scroll event:", e2);
      throw err;
    }
  }
  onTouchChange(event) {
    event.preventDefault();
    event.stopPropagation();
    this.scrollTop -= event.translationY;
  }
  onDragStart(element, uri, event) {
    if (!event.dataTransfer) {
      return;
    }
    const elements = this.dnd.getDragElements(element);
    event.dataTransfer.effectAllowed = "copyMove";
    event.dataTransfer.setData(DataTransfers.RESOURCES, JSON.stringify([uri]));
    if (event.dataTransfer.setDragImage) {
      let label2;
      if (this.dnd.getDragLabel) {
        label2 = this.dnd.getDragLabel(elements, event);
      }
      if (typeof label2 === "undefined") {
        label2 = String(elements.length);
      }
      const dragImage = $(".monaco-drag-image");
      dragImage.textContent = label2;
      document.body.appendChild(dragImage);
      event.dataTransfer.setDragImage(dragImage, -10, -10);
      setTimeout(() => document.body.removeChild(dragImage), 0);
    }
    this.currentDragData = new ElementsDragAndDropData(elements);
    StaticDND.CurrentDragAndDropData = new ExternalElementsDragAndDropData(elements);
    if (this.dnd.onDragStart) {
      this.dnd.onDragStart(this.currentDragData, event);
    }
  }
  onDragOver(event) {
    event.browserEvent.preventDefault();
    this.onDragLeaveTimeout.dispose();
    if (StaticDND.CurrentDragAndDropData && StaticDND.CurrentDragAndDropData.getData() === "vscode-ui") {
      return false;
    }
    this.setupDragAndDropScrollTopAnimation(event.browserEvent);
    if (!event.browserEvent.dataTransfer) {
      return false;
    }
    if (!this.currentDragData) {
      if (StaticDND.CurrentDragAndDropData) {
        this.currentDragData = StaticDND.CurrentDragAndDropData;
      } else {
        if (!event.browserEvent.dataTransfer.types) {
          return false;
        }
        this.currentDragData = new NativeDragAndDropData();
      }
    }
    const result = this.dnd.onDragOver(this.currentDragData, event.element, event.index, event.browserEvent);
    this.canDrop = typeof result === "boolean" ? result : result.accept;
    if (!this.canDrop) {
      this.currentDragFeedback = void 0;
      this.currentDragFeedbackDisposable.dispose();
      return false;
    }
    event.browserEvent.dataTransfer.dropEffect = typeof result !== "boolean" && result.effect === 0 ? "copy" : "move";
    let feedback;
    if (typeof result !== "boolean" && result.feedback) {
      feedback = result.feedback;
    } else {
      if (typeof event.index === "undefined") {
        feedback = [-1];
      } else {
        feedback = [event.index];
      }
    }
    feedback = distinct(feedback).filter((i3) => i3 >= -1 && i3 < this.length).sort((a2, b2) => a2 - b2);
    feedback = feedback[0] === -1 ? [-1] : feedback;
    if (equalsDragFeedback(this.currentDragFeedback, feedback)) {
      return true;
    }
    this.currentDragFeedback = feedback;
    this.currentDragFeedbackDisposable.dispose();
    if (feedback[0] === -1) {
      addClass(this.domNode, "drop-target");
      addClass(this.rowsContainer, "drop-target");
      this.currentDragFeedbackDisposable = toDisposable(() => {
        removeClass(this.domNode, "drop-target");
        removeClass(this.rowsContainer, "drop-target");
      });
    } else {
      for (const index3 of feedback) {
        const item = this.items[index3];
        item.dropTarget = true;
        if (item.row && item.row.domNode) {
          addClass(item.row.domNode, "drop-target");
        }
      }
      this.currentDragFeedbackDisposable = toDisposable(() => {
        for (const index3 of feedback) {
          const item = this.items[index3];
          item.dropTarget = false;
          if (item.row && item.row.domNode) {
            removeClass(item.row.domNode, "drop-target");
          }
        }
      });
    }
    return true;
  }
  onDragLeave() {
    this.onDragLeaveTimeout.dispose();
    this.onDragLeaveTimeout = disposableTimeout(() => this.clearDragOverFeedback(), 100);
  }
  onDrop(event) {
    if (!this.canDrop) {
      return;
    }
    const dragData = this.currentDragData;
    this.teardownDragAndDropScrollTopAnimation();
    this.clearDragOverFeedback();
    this.currentDragData = void 0;
    StaticDND.CurrentDragAndDropData = void 0;
    if (!dragData || !event.browserEvent.dataTransfer) {
      return;
    }
    event.browserEvent.preventDefault();
    dragData.update(event.browserEvent.dataTransfer);
    this.dnd.drop(dragData, event.element, event.index, event.browserEvent);
  }
  onDragEnd(event) {
    this.canDrop = false;
    this.teardownDragAndDropScrollTopAnimation();
    this.clearDragOverFeedback();
    this.currentDragData = void 0;
    StaticDND.CurrentDragAndDropData = void 0;
    if (this.dnd.onDragEnd) {
      this.dnd.onDragEnd(event);
    }
  }
  clearDragOverFeedback() {
    this.currentDragFeedback = void 0;
    this.currentDragFeedbackDisposable.dispose();
    this.currentDragFeedbackDisposable = Disposable.None;
  }
  setupDragAndDropScrollTopAnimation(event) {
    if (!this.dragOverAnimationDisposable) {
      const viewTop = getTopLeftOffset(this.domNode).top;
      this.dragOverAnimationDisposable = animate(this.animateDragAndDropScrollTop.bind(this, viewTop));
    }
    this.dragOverAnimationStopDisposable.dispose();
    this.dragOverAnimationStopDisposable = disposableTimeout(() => {
      if (this.dragOverAnimationDisposable) {
        this.dragOverAnimationDisposable.dispose();
        this.dragOverAnimationDisposable = void 0;
      }
    }, 1e3);
    this.dragOverMouseY = event.pageY;
  }
  animateDragAndDropScrollTop(viewTop) {
    if (this.dragOverMouseY === void 0) {
      return;
    }
    const diff = this.dragOverMouseY - viewTop;
    const upperLimit = this.renderHeight - 35;
    if (diff < 35) {
      this.scrollTop += Math.max(-14, Math.floor(0.3 * (diff - 35)));
    } else if (diff > upperLimit) {
      this.scrollTop += Math.min(14, Math.floor(0.3 * (diff - upperLimit)));
    }
  }
  teardownDragAndDropScrollTopAnimation() {
    this.dragOverAnimationStopDisposable.dispose();
    if (this.dragOverAnimationDisposable) {
      this.dragOverAnimationDisposable.dispose();
      this.dragOverAnimationDisposable = void 0;
    }
  }
  getItemIndexFromEventTarget(target) {
    const scrollableElement = this.scrollableElement.getDomNode();
    let element = target;
    while (element instanceof HTMLElement && element !== this.rowsContainer && scrollableElement.contains(element)) {
      const rawIndex = element.getAttribute("data-index");
      if (rawIndex) {
        const index3 = Number(rawIndex);
        if (!isNaN(index3)) {
          return index3;
        }
      }
      element = element.parentElement;
    }
    return void 0;
  }
  getRenderRange(renderTop, renderHeight) {
    return {
      start: this.rangeMap.indexAt(renderTop),
      end: this.rangeMap.indexAfter(renderTop + renderHeight - 1)
    };
  }
  _rerender(renderTop, renderHeight) {
    const previousRenderRange = this.getRenderRange(renderTop, renderHeight);
    let anchorElementIndex;
    let anchorElementTopDelta;
    if (renderTop === this.elementTop(previousRenderRange.start)) {
      anchorElementIndex = previousRenderRange.start;
      anchorElementTopDelta = 0;
    } else if (previousRenderRange.end - previousRenderRange.start > 1) {
      anchorElementIndex = previousRenderRange.start + 1;
      anchorElementTopDelta = this.elementTop(anchorElementIndex) - renderTop;
    }
    let heightDiff = 0;
    while (true) {
      const renderRange = this.getRenderRange(renderTop, renderHeight);
      let didChange = false;
      for (let i3 = renderRange.start; i3 < renderRange.end; i3++) {
        const diff = this.probeDynamicHeight(i3);
        if (diff !== 0) {
          this.rangeMap.splice(i3, 1, [this.items[i3]]);
        }
        heightDiff += diff;
        didChange = didChange || diff !== 0;
      }
      if (!didChange) {
        if (heightDiff !== 0) {
          this.eventuallyUpdateScrollDimensions();
        }
        const unrenderRanges = Range$1.relativeComplement(previousRenderRange, renderRange);
        for (const range3 of unrenderRanges) {
          for (let i3 = range3.start; i3 < range3.end; i3++) {
            if (this.items[i3].row) {
              this.removeItemFromDOM(i3);
            }
          }
        }
        const renderRanges = Range$1.relativeComplement(renderRange, previousRenderRange);
        for (const range3 of renderRanges) {
          for (let i3 = range3.start; i3 < range3.end; i3++) {
            const afterIndex = i3 + 1;
            const beforeRow = afterIndex < this.items.length ? this.items[afterIndex].row : null;
            const beforeElement = beforeRow ? beforeRow.domNode : null;
            this.insertItemInDOM(i3, beforeElement);
          }
        }
        for (let i3 = renderRange.start; i3 < renderRange.end; i3++) {
          if (this.items[i3].row) {
            this.updateItemInDOM(this.items[i3], i3);
          }
        }
        if (typeof anchorElementIndex === "number") {
          this.scrollTop = this.elementTop(anchorElementIndex) - anchorElementTopDelta;
        }
        this._onDidChangeContentHeight.fire(this.contentHeight);
        return;
      }
    }
  }
  probeDynamicHeight(index3) {
    const item = this.items[index3];
    if (!item.hasDynamicHeight || item.lastDynamicHeightWidth === this.renderWidth) {
      return 0;
    }
    if (!!this.virtualDelegate.hasDynamicHeight && !this.virtualDelegate.hasDynamicHeight(item.element)) {
      return 0;
    }
    const size2 = item.size;
    if (!this.setRowHeight && item.row && item.row.domNode) {
      let newSize2 = item.row.domNode.offsetHeight;
      item.size = newSize2;
      item.lastDynamicHeightWidth = this.renderWidth;
      return newSize2 - size2;
    }
    const row = this.cache.alloc(item.templateId);
    row.domNode.style.height = "";
    this.rowsContainer.appendChild(row.domNode);
    const renderer = this.renderers.get(item.templateId);
    if (renderer) {
      renderer.renderElement(item.element, index3, row.templateData, void 0);
      if (renderer.disposeElement) {
        renderer.disposeElement(item.element, index3, row.templateData, void 0);
      }
    }
    item.size = row.domNode.offsetHeight;
    if (this.virtualDelegate.setDynamicHeight) {
      this.virtualDelegate.setDynamicHeight(item.element, item.size);
    }
    item.lastDynamicHeightWidth = this.renderWidth;
    this.rowsContainer.removeChild(row.domNode);
    this.cache.release(row);
    return item.size - size2;
  }
  getNextToLastElement(ranges) {
    const lastRange = ranges[ranges.length - 1];
    if (!lastRange) {
      return null;
    }
    const nextToLastItem = this.items[lastRange.end];
    if (!nextToLastItem) {
      return null;
    }
    if (!nextToLastItem.row) {
      return null;
    }
    return nextToLastItem.row.domNode;
  }
  getElementDomId(index3) {
    return `${this.domId}_${index3}`;
  }
  dispose() {
    if (this.items) {
      for (const item of this.items) {
        if (item.row) {
          const renderer = this.renderers.get(item.row.templateId);
          if (renderer) {
            renderer.disposeTemplate(item.row.templateData);
          }
        }
      }
      this.items = [];
    }
    if (this.domNode && this.domNode.parentNode) {
      this.domNode.parentNode.removeChild(this.domNode);
    }
    dispose(this.disposables);
  }
};
ListView.InstanceCount = 0;
__decorate$d([
  memoize
], ListView.prototype, "onMouseClick", null);
__decorate$d([
  memoize
], ListView.prototype, "onMouseDblClick", null);
__decorate$d([
  memoize
], ListView.prototype, "onMouseMiddleClick", null);
__decorate$d([
  memoize
], ListView.prototype, "onMouseDown", null);
__decorate$d([
  memoize
], ListView.prototype, "onContextMenu", null);
__decorate$d([
  memoize
], ListView.prototype, "onTouchStart", null);
__decorate$d([
  memoize
], ListView.prototype, "onTap", null);
var CombinedSpliceable = class {
  constructor(spliceables) {
    this.spliceables = spliceables;
  }
  splice(start3, deleteCount, elements) {
    this.spliceables.forEach((s2) => s2.splice(start3, deleteCount, elements));
  }
};
function clamp2(value, min2, max2) {
  return Math.min(Math.max(value, min2), max2);
}
var __decorate$e = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var TraitRenderer = class {
  constructor(trait) {
    this.trait = trait;
    this.renderedElements = [];
  }
  get templateId() {
    return `template:${this.trait.trait}`;
  }
  renderTemplate(container) {
    return container;
  }
  renderElement(element, index3, templateData) {
    const renderedElementIndex = firstIndex(this.renderedElements, (el) => el.templateData === templateData);
    if (renderedElementIndex >= 0) {
      const rendered = this.renderedElements[renderedElementIndex];
      this.trait.unrender(templateData);
      rendered.index = index3;
    } else {
      const rendered = {index: index3, templateData};
      this.renderedElements.push(rendered);
    }
    this.trait.renderIndex(index3, templateData);
  }
  splice(start3, deleteCount, insertCount) {
    const rendered = [];
    for (const renderedElement of this.renderedElements) {
      if (renderedElement.index < start3) {
        rendered.push(renderedElement);
      } else if (renderedElement.index >= start3 + deleteCount) {
        rendered.push({
          index: renderedElement.index + insertCount - deleteCount,
          templateData: renderedElement.templateData
        });
      }
    }
    this.renderedElements = rendered;
  }
  renderIndexes(indexes) {
    for (const {index: index3, templateData} of this.renderedElements) {
      if (indexes.indexOf(index3) > -1) {
        this.trait.renderIndex(index3, templateData);
      }
    }
  }
  disposeTemplate(templateData) {
    const index3 = firstIndex(this.renderedElements, (el) => el.templateData === templateData);
    if (index3 < 0) {
      return;
    }
    this.renderedElements.splice(index3, 1);
  }
};
var Trait = class {
  constructor(_trait) {
    this._trait = _trait;
    this.indexes = [];
    this.sortedIndexes = [];
    this._onChange = new Emitter();
    this.onChange = this._onChange.event;
  }
  get trait() {
    return this._trait;
  }
  get renderer() {
    return new TraitRenderer(this);
  }
  splice(start3, deleteCount, elements) {
    const diff = elements.length - deleteCount;
    const end2 = start3 + deleteCount;
    const indexes = [
      ...this.sortedIndexes.filter((i3) => i3 < start3),
      ...elements.map((hasTrait, i3) => hasTrait ? i3 + start3 : -1).filter((i3) => i3 !== -1),
      ...this.sortedIndexes.filter((i3) => i3 >= end2).map((i3) => i3 + diff)
    ];
    this.renderer.splice(start3, deleteCount, elements.length);
    this._set(indexes, indexes);
  }
  renderIndex(index3, container) {
    toggleClass(container, this._trait, this.contains(index3));
  }
  unrender(container) {
    removeClass(container, this._trait);
  }
  set(indexes, browserEvent) {
    return this._set(indexes, [...indexes].sort(numericSort), browserEvent);
  }
  _set(indexes, sortedIndexes, browserEvent) {
    const result = this.indexes;
    const sortedResult = this.sortedIndexes;
    this.indexes = indexes;
    this.sortedIndexes = sortedIndexes;
    const toRender = disjunction(sortedResult, indexes);
    this.renderer.renderIndexes(toRender);
    this._onChange.fire({indexes, browserEvent});
    return result;
  }
  get() {
    return this.indexes;
  }
  contains(index3) {
    return binarySearch(this.sortedIndexes, index3, numericSort) >= 0;
  }
  dispose() {
    dispose(this._onChange);
  }
};
__decorate$e([
  memoize
], Trait.prototype, "renderer", null);
var SelectionTrait = class extends Trait {
  constructor(setAriaSelected) {
    super("selected");
    this.setAriaSelected = setAriaSelected;
  }
  renderIndex(index3, container) {
    super.renderIndex(index3, container);
    if (this.setAriaSelected) {
      if (this.contains(index3)) {
        container.setAttribute("aria-selected", "true");
      } else {
        container.setAttribute("aria-selected", "false");
      }
    }
  }
};
var TraitSpliceable = class {
  constructor(trait, view, identityProvider) {
    this.trait = trait;
    this.view = view;
    this.identityProvider = identityProvider;
  }
  splice(start3, deleteCount, elements) {
    if (!this.identityProvider) {
      return this.trait.splice(start3, deleteCount, elements.map(() => false));
    }
    const pastElementsWithTrait = this.trait.get().map((i3) => this.identityProvider.getId(this.view.element(i3)).toString());
    const elementsWithTrait = elements.map((e2) => pastElementsWithTrait.indexOf(this.identityProvider.getId(e2).toString()) > -1);
    this.trait.splice(start3, deleteCount, elementsWithTrait);
  }
};
function isInputElement(e2) {
  return e2.tagName === "INPUT" || e2.tagName === "TEXTAREA";
}
function isMonacoEditor(e2) {
  if (hasClass(e2, "monaco-editor")) {
    return true;
  }
  if (hasClass(e2, "monaco-list")) {
    return false;
  }
  if (!e2.parentElement) {
    return false;
  }
  return isMonacoEditor(e2.parentElement);
}
var KeyboardController = class {
  constructor(list3, view, options) {
    this.list = list3;
    this.view = view;
    this.disposables = new DisposableStore();
    const multipleSelectionSupport = options.multipleSelectionSupport !== false;
    const onKeyDown = Event.chain(domEvent(view.domNode, "keydown")).filter((e2) => !isInputElement(e2.target)).map((e2) => new StandardKeyboardEvent(e2));
    onKeyDown.filter((e2) => e2.keyCode === 3).on(this.onEnter, this, this.disposables);
    onKeyDown.filter((e2) => e2.keyCode === 16).on(this.onUpArrow, this, this.disposables);
    onKeyDown.filter((e2) => e2.keyCode === 18).on(this.onDownArrow, this, this.disposables);
    onKeyDown.filter((e2) => e2.keyCode === 11).on(this.onPageUpArrow, this, this.disposables);
    onKeyDown.filter((e2) => e2.keyCode === 12).on(this.onPageDownArrow, this, this.disposables);
    onKeyDown.filter((e2) => e2.keyCode === 9).on(this.onEscape, this, this.disposables);
    if (multipleSelectionSupport) {
      onKeyDown.filter((e2) => (isMacintosh ? e2.metaKey : e2.ctrlKey) && e2.keyCode === 31).on(this.onCtrlA, this, this.disposables);
    }
  }
  onEnter(e2) {
    e2.preventDefault();
    e2.stopPropagation();
    this.list.setSelection(this.list.getFocus(), e2.browserEvent);
  }
  onUpArrow(e2) {
    e2.preventDefault();
    e2.stopPropagation();
    this.list.focusPrevious(1, false, e2.browserEvent);
    this.list.reveal(this.list.getFocus()[0]);
    this.view.domNode.focus();
  }
  onDownArrow(e2) {
    e2.preventDefault();
    e2.stopPropagation();
    this.list.focusNext(1, false, e2.browserEvent);
    this.list.reveal(this.list.getFocus()[0]);
    this.view.domNode.focus();
  }
  onPageUpArrow(e2) {
    e2.preventDefault();
    e2.stopPropagation();
    this.list.focusPreviousPage(e2.browserEvent);
    this.list.reveal(this.list.getFocus()[0]);
    this.view.domNode.focus();
  }
  onPageDownArrow(e2) {
    e2.preventDefault();
    e2.stopPropagation();
    this.list.focusNextPage(e2.browserEvent);
    this.list.reveal(this.list.getFocus()[0]);
    this.view.domNode.focus();
  }
  onCtrlA(e2) {
    e2.preventDefault();
    e2.stopPropagation();
    this.list.setSelection(range(this.list.length), e2.browserEvent);
    this.view.domNode.focus();
  }
  onEscape(e2) {
    e2.preventDefault();
    e2.stopPropagation();
    this.list.setSelection([], e2.browserEvent);
    this.view.domNode.focus();
  }
  dispose() {
    this.disposables.dispose();
  }
};
var TypeLabelControllerState;
(function(TypeLabelControllerState2) {
  TypeLabelControllerState2[TypeLabelControllerState2["Idle"] = 0] = "Idle";
  TypeLabelControllerState2[TypeLabelControllerState2["Typing"] = 1] = "Typing";
})(TypeLabelControllerState || (TypeLabelControllerState = {}));
var DefaultKeyboardNavigationDelegate = new class {
  mightProducePrintableCharacter(event) {
    if (event.ctrlKey || event.metaKey || event.altKey) {
      return false;
    }
    return event.keyCode >= 31 && event.keyCode <= 56 || event.keyCode >= 21 && event.keyCode <= 30 || event.keyCode >= 93 && event.keyCode <= 102 || event.keyCode >= 80 && event.keyCode <= 90;
  }
}();
var TypeLabelController = class {
  constructor(list3, view, keyboardNavigationLabelProvider, delegate) {
    this.list = list3;
    this.view = view;
    this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
    this.delegate = delegate;
    this.enabled = false;
    this.state = TypeLabelControllerState.Idle;
    this.automaticKeyboardNavigation = true;
    this.triggered = false;
    this.previouslyFocused = -1;
    this.enabledDisposables = new DisposableStore();
    this.disposables = new DisposableStore();
    this.updateOptions(list3.options);
  }
  updateOptions(options) {
    const enableKeyboardNavigation = typeof options.enableKeyboardNavigation === "undefined" ? true : !!options.enableKeyboardNavigation;
    if (enableKeyboardNavigation) {
      this.enable();
    } else {
      this.disable();
    }
    if (typeof options.automaticKeyboardNavigation !== "undefined") {
      this.automaticKeyboardNavigation = options.automaticKeyboardNavigation;
    }
  }
  enable() {
    if (this.enabled) {
      return;
    }
    const onChar = Event.chain(domEvent(this.view.domNode, "keydown")).filter((e2) => !isInputElement(e2.target)).filter(() => this.automaticKeyboardNavigation || this.triggered).map((event) => new StandardKeyboardEvent(event)).filter((e2) => this.delegate.mightProducePrintableCharacter(e2)).forEach((e2) => {
      e2.stopPropagation();
      e2.preventDefault();
    }).map((event) => event.browserEvent.key).event;
    const onClear = Event.debounce(onChar, () => null, 800);
    const onInput = Event.reduce(Event.any(onChar, onClear), (r3, i3) => i3 === null ? null : (r3 || "") + i3);
    onInput(this.onInput, this, this.enabledDisposables);
    onClear(this.onClear, this, this.enabledDisposables);
    this.enabled = true;
    this.triggered = false;
  }
  disable() {
    if (!this.enabled) {
      return;
    }
    this.enabledDisposables.clear();
    this.enabled = false;
    this.triggered = false;
  }
  onClear() {
    var _a;
    const focus = this.list.getFocus();
    if (focus.length > 0 && focus[0] === this.previouslyFocused) {
      const ariaLabel = (_a = this.list.options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.getAriaLabel(this.list.element(focus[0]));
      if (ariaLabel) {
        alert3(ariaLabel);
      }
    }
    this.previouslyFocused = -1;
  }
  onInput(word) {
    if (!word) {
      this.state = TypeLabelControllerState.Idle;
      this.triggered = false;
      return;
    }
    const focus = this.list.getFocus();
    const start3 = focus.length > 0 ? focus[0] : 0;
    const delta = this.state === TypeLabelControllerState.Idle ? 1 : 0;
    this.state = TypeLabelControllerState.Typing;
    for (let i3 = 0; i3 < this.list.length; i3++) {
      const index3 = (start3 + i3 + delta) % this.list.length;
      const label2 = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index3));
      const labelStr = label2 && label2.toString();
      if (typeof labelStr === "undefined" || matchesPrefix(word, labelStr)) {
        this.previouslyFocused = start3;
        this.list.setFocus([index3]);
        this.list.reveal(index3);
        return;
      }
    }
  }
  dispose() {
    this.disable();
    this.enabledDisposables.dispose();
    this.disposables.dispose();
  }
};
var DOMFocusController = class {
  constructor(list3, view) {
    this.list = list3;
    this.view = view;
    this.disposables = new DisposableStore();
    const onKeyDown = Event.chain(domEvent(view.domNode, "keydown")).filter((e2) => !isInputElement(e2.target)).map((e2) => new StandardKeyboardEvent(e2));
    onKeyDown.filter((e2) => e2.keyCode === 2 && !e2.ctrlKey && !e2.metaKey && !e2.shiftKey && !e2.altKey).on(this.onTab, this, this.disposables);
  }
  onTab(e2) {
    if (e2.target !== this.view.domNode) {
      return;
    }
    const focus = this.list.getFocus();
    if (focus.length === 0) {
      return;
    }
    const focusedDomElement = this.view.domElement(focus[0]);
    if (!focusedDomElement) {
      return;
    }
    const tabIndexElement = focusedDomElement.querySelector("[tabIndex]");
    if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) {
      return;
    }
    const style = window.getComputedStyle(tabIndexElement);
    if (style.visibility === "hidden" || style.display === "none") {
      return;
    }
    e2.preventDefault();
    e2.stopPropagation();
    tabIndexElement.focus();
  }
  dispose() {
    this.disposables.dispose();
  }
};
function isSelectionSingleChangeEvent(event) {
  return isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey;
}
function isSelectionRangeChangeEvent(event) {
  return event.browserEvent.shiftKey;
}
function isMouseRightClick(event) {
  return event instanceof MouseEvent && event.button === 2;
}
var DefaultMultipleSelectionController = {
  isSelectionSingleChangeEvent,
  isSelectionRangeChangeEvent
};
var MouseController = class {
  constructor(list3) {
    this.list = list3;
    this.disposables = new DisposableStore();
    this._onPointer = new Emitter();
    this.onPointer = this._onPointer.event;
    this.multipleSelectionSupport = !(list3.options.multipleSelectionSupport === false);
    if (this.multipleSelectionSupport) {
      this.multipleSelectionController = list3.options.multipleSelectionController || DefaultMultipleSelectionController;
    }
    this.mouseSupport = typeof list3.options.mouseSupport === "undefined" || !!list3.options.mouseSupport;
    if (this.mouseSupport) {
      list3.onMouseDown(this.onMouseDown, this, this.disposables);
      list3.onContextMenu(this.onContextMenu, this, this.disposables);
      list3.onMouseDblClick(this.onDoubleClick, this, this.disposables);
      list3.onTouchStart(this.onMouseDown, this, this.disposables);
      this.disposables.add(Gesture.addTarget(list3.getHTMLElement()));
    }
    Event.any(list3.onMouseClick, list3.onMouseMiddleClick, list3.onTap)(this.onViewPointer, this, this.disposables);
  }
  isSelectionSingleChangeEvent(event) {
    if (this.multipleSelectionController) {
      return this.multipleSelectionController.isSelectionSingleChangeEvent(event);
    }
    return isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey;
  }
  isSelectionRangeChangeEvent(event) {
    if (this.multipleSelectionController) {
      return this.multipleSelectionController.isSelectionRangeChangeEvent(event);
    }
    return event.browserEvent.shiftKey;
  }
  isSelectionChangeEvent(event) {
    return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event);
  }
  onMouseDown(e2) {
    if (isMonacoEditor(e2.browserEvent.target)) {
      return;
    }
    if (document.activeElement !== e2.browserEvent.target) {
      this.list.domFocus();
    }
  }
  onContextMenu(e2) {
    if (isMonacoEditor(e2.browserEvent.target)) {
      return;
    }
    const focus = typeof e2.index === "undefined" ? [] : [e2.index];
    this.list.setFocus(focus, e2.browserEvent);
  }
  onViewPointer(e2) {
    if (!this.mouseSupport) {
      return;
    }
    if (isInputElement(e2.browserEvent.target) || isMonacoEditor(e2.browserEvent.target)) {
      return;
    }
    let reference2 = this.list.getFocus()[0];
    const selection2 = this.list.getSelection();
    reference2 = reference2 === void 0 ? selection2[0] : reference2;
    const focus = e2.index;
    if (typeof focus === "undefined") {
      this.list.setFocus([], e2.browserEvent);
      this.list.setSelection([], e2.browserEvent);
      return;
    }
    if (this.multipleSelectionSupport && this.isSelectionRangeChangeEvent(e2)) {
      return this.changeSelection(e2, reference2);
    }
    if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e2)) {
      return this.changeSelection(e2, reference2);
    }
    this.list.setFocus([focus], e2.browserEvent);
    if (!isMouseRightClick(e2.browserEvent)) {
      this.list.setSelection([focus], e2.browserEvent);
    }
    this._onPointer.fire(e2);
  }
  onDoubleClick(e2) {
    if (isInputElement(e2.browserEvent.target) || isMonacoEditor(e2.browserEvent.target)) {
      return;
    }
    if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e2)) {
      return;
    }
    const focus = this.list.getFocus();
    this.list.setSelection(focus, e2.browserEvent);
  }
  changeSelection(e2, reference2) {
    const focus = e2.index;
    if (this.isSelectionRangeChangeEvent(e2) && reference2 !== void 0) {
      const min2 = Math.min(reference2, focus);
      const max2 = Math.max(reference2, focus);
      const rangeSelection = range(min2, max2 + 1);
      const selection2 = this.list.getSelection();
      const contiguousRange = getContiguousRangeContaining(disjunction(selection2, [reference2]), reference2);
      if (contiguousRange.length === 0) {
        return;
      }
      const newSelection = disjunction(rangeSelection, relativeComplement(selection2, contiguousRange));
      this.list.setSelection(newSelection, e2.browserEvent);
    } else if (this.isSelectionSingleChangeEvent(e2)) {
      const selection2 = this.list.getSelection();
      const newSelection = selection2.filter((i3) => i3 !== focus);
      this.list.setFocus([focus]);
      if (selection2.length === newSelection.length) {
        this.list.setSelection([...newSelection, focus], e2.browserEvent);
      } else {
        this.list.setSelection(newSelection, e2.browserEvent);
      }
    }
  }
  dispose() {
    this.disposables.dispose();
  }
};
var DefaultStyleController = class {
  constructor(styleElement, selectorSuffix) {
    this.styleElement = styleElement;
    this.selectorSuffix = selectorSuffix;
  }
  style(styles6) {
    const suffix = this.selectorSuffix && `.${this.selectorSuffix}`;
    const content2 = [];
    if (styles6.listBackground) {
      if (styles6.listBackground.isOpaque()) {
        content2.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles6.listBackground}; }`);
      } else if (!isMacintosh) {
        console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`);
      }
    }
    if (styles6.listFocusBackground) {
      content2.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles6.listFocusBackground}; }`);
      content2.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles6.listFocusBackground}; }`);
    }
    if (styles6.listFocusForeground) {
      content2.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles6.listFocusForeground}; }`);
    }
    if (styles6.listActiveSelectionBackground) {
      content2.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles6.listActiveSelectionBackground}; }`);
      content2.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles6.listActiveSelectionBackground}; }`);
    }
    if (styles6.listActiveSelectionForeground) {
      content2.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles6.listActiveSelectionForeground}; }`);
    }
    if (styles6.listFocusAndSelectionBackground) {
      content2.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles6.listFocusAndSelectionBackground}; }
			`);
    }
    if (styles6.listFocusAndSelectionForeground) {
      content2.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles6.listFocusAndSelectionForeground}; }
			`);
    }
    if (styles6.listInactiveFocusBackground) {
      content2.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color:  ${styles6.listInactiveFocusBackground}; }`);
      content2.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color:  ${styles6.listInactiveFocusBackground}; }`);
    }
    if (styles6.listInactiveSelectionBackground) {
      content2.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color:  ${styles6.listInactiveSelectionBackground}; }`);
      content2.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color:  ${styles6.listInactiveSelectionBackground}; }`);
    }
    if (styles6.listInactiveSelectionForeground) {
      content2.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles6.listInactiveSelectionForeground}; }`);
    }
    if (styles6.listHoverBackground) {
      content2.push(`.monaco-list${suffix}:not(.drop-target) .monaco-list-row:hover:not(.selected):not(.focused) { background-color:  ${styles6.listHoverBackground}; }`);
    }
    if (styles6.listHoverForeground) {
      content2.push(`.monaco-list${suffix} .monaco-list-row:hover:not(.selected):not(.focused) { color:  ${styles6.listHoverForeground}; }`);
    }
    if (styles6.listSelectionOutline) {
      content2.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles6.listSelectionOutline}; outline-offset: -1px; }`);
    }
    if (styles6.listFocusOutline) {
      content2.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles6.listFocusOutline}; outline-offset: -1px; }
			`);
    }
    if (styles6.listInactiveFocusOutline) {
      content2.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles6.listInactiveFocusOutline}; outline-offset: -1px; }`);
    }
    if (styles6.listHoverOutline) {
      content2.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles6.listHoverOutline}; outline-offset: -1px; }`);
    }
    if (styles6.listDropBackground) {
      content2.push(`
				.monaco-list${suffix}.drop-target,
				.monaco-list${suffix} .monaco-list-rows.drop-target,
				.monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles6.listDropBackground} !important; color: inherit !important; }
			`);
    }
    if (styles6.listFilterWidgetBackground) {
      content2.push(`.monaco-list-type-filter { background-color: ${styles6.listFilterWidgetBackground} }`);
    }
    if (styles6.listFilterWidgetOutline) {
      content2.push(`.monaco-list-type-filter { border: 1px solid ${styles6.listFilterWidgetOutline}; }`);
    }
    if (styles6.listFilterWidgetNoMatchesOutline) {
      content2.push(`.monaco-list-type-filter.no-matches { border: 1px solid ${styles6.listFilterWidgetNoMatchesOutline}; }`);
    }
    if (styles6.listMatchesShadow) {
      content2.push(`.monaco-list-type-filter { box-shadow: 1px 1px 1px ${styles6.listMatchesShadow}; }`);
    }
    const newStyles = content2.join("\n");
    if (newStyles !== this.styleElement.innerHTML) {
      this.styleElement.innerHTML = newStyles;
    }
  }
};
var defaultStyles = {
  listFocusBackground: Color.fromHex("#7FB0D0"),
  listActiveSelectionBackground: Color.fromHex("#0E639C"),
  listActiveSelectionForeground: Color.fromHex("#FFFFFF"),
  listFocusAndSelectionBackground: Color.fromHex("#094771"),
  listFocusAndSelectionForeground: Color.fromHex("#FFFFFF"),
  listInactiveSelectionBackground: Color.fromHex("#3F3F46"),
  listHoverBackground: Color.fromHex("#2A2D2E"),
  listDropBackground: Color.fromHex("#383B3D"),
  treeIndentGuidesStroke: Color.fromHex("#a9a9a9")
};
var DefaultOptions$1 = {
  keyboardSupport: true,
  mouseSupport: true,
  multipleSelectionSupport: true,
  dnd: {
    getDragURI() {
      return null;
    },
    onDragStart() {
    },
    onDragOver() {
      return false;
    },
    drop() {
    }
  }
};
function getContiguousRangeContaining(range3, value) {
  const index3 = range3.indexOf(value);
  if (index3 === -1) {
    return [];
  }
  const result = [];
  let i3 = index3 - 1;
  while (i3 >= 0 && range3[i3] === value - (index3 - i3)) {
    result.push(range3[i3--]);
  }
  result.reverse();
  i3 = index3;
  while (i3 < range3.length && range3[i3] === value + (i3 - index3)) {
    result.push(range3[i3++]);
  }
  return result;
}
function disjunction(one2, other) {
  const result = [];
  let i3 = 0, j = 0;
  while (i3 < one2.length || j < other.length) {
    if (i3 >= one2.length) {
      result.push(other[j++]);
    } else if (j >= other.length) {
      result.push(one2[i3++]);
    } else if (one2[i3] === other[j]) {
      result.push(one2[i3]);
      i3++;
      j++;
      continue;
    } else if (one2[i3] < other[j]) {
      result.push(one2[i3++]);
    } else {
      result.push(other[j++]);
    }
  }
  return result;
}
function relativeComplement(one2, other) {
  const result = [];
  let i3 = 0, j = 0;
  while (i3 < one2.length || j < other.length) {
    if (i3 >= one2.length) {
      result.push(other[j++]);
    } else if (j >= other.length) {
      result.push(one2[i3++]);
    } else if (one2[i3] === other[j]) {
      i3++;
      j++;
      continue;
    } else if (one2[i3] < other[j]) {
      result.push(one2[i3++]);
    } else {
      j++;
    }
  }
  return result;
}
var numericSort = (a2, b2) => a2 - b2;
var PipelineRenderer = class {
  constructor(_templateId, renderers) {
    this._templateId = _templateId;
    this.renderers = renderers;
  }
  get templateId() {
    return this._templateId;
  }
  renderTemplate(container) {
    return this.renderers.map((r3) => r3.renderTemplate(container));
  }
  renderElement(element, index3, templateData, height) {
    let i3 = 0;
    for (const renderer of this.renderers) {
      renderer.renderElement(element, index3, templateData[i3++], height);
    }
  }
  disposeElement(element, index3, templateData, height) {
    let i3 = 0;
    for (const renderer of this.renderers) {
      if (renderer.disposeElement) {
        renderer.disposeElement(element, index3, templateData[i3], height);
      }
      i3 += 1;
    }
  }
  disposeTemplate(templateData) {
    let i3 = 0;
    for (const renderer of this.renderers) {
      renderer.disposeTemplate(templateData[i3++]);
    }
  }
};
var AccessibiltyRenderer = class {
  constructor(accessibilityProvider) {
    this.accessibilityProvider = accessibilityProvider;
    this.templateId = "a18n";
  }
  renderTemplate(container) {
    return container;
  }
  renderElement(element, index3, container) {
    const ariaLabel = this.accessibilityProvider.getAriaLabel(element);
    if (ariaLabel) {
      container.setAttribute("aria-label", ariaLabel);
    } else {
      container.removeAttribute("aria-label");
    }
    const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element);
    if (typeof ariaLevel === "number") {
      container.setAttribute("aria-level", `${ariaLevel}`);
    } else {
      container.removeAttribute("aria-level");
    }
  }
  disposeTemplate(templateData) {
  }
};
var ListViewDragAndDrop = class {
  constructor(list3, dnd) {
    this.list = list3;
    this.dnd = dnd;
  }
  getDragElements(element) {
    const selection2 = this.list.getSelectedElements();
    const elements = selection2.indexOf(element) > -1 ? selection2 : [element];
    return elements;
  }
  getDragURI(element) {
    return this.dnd.getDragURI(element);
  }
  getDragLabel(elements, originalEvent) {
    if (this.dnd.getDragLabel) {
      return this.dnd.getDragLabel(elements, originalEvent);
    }
    return void 0;
  }
  onDragStart(data2, originalEvent) {
    if (this.dnd.onDragStart) {
      this.dnd.onDragStart(data2, originalEvent);
    }
  }
  onDragOver(data2, targetElement, targetIndex, originalEvent) {
    return this.dnd.onDragOver(data2, targetElement, targetIndex, originalEvent);
  }
  onDragEnd(originalEvent) {
    if (this.dnd.onDragEnd) {
      this.dnd.onDragEnd(originalEvent);
    }
  }
  drop(data2, targetElement, targetIndex, originalEvent) {
    this.dnd.drop(data2, targetElement, targetIndex, originalEvent);
  }
};
var List2 = class {
  constructor(user, container, virtualDelegate, renderers, _options = DefaultOptions$1) {
    var _a;
    this.user = user;
    this._options = _options;
    this.eventBufferer = new EventBufferer();
    this._ariaLabel = "";
    this.disposables = new DisposableStore();
    this.didJustPressContextMenuKey = false;
    this._onDidDispose = new Emitter();
    this.onDidDispose = this._onDidDispose.event;
    const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? (_a = this._options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.getWidgetRole() : "list";
    this.selection = new SelectionTrait(role !== "listbox");
    this.focus = new Trait("focused");
    mixin(_options, defaultStyles, false);
    const baseRenderers = [this.focus.renderer, this.selection.renderer];
    this.accessibilityProvider = _options.accessibilityProvider;
    if (this.accessibilityProvider) {
      baseRenderers.push(new AccessibiltyRenderer(this.accessibilityProvider));
      if (this.accessibilityProvider.onDidChangeActiveDescendant) {
        this.accessibilityProvider.onDidChangeActiveDescendant(this.onDidChangeActiveDescendant, this, this.disposables);
      }
    }
    renderers = renderers.map((r3) => new PipelineRenderer(r3.templateId, [...baseRenderers, r3]));
    const viewOptions = Object.assign(Object.assign({}, _options), {dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd)});
    this.view = new ListView(container, virtualDelegate, renderers, viewOptions);
    this.view.domNode.setAttribute("role", role);
    if (_options.styleController) {
      this.styleController = _options.styleController(this.view.domId);
    } else {
      const styleElement = createStyleSheet(this.view.domNode);
      this.styleController = new DefaultStyleController(styleElement, this.view.domId);
    }
    this.spliceable = new CombinedSpliceable([
      new TraitSpliceable(this.focus, this.view, _options.identityProvider),
      new TraitSpliceable(this.selection, this.view, _options.identityProvider),
      this.view
    ]);
    this.disposables.add(this.focus);
    this.disposables.add(this.selection);
    this.disposables.add(this.view);
    this.disposables.add(this._onDidDispose);
    this.onDidFocus = Event.map(domEvent(this.view.domNode, "focus", true), () => null);
    this.onDidBlur = Event.map(domEvent(this.view.domNode, "blur", true), () => null);
    this.disposables.add(new DOMFocusController(this, this.view));
    if (typeof _options.keyboardSupport !== "boolean" || _options.keyboardSupport) {
      const controller = new KeyboardController(this, this.view, _options);
      this.disposables.add(controller);
    }
    if (_options.keyboardNavigationLabelProvider) {
      const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate;
      this.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider, delegate);
      this.disposables.add(this.typeLabelController);
    }
    this.mouseController = this.createMouseController(_options);
    this.disposables.add(this.mouseController);
    this.onDidChangeFocus(this._onFocusChange, this, this.disposables);
    this.onDidChangeSelection(this._onSelectionChange, this, this.disposables);
    if (this.accessibilityProvider) {
      this.ariaLabel = this.accessibilityProvider.getWidgetAriaLabel();
    }
    if (_options.multipleSelectionSupport) {
      this.view.domNode.setAttribute("aria-multiselectable", "true");
    }
  }
  get onDidChangeFocus() {
    return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), (e2) => this.toListEvent(e2));
  }
  get onDidChangeSelection() {
    return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), (e2) => this.toListEvent(e2));
  }
  get domId() {
    return this.view.domId;
  }
  get onMouseClick() {
    return this.view.onMouseClick;
  }
  get onMouseDblClick() {
    return this.view.onMouseDblClick;
  }
  get onMouseMiddleClick() {
    return this.view.onMouseMiddleClick;
  }
  get onPointer() {
    return this.mouseController.onPointer;
  }
  get onMouseDown() {
    return this.view.onMouseDown;
  }
  get onTouchStart() {
    return this.view.onTouchStart;
  }
  get onTap() {
    return this.view.onTap;
  }
  get onContextMenu() {
    const fromKeydown = Event.chain(domEvent(this.view.domNode, "keydown")).map((e2) => new StandardKeyboardEvent(e2)).filter((e2) => this.didJustPressContextMenuKey = e2.keyCode === 58 || e2.shiftKey && e2.keyCode === 68).filter((e2) => {
      e2.preventDefault();
      e2.stopPropagation();
      return false;
    }).event;
    const fromKeyup = Event.chain(domEvent(this.view.domNode, "keyup")).filter(() => {
      const didJustPressContextMenuKey = this.didJustPressContextMenuKey;
      this.didJustPressContextMenuKey = false;
      return didJustPressContextMenuKey;
    }).filter(() => this.getFocus().length > 0 && !!this.view.domElement(this.getFocus()[0])).map((browserEvent) => {
      const index3 = this.getFocus()[0];
      const element = this.view.element(index3);
      const anchor = this.view.domElement(index3);
      return {index: index3, element, anchor, browserEvent};
    }).event;
    const fromMouse = Event.chain(this.view.onContextMenu).filter(() => !this.didJustPressContextMenuKey).map(({element, index: index3, browserEvent}) => ({element, index: index3, anchor: {x: browserEvent.clientX + 1, y: browserEvent.clientY}, browserEvent})).event;
    return Event.any(fromKeydown, fromKeyup, fromMouse);
  }
  get onKeyDown() {
    return domEvent(this.view.domNode, "keydown");
  }
  createMouseController(options) {
    return new MouseController(this);
  }
  updateOptions(optionsUpdate = {}) {
    this._options = Object.assign(Object.assign({}, this._options), optionsUpdate);
    if (this.typeLabelController) {
      this.typeLabelController.updateOptions(this._options);
    }
    this.view.updateOptions(optionsUpdate);
  }
  get options() {
    return this._options;
  }
  splice(start3, deleteCount, elements = []) {
    if (start3 < 0 || start3 > this.view.length) {
      throw new ListError(this.user, `Invalid start index: ${start3}`);
    }
    if (deleteCount < 0) {
      throw new ListError(this.user, `Invalid delete count: ${deleteCount}`);
    }
    if (deleteCount === 0 && elements.length === 0) {
      return;
    }
    this.eventBufferer.bufferEvents(() => this.spliceable.splice(start3, deleteCount, elements));
  }
  rerender() {
    this.view.rerender();
  }
  element(index3) {
    return this.view.element(index3);
  }
  get length() {
    return this.view.length;
  }
  get contentHeight() {
    return this.view.contentHeight;
  }
  get scrollTop() {
    return this.view.getScrollTop();
  }
  set scrollTop(scrollTop) {
    this.view.setScrollTop(scrollTop);
  }
  get ariaLabel() {
    return this._ariaLabel;
  }
  set ariaLabel(value) {
    this._ariaLabel = value;
    this.view.domNode.setAttribute("aria-label", value);
  }
  domFocus() {
    this.view.domNode.focus();
  }
  layout(height, width2) {
    this.view.layout(height, width2);
  }
  setSelection(indexes, browserEvent) {
    for (const index3 of indexes) {
      if (index3 < 0 || index3 >= this.length) {
        throw new ListError(this.user, `Invalid index ${index3}`);
      }
    }
    this.selection.set(indexes, browserEvent);
  }
  getSelection() {
    return this.selection.get();
  }
  getSelectedElements() {
    return this.getSelection().map((i3) => this.view.element(i3));
  }
  setFocus(indexes, browserEvent) {
    for (const index3 of indexes) {
      if (index3 < 0 || index3 >= this.length) {
        throw new ListError(this.user, `Invalid index ${index3}`);
      }
    }
    this.focus.set(indexes, browserEvent);
  }
  focusNext(n3 = 1, loop = false, browserEvent, filter3) {
    if (this.length === 0) {
      return;
    }
    const focus = this.focus.get();
    const index3 = this.findNextIndex(focus.length > 0 ? focus[0] + n3 : 0, loop, filter3);
    if (index3 > -1) {
      this.setFocus([index3], browserEvent);
    }
  }
  focusPrevious(n3 = 1, loop = false, browserEvent, filter3) {
    if (this.length === 0) {
      return;
    }
    const focus = this.focus.get();
    const index3 = this.findPreviousIndex(focus.length > 0 ? focus[0] - n3 : 0, loop, filter3);
    if (index3 > -1) {
      this.setFocus([index3], browserEvent);
    }
  }
  focusNextPage(browserEvent, filter3) {
    let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight);
    lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
    const lastPageElement = this.view.element(lastPageIndex);
    const currentlyFocusedElement = this.getFocusedElements()[0];
    if (currentlyFocusedElement !== lastPageElement) {
      const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter3);
      if (lastGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(lastGoodPageIndex)) {
        this.setFocus([lastGoodPageIndex], browserEvent);
      } else {
        this.setFocus([lastPageIndex], browserEvent);
      }
    } else {
      const previousScrollTop = this.view.getScrollTop();
      this.view.setScrollTop(previousScrollTop + this.view.renderHeight - this.view.elementHeight(lastPageIndex));
      if (this.view.getScrollTop() !== previousScrollTop) {
        setTimeout(() => this.focusNextPage(browserEvent, filter3), 0);
      }
    }
  }
  focusPreviousPage(browserEvent, filter3) {
    let firstPageIndex;
    const scrollTop = this.view.getScrollTop();
    if (scrollTop === 0) {
      firstPageIndex = this.view.indexAt(scrollTop);
    } else {
      firstPageIndex = this.view.indexAfter(scrollTop - 1);
    }
    const firstPageElement = this.view.element(firstPageIndex);
    const currentlyFocusedElement = this.getFocusedElements()[0];
    if (currentlyFocusedElement !== firstPageElement) {
      const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter3);
      if (firstGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(firstGoodPageIndex)) {
        this.setFocus([firstGoodPageIndex], browserEvent);
      } else {
        this.setFocus([firstPageIndex], browserEvent);
      }
    } else {
      const previousScrollTop = scrollTop;
      this.view.setScrollTop(scrollTop - this.view.renderHeight);
      if (this.view.getScrollTop() !== previousScrollTop) {
        setTimeout(() => this.focusPreviousPage(browserEvent, filter3), 0);
      }
    }
  }
  focusLast(browserEvent, filter3) {
    if (this.length === 0) {
      return;
    }
    const index3 = this.findPreviousIndex(this.length - 1, false, filter3);
    if (index3 > -1) {
      this.setFocus([index3], browserEvent);
    }
  }
  focusFirst(browserEvent, filter3) {
    this.focusNth(0, browserEvent, filter3);
  }
  focusNth(n3, browserEvent, filter3) {
    if (this.length === 0) {
      return;
    }
    const index3 = this.findNextIndex(n3, false, filter3);
    if (index3 > -1) {
      this.setFocus([index3], browserEvent);
    }
  }
  findNextIndex(index3, loop = false, filter3) {
    for (let i3 = 0; i3 < this.length; i3++) {
      if (index3 >= this.length && !loop) {
        return -1;
      }
      index3 = index3 % this.length;
      if (!filter3 || filter3(this.element(index3))) {
        return index3;
      }
      index3++;
    }
    return -1;
  }
  findPreviousIndex(index3, loop = false, filter3) {
    for (let i3 = 0; i3 < this.length; i3++) {
      if (index3 < 0 && !loop) {
        return -1;
      }
      index3 = (this.length + index3 % this.length) % this.length;
      if (!filter3 || filter3(this.element(index3))) {
        return index3;
      }
      index3--;
    }
    return -1;
  }
  getFocus() {
    return this.focus.get();
  }
  getFocusedElements() {
    return this.getFocus().map((i3) => this.view.element(i3));
  }
  reveal(index3, relativeTop) {
    if (index3 < 0 || index3 >= this.length) {
      throw new ListError(this.user, `Invalid index ${index3}`);
    }
    const scrollTop = this.view.getScrollTop();
    const elementTop = this.view.elementTop(index3);
    const elementHeight = this.view.elementHeight(index3);
    if (isNumber2(relativeTop)) {
      const m2 = elementHeight - this.view.renderHeight;
      this.view.setScrollTop(m2 * clamp2(relativeTop, 0, 1) + elementTop);
    } else {
      const viewItemBottom = elementTop + elementHeight;
      const wrapperBottom = scrollTop + this.view.renderHeight;
      if (elementTop < scrollTop && viewItemBottom >= wrapperBottom)
        ;
      else if (elementTop < scrollTop) {
        this.view.setScrollTop(elementTop);
      } else if (viewItemBottom >= wrapperBottom) {
        this.view.setScrollTop(viewItemBottom - this.view.renderHeight);
      }
    }
  }
  getRelativeTop(index3) {
    if (index3 < 0 || index3 >= this.length) {
      throw new ListError(this.user, `Invalid index ${index3}`);
    }
    const scrollTop = this.view.getScrollTop();
    const elementTop = this.view.elementTop(index3);
    const elementHeight = this.view.elementHeight(index3);
    if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) {
      return null;
    }
    const m2 = elementHeight - this.view.renderHeight;
    return Math.abs((scrollTop - elementTop) / m2);
  }
  getHTMLElement() {
    return this.view.domNode;
  }
  style(styles6) {
    this.styleController.style(styles6);
  }
  toListEvent({indexes, browserEvent}) {
    return {indexes, elements: indexes.map((i3) => this.view.element(i3)), browserEvent};
  }
  _onFocusChange() {
    const focus = this.focus.get();
    toggleClass(this.view.domNode, "element-focused", focus.length > 0);
    this.onDidChangeActiveDescendant();
  }
  onDidChangeActiveDescendant() {
    var _a;
    const focus = this.focus.get();
    if (focus.length > 0) {
      let id3;
      if ((_a = this.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.getActiveDescendantId) {
        id3 = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0]));
      }
      this.view.domNode.setAttribute("aria-activedescendant", id3 || this.view.getElementDomId(focus[0]));
    } else {
      this.view.domNode.removeAttribute("aria-activedescendant");
    }
  }
  _onSelectionChange() {
    const selection2 = this.selection.get();
    toggleClass(this.view.domNode, "selection-none", selection2.length === 0);
    toggleClass(this.view.domNode, "selection-single", selection2.length === 1);
    toggleClass(this.view.domNode, "selection-multiple", selection2.length > 1);
  }
  dispose() {
    this._onDidDispose.fire();
    this.disposables.dispose();
    this._onDidDispose.dispose();
  }
};
__decorate$e([
  memoize
], List2.prototype, "onDidChangeFocus", null);
__decorate$e([
  memoize
], List2.prototype, "onDidChangeSelection", null);
__decorate$e([
  memoize
], List2.prototype, "onContextMenu", null);
var PagedRenderer = class {
  constructor(renderer, modelProvider) {
    this.renderer = renderer;
    this.modelProvider = modelProvider;
  }
  get templateId() {
    return this.renderer.templateId;
  }
  renderTemplate(container) {
    const data2 = this.renderer.renderTemplate(container);
    return {data: data2, disposable: Disposable.None};
  }
  renderElement(index3, _23, data2, height) {
    if (data2.disposable) {
      data2.disposable.dispose();
    }
    if (!data2.data) {
      return;
    }
    const model = this.modelProvider();
    if (model.isResolved(index3)) {
      return this.renderer.renderElement(model.get(index3), index3, data2.data, height);
    }
    const cts = new CancellationTokenSource();
    const promise = model.resolve(index3, cts.token);
    data2.disposable = {dispose: () => cts.cancel()};
    this.renderer.renderPlaceholder(index3, data2.data);
    promise.then((entry) => this.renderer.renderElement(entry, index3, data2.data, height));
  }
  disposeTemplate(data2) {
    if (data2.disposable) {
      data2.disposable.dispose();
      data2.disposable = void 0;
    }
    if (data2.data) {
      this.renderer.disposeTemplate(data2.data);
      data2.data = void 0;
    }
  }
};
var PagedAccessibilityProvider = class {
  constructor(modelProvider, accessibilityProvider) {
    this.modelProvider = modelProvider;
    this.accessibilityProvider = accessibilityProvider;
  }
  getWidgetAriaLabel() {
    return this.accessibilityProvider.getWidgetAriaLabel();
  }
  getAriaLabel(index3) {
    const model = this.modelProvider();
    if (!model.isResolved(index3)) {
      return null;
    }
    return this.accessibilityProvider.getAriaLabel(model.get(index3));
  }
};
function fromPagedListOptions(modelProvider, options) {
  return Object.assign(Object.assign({}, options), {accessibilityProvider: options.accessibilityProvider && new PagedAccessibilityProvider(modelProvider, options.accessibilityProvider)});
}
var PagedList = class {
  constructor(user, container, virtualDelegate, renderers, options = {}) {
    const modelProvider = () => this.model;
    const pagedRenderers = renderers.map((r3) => new PagedRenderer(r3, modelProvider));
    this.list = new List2(user, container, virtualDelegate, pagedRenderers, fromPagedListOptions(modelProvider, options));
  }
  updateOptions(options) {
    this.list.updateOptions(options);
  }
  getHTMLElement() {
    return this.list.getHTMLElement();
  }
  get onDidFocus() {
    return this.list.onDidFocus;
  }
  get onDidDispose() {
    return this.list.onDidDispose;
  }
  get onMouseDblClick() {
    return Event.map(this.list.onMouseDblClick, ({element, index: index3, browserEvent}) => ({element: element === void 0 ? void 0 : this._model.get(element), index: index3, browserEvent}));
  }
  get onPointer() {
    return Event.map(this.list.onPointer, ({element, index: index3, browserEvent}) => ({element: element === void 0 ? void 0 : this._model.get(element), index: index3, browserEvent}));
  }
  get onDidChangeFocus() {
    return Event.map(this.list.onDidChangeFocus, ({elements, indexes, browserEvent}) => ({elements: elements.map((e2) => this._model.get(e2)), indexes, browserEvent}));
  }
  get onDidChangeSelection() {
    return Event.map(this.list.onDidChangeSelection, ({elements, indexes, browserEvent}) => ({elements: elements.map((e2) => this._model.get(e2)), indexes, browserEvent}));
  }
  get model() {
    return this._model;
  }
  set model(model) {
    this._model = model;
    this.list.splice(0, this.list.length, range(model.length));
  }
  getFocus() {
    return this.list.getFocus();
  }
  setSelection(indexes, browserEvent) {
    this.list.setSelection(indexes, browserEvent);
  }
  getSelection() {
    return this.list.getSelection();
  }
  style(styles6) {
    this.list.style(styles6);
  }
  dispose() {
    this.list.dispose();
  }
};
var InputFocusedContextKey = "inputFocus";
function __snowpack__injectStyle$u(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$u("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-tl-row {\r\n	display: flex;\r\n	height: 100%;\r\n	align-items: center;\r\n	position: relative;\r\n}\r\n\r\n.monaco-tl-indent {\r\n	height: 100%;\r\n	position: absolute;\r\n	top: 0;\r\n	left: 16px;\r\n	pointer-events: none;\r\n}\r\n\r\n.hide-arrows .monaco-tl-indent {\r\n	left: 12px;\r\n}\r\n\r\n.monaco-tl-indent > .indent-guide {\r\n	display: inline-block;\r\n	box-sizing: border-box;\r\n	height: 100%;\r\n	border-left: 1px solid transparent;\r\n}\r\n\r\n.monaco-tl-indent > .indent-guide {\r\n	transition: border-color 0.1s linear;\r\n}\r\n\r\n.monaco-tl-twistie,\r\n.monaco-tl-contents {\r\n	height: 100%;\r\n}\r\n\r\n.monaco-tl-twistie {\r\n	font-size: 10px;\r\n	text-align: right;\r\n	padding-right: 6px;\r\n	flex-shrink: 0;\r\n	width: 16px;\r\n	display: flex !important;\r\n	align-items: center;\r\n	justify-content: center;\r\n	color: inherit !important;\r\n	transform: translateX(3px);\r\n}\r\n\r\n.monaco-tl-contents {\r\n	flex: 1;\r\n	overflow: hidden;\r\n}\r\n\r\n.monaco-tl-twistie.collapsed::before {\r\n	transform: rotate(-90deg);\r\n}\r\n\r\n.monaco-tl-twistie.codicon-tree-item-loading::before {\r\n	/* Use steps to throttle FPS to reduce CPU usage */\r\n	animation: codicon-spin 1.25s steps(30) infinite;\r\n}\r\n");
var TreeMouseEventTarget;
(function(TreeMouseEventTarget2) {
  TreeMouseEventTarget2[TreeMouseEventTarget2["Unknown"] = 0] = "Unknown";
  TreeMouseEventTarget2[TreeMouseEventTarget2["Twistie"] = 1] = "Twistie";
  TreeMouseEventTarget2[TreeMouseEventTarget2["Element"] = 2] = "Element";
})(TreeMouseEventTarget || (TreeMouseEventTarget = {}));
var TreeError = class extends Error {
  constructor(user, message) {
    super(`TreeError [${user}] ${message}`);
  }
};
var WeakMapper = class {
  constructor(fn) {
    this.fn = fn;
    this._map = new WeakMap();
  }
  map(key) {
    let result = this._map.get(key);
    if (!result) {
      result = this.fn(key);
      this._map.set(key, result);
    }
    return result;
  }
};
function isFilterResult(obj) {
  return typeof obj === "object" && "visibility" in obj && "data" in obj;
}
function getVisibleState(visibility) {
  switch (visibility) {
    case true:
      return 1;
    case false:
      return 0;
    default:
      return visibility;
  }
}
function isCollapsibleStateUpdate(update) {
  return typeof update.collapsible === "boolean";
}
var IndexTreeModel = class {
  constructor(user, list3, rootElement, options = {}) {
    this.user = user;
    this.list = list3;
    this.rootRef = [];
    this.eventBufferer = new EventBufferer();
    this._onDidChangeCollapseState = new Emitter();
    this.onDidChangeCollapseState = this.eventBufferer.wrapEvent(this._onDidChangeCollapseState.event);
    this._onDidChangeRenderNodeCount = new Emitter();
    this.onDidChangeRenderNodeCount = this.eventBufferer.wrapEvent(this._onDidChangeRenderNodeCount.event);
    this._onDidSplice = new Emitter();
    this.onDidSplice = this._onDidSplice.event;
    this.collapseByDefault = typeof options.collapseByDefault === "undefined" ? false : options.collapseByDefault;
    this.filter = options.filter;
    this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === "undefined" ? false : options.autoExpandSingleChildren;
    this.root = {
      parent: void 0,
      element: rootElement,
      children: [],
      depth: 0,
      visibleChildrenCount: 0,
      visibleChildIndex: -1,
      collapsible: false,
      collapsed: false,
      renderNodeCount: 0,
      visibility: 1,
      visible: true,
      filterData: void 0
    };
  }
  splice(location2, deleteCount, toInsert = Iterable.empty(), onDidCreateNode, onDidDeleteNode) {
    if (location2.length === 0) {
      throw new TreeError(this.user, "Invalid tree location");
    }
    const {parentNode, listIndex, revealed, visible} = this.getParentNodeWithListIndex(location2);
    const treeListElementsToInsert = [];
    const nodesToInsertIterator = Iterable.map(toInsert, (el) => this.createTreeNode(el, parentNode, parentNode.visible ? 1 : 0, revealed, treeListElementsToInsert, onDidCreateNode));
    const lastIndex = location2[location2.length - 1];
    let visibleChildStartIndex = 0;
    for (let i3 = lastIndex; i3 >= 0 && i3 < parentNode.children.length; i3--) {
      const child = parentNode.children[i3];
      if (child.visible) {
        visibleChildStartIndex = child.visibleChildIndex;
        break;
      }
    }
    const nodesToInsert = [];
    let insertedVisibleChildrenCount = 0;
    let renderNodeCount = 0;
    for (const child of nodesToInsertIterator) {
      nodesToInsert.push(child);
      renderNodeCount += child.renderNodeCount;
      if (child.visible) {
        child.visibleChildIndex = visibleChildStartIndex + insertedVisibleChildrenCount++;
      }
    }
    const deletedNodes = parentNode.children.splice(lastIndex, deleteCount, ...nodesToInsert);
    let deletedVisibleChildrenCount = 0;
    for (const child of deletedNodes) {
      if (child.visible) {
        deletedVisibleChildrenCount++;
      }
    }
    if (deletedVisibleChildrenCount !== 0) {
      for (let i3 = lastIndex + nodesToInsert.length; i3 < parentNode.children.length; i3++) {
        const child = parentNode.children[i3];
        if (child.visible) {
          child.visibleChildIndex -= deletedVisibleChildrenCount;
        }
      }
    }
    parentNode.visibleChildrenCount += insertedVisibleChildrenCount - deletedVisibleChildrenCount;
    if (revealed && visible) {
      const visibleDeleteCount = deletedNodes.reduce((r3, node2) => r3 + (node2.visible ? node2.renderNodeCount : 0), 0);
      this._updateAncestorsRenderNodeCount(parentNode, renderNodeCount - visibleDeleteCount);
      this.list.splice(listIndex, visibleDeleteCount, treeListElementsToInsert);
    }
    if (deletedNodes.length > 0 && onDidDeleteNode) {
      const visit = (node2) => {
        onDidDeleteNode(node2);
        node2.children.forEach(visit);
      };
      deletedNodes.forEach(visit);
    }
    this._onDidSplice.fire({insertedNodes: nodesToInsert, deletedNodes});
    let node = parentNode;
    while (node) {
      if (node.visibility === 2) {
        this.refilter();
        break;
      }
      node = node.parent;
    }
  }
  rerender(location2) {
    if (location2.length === 0) {
      throw new TreeError(this.user, "Invalid tree location");
    }
    const {node, listIndex, revealed} = this.getTreeNodeWithListIndex(location2);
    if (node.visible && revealed) {
      this.list.splice(listIndex, 1, [node]);
    }
  }
  has(location2) {
    return this.hasTreeNode(location2);
  }
  getListIndex(location2) {
    const {listIndex, visible, revealed} = this.getTreeNodeWithListIndex(location2);
    return visible && revealed ? listIndex : -1;
  }
  getListRenderCount(location2) {
    return this.getTreeNode(location2).renderNodeCount;
  }
  isCollapsible(location2) {
    return this.getTreeNode(location2).collapsible;
  }
  setCollapsible(location2, collapsible2) {
    const node = this.getTreeNode(location2);
    if (typeof collapsible2 === "undefined") {
      collapsible2 = !node.collapsible;
    }
    const update = {collapsible: collapsible2};
    return this.eventBufferer.bufferEvents(() => this._setCollapseState(location2, update));
  }
  isCollapsed(location2) {
    return this.getTreeNode(location2).collapsed;
  }
  setCollapsed(location2, collapsed, recursive) {
    const node = this.getTreeNode(location2);
    if (typeof collapsed === "undefined") {
      collapsed = !node.collapsed;
    }
    const update = {collapsed, recursive: recursive || false};
    return this.eventBufferer.bufferEvents(() => this._setCollapseState(location2, update));
  }
  _setCollapseState(location2, update) {
    const {node, listIndex, revealed} = this.getTreeNodeWithListIndex(location2);
    const result = this._setListNodeCollapseState(node, listIndex, revealed, update);
    if (node !== this.root && this.autoExpandSingleChildren && result && !isCollapsibleStateUpdate(update) && node.collapsible && !node.collapsed && !update.recursive) {
      let onlyVisibleChildIndex = -1;
      for (let i3 = 0; i3 < node.children.length; i3++) {
        const child = node.children[i3];
        if (child.visible) {
          if (onlyVisibleChildIndex > -1) {
            onlyVisibleChildIndex = -1;
            break;
          } else {
            onlyVisibleChildIndex = i3;
          }
        }
      }
      if (onlyVisibleChildIndex > -1) {
        this._setCollapseState([...location2, onlyVisibleChildIndex], update);
      }
    }
    return result;
  }
  _setListNodeCollapseState(node, listIndex, revealed, update) {
    const result = this._setNodeCollapseState(node, update, false);
    if (!revealed || !node.visible || !result) {
      return result;
    }
    const previousRenderNodeCount = node.renderNodeCount;
    const toInsert = this.updateNodeAfterCollapseChange(node);
    const deleteCount = previousRenderNodeCount - (listIndex === -1 ? 0 : 1);
    this.list.splice(listIndex + 1, deleteCount, toInsert.slice(1));
    return result;
  }
  _setNodeCollapseState(node, update, deep) {
    let result;
    if (node === this.root) {
      result = false;
    } else {
      if (isCollapsibleStateUpdate(update)) {
        result = node.collapsible !== update.collapsible;
        node.collapsible = update.collapsible;
      } else if (!node.collapsible) {
        result = false;
      } else {
        result = node.collapsed !== update.collapsed;
        node.collapsed = update.collapsed;
      }
      if (result) {
        this._onDidChangeCollapseState.fire({node, deep});
      }
    }
    if (!isCollapsibleStateUpdate(update) && update.recursive) {
      for (const child of node.children) {
        result = this._setNodeCollapseState(child, update, true) || result;
      }
    }
    return result;
  }
  expandTo(location2) {
    this.eventBufferer.bufferEvents(() => {
      let node = this.getTreeNode(location2);
      while (node.parent) {
        node = node.parent;
        location2 = location2.slice(0, location2.length - 1);
        if (node.collapsed) {
          this._setCollapseState(location2, {collapsed: false, recursive: false});
        }
      }
    });
  }
  refilter() {
    const previousRenderNodeCount = this.root.renderNodeCount;
    const toInsert = this.updateNodeAfterFilterChange(this.root);
    this.list.splice(0, previousRenderNodeCount, toInsert);
  }
  createTreeNode(treeElement, parent, parentVisibility, revealed, treeListElements, onDidCreateNode) {
    const node = {
      parent,
      element: treeElement.element,
      children: [],
      depth: parent.depth + 1,
      visibleChildrenCount: 0,
      visibleChildIndex: -1,
      collapsible: typeof treeElement.collapsible === "boolean" ? treeElement.collapsible : typeof treeElement.collapsed !== "undefined",
      collapsed: typeof treeElement.collapsed === "undefined" ? this.collapseByDefault : treeElement.collapsed,
      renderNodeCount: 1,
      visibility: 1,
      visible: true,
      filterData: void 0
    };
    const visibility = this._filterNode(node, parentVisibility);
    node.visibility = visibility;
    if (revealed) {
      treeListElements.push(node);
    }
    const childElements = treeElement.children || Iterable.empty();
    const childRevealed = revealed && visibility !== 0 && !node.collapsed;
    const childNodes = Iterable.map(childElements, (el) => this.createTreeNode(el, node, visibility, childRevealed, treeListElements, onDidCreateNode));
    let visibleChildrenCount = 0;
    let renderNodeCount = 1;
    for (const child of childNodes) {
      node.children.push(child);
      renderNodeCount += child.renderNodeCount;
      if (child.visible) {
        child.visibleChildIndex = visibleChildrenCount++;
      }
    }
    node.collapsible = node.collapsible || node.children.length > 0;
    node.visibleChildrenCount = visibleChildrenCount;
    node.visible = visibility === 2 ? visibleChildrenCount > 0 : visibility === 1;
    if (!node.visible) {
      node.renderNodeCount = 0;
      if (revealed) {
        treeListElements.pop();
      }
    } else if (!node.collapsed) {
      node.renderNodeCount = renderNodeCount;
    }
    if (onDidCreateNode) {
      onDidCreateNode(node);
    }
    return node;
  }
  updateNodeAfterCollapseChange(node) {
    const previousRenderNodeCount = node.renderNodeCount;
    const result = [];
    this._updateNodeAfterCollapseChange(node, result);
    this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount);
    return result;
  }
  _updateNodeAfterCollapseChange(node, result) {
    if (node.visible === false) {
      return 0;
    }
    result.push(node);
    node.renderNodeCount = 1;
    if (!node.collapsed) {
      for (const child of node.children) {
        node.renderNodeCount += this._updateNodeAfterCollapseChange(child, result);
      }
    }
    this._onDidChangeRenderNodeCount.fire(node);
    return node.renderNodeCount;
  }
  updateNodeAfterFilterChange(node) {
    const previousRenderNodeCount = node.renderNodeCount;
    const result = [];
    this._updateNodeAfterFilterChange(node, node.visible ? 1 : 0, result);
    this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount);
    return result;
  }
  _updateNodeAfterFilterChange(node, parentVisibility, result, revealed = true) {
    let visibility;
    if (node !== this.root) {
      visibility = this._filterNode(node, parentVisibility);
      if (visibility === 0) {
        node.visible = false;
        node.renderNodeCount = 0;
        return false;
      }
      if (revealed) {
        result.push(node);
      }
    }
    const resultStartLength = result.length;
    node.renderNodeCount = node === this.root ? 0 : 1;
    let hasVisibleDescendants = false;
    if (!node.collapsed || visibility !== 0) {
      let visibleChildIndex = 0;
      for (const child of node.children) {
        hasVisibleDescendants = this._updateNodeAfterFilterChange(child, visibility, result, revealed && !node.collapsed) || hasVisibleDescendants;
        if (child.visible) {
          child.visibleChildIndex = visibleChildIndex++;
        }
      }
      node.visibleChildrenCount = visibleChildIndex;
    } else {
      node.visibleChildrenCount = 0;
    }
    if (node !== this.root) {
      node.visible = visibility === 2 ? hasVisibleDescendants : visibility === 1;
    }
    if (!node.visible) {
      node.renderNodeCount = 0;
      if (revealed) {
        result.pop();
      }
    } else if (!node.collapsed) {
      node.renderNodeCount += result.length - resultStartLength;
    }
    this._onDidChangeRenderNodeCount.fire(node);
    return node.visible;
  }
  _updateAncestorsRenderNodeCount(node, diff) {
    if (diff === 0) {
      return;
    }
    while (node) {
      node.renderNodeCount += diff;
      this._onDidChangeRenderNodeCount.fire(node);
      node = node.parent;
    }
  }
  _filterNode(node, parentVisibility) {
    const result = this.filter ? this.filter.filter(node.element, parentVisibility) : 1;
    if (typeof result === "boolean") {
      node.filterData = void 0;
      return result ? 1 : 0;
    } else if (isFilterResult(result)) {
      node.filterData = result.data;
      return getVisibleState(result.visibility);
    } else {
      node.filterData = void 0;
      return getVisibleState(result);
    }
  }
  hasTreeNode(location2, node = this.root) {
    if (!location2 || location2.length === 0) {
      return true;
    }
    const [index3, ...rest] = location2;
    if (index3 < 0 || index3 > node.children.length) {
      return false;
    }
    return this.hasTreeNode(rest, node.children[index3]);
  }
  getTreeNode(location2, node = this.root) {
    if (!location2 || location2.length === 0) {
      return node;
    }
    const [index3, ...rest] = location2;
    if (index3 < 0 || index3 > node.children.length) {
      throw new TreeError(this.user, "Invalid tree location");
    }
    return this.getTreeNode(rest, node.children[index3]);
  }
  getTreeNodeWithListIndex(location2) {
    if (location2.length === 0) {
      return {node: this.root, listIndex: -1, revealed: true, visible: false};
    }
    const {parentNode, listIndex, revealed, visible} = this.getParentNodeWithListIndex(location2);
    const index3 = location2[location2.length - 1];
    if (index3 < 0 || index3 > parentNode.children.length) {
      throw new TreeError(this.user, "Invalid tree location");
    }
    const node = parentNode.children[index3];
    return {node, listIndex, revealed, visible: visible && node.visible};
  }
  getParentNodeWithListIndex(location2, node = this.root, listIndex = 0, revealed = true, visible = true) {
    const [index3, ...rest] = location2;
    if (index3 < 0 || index3 > node.children.length) {
      throw new TreeError(this.user, "Invalid tree location");
    }
    for (let i3 = 0; i3 < index3; i3++) {
      listIndex += node.children[i3].renderNodeCount;
    }
    revealed = revealed && !node.collapsed;
    visible = visible && node.visible;
    if (rest.length === 0) {
      return {parentNode: node, listIndex, revealed, visible};
    }
    return this.getParentNodeWithListIndex(rest, node.children[index3], listIndex + 1, revealed, visible);
  }
  getNode(location2 = []) {
    return this.getTreeNode(location2);
  }
  getNodeLocation(node) {
    const location2 = [];
    let indexTreeNode = node;
    while (indexTreeNode.parent) {
      location2.push(indexTreeNode.parent.children.indexOf(indexTreeNode));
      indexTreeNode = indexTreeNode.parent;
    }
    return location2.reverse();
  }
  getParentNodeLocation(location2) {
    if (location2.length === 0) {
      return void 0;
    } else if (location2.length === 1) {
      return [];
    } else {
      return tail2(location2)[0];
    }
  }
};
var treeItemExpandedIcon = registerIcon("tree-item-expanded", Codicon.chevronDown);
var treeFilterOnTypeOnIcon = registerIcon("tree-filter-on-type-on", Codicon.listFilter);
var treeFilterOnTypeOffIcon = registerIcon("tree-filter-on-type-off", Codicon.listSelection);
var treeFilterClearIcon = registerIcon("tree-filter-clear", Codicon.close);
var treeItemLoadingIcon = registerIcon("tree-item-loading", Codicon.loading);
var TreeElementsDragAndDropData = class extends ElementsDragAndDropData {
  constructor(data2) {
    super(data2.elements.map((node) => node.element));
    this.data = data2;
  }
};
function asTreeDragAndDropData(data2) {
  if (data2 instanceof ElementsDragAndDropData) {
    return new TreeElementsDragAndDropData(data2);
  }
  return data2;
}
var TreeNodeListDragAndDrop = class {
  constructor(modelProvider, dnd) {
    this.modelProvider = modelProvider;
    this.dnd = dnd;
    this.autoExpandDisposable = Disposable.None;
  }
  getDragURI(node) {
    return this.dnd.getDragURI(node.element);
  }
  getDragLabel(nodes, originalEvent) {
    if (this.dnd.getDragLabel) {
      return this.dnd.getDragLabel(nodes.map((node) => node.element), originalEvent);
    }
    return void 0;
  }
  onDragStart(data2, originalEvent) {
    if (this.dnd.onDragStart) {
      this.dnd.onDragStart(asTreeDragAndDropData(data2), originalEvent);
    }
  }
  onDragOver(data2, targetNode, targetIndex, originalEvent, raw = true) {
    const result = this.dnd.onDragOver(asTreeDragAndDropData(data2), targetNode && targetNode.element, targetIndex, originalEvent);
    const didChangeAutoExpandNode = this.autoExpandNode !== targetNode;
    if (didChangeAutoExpandNode) {
      this.autoExpandDisposable.dispose();
      this.autoExpandNode = targetNode;
    }
    if (typeof targetNode === "undefined") {
      return result;
    }
    if (didChangeAutoExpandNode && typeof result !== "boolean" && result.autoExpand) {
      this.autoExpandDisposable = disposableTimeout(() => {
        const model2 = this.modelProvider();
        const ref2 = model2.getNodeLocation(targetNode);
        if (model2.isCollapsed(ref2)) {
          model2.setCollapsed(ref2, false);
        }
        this.autoExpandNode = void 0;
      }, 500);
    }
    if (typeof result === "boolean" || !result.accept || typeof result.bubble === "undefined" || result.feedback) {
      if (!raw) {
        const accept = typeof result === "boolean" ? result : result.accept;
        const effect2 = typeof result === "boolean" ? void 0 : result.effect;
        return {accept, effect: effect2, feedback: [targetIndex]};
      }
      return result;
    }
    if (result.bubble === 1) {
      const model2 = this.modelProvider();
      const ref2 = model2.getNodeLocation(targetNode);
      const parentRef = model2.getParentNodeLocation(ref2);
      const parentNode = model2.getNode(parentRef);
      const parentIndex = parentRef && model2.getListIndex(parentRef);
      return this.onDragOver(data2, parentNode, parentIndex, originalEvent, false);
    }
    const model = this.modelProvider();
    const ref = model.getNodeLocation(targetNode);
    const start3 = model.getListIndex(ref);
    const length = model.getListRenderCount(ref);
    return Object.assign(Object.assign({}, result), {feedback: range(start3, start3 + length)});
  }
  drop(data2, targetNode, targetIndex, originalEvent) {
    this.autoExpandDisposable.dispose();
    this.autoExpandNode = void 0;
    this.dnd.drop(asTreeDragAndDropData(data2), targetNode && targetNode.element, targetIndex, originalEvent);
  }
  onDragEnd(originalEvent) {
    if (this.dnd.onDragEnd) {
      this.dnd.onDragEnd(originalEvent);
    }
  }
};
function asListOptions(modelProvider, options) {
  return options && Object.assign(Object.assign({}, options), {identityProvider: options.identityProvider && {
    getId(el) {
      return options.identityProvider.getId(el.element);
    }
  }, dnd: options.dnd && new TreeNodeListDragAndDrop(modelProvider, options.dnd), multipleSelectionController: options.multipleSelectionController && {
    isSelectionSingleChangeEvent(e2) {
      return options.multipleSelectionController.isSelectionSingleChangeEvent(Object.assign(Object.assign({}, e2), {element: e2.element}));
    },
    isSelectionRangeChangeEvent(e2) {
      return options.multipleSelectionController.isSelectionRangeChangeEvent(Object.assign(Object.assign({}, e2), {element: e2.element}));
    }
  }, accessibilityProvider: options.accessibilityProvider && Object.assign(Object.assign({}, options.accessibilityProvider), {
    getSetSize(node) {
      const model = modelProvider();
      const ref = model.getNodeLocation(node);
      const parentRef = model.getParentNodeLocation(ref);
      const parentNode = model.getNode(parentRef);
      return parentNode.visibleChildrenCount;
    },
    getPosInSet(node) {
      return node.visibleChildIndex + 1;
    },
    isChecked: options.accessibilityProvider && options.accessibilityProvider.isChecked ? (node) => {
      return options.accessibilityProvider.isChecked(node.element);
    } : void 0,
    getRole: options.accessibilityProvider && options.accessibilityProvider.getRole ? (node) => {
      return options.accessibilityProvider.getRole(node.element);
    } : () => "treeitem",
    getAriaLabel(e2) {
      return options.accessibilityProvider.getAriaLabel(e2.element);
    },
    getWidgetAriaLabel() {
      return options.accessibilityProvider.getWidgetAriaLabel();
    },
    getWidgetRole: options.accessibilityProvider && options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => "tree",
    getAriaLevel(node) {
      return node.depth;
    },
    getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && ((node) => {
      return options.accessibilityProvider.getActiveDescendantId(node.element);
    })
  }), keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, options.keyboardNavigationLabelProvider), {getKeyboardNavigationLabel(node) {
    return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(node.element);
  }}), enableKeyboardNavigation: options.simpleKeyboardNavigation});
}
var ComposedTreeDelegate = class {
  constructor(delegate) {
    this.delegate = delegate;
  }
  getHeight(element) {
    return this.delegate.getHeight(element.element);
  }
  getTemplateId(element) {
    return this.delegate.getTemplateId(element.element);
  }
  hasDynamicHeight(element) {
    return !!this.delegate.hasDynamicHeight && this.delegate.hasDynamicHeight(element.element);
  }
  setDynamicHeight(element, height) {
    if (this.delegate.setDynamicHeight) {
      this.delegate.setDynamicHeight(element.element, height);
    }
  }
};
var RenderIndentGuides;
(function(RenderIndentGuides2) {
  RenderIndentGuides2["None"] = "none";
  RenderIndentGuides2["OnHover"] = "onHover";
  RenderIndentGuides2["Always"] = "always";
})(RenderIndentGuides || (RenderIndentGuides = {}));
var EventCollection = class {
  constructor(onDidChange, _elements = []) {
    this._elements = _elements;
    this.onDidChange = Event.forEach(onDidChange, (elements) => this._elements = elements);
  }
  get elements() {
    return this._elements;
  }
};
var TreeRenderer = class {
  constructor(renderer, modelProvider, onDidChangeCollapseState, activeNodes, options = {}) {
    this.renderer = renderer;
    this.modelProvider = modelProvider;
    this.activeNodes = activeNodes;
    this.renderedElements = new Map();
    this.renderedNodes = new Map();
    this.indent = TreeRenderer.DefaultIndent;
    this.hideTwistiesOfChildlessElements = false;
    this.shouldRenderIndentGuides = false;
    this.renderedIndentGuides = new SetMap();
    this.activeIndentNodes = new Set();
    this.indentGuidesDisposable = Disposable.None;
    this.disposables = new DisposableStore();
    this.templateId = renderer.templateId;
    this.updateOptions(options);
    Event.map(onDidChangeCollapseState, (e2) => e2.node)(this.onDidChangeNodeTwistieState, this, this.disposables);
    if (renderer.onDidChangeTwistieState) {
      renderer.onDidChangeTwistieState(this.onDidChangeTwistieState, this, this.disposables);
    }
  }
  updateOptions(options = {}) {
    if (typeof options.indent !== "undefined") {
      this.indent = clamp2(options.indent, 0, 40);
    }
    if (typeof options.renderIndentGuides !== "undefined") {
      const shouldRenderIndentGuides = options.renderIndentGuides !== RenderIndentGuides.None;
      if (shouldRenderIndentGuides !== this.shouldRenderIndentGuides) {
        this.shouldRenderIndentGuides = shouldRenderIndentGuides;
        this.indentGuidesDisposable.dispose();
        if (shouldRenderIndentGuides) {
          const disposables = new DisposableStore();
          this.activeNodes.onDidChange(this._onDidChangeActiveNodes, this, disposables);
          this.indentGuidesDisposable = disposables;
          this._onDidChangeActiveNodes(this.activeNodes.elements);
        }
      }
    }
    if (typeof options.hideTwistiesOfChildlessElements !== "undefined") {
      this.hideTwistiesOfChildlessElements = options.hideTwistiesOfChildlessElements;
    }
  }
  renderTemplate(container) {
    const el = append(container, $(".monaco-tl-row"));
    const indent = append(el, $(".monaco-tl-indent"));
    const twistie = append(el, $(".monaco-tl-twistie"));
    const contents = append(el, $(".monaco-tl-contents"));
    const templateData = this.renderer.renderTemplate(contents);
    return {container, indent, twistie, indentGuidesDisposable: Disposable.None, templateData};
  }
  renderElement(node, index3, templateData, height) {
    if (typeof height === "number") {
      this.renderedNodes.set(node, {templateData, height});
      this.renderedElements.set(node.element, node);
    }
    const indent = TreeRenderer.DefaultIndent + (node.depth - 1) * this.indent;
    templateData.twistie.style.paddingLeft = `${indent}px`;
    templateData.indent.style.width = `${indent + this.indent - 16}px`;
    this.renderTwistie(node, templateData);
    if (typeof height === "number") {
      this.renderIndentGuides(node, templateData);
    }
    this.renderer.renderElement(node, index3, templateData.templateData, height);
  }
  disposeElement(node, index3, templateData, height) {
    templateData.indentGuidesDisposable.dispose();
    if (this.renderer.disposeElement) {
      this.renderer.disposeElement(node, index3, templateData.templateData, height);
    }
    if (typeof height === "number") {
      this.renderedNodes.delete(node);
      this.renderedElements.delete(node.element);
    }
  }
  disposeTemplate(templateData) {
    this.renderer.disposeTemplate(templateData.templateData);
  }
  onDidChangeTwistieState(element) {
    const node = this.renderedElements.get(element);
    if (!node) {
      return;
    }
    this.onDidChangeNodeTwistieState(node);
  }
  onDidChangeNodeTwistieState(node) {
    const data2 = this.renderedNodes.get(node);
    if (!data2) {
      return;
    }
    this.renderTwistie(node, data2.templateData);
    this._onDidChangeActiveNodes(this.activeNodes.elements);
    this.renderIndentGuides(node, data2.templateData);
  }
  renderTwistie(node, templateData) {
    if (this.renderer.renderTwistie) {
      this.renderer.renderTwistie(node.element, templateData.twistie);
    }
    if (node.collapsible && (!this.hideTwistiesOfChildlessElements || node.visibleChildrenCount > 0)) {
      addClasses(templateData.twistie, treeItemExpandedIcon.classNames, "collapsible");
      toggleClass(templateData.twistie, "collapsed", node.collapsed);
    } else {
      removeClasses(templateData.twistie, treeItemExpandedIcon.classNames, "collapsible", "collapsed");
    }
    if (node.collapsible) {
      templateData.container.setAttribute("aria-expanded", String(!node.collapsed));
    } else {
      templateData.container.removeAttribute("aria-expanded");
    }
  }
  renderIndentGuides(target, templateData) {
    clearNode(templateData.indent);
    templateData.indentGuidesDisposable.dispose();
    if (!this.shouldRenderIndentGuides) {
      return;
    }
    const disposableStore = new DisposableStore();
    const model = this.modelProvider();
    let node = target;
    while (true) {
      const ref = model.getNodeLocation(node);
      const parentRef = model.getParentNodeLocation(ref);
      if (!parentRef) {
        break;
      }
      const parent = model.getNode(parentRef);
      const guide = $(".indent-guide", {style: `width: ${this.indent}px`});
      if (this.activeIndentNodes.has(parent)) {
        addClass(guide, "active");
      }
      if (templateData.indent.childElementCount === 0) {
        templateData.indent.appendChild(guide);
      } else {
        templateData.indent.insertBefore(guide, templateData.indent.firstElementChild);
      }
      this.renderedIndentGuides.add(parent, guide);
      disposableStore.add(toDisposable(() => this.renderedIndentGuides.delete(parent, guide)));
      node = parent;
    }
    templateData.indentGuidesDisposable = disposableStore;
  }
  _onDidChangeActiveNodes(nodes) {
    if (!this.shouldRenderIndentGuides) {
      return;
    }
    const set3 = new Set();
    const model = this.modelProvider();
    nodes.forEach((node) => {
      const ref = model.getNodeLocation(node);
      try {
        const parentRef = model.getParentNodeLocation(ref);
        if (node.collapsible && node.children.length > 0 && !node.collapsed) {
          set3.add(node);
        } else if (parentRef) {
          set3.add(model.getNode(parentRef));
        }
      } catch (_a) {
      }
    });
    this.activeIndentNodes.forEach((node) => {
      if (!set3.has(node)) {
        this.renderedIndentGuides.forEach(node, (line) => removeClass(line, "active"));
      }
    });
    set3.forEach((node) => {
      if (!this.activeIndentNodes.has(node)) {
        this.renderedIndentGuides.forEach(node, (line) => addClass(line, "active"));
      }
    });
    this.activeIndentNodes = set3;
  }
  dispose() {
    this.renderedNodes.clear();
    this.renderedElements.clear();
    this.indentGuidesDisposable.dispose();
    dispose(this.disposables);
  }
};
TreeRenderer.DefaultIndent = 8;
var TypeFilter = class {
  constructor(tree, keyboardNavigationLabelProvider, _filter) {
    this.tree = tree;
    this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
    this._filter = _filter;
    this._totalCount = 0;
    this._matchCount = 0;
    this._pattern = "";
    this._lowercasePattern = "";
    this.disposables = new DisposableStore();
    tree.onWillRefilter(this.reset, this, this.disposables);
  }
  get totalCount() {
    return this._totalCount;
  }
  get matchCount() {
    return this._matchCount;
  }
  set pattern(pattern) {
    this._pattern = pattern;
    this._lowercasePattern = pattern.toLowerCase();
  }
  filter(element, parentVisibility) {
    if (this._filter) {
      const result = this._filter.filter(element, parentVisibility);
      if (this.tree.options.simpleKeyboardNavigation) {
        return result;
      }
      let visibility;
      if (typeof result === "boolean") {
        visibility = result ? 1 : 0;
      } else if (isFilterResult(result)) {
        visibility = getVisibleState(result.visibility);
      } else {
        visibility = result;
      }
      if (visibility === 0) {
        return false;
      }
    }
    this._totalCount++;
    if (this.tree.options.simpleKeyboardNavigation || !this._pattern) {
      this._matchCount++;
      return {data: FuzzyScore.Default, visibility: true};
    }
    const label2 = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(element);
    const labelStr = label2 && label2.toString();
    if (typeof labelStr === "undefined") {
      return {data: FuzzyScore.Default, visibility: true};
    }
    const score2 = fuzzyScore(this._pattern, this._lowercasePattern, 0, labelStr, labelStr.toLowerCase(), 0, true);
    if (!score2) {
      if (this.tree.options.filterOnType) {
        return 2;
      } else {
        return {data: FuzzyScore.Default, visibility: true};
      }
    }
    this._matchCount++;
    return {data: score2, visibility: true};
  }
  reset() {
    this._totalCount = 0;
    this._matchCount = 0;
  }
  dispose() {
    dispose(this.disposables);
  }
};
var TypeFilterController = class {
  constructor(tree, model, view, filter3, keyboardNavigationDelegate) {
    this.tree = tree;
    this.view = view;
    this.filter = filter3;
    this.keyboardNavigationDelegate = keyboardNavigationDelegate;
    this._enabled = false;
    this._pattern = "";
    this._empty = false;
    this._onDidChangeEmptyState = new Emitter();
    this.positionClassName = "ne";
    this.automaticKeyboardNavigation = true;
    this.triggered = false;
    this._onDidChangePattern = new Emitter();
    this.enabledDisposables = new DisposableStore();
    this.disposables = new DisposableStore();
    this.domNode = $(`.monaco-list-type-filter.${this.positionClassName}`);
    this.domNode.draggable = true;
    domEvent(this.domNode, "dragstart")(this.onDragStart, this, this.disposables);
    this.messageDomNode = append(view.getHTMLElement(), $(`.monaco-list-type-filter-message`));
    this.labelDomNode = append(this.domNode, $("span.label"));
    const controls = append(this.domNode, $(".controls"));
    this._filterOnType = !!tree.options.filterOnType;
    this.filterOnTypeDomNode = append(controls, $("input.filter"));
    this.filterOnTypeDomNode.type = "checkbox";
    this.filterOnTypeDomNode.checked = this._filterOnType;
    this.filterOnTypeDomNode.tabIndex = -1;
    this.updateFilterOnTypeTitleAndIcon();
    domEvent(this.filterOnTypeDomNode, "input")(this.onDidChangeFilterOnType, this, this.disposables);
    this.clearDomNode = append(controls, $("button.clear" + treeFilterClearIcon.cssSelector));
    this.clearDomNode.tabIndex = -1;
    this.clearDomNode.title = localize("clear", "Clear");
    this.keyboardNavigationEventFilter = tree.options.keyboardNavigationEventFilter;
    model.onDidSplice(this.onDidSpliceModel, this, this.disposables);
    this.updateOptions(tree.options);
  }
  get enabled() {
    return this._enabled;
  }
  get pattern() {
    return this._pattern;
  }
  get filterOnType() {
    return this._filterOnType;
  }
  updateOptions(options) {
    if (options.simpleKeyboardNavigation) {
      this.disable();
    } else {
      this.enable();
    }
    if (typeof options.filterOnType !== "undefined") {
      this._filterOnType = !!options.filterOnType;
      this.filterOnTypeDomNode.checked = this._filterOnType;
    }
    if (typeof options.automaticKeyboardNavigation !== "undefined") {
      this.automaticKeyboardNavigation = options.automaticKeyboardNavigation;
    }
    this.tree.refilter();
    this.render();
    if (!this.automaticKeyboardNavigation) {
      this.onEventOrInput("");
    }
  }
  enable() {
    if (this._enabled) {
      return;
    }
    const onKeyDown = Event.chain(domEvent(this.view.getHTMLElement(), "keydown")).filter((e2) => !isInputElement(e2.target) || e2.target === this.filterOnTypeDomNode).filter((e2) => e2.key !== "Dead" && !/^Media/.test(e2.key)).map((e2) => new StandardKeyboardEvent(e2)).filter(this.keyboardNavigationEventFilter || (() => true)).filter(() => this.automaticKeyboardNavigation || this.triggered).filter((e2) => this.keyboardNavigationDelegate.mightProducePrintableCharacter(e2) && !(e2.keyCode === 18 || e2.keyCode === 16 || e2.keyCode === 15 || e2.keyCode === 17) || ((this.pattern.length > 0 || this.triggered) && ((e2.keyCode === 9 || e2.keyCode === 1) && !e2.altKey && !e2.ctrlKey && !e2.metaKey) || e2.keyCode === 1 && (isMacintosh ? e2.altKey && !e2.metaKey : e2.ctrlKey) && !e2.shiftKey)).forEach((e2) => {
      e2.stopPropagation();
      e2.preventDefault();
    }).event;
    const onClear = domEvent(this.clearDomNode, "click");
    Event.chain(Event.any(onKeyDown, onClear)).event(this.onEventOrInput, this, this.enabledDisposables);
    this.filter.pattern = "";
    this.tree.refilter();
    this.render();
    this._enabled = true;
    this.triggered = false;
  }
  disable() {
    if (!this._enabled) {
      return;
    }
    this.domNode.remove();
    this.enabledDisposables.clear();
    this.tree.refilter();
    this.render();
    this._enabled = false;
    this.triggered = false;
  }
  onEventOrInput(e2) {
    if (typeof e2 === "string") {
      this.onInput(e2);
    } else if (e2 instanceof MouseEvent || e2.keyCode === 9 || e2.keyCode === 1 && (isMacintosh ? e2.altKey : e2.ctrlKey)) {
      this.onInput("");
    } else if (e2.keyCode === 1) {
      this.onInput(this.pattern.length === 0 ? "" : this.pattern.substr(0, this.pattern.length - 1));
    } else {
      this.onInput(this.pattern + e2.browserEvent.key);
    }
  }
  onInput(pattern) {
    const container = this.view.getHTMLElement();
    if (pattern && !this.domNode.parentElement) {
      container.append(this.domNode);
    } else if (!pattern && this.domNode.parentElement) {
      this.domNode.remove();
      this.tree.domFocus();
    }
    this._pattern = pattern;
    this._onDidChangePattern.fire(pattern);
    this.filter.pattern = pattern;
    this.tree.refilter();
    if (pattern) {
      this.tree.focusNext(0, true, void 0, (node) => !FuzzyScore.isDefault(node.filterData));
    }
    const focus = this.tree.getFocus();
    if (focus.length > 0) {
      const element = focus[0];
      if (this.tree.getRelativeTop(element) === null) {
        this.tree.reveal(element, 0.5);
      }
    }
    this.render();
    if (!pattern) {
      this.triggered = false;
    }
  }
  onDragStart() {
    const container = this.view.getHTMLElement();
    const {left: left2} = getDomNodePagePosition(container);
    const containerWidth = container.clientWidth;
    const midContainerWidth = containerWidth / 2;
    const width2 = this.domNode.clientWidth;
    const disposables = new DisposableStore();
    let positionClassName = this.positionClassName;
    const updatePosition = () => {
      switch (positionClassName) {
        case "nw":
          this.domNode.style.top = `4px`;
          this.domNode.style.left = `4px`;
          break;
        case "ne":
          this.domNode.style.top = `4px`;
          this.domNode.style.left = `${containerWidth - width2 - 6}px`;
          break;
      }
    };
    const onDragOver = (event) => {
      event.preventDefault();
      const x2 = event.screenX - left2;
      if (event.dataTransfer) {
        event.dataTransfer.dropEffect = "none";
      }
      if (x2 < midContainerWidth) {
        positionClassName = "nw";
      } else {
        positionClassName = "ne";
      }
      updatePosition();
    };
    const onDragEnd = () => {
      this.positionClassName = positionClassName;
      this.domNode.className = `monaco-list-type-filter ${this.positionClassName}`;
      this.domNode.style.top = "";
      this.domNode.style.left = "";
      dispose(disposables);
    };
    updatePosition();
    removeClass(this.domNode, positionClassName);
    addClass(this.domNode, "dragging");
    disposables.add(toDisposable(() => removeClass(this.domNode, "dragging")));
    domEvent(document, "dragover")(onDragOver, null, disposables);
    domEvent(this.domNode, "dragend")(onDragEnd, null, disposables);
    StaticDND.CurrentDragAndDropData = new DragAndDropData("vscode-ui");
    disposables.add(toDisposable(() => StaticDND.CurrentDragAndDropData = void 0));
  }
  onDidSpliceModel() {
    if (!this._enabled || this.pattern.length === 0) {
      return;
    }
    this.tree.refilter();
    this.render();
  }
  onDidChangeFilterOnType() {
    this.tree.updateOptions({filterOnType: this.filterOnTypeDomNode.checked});
    this.tree.refilter();
    this.tree.domFocus();
    this.render();
    this.updateFilterOnTypeTitleAndIcon();
  }
  updateFilterOnTypeTitleAndIcon() {
    if (this.filterOnType) {
      removeClasses(this.filterOnTypeDomNode, treeFilterOnTypeOffIcon.classNames);
      addClasses(this.filterOnTypeDomNode, treeFilterOnTypeOnIcon.classNames);
      this.filterOnTypeDomNode.title = localize("disable filter on type", "Disable Filter on Type");
    } else {
      removeClasses(this.filterOnTypeDomNode, treeFilterOnTypeOnIcon.classNames);
      addClasses(this.filterOnTypeDomNode, treeFilterOnTypeOffIcon.classNames);
      this.filterOnTypeDomNode.title = localize("enable filter on type", "Enable Filter on Type");
    }
  }
  render() {
    const noMatches = this.filter.totalCount > 0 && this.filter.matchCount === 0;
    if (this.pattern && this.tree.options.filterOnType && noMatches) {
      this.messageDomNode.textContent = localize("empty", "No elements found");
      this._empty = true;
    } else {
      this.messageDomNode.innerText = "";
      this._empty = false;
    }
    toggleClass(this.domNode, "no-matches", noMatches);
    this.domNode.title = localize("found", "Matched {0} out of {1} elements", this.filter.matchCount, this.filter.totalCount);
    this.labelDomNode.textContent = this.pattern.length > 16 ? "…" + this.pattern.substr(this.pattern.length - 16) : this.pattern;
    this._onDidChangeEmptyState.fire(this._empty);
  }
  shouldAllowFocus(node) {
    if (!this.enabled || !this.pattern || this.filterOnType) {
      return true;
    }
    if (this.filter.totalCount > 0 && this.filter.matchCount <= 1) {
      return true;
    }
    return !FuzzyScore.isDefault(node.filterData);
  }
  dispose() {
    if (this._enabled) {
      this.domNode.remove();
      this.enabledDisposables.dispose();
      this._enabled = false;
      this.triggered = false;
    }
    this._onDidChangePattern.dispose();
    dispose(this.disposables);
  }
};
function asTreeMouseEvent(event) {
  let target = TreeMouseEventTarget.Unknown;
  if (hasParentWithClass(event.browserEvent.target, "monaco-tl-twistie", "monaco-tl-row")) {
    target = TreeMouseEventTarget.Twistie;
  } else if (hasParentWithClass(event.browserEvent.target, "monaco-tl-contents", "monaco-tl-row")) {
    target = TreeMouseEventTarget.Element;
  }
  return {
    browserEvent: event.browserEvent,
    element: event.element ? event.element.element : null,
    target
  };
}
function dfs(node, fn) {
  fn(node);
  node.children.forEach((child) => dfs(child, fn));
}
var Trait$1 = class {
  constructor(identityProvider) {
    this.identityProvider = identityProvider;
    this.nodes = [];
    this._onDidChange = new Emitter();
    this.onDidChange = this._onDidChange.event;
  }
  get nodeSet() {
    if (!this._nodeSet) {
      this._nodeSet = this.createNodeSet();
    }
    return this._nodeSet;
  }
  set(nodes, browserEvent) {
    if (equals(this.nodes, nodes)) {
      return;
    }
    this._set(nodes, false, browserEvent);
  }
  _set(nodes, silent, browserEvent) {
    this.nodes = [...nodes];
    this.elements = void 0;
    this._nodeSet = void 0;
    if (!silent) {
      const that = this;
      this._onDidChange.fire({get elements() {
        return that.get();
      }, browserEvent});
    }
  }
  get() {
    if (!this.elements) {
      this.elements = this.nodes.map((node) => node.element);
    }
    return [...this.elements];
  }
  getNodes() {
    return this.nodes;
  }
  has(node) {
    return this.nodeSet.has(node);
  }
  onDidModelSplice({insertedNodes, deletedNodes}) {
    if (!this.identityProvider) {
      const set3 = this.createNodeSet();
      const visit = (node) => set3.delete(node);
      deletedNodes.forEach((node) => dfs(node, visit));
      this.set([...set3.values()]);
      return;
    }
    const deletedNodesIdSet = new Set();
    const deletedNodesVisitor = (node) => deletedNodesIdSet.add(this.identityProvider.getId(node.element).toString());
    deletedNodes.forEach((node) => dfs(node, deletedNodesVisitor));
    const insertedNodesMap = new Map();
    const insertedNodesVisitor = (node) => insertedNodesMap.set(this.identityProvider.getId(node.element).toString(), node);
    insertedNodes.forEach((node) => dfs(node, insertedNodesVisitor));
    const nodes = [];
    for (const node of this.nodes) {
      const id3 = this.identityProvider.getId(node.element).toString();
      const wasDeleted = deletedNodesIdSet.has(id3);
      if (!wasDeleted) {
        nodes.push(node);
      } else {
        const insertedNode = insertedNodesMap.get(id3);
        if (insertedNode) {
          nodes.push(insertedNode);
        }
      }
    }
    this._set(nodes, true);
  }
  createNodeSet() {
    const set3 = new Set();
    for (const node of this.nodes) {
      set3.add(node);
    }
    return set3;
  }
};
var TreeNodeListMouseController = class extends MouseController {
  constructor(list3, tree) {
    super(list3);
    this.tree = tree;
  }
  onViewPointer(e2) {
    if (isInputElement(e2.browserEvent.target) || isMonacoEditor(e2.browserEvent.target)) {
      return;
    }
    const node = e2.element;
    if (!node) {
      return super.onViewPointer(e2);
    }
    if (this.isSelectionRangeChangeEvent(e2) || this.isSelectionSingleChangeEvent(e2)) {
      return super.onViewPointer(e2);
    }
    const target = e2.browserEvent.target;
    const onTwistie = hasClass(target, "monaco-tl-twistie") || hasClass(target, "monaco-icon-label") && hasClass(target, "folder-icon") && e2.browserEvent.offsetX < 16;
    let expandOnlyOnTwistieClick = false;
    if (typeof this.tree.expandOnlyOnTwistieClick === "function") {
      expandOnlyOnTwistieClick = this.tree.expandOnlyOnTwistieClick(node.element);
    } else {
      expandOnlyOnTwistieClick = !!this.tree.expandOnlyOnTwistieClick;
    }
    if (expandOnlyOnTwistieClick && !onTwistie) {
      return super.onViewPointer(e2);
    }
    if (this.tree.expandOnlyOnDoubleClick && e2.browserEvent.detail !== 2 && !onTwistie) {
      return super.onViewPointer(e2);
    }
    if (node.collapsible) {
      const model = this.tree.model;
      const location2 = model.getNodeLocation(node);
      const recursive = e2.browserEvent.altKey;
      model.setCollapsed(location2, void 0, recursive);
      if (expandOnlyOnTwistieClick && onTwistie) {
        return;
      }
    }
    super.onViewPointer(e2);
  }
  onDoubleClick(e2) {
    const onTwistie = hasClass(e2.browserEvent.target, "monaco-tl-twistie");
    if (onTwistie) {
      return;
    }
    super.onDoubleClick(e2);
  }
};
var TreeNodeList = class extends List2 {
  constructor(user, container, virtualDelegate, renderers, focusTrait, selectionTrait, options) {
    super(user, container, virtualDelegate, renderers, options);
    this.focusTrait = focusTrait;
    this.selectionTrait = selectionTrait;
  }
  createMouseController(options) {
    return new TreeNodeListMouseController(this, options.tree);
  }
  splice(start3, deleteCount, elements = []) {
    super.splice(start3, deleteCount, elements);
    if (elements.length === 0) {
      return;
    }
    const additionalFocus = [];
    const additionalSelection = [];
    elements.forEach((node, index3) => {
      if (this.focusTrait.has(node)) {
        additionalFocus.push(start3 + index3);
      }
      if (this.selectionTrait.has(node)) {
        additionalSelection.push(start3 + index3);
      }
    });
    if (additionalFocus.length > 0) {
      super.setFocus(distinctES6([...super.getFocus(), ...additionalFocus]));
    }
    if (additionalSelection.length > 0) {
      super.setSelection(distinctES6([...super.getSelection(), ...additionalSelection]));
    }
  }
  setFocus(indexes, browserEvent, fromAPI = false) {
    super.setFocus(indexes, browserEvent);
    if (!fromAPI) {
      this.focusTrait.set(indexes.map((i3) => this.element(i3)), browserEvent);
    }
  }
  setSelection(indexes, browserEvent, fromAPI = false) {
    super.setSelection(indexes, browserEvent);
    if (!fromAPI) {
      this.selectionTrait.set(indexes.map((i3) => this.element(i3)), browserEvent);
    }
  }
};
var AbstractTree = class {
  constructor(user, container, delegate, renderers, _options = {}) {
    this._options = _options;
    this.eventBufferer = new EventBufferer();
    this.disposables = new DisposableStore();
    this._onWillRefilter = new Emitter();
    this.onWillRefilter = this._onWillRefilter.event;
    this._onDidUpdateOptions = new Emitter();
    const treeDelegate = new ComposedTreeDelegate(delegate);
    const onDidChangeCollapseStateRelay = new Relay();
    const onDidChangeActiveNodes = new Relay();
    const activeNodes = new EventCollection(onDidChangeActiveNodes.event);
    this.renderers = renderers.map((r3) => new TreeRenderer(r3, () => this.model, onDidChangeCollapseStateRelay.event, activeNodes, _options));
    for (let r3 of this.renderers) {
      this.disposables.add(r3);
    }
    let filter3;
    if (_options.keyboardNavigationLabelProvider) {
      filter3 = new TypeFilter(this, _options.keyboardNavigationLabelProvider, _options.filter);
      _options = Object.assign(Object.assign({}, _options), {filter: filter3});
      this.disposables.add(filter3);
    }
    this.focus = new Trait$1(_options.identityProvider);
    this.selection = new Trait$1(_options.identityProvider);
    this.view = new TreeNodeList(user, container, treeDelegate, this.renderers, this.focus, this.selection, Object.assign(Object.assign({}, asListOptions(() => this.model, _options)), {tree: this}));
    this.model = this.createModel(user, this.view, _options);
    onDidChangeCollapseStateRelay.input = this.model.onDidChangeCollapseState;
    const onDidModelSplice = Event.forEach(this.model.onDidSplice, (e2) => {
      this.eventBufferer.bufferEvents(() => {
        this.focus.onDidModelSplice(e2);
        this.selection.onDidModelSplice(e2);
      });
    });
    onDidModelSplice(() => null, null, this.disposables);
    onDidChangeActiveNodes.input = Event.chain(Event.any(onDidModelSplice, this.focus.onDidChange, this.selection.onDidChange)).debounce(() => null, 0).map(() => {
      const set3 = new Set();
      for (const node of this.focus.getNodes()) {
        set3.add(node);
      }
      for (const node of this.selection.getNodes()) {
        set3.add(node);
      }
      return [...set3.values()];
    }).event;
    if (_options.keyboardSupport !== false) {
      const onKeyDown = Event.chain(this.view.onKeyDown).filter((e2) => !isInputElement(e2.target)).map((e2) => new StandardKeyboardEvent(e2));
      onKeyDown.filter((e2) => e2.keyCode === 15).on(this.onLeftArrow, this, this.disposables);
      onKeyDown.filter((e2) => e2.keyCode === 17).on(this.onRightArrow, this, this.disposables);
      onKeyDown.filter((e2) => e2.keyCode === 10).on(this.onSpace, this, this.disposables);
    }
    if (_options.keyboardNavigationLabelProvider) {
      const delegate2 = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate;
      this.typeFilterController = new TypeFilterController(this, this.model, this.view, filter3, delegate2);
      this.focusNavigationFilter = (node) => this.typeFilterController.shouldAllowFocus(node);
      this.disposables.add(this.typeFilterController);
    }
    this.styleElement = createStyleSheet(this.view.getHTMLElement());
    toggleClass(this.getHTMLElement(), "always", this._options.renderIndentGuides === RenderIndentGuides.Always);
  }
  get onDidChangeFocus() {
    return this.eventBufferer.wrapEvent(this.focus.onDidChange);
  }
  get onDidChangeSelection() {
    return this.eventBufferer.wrapEvent(this.selection.onDidChange);
  }
  get onMouseDblClick() {
    return Event.map(this.view.onMouseDblClick, asTreeMouseEvent);
  }
  get onPointer() {
    return Event.map(this.view.onPointer, asTreeMouseEvent);
  }
  get onDidFocus() {
    return this.view.onDidFocus;
  }
  get onDidChangeCollapseState() {
    return this.model.onDidChangeCollapseState;
  }
  get expandOnlyOnDoubleClick() {
    var _a;
    return (_a = this._options.expandOnlyOnDoubleClick) !== null && _a !== void 0 ? _a : false;
  }
  get expandOnlyOnTwistieClick() {
    return typeof this._options.expandOnlyOnTwistieClick === "undefined" ? false : this._options.expandOnlyOnTwistieClick;
  }
  get onDidDispose() {
    return this.view.onDidDispose;
  }
  updateOptions(optionsUpdate = {}) {
    this._options = Object.assign(Object.assign({}, this._options), optionsUpdate);
    for (const renderer of this.renderers) {
      renderer.updateOptions(optionsUpdate);
    }
    this.view.updateOptions({
      enableKeyboardNavigation: this._options.simpleKeyboardNavigation,
      automaticKeyboardNavigation: this._options.automaticKeyboardNavigation,
      smoothScrolling: this._options.smoothScrolling,
      horizontalScrolling: this._options.horizontalScrolling
    });
    if (this.typeFilterController) {
      this.typeFilterController.updateOptions(this._options);
    }
    this._onDidUpdateOptions.fire(this._options);
    toggleClass(this.getHTMLElement(), "always", this._options.renderIndentGuides === RenderIndentGuides.Always);
  }
  get options() {
    return this._options;
  }
  getHTMLElement() {
    return this.view.getHTMLElement();
  }
  get scrollTop() {
    return this.view.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.view.scrollTop = scrollTop;
  }
  domFocus() {
    this.view.domFocus();
  }
  layout(height, width2) {
    this.view.layout(height, width2);
  }
  style(styles6) {
    const suffix = `.${this.view.domId}`;
    const content2 = [];
    if (styles6.treeIndentGuidesStroke) {
      content2.push(`.monaco-list${suffix}:hover .monaco-tl-indent > .indent-guide, .monaco-list${suffix}.always .monaco-tl-indent > .indent-guide  { border-color: ${styles6.treeIndentGuidesStroke.transparent(0.4)}; }`);
      content2.push(`.monaco-list${suffix} .monaco-tl-indent > .indent-guide.active { border-color: ${styles6.treeIndentGuidesStroke}; }`);
    }
    const newStyles = content2.join("\n");
    if (newStyles !== this.styleElement.innerHTML) {
      this.styleElement.innerHTML = newStyles;
    }
    this.view.style(styles6);
  }
  collapse(location2, recursive = false) {
    return this.model.setCollapsed(location2, true, recursive);
  }
  expand(location2, recursive = false) {
    return this.model.setCollapsed(location2, false, recursive);
  }
  isCollapsible(location2) {
    return this.model.isCollapsible(location2);
  }
  setCollapsible(location2, collapsible2) {
    return this.model.setCollapsible(location2, collapsible2);
  }
  isCollapsed(location2) {
    return this.model.isCollapsed(location2);
  }
  refilter() {
    this._onWillRefilter.fire(void 0);
    this.model.refilter();
  }
  setSelection(elements, browserEvent) {
    const nodes = elements.map((e2) => this.model.getNode(e2));
    this.selection.set(nodes, browserEvent);
    const indexes = elements.map((e2) => this.model.getListIndex(e2)).filter((i3) => i3 > -1);
    this.view.setSelection(indexes, browserEvent, true);
  }
  getSelection() {
    return this.selection.get();
  }
  setFocus(elements, browserEvent) {
    const nodes = elements.map((e2) => this.model.getNode(e2));
    this.focus.set(nodes, browserEvent);
    const indexes = elements.map((e2) => this.model.getListIndex(e2)).filter((i3) => i3 > -1);
    this.view.setFocus(indexes, browserEvent, true);
  }
  focusNext(n3 = 1, loop = false, browserEvent, filter3 = this.focusNavigationFilter) {
    this.view.focusNext(n3, loop, browserEvent, filter3);
  }
  getFocus() {
    return this.focus.get();
  }
  reveal(location2, relativeTop) {
    this.model.expandTo(location2);
    const index3 = this.model.getListIndex(location2);
    if (index3 === -1) {
      return;
    }
    this.view.reveal(index3, relativeTop);
  }
  getRelativeTop(location2) {
    const index3 = this.model.getListIndex(location2);
    if (index3 === -1) {
      return null;
    }
    return this.view.getRelativeTop(index3);
  }
  onLeftArrow(e2) {
    e2.preventDefault();
    e2.stopPropagation();
    const nodes = this.view.getFocusedElements();
    if (nodes.length === 0) {
      return;
    }
    const node = nodes[0];
    const location2 = this.model.getNodeLocation(node);
    const didChange = this.model.setCollapsed(location2, true);
    if (!didChange) {
      const parentLocation = this.model.getParentNodeLocation(location2);
      if (!parentLocation) {
        return;
      }
      const parentListIndex = this.model.getListIndex(parentLocation);
      this.view.reveal(parentListIndex);
      this.view.setFocus([parentListIndex]);
    }
  }
  onRightArrow(e2) {
    e2.preventDefault();
    e2.stopPropagation();
    const nodes = this.view.getFocusedElements();
    if (nodes.length === 0) {
      return;
    }
    const node = nodes[0];
    const location2 = this.model.getNodeLocation(node);
    const didChange = this.model.setCollapsed(location2, false);
    if (!didChange) {
      if (!node.children.some((child) => child.visible)) {
        return;
      }
      const [focusedIndex] = this.view.getFocus();
      const firstChildIndex = focusedIndex + 1;
      this.view.reveal(firstChildIndex);
      this.view.setFocus([firstChildIndex]);
    }
  }
  onSpace(e2) {
    e2.preventDefault();
    e2.stopPropagation();
    const nodes = this.view.getFocusedElements();
    if (nodes.length === 0) {
      return;
    }
    const node = nodes[0];
    const location2 = this.model.getNodeLocation(node);
    const recursive = e2.browserEvent.altKey;
    this.model.setCollapsed(location2, void 0, recursive);
  }
  dispose() {
    dispose(this.disposables);
    this.view.dispose();
  }
};
var ObjectTreeModel = class {
  constructor(user, list3, options = {}) {
    this.user = user;
    this.rootRef = null;
    this.nodes = new Map();
    this.nodesByIdentity = new Map();
    this.model = new IndexTreeModel(user, list3, null, options);
    this.onDidSplice = this.model.onDidSplice;
    this.onDidChangeCollapseState = this.model.onDidChangeCollapseState;
    this.onDidChangeRenderNodeCount = this.model.onDidChangeRenderNodeCount;
    if (options.sorter) {
      this.sorter = {
        compare(a2, b2) {
          return options.sorter.compare(a2.element, b2.element);
        }
      };
    }
    this.identityProvider = options.identityProvider;
  }
  setChildren(element, children2 = Iterable.empty(), onDidCreateNode, onDidDeleteNode) {
    const location2 = this.getElementLocation(element);
    this._setChildren(location2, this.preserveCollapseState(children2), onDidCreateNode, onDidDeleteNode);
  }
  _setChildren(location2, children2 = Iterable.empty(), onDidCreateNode, onDidDeleteNode) {
    const insertedElements = new Set();
    const insertedElementIds = new Set();
    const _onDidCreateNode = (node) => {
      if (node.element === null) {
        return;
      }
      const tnode = node;
      insertedElements.add(tnode.element);
      this.nodes.set(tnode.element, tnode);
      if (this.identityProvider) {
        const id3 = this.identityProvider.getId(tnode.element).toString();
        insertedElementIds.add(id3);
        this.nodesByIdentity.set(id3, tnode);
      }
      if (onDidCreateNode) {
        onDidCreateNode(tnode);
      }
    };
    const _onDidDeleteNode = (node) => {
      if (node.element === null) {
        return;
      }
      const tnode = node;
      if (!insertedElements.has(tnode.element)) {
        this.nodes.delete(tnode.element);
      }
      if (this.identityProvider) {
        const id3 = this.identityProvider.getId(tnode.element).toString();
        if (!insertedElementIds.has(id3)) {
          this.nodesByIdentity.delete(id3);
        }
      }
      if (onDidDeleteNode) {
        onDidDeleteNode(tnode);
      }
    };
    this.model.splice([...location2, 0], Number.MAX_VALUE, children2, _onDidCreateNode, _onDidDeleteNode);
  }
  preserveCollapseState(elements = Iterable.empty()) {
    if (this.sorter) {
      elements = mergeSort([...elements], this.sorter.compare.bind(this.sorter));
    }
    return Iterable.map(elements, (treeElement) => {
      let node = this.nodes.get(treeElement.element);
      if (!node && this.identityProvider) {
        const id3 = this.identityProvider.getId(treeElement.element).toString();
        node = this.nodesByIdentity.get(id3);
      }
      if (!node) {
        return Object.assign(Object.assign({}, treeElement), {children: this.preserveCollapseState(treeElement.children)});
      }
      const collapsible2 = typeof treeElement.collapsible === "boolean" ? treeElement.collapsible : node.collapsible;
      const collapsed = typeof treeElement.collapsed !== "undefined" ? treeElement.collapsed : node.collapsed;
      return Object.assign(Object.assign({}, treeElement), {
        collapsible: collapsible2,
        collapsed,
        children: this.preserveCollapseState(treeElement.children)
      });
    });
  }
  rerender(element) {
    const location2 = this.getElementLocation(element);
    this.model.rerender(location2);
  }
  has(element) {
    return this.nodes.has(element);
  }
  getListIndex(element) {
    const location2 = this.getElementLocation(element);
    return this.model.getListIndex(location2);
  }
  getListRenderCount(element) {
    const location2 = this.getElementLocation(element);
    return this.model.getListRenderCount(location2);
  }
  isCollapsible(element) {
    const location2 = this.getElementLocation(element);
    return this.model.isCollapsible(location2);
  }
  setCollapsible(element, collapsible2) {
    const location2 = this.getElementLocation(element);
    return this.model.setCollapsible(location2, collapsible2);
  }
  isCollapsed(element) {
    const location2 = this.getElementLocation(element);
    return this.model.isCollapsed(location2);
  }
  setCollapsed(element, collapsed, recursive) {
    const location2 = this.getElementLocation(element);
    return this.model.setCollapsed(location2, collapsed, recursive);
  }
  expandTo(element) {
    const location2 = this.getElementLocation(element);
    this.model.expandTo(location2);
  }
  refilter() {
    this.model.refilter();
  }
  getNode(element = null) {
    if (element === null) {
      return this.model.getNode(this.model.rootRef);
    }
    const node = this.nodes.get(element);
    if (!node) {
      throw new TreeError(this.user, `Tree element not found: ${element}`);
    }
    return node;
  }
  getNodeLocation(node) {
    return node.element;
  }
  getParentNodeLocation(element) {
    if (element === null) {
      throw new TreeError(this.user, `Invalid getParentNodeLocation call`);
    }
    const node = this.nodes.get(element);
    if (!node) {
      throw new TreeError(this.user, `Tree element not found: ${element}`);
    }
    const location2 = this.model.getNodeLocation(node);
    const parentLocation = this.model.getParentNodeLocation(location2);
    const parent = this.model.getNode(parentLocation);
    return parent.element;
  }
  getElementLocation(element) {
    if (element === null) {
      return [];
    }
    const node = this.nodes.get(element);
    if (!node) {
      throw new TreeError(this.user, `Tree element not found: ${element}`);
    }
    return this.model.getNodeLocation(node);
  }
};
function noCompress(element) {
  const elements = [element.element];
  const incompressible = element.incompressible || false;
  return {
    element: {elements, incompressible},
    children: Iterable.map(Iterable.from(element.children), noCompress),
    collapsible: element.collapsible,
    collapsed: element.collapsed
  };
}
function compress(element) {
  const elements = [element.element];
  const incompressible = element.incompressible || false;
  let childrenIterator;
  let children2;
  while (true) {
    [children2, childrenIterator] = Iterable.consume(Iterable.from(element.children), 2);
    if (children2.length !== 1) {
      break;
    }
    element = children2[0];
    if (element.incompressible) {
      break;
    }
    elements.push(element.element);
  }
  return {
    element: {elements, incompressible},
    children: Iterable.map(Iterable.concat(children2, childrenIterator), compress),
    collapsible: element.collapsible,
    collapsed: element.collapsed
  };
}
function _decompress(element, index3 = 0) {
  let children2;
  if (index3 < element.element.elements.length - 1) {
    children2 = [_decompress(element, index3 + 1)];
  } else {
    children2 = Iterable.map(Iterable.from(element.children), (el) => _decompress(el, 0));
  }
  if (index3 === 0 && element.element.incompressible) {
    return {
      element: element.element.elements[index3],
      children: children2,
      incompressible: true,
      collapsible: element.collapsible,
      collapsed: element.collapsed
    };
  }
  return {
    element: element.element.elements[index3],
    children: children2,
    collapsible: element.collapsible,
    collapsed: element.collapsed
  };
}
function decompress(element) {
  return _decompress(element, 0);
}
function splice(treeElement, element, children2) {
  if (treeElement.element === element) {
    return Object.assign(Object.assign({}, treeElement), {children: children2});
  }
  return Object.assign(Object.assign({}, treeElement), {children: Iterable.map(Iterable.from(treeElement.children), (e2) => splice(e2, element, children2))});
}
var CompressedObjectTreeModel = class {
  constructor(user, list3, options = {}) {
    this.user = user;
    this.rootRef = null;
    this.nodes = new Map();
    this.model = new ObjectTreeModel(user, list3, options);
    this.enabled = typeof options.compressionEnabled === "undefined" ? true : options.compressionEnabled;
  }
  get onDidSplice() {
    return this.model.onDidSplice;
  }
  get onDidChangeCollapseState() {
    return this.model.onDidChangeCollapseState;
  }
  get onDidChangeRenderNodeCount() {
    return this.model.onDidChangeRenderNodeCount;
  }
  setChildren(element, children2 = Iterable.empty()) {
    if (element === null) {
      const compressedChildren = Iterable.map(children2, this.enabled ? compress : noCompress);
      this._setChildren(null, compressedChildren);
      return;
    }
    const compressedNode = this.nodes.get(element);
    if (!compressedNode) {
      throw new Error("Unknown compressed tree node");
    }
    const node = this.model.getNode(compressedNode);
    const compressedParentNode = this.model.getParentNodeLocation(compressedNode);
    const parent = this.model.getNode(compressedParentNode);
    const decompressedElement = decompress(node);
    const splicedElement = splice(decompressedElement, element, children2);
    const recompressedElement = (this.enabled ? compress : noCompress)(splicedElement);
    const parentChildren = parent.children.map((child) => child === node ? recompressedElement : child);
    this._setChildren(parent.element, parentChildren);
  }
  setCompressionEnabled(enabled) {
    if (enabled === this.enabled) {
      return;
    }
    this.enabled = enabled;
    const root4 = this.model.getNode();
    const rootChildren = root4.children;
    const decompressedRootChildren = Iterable.map(rootChildren, decompress);
    const recompressedRootChildren = Iterable.map(decompressedRootChildren, enabled ? compress : noCompress);
    this._setChildren(null, recompressedRootChildren);
  }
  _setChildren(node, children2) {
    const insertedElements = new Set();
    const _onDidCreateNode = (node2) => {
      for (const element of node2.element.elements) {
        insertedElements.add(element);
        this.nodes.set(element, node2.element);
      }
    };
    const _onDidDeleteNode = (node2) => {
      for (const element of node2.element.elements) {
        if (!insertedElements.has(element)) {
          this.nodes.delete(element);
        }
      }
    };
    this.model.setChildren(node, children2, _onDidCreateNode, _onDidDeleteNode);
  }
  has(element) {
    return this.nodes.has(element);
  }
  getListIndex(location2) {
    const node = this.getCompressedNode(location2);
    return this.model.getListIndex(node);
  }
  getListRenderCount(location2) {
    const node = this.getCompressedNode(location2);
    return this.model.getListRenderCount(node);
  }
  getNode(location2) {
    if (typeof location2 === "undefined") {
      return this.model.getNode();
    }
    const node = this.getCompressedNode(location2);
    return this.model.getNode(node);
  }
  getNodeLocation(node) {
    const compressedNode = this.model.getNodeLocation(node);
    if (compressedNode === null) {
      return null;
    }
    return compressedNode.elements[compressedNode.elements.length - 1];
  }
  getParentNodeLocation(location2) {
    const compressedNode = this.getCompressedNode(location2);
    const parentNode = this.model.getParentNodeLocation(compressedNode);
    if (parentNode === null) {
      return null;
    }
    return parentNode.elements[parentNode.elements.length - 1];
  }
  isCollapsible(location2) {
    const compressedNode = this.getCompressedNode(location2);
    return this.model.isCollapsible(compressedNode);
  }
  setCollapsible(location2, collapsible2) {
    const compressedNode = this.getCompressedNode(location2);
    return this.model.setCollapsible(compressedNode, collapsible2);
  }
  isCollapsed(location2) {
    const compressedNode = this.getCompressedNode(location2);
    return this.model.isCollapsed(compressedNode);
  }
  setCollapsed(location2, collapsed, recursive) {
    const compressedNode = this.getCompressedNode(location2);
    return this.model.setCollapsed(compressedNode, collapsed, recursive);
  }
  expandTo(location2) {
    const compressedNode = this.getCompressedNode(location2);
    this.model.expandTo(compressedNode);
  }
  rerender(location2) {
    const compressedNode = this.getCompressedNode(location2);
    this.model.rerender(compressedNode);
  }
  refilter() {
    this.model.refilter();
  }
  getCompressedNode(element) {
    if (element === null) {
      return null;
    }
    const node = this.nodes.get(element);
    if (!node) {
      throw new TreeError(this.user, `Tree element not found: ${element}`);
    }
    return node;
  }
};
var DefaultElementMapper = (elements) => elements[elements.length - 1];
var CompressedTreeNodeWrapper = class {
  constructor(unwrapper, node) {
    this.unwrapper = unwrapper;
    this.node = node;
  }
  get element() {
    return this.node.element === null ? null : this.unwrapper(this.node.element);
  }
  get children() {
    return this.node.children.map((node) => new CompressedTreeNodeWrapper(this.unwrapper, node));
  }
  get depth() {
    return this.node.depth;
  }
  get visibleChildrenCount() {
    return this.node.visibleChildrenCount;
  }
  get visibleChildIndex() {
    return this.node.visibleChildIndex;
  }
  get collapsible() {
    return this.node.collapsible;
  }
  get collapsed() {
    return this.node.collapsed;
  }
  get visible() {
    return this.node.visible;
  }
  get filterData() {
    return this.node.filterData;
  }
};
function mapList(nodeMapper, list3) {
  return {
    splice(start3, deleteCount, toInsert) {
      list3.splice(start3, deleteCount, toInsert.map((node) => nodeMapper.map(node)));
    },
    updateElementHeight(index3, height) {
      list3.updateElementHeight(index3, height);
    }
  };
}
function mapOptions(compressedNodeUnwrapper, options) {
  return Object.assign(Object.assign({}, options), {sorter: options.sorter && {
    compare(node, otherNode) {
      return options.sorter.compare(node.elements[0], otherNode.elements[0]);
    }
  }, identityProvider: options.identityProvider && {
    getId(node) {
      return options.identityProvider.getId(compressedNodeUnwrapper(node));
    }
  }, filter: options.filter && {
    filter(node, parentVisibility) {
      return options.filter.filter(compressedNodeUnwrapper(node), parentVisibility);
    }
  }});
}
var CompressibleObjectTreeModel = class {
  constructor(user, list3, options = {}) {
    this.rootRef = null;
    this.elementMapper = options.elementMapper || DefaultElementMapper;
    const compressedNodeUnwrapper = (node) => this.elementMapper(node.elements);
    this.nodeMapper = new WeakMapper((node) => new CompressedTreeNodeWrapper(compressedNodeUnwrapper, node));
    this.model = new CompressedObjectTreeModel(user, mapList(this.nodeMapper, list3), mapOptions(compressedNodeUnwrapper, options));
  }
  get onDidSplice() {
    return Event.map(this.model.onDidSplice, ({insertedNodes, deletedNodes}) => ({
      insertedNodes: insertedNodes.map((node) => this.nodeMapper.map(node)),
      deletedNodes: deletedNodes.map((node) => this.nodeMapper.map(node))
    }));
  }
  get onDidChangeCollapseState() {
    return Event.map(this.model.onDidChangeCollapseState, ({node, deep}) => ({
      node: this.nodeMapper.map(node),
      deep
    }));
  }
  get onDidChangeRenderNodeCount() {
    return Event.map(this.model.onDidChangeRenderNodeCount, (node) => this.nodeMapper.map(node));
  }
  setChildren(element, children2 = Iterable.empty()) {
    this.model.setChildren(element, children2);
  }
  setCompressionEnabled(enabled) {
    this.model.setCompressionEnabled(enabled);
  }
  has(location2) {
    return this.model.has(location2);
  }
  getListIndex(location2) {
    return this.model.getListIndex(location2);
  }
  getListRenderCount(location2) {
    return this.model.getListRenderCount(location2);
  }
  getNode(location2) {
    return this.nodeMapper.map(this.model.getNode(location2));
  }
  getNodeLocation(node) {
    return node.element;
  }
  getParentNodeLocation(location2) {
    return this.model.getParentNodeLocation(location2);
  }
  isCollapsible(location2) {
    return this.model.isCollapsible(location2);
  }
  setCollapsible(location2, collapsed) {
    return this.model.setCollapsible(location2, collapsed);
  }
  isCollapsed(location2) {
    return this.model.isCollapsed(location2);
  }
  setCollapsed(location2, collapsed, recursive) {
    return this.model.setCollapsed(location2, collapsed, recursive);
  }
  expandTo(location2) {
    return this.model.expandTo(location2);
  }
  rerender(location2) {
    return this.model.rerender(location2);
  }
  refilter() {
    return this.model.refilter();
  }
  getCompressedTreeNode(location2 = null) {
    return this.model.getNode(location2);
  }
};
var __decorate$f = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var ObjectTree = class extends AbstractTree {
  constructor(user, container, delegate, renderers, options = {}) {
    super(user, container, delegate, renderers, options);
  }
  get onDidChangeCollapseState() {
    return this.model.onDidChangeCollapseState;
  }
  setChildren(element, children2 = Iterable.empty()) {
    this.model.setChildren(element, children2);
  }
  rerender(element) {
    if (element === void 0) {
      this.view.rerender();
      return;
    }
    this.model.rerender(element);
  }
  hasElement(element) {
    return this.model.has(element);
  }
  createModel(user, view, options) {
    return new ObjectTreeModel(user, view, options);
  }
};
var CompressibleRenderer = class {
  constructor(_compressedTreeNodeProvider, renderer) {
    this._compressedTreeNodeProvider = _compressedTreeNodeProvider;
    this.renderer = renderer;
    this.templateId = renderer.templateId;
    if (renderer.onDidChangeTwistieState) {
      this.onDidChangeTwistieState = renderer.onDidChangeTwistieState;
    }
  }
  get compressedTreeNodeProvider() {
    return this._compressedTreeNodeProvider();
  }
  renderTemplate(container) {
    const data2 = this.renderer.renderTemplate(container);
    return {compressedTreeNode: void 0, data: data2};
  }
  renderElement(node, index3, templateData, height) {
    const compressedTreeNode = this.compressedTreeNodeProvider.getCompressedTreeNode(node.element);
    if (compressedTreeNode.element.elements.length === 1) {
      templateData.compressedTreeNode = void 0;
      this.renderer.renderElement(node, index3, templateData.data, height);
    } else {
      templateData.compressedTreeNode = compressedTreeNode;
      this.renderer.renderCompressedElements(compressedTreeNode, index3, templateData.data, height);
    }
  }
  disposeElement(node, index3, templateData, height) {
    if (templateData.compressedTreeNode) {
      if (this.renderer.disposeCompressedElements) {
        this.renderer.disposeCompressedElements(templateData.compressedTreeNode, index3, templateData.data, height);
      }
    } else {
      if (this.renderer.disposeElement) {
        this.renderer.disposeElement(node, index3, templateData.data, height);
      }
    }
  }
  disposeTemplate(templateData) {
    this.renderer.disposeTemplate(templateData.data);
  }
  renderTwistie(element, twistieElement) {
    if (this.renderer.renderTwistie) {
      this.renderer.renderTwistie(element, twistieElement);
    }
  }
};
__decorate$f([
  memoize
], CompressibleRenderer.prototype, "compressedTreeNodeProvider", null);
function asObjectTreeOptions(compressedTreeNodeProvider, options) {
  return options && Object.assign(Object.assign({}, options), {keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
    getKeyboardNavigationLabel(e2) {
      let compressedTreeNode;
      try {
        compressedTreeNode = compressedTreeNodeProvider().getCompressedTreeNode(e2);
      } catch (_a) {
        return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e2);
      }
      if (compressedTreeNode.element.elements.length === 1) {
        return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e2);
      } else {
        return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(compressedTreeNode.element.elements);
      }
    }
  }});
}
var CompressibleObjectTree = class extends ObjectTree {
  constructor(user, container, delegate, renderers, options = {}) {
    const compressedTreeNodeProvider = () => this;
    const compressibleRenderers = renderers.map((r3) => new CompressibleRenderer(compressedTreeNodeProvider, r3));
    super(user, container, delegate, compressibleRenderers, asObjectTreeOptions(compressedTreeNodeProvider, options));
  }
  setChildren(element, children2 = Iterable.empty()) {
    this.model.setChildren(element, children2);
  }
  createModel(user, view, options) {
    return new CompressibleObjectTreeModel(user, view, options);
  }
  updateOptions(optionsUpdate = {}) {
    super.updateOptions(optionsUpdate);
    if (typeof optionsUpdate.compressionEnabled !== "undefined") {
      this.model.setCompressionEnabled(optionsUpdate.compressionEnabled);
    }
  }
  getCompressedTreeNode(element = null) {
    return this.model.getCompressedTreeNode(element);
  }
};
var __awaiter$7 = function(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function createAsyncDataTreeNode(props) {
  return Object.assign(Object.assign({}, props), {children: [], refreshPromise: void 0, stale: true, slow: false, collapsedByDefault: void 0});
}
function isAncestor$1(ancestor, descendant) {
  if (!descendant.parent) {
    return false;
  } else if (descendant.parent === ancestor) {
    return true;
  } else {
    return isAncestor$1(ancestor, descendant.parent);
  }
}
function intersects(node, other) {
  return node === other || isAncestor$1(node, other) || isAncestor$1(other, node);
}
var AsyncDataTreeNodeWrapper = class {
  constructor(node) {
    this.node = node;
  }
  get element() {
    return this.node.element.element;
  }
  get children() {
    return this.node.children.map((node) => new AsyncDataTreeNodeWrapper(node));
  }
  get depth() {
    return this.node.depth;
  }
  get visibleChildrenCount() {
    return this.node.visibleChildrenCount;
  }
  get visibleChildIndex() {
    return this.node.visibleChildIndex;
  }
  get collapsible() {
    return this.node.collapsible;
  }
  get collapsed() {
    return this.node.collapsed;
  }
  get visible() {
    return this.node.visible;
  }
  get filterData() {
    return this.node.filterData;
  }
};
var AsyncDataTreeRenderer = class {
  constructor(renderer, nodeMapper, onDidChangeTwistieState) {
    this.renderer = renderer;
    this.nodeMapper = nodeMapper;
    this.onDidChangeTwistieState = onDidChangeTwistieState;
    this.renderedNodes = new Map();
    this.templateId = renderer.templateId;
  }
  renderTemplate(container) {
    const templateData = this.renderer.renderTemplate(container);
    return {templateData};
  }
  renderElement(node, index3, templateData, height) {
    this.renderer.renderElement(this.nodeMapper.map(node), index3, templateData.templateData, height);
  }
  renderTwistie(element, twistieElement) {
    if (element.slow) {
      addClasses(twistieElement, treeItemLoadingIcon.classNames);
    } else {
      removeClasses(twistieElement, treeItemLoadingIcon.classNames);
    }
    return false;
  }
  disposeElement(node, index3, templateData, height) {
    if (this.renderer.disposeElement) {
      this.renderer.disposeElement(this.nodeMapper.map(node), index3, templateData.templateData, height);
    }
  }
  disposeTemplate(templateData) {
    this.renderer.disposeTemplate(templateData.templateData);
  }
  dispose() {
    this.renderedNodes.clear();
  }
};
function asTreeEvent(e2) {
  return {
    browserEvent: e2.browserEvent,
    elements: e2.elements.map((e3) => e3.element)
  };
}
function asTreeMouseEvent$1(e2) {
  return {
    browserEvent: e2.browserEvent,
    element: e2.element && e2.element.element,
    target: e2.target
  };
}
var AsyncDataTreeElementsDragAndDropData = class extends ElementsDragAndDropData {
  constructor(data2) {
    super(data2.elements.map((node) => node.element));
    this.data = data2;
  }
};
function asAsyncDataTreeDragAndDropData(data2) {
  if (data2 instanceof ElementsDragAndDropData) {
    return new AsyncDataTreeElementsDragAndDropData(data2);
  }
  return data2;
}
var AsyncDataTreeNodeListDragAndDrop = class {
  constructor(dnd) {
    this.dnd = dnd;
  }
  getDragURI(node) {
    return this.dnd.getDragURI(node.element);
  }
  getDragLabel(nodes, originalEvent) {
    if (this.dnd.getDragLabel) {
      return this.dnd.getDragLabel(nodes.map((node) => node.element), originalEvent);
    }
    return void 0;
  }
  onDragStart(data2, originalEvent) {
    if (this.dnd.onDragStart) {
      this.dnd.onDragStart(asAsyncDataTreeDragAndDropData(data2), originalEvent);
    }
  }
  onDragOver(data2, targetNode, targetIndex, originalEvent, raw = true) {
    return this.dnd.onDragOver(asAsyncDataTreeDragAndDropData(data2), targetNode && targetNode.element, targetIndex, originalEvent);
  }
  drop(data2, targetNode, targetIndex, originalEvent) {
    this.dnd.drop(asAsyncDataTreeDragAndDropData(data2), targetNode && targetNode.element, targetIndex, originalEvent);
  }
  onDragEnd(originalEvent) {
    if (this.dnd.onDragEnd) {
      this.dnd.onDragEnd(originalEvent);
    }
  }
};
function asObjectTreeOptions$1(options) {
  return options && Object.assign(Object.assign({}, options), {collapseByDefault: true, identityProvider: options.identityProvider && {
    getId(el) {
      return options.identityProvider.getId(el.element);
    }
  }, dnd: options.dnd && new AsyncDataTreeNodeListDragAndDrop(options.dnd), multipleSelectionController: options.multipleSelectionController && {
    isSelectionSingleChangeEvent(e2) {
      return options.multipleSelectionController.isSelectionSingleChangeEvent(Object.assign(Object.assign({}, e2), {element: e2.element}));
    },
    isSelectionRangeChangeEvent(e2) {
      return options.multipleSelectionController.isSelectionRangeChangeEvent(Object.assign(Object.assign({}, e2), {element: e2.element}));
    }
  }, accessibilityProvider: options.accessibilityProvider && Object.assign(Object.assign({}, options.accessibilityProvider), {
    getPosInSet: void 0,
    getSetSize: void 0,
    getRole: options.accessibilityProvider.getRole ? (el) => {
      return options.accessibilityProvider.getRole(el.element);
    } : () => "treeitem",
    isChecked: options.accessibilityProvider.isChecked ? (e2) => {
      var _a;
      return !!((_a = options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.isChecked(e2.element));
    } : void 0,
    getAriaLabel(e2) {
      return options.accessibilityProvider.getAriaLabel(e2.element);
    },
    getWidgetAriaLabel() {
      return options.accessibilityProvider.getWidgetAriaLabel();
    },
    getWidgetRole: options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => "tree",
    getAriaLevel: options.accessibilityProvider.getAriaLevel && ((node) => {
      return options.accessibilityProvider.getAriaLevel(node.element);
    }),
    getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && ((node) => {
      return options.accessibilityProvider.getActiveDescendantId(node.element);
    })
  }), filter: options.filter && {
    filter(e2, parentVisibility) {
      return options.filter.filter(e2.element, parentVisibility);
    }
  }, keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, options.keyboardNavigationLabelProvider), {getKeyboardNavigationLabel(e2) {
    return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e2.element);
  }}), sorter: void 0, expandOnlyOnTwistieClick: typeof options.expandOnlyOnTwistieClick === "undefined" ? void 0 : typeof options.expandOnlyOnTwistieClick !== "function" ? options.expandOnlyOnTwistieClick : (e2) => options.expandOnlyOnTwistieClick(e2.element), additionalScrollHeight: options.additionalScrollHeight});
}
function dfs$1(node, fn) {
  fn(node);
  node.children.forEach((child) => dfs$1(child, fn));
}
var AsyncDataTree = class {
  constructor(user, container, delegate, renderers, dataSource, options = {}) {
    this.user = user;
    this.dataSource = dataSource;
    this.nodes = new Map();
    this.subTreeRefreshPromises = new Map();
    this.refreshPromises = new Map();
    this._onDidRender = new Emitter();
    this._onDidChangeNodeSlowState = new Emitter();
    this.nodeMapper = new WeakMapper((node) => new AsyncDataTreeNodeWrapper(node));
    this.disposables = new DisposableStore();
    this.identityProvider = options.identityProvider;
    this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === "undefined" ? false : options.autoExpandSingleChildren;
    this.sorter = options.sorter;
    this.collapseByDefault = options.collapseByDefault;
    this.tree = this.createTree(user, container, delegate, renderers, options);
    this.root = createAsyncDataTreeNode({
      element: void 0,
      parent: null,
      hasChildren: true
    });
    if (this.identityProvider) {
      this.root = Object.assign(Object.assign({}, this.root), {id: null});
    }
    this.nodes.set(null, this.root);
    this.tree.onDidChangeCollapseState(this._onDidChangeCollapseState, this, this.disposables);
  }
  get onDidChangeFocus() {
    return Event.map(this.tree.onDidChangeFocus, asTreeEvent);
  }
  get onDidChangeSelection() {
    return Event.map(this.tree.onDidChangeSelection, asTreeEvent);
  }
  get onMouseDblClick() {
    return Event.map(this.tree.onMouseDblClick, asTreeMouseEvent$1);
  }
  get onPointer() {
    return Event.map(this.tree.onPointer, asTreeMouseEvent$1);
  }
  get onDidFocus() {
    return this.tree.onDidFocus;
  }
  get onDidDispose() {
    return this.tree.onDidDispose;
  }
  createTree(user, container, delegate, renderers, options) {
    const objectTreeDelegate = new ComposedTreeDelegate(delegate);
    const objectTreeRenderers = renderers.map((r3) => new AsyncDataTreeRenderer(r3, this.nodeMapper, this._onDidChangeNodeSlowState.event));
    const objectTreeOptions = asObjectTreeOptions$1(options) || {};
    return new ObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
  }
  updateOptions(options = {}) {
    this.tree.updateOptions(options);
  }
  getHTMLElement() {
    return this.tree.getHTMLElement();
  }
  get scrollTop() {
    return this.tree.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.tree.scrollTop = scrollTop;
  }
  domFocus() {
    this.tree.domFocus();
  }
  layout(height, width2) {
    this.tree.layout(height, width2);
  }
  style(styles6) {
    this.tree.style(styles6);
  }
  getInput() {
    return this.root.element;
  }
  setInput(input, viewState) {
    return __awaiter$7(this, void 0, void 0, function* () {
      this.refreshPromises.forEach((promise) => promise.cancel());
      this.refreshPromises.clear();
      this.root.element = input;
      const viewStateContext = viewState && {viewState, focus: [], selection: []};
      yield this._updateChildren(input, true, false, viewStateContext);
      if (viewStateContext) {
        this.tree.setFocus(viewStateContext.focus);
        this.tree.setSelection(viewStateContext.selection);
      }
      if (viewState && typeof viewState.scrollTop === "number") {
        this.scrollTop = viewState.scrollTop;
      }
    });
  }
  _updateChildren(element = this.root.element, recursive = true, rerender = false, viewStateContext) {
    return __awaiter$7(this, void 0, void 0, function* () {
      if (typeof this.root.element === "undefined") {
        throw new TreeError(this.user, "Tree input not set");
      }
      if (this.root.refreshPromise) {
        yield this.root.refreshPromise;
        yield Event.toPromise(this._onDidRender.event);
      }
      const node = this.getDataNode(element);
      yield this.refreshAndRenderNode(node, recursive, viewStateContext);
      if (rerender) {
        try {
          this.tree.rerender(node);
        } catch (_a) {
        }
      }
    });
  }
  rerender(element) {
    if (element === void 0 || element === this.root.element) {
      this.tree.rerender();
      return;
    }
    const node = this.getDataNode(element);
    this.tree.rerender(node);
  }
  collapse(element, recursive = false) {
    const node = this.getDataNode(element);
    return this.tree.collapse(node === this.root ? null : node, recursive);
  }
  expand(element, recursive = false) {
    return __awaiter$7(this, void 0, void 0, function* () {
      if (typeof this.root.element === "undefined") {
        throw new TreeError(this.user, "Tree input not set");
      }
      if (this.root.refreshPromise) {
        yield this.root.refreshPromise;
        yield Event.toPromise(this._onDidRender.event);
      }
      const node = this.getDataNode(element);
      if (this.tree.hasElement(node) && !this.tree.isCollapsible(node)) {
        return false;
      }
      if (node.refreshPromise) {
        yield this.root.refreshPromise;
        yield Event.toPromise(this._onDidRender.event);
      }
      if (node !== this.root && !node.refreshPromise && !this.tree.isCollapsed(node)) {
        return false;
      }
      const result = this.tree.expand(node === this.root ? null : node, recursive);
      if (node.refreshPromise) {
        yield this.root.refreshPromise;
        yield Event.toPromise(this._onDidRender.event);
      }
      return result;
    });
  }
  setSelection(elements, browserEvent) {
    const nodes = elements.map((e2) => this.getDataNode(e2));
    this.tree.setSelection(nodes, browserEvent);
  }
  getSelection() {
    const nodes = this.tree.getSelection();
    return nodes.map((n3) => n3.element);
  }
  setFocus(elements, browserEvent) {
    const nodes = elements.map((e2) => this.getDataNode(e2));
    this.tree.setFocus(nodes, browserEvent);
  }
  getFocus() {
    const nodes = this.tree.getFocus();
    return nodes.map((n3) => n3.element);
  }
  reveal(element, relativeTop) {
    this.tree.reveal(this.getDataNode(element), relativeTop);
  }
  getDataNode(element) {
    const node = this.nodes.get(element === this.root.element ? null : element);
    if (!node) {
      throw new TreeError(this.user, `Data tree node not found: ${element}`);
    }
    return node;
  }
  refreshAndRenderNode(node, recursive, viewStateContext) {
    return __awaiter$7(this, void 0, void 0, function* () {
      yield this.refreshNode(node, recursive, viewStateContext);
      this.render(node, viewStateContext);
    });
  }
  refreshNode(node, recursive, viewStateContext) {
    return __awaiter$7(this, void 0, void 0, function* () {
      let result;
      this.subTreeRefreshPromises.forEach((refreshPromise, refreshNode) => {
        if (!result && intersects(refreshNode, node)) {
          result = refreshPromise.then(() => this.refreshNode(node, recursive, viewStateContext));
        }
      });
      if (result) {
        return result;
      }
      return this.doRefreshSubTree(node, recursive, viewStateContext);
    });
  }
  doRefreshSubTree(node, recursive, viewStateContext) {
    return __awaiter$7(this, void 0, void 0, function* () {
      let done;
      node.refreshPromise = new Promise((c3) => done = c3);
      this.subTreeRefreshPromises.set(node, node.refreshPromise);
      node.refreshPromise.finally(() => {
        node.refreshPromise = void 0;
        this.subTreeRefreshPromises.delete(node);
      });
      try {
        const childrenToRefresh = yield this.doRefreshNode(node, recursive, viewStateContext);
        node.stale = false;
        yield Promise.all(childrenToRefresh.map((child) => this.doRefreshSubTree(child, recursive, viewStateContext)));
      } finally {
        done();
      }
    });
  }
  doRefreshNode(node, recursive, viewStateContext) {
    return __awaiter$7(this, void 0, void 0, function* () {
      node.hasChildren = !!this.dataSource.hasChildren(node.element);
      let childrenPromise;
      if (!node.hasChildren) {
        childrenPromise = Promise.resolve(Iterable.empty());
      } else {
        const slowTimeout = timeout(800);
        slowTimeout.then(() => {
          node.slow = true;
          this._onDidChangeNodeSlowState.fire(node);
        }, (_23) => null);
        childrenPromise = this.doGetChildren(node).finally(() => slowTimeout.cancel());
      }
      try {
        const children2 = yield childrenPromise;
        return this.setChildren(node, children2, recursive, viewStateContext);
      } catch (err) {
        if (node !== this.root) {
          this.tree.collapse(node === this.root ? null : node);
        }
        if (isPromiseCanceledError(err)) {
          return [];
        }
        throw err;
      } finally {
        if (node.slow) {
          node.slow = false;
          this._onDidChangeNodeSlowState.fire(node);
        }
      }
    });
  }
  doGetChildren(node) {
    let result = this.refreshPromises.get(node);
    if (result) {
      return result;
    }
    result = createCancelablePromise(() => __awaiter$7(this, void 0, void 0, function* () {
      const children2 = yield this.dataSource.getChildren(node.element);
      return this.processChildren(children2);
    }));
    this.refreshPromises.set(node, result);
    return result.finally(() => {
      this.refreshPromises.delete(node);
    });
  }
  _onDidChangeCollapseState({node, deep}) {
    if (node.element === null) {
      return;
    }
    if (!node.collapsed && node.element.stale) {
      if (deep) {
        this.collapse(node.element.element);
      } else {
        this.refreshAndRenderNode(node.element, false).catch(onUnexpectedError);
      }
    }
  }
  setChildren(node, childrenElementsIterable, recursive, viewStateContext) {
    const childrenElements = [...childrenElementsIterable];
    if (node.children.length === 0 && childrenElements.length === 0) {
      return [];
    }
    const nodesToForget = new Map();
    const childrenTreeNodesById = new Map();
    for (const child of node.children) {
      nodesToForget.set(child.element, child);
      if (this.identityProvider) {
        const collapsed = this.tree.isCollapsed(child);
        childrenTreeNodesById.set(child.id, {node: child, collapsed});
      }
    }
    const childrenToRefresh = [];
    const children2 = childrenElements.map((element) => {
      const hasChildren2 = !!this.dataSource.hasChildren(element);
      if (!this.identityProvider) {
        const asyncDataTreeNode = createAsyncDataTreeNode({element, parent: node, hasChildren: hasChildren2});
        if (hasChildren2 && this.collapseByDefault && !this.collapseByDefault(element)) {
          asyncDataTreeNode.collapsedByDefault = false;
          childrenToRefresh.push(asyncDataTreeNode);
        }
        return asyncDataTreeNode;
      }
      const id3 = this.identityProvider.getId(element).toString();
      const result = childrenTreeNodesById.get(id3);
      if (result) {
        const asyncDataTreeNode = result.node;
        nodesToForget.delete(asyncDataTreeNode.element);
        this.nodes.delete(asyncDataTreeNode.element);
        this.nodes.set(element, asyncDataTreeNode);
        asyncDataTreeNode.element = element;
        asyncDataTreeNode.hasChildren = hasChildren2;
        if (recursive) {
          if (result.collapsed) {
            asyncDataTreeNode.children.forEach((node2) => dfs$1(node2, (node3) => this.nodes.delete(node3.element)));
            asyncDataTreeNode.children.splice(0, asyncDataTreeNode.children.length);
            asyncDataTreeNode.stale = true;
          } else {
            childrenToRefresh.push(asyncDataTreeNode);
          }
        } else if (hasChildren2 && this.collapseByDefault && !this.collapseByDefault(element)) {
          asyncDataTreeNode.collapsedByDefault = false;
          childrenToRefresh.push(asyncDataTreeNode);
        }
        return asyncDataTreeNode;
      }
      const childAsyncDataTreeNode = createAsyncDataTreeNode({element, parent: node, id: id3, hasChildren: hasChildren2});
      if (viewStateContext && viewStateContext.viewState.focus && viewStateContext.viewState.focus.indexOf(id3) > -1) {
        viewStateContext.focus.push(childAsyncDataTreeNode);
      }
      if (viewStateContext && viewStateContext.viewState.selection && viewStateContext.viewState.selection.indexOf(id3) > -1) {
        viewStateContext.selection.push(childAsyncDataTreeNode);
      }
      if (viewStateContext && viewStateContext.viewState.expanded && viewStateContext.viewState.expanded.indexOf(id3) > -1) {
        childrenToRefresh.push(childAsyncDataTreeNode);
      } else if (hasChildren2 && this.collapseByDefault && !this.collapseByDefault(element)) {
        childAsyncDataTreeNode.collapsedByDefault = false;
        childrenToRefresh.push(childAsyncDataTreeNode);
      }
      return childAsyncDataTreeNode;
    });
    for (const node2 of nodesToForget.values()) {
      dfs$1(node2, (node3) => this.nodes.delete(node3.element));
    }
    for (const child of children2) {
      this.nodes.set(child.element, child);
    }
    node.children.splice(0, node.children.length, ...children2);
    if (node !== this.root && this.autoExpandSingleChildren && children2.length === 1 && childrenToRefresh.length === 0) {
      children2[0].collapsedByDefault = false;
      childrenToRefresh.push(children2[0]);
    }
    return childrenToRefresh;
  }
  render(node, viewStateContext) {
    const children2 = node.children.map((node2) => this.asTreeElement(node2, viewStateContext));
    this.tree.setChildren(node === this.root ? null : node, children2);
    if (node !== this.root) {
      this.tree.setCollapsible(node, node.hasChildren);
    }
    this._onDidRender.fire();
  }
  asTreeElement(node, viewStateContext) {
    if (node.stale) {
      return {
        element: node,
        collapsible: node.hasChildren,
        collapsed: true
      };
    }
    let collapsed;
    if (viewStateContext && viewStateContext.viewState.expanded && node.id && viewStateContext.viewState.expanded.indexOf(node.id) > -1) {
      collapsed = false;
    } else {
      collapsed = node.collapsedByDefault;
    }
    node.collapsedByDefault = void 0;
    return {
      element: node,
      children: node.hasChildren ? Iterable.map(node.children, (child) => this.asTreeElement(child, viewStateContext)) : [],
      collapsible: node.hasChildren,
      collapsed
    };
  }
  processChildren(children2) {
    if (this.sorter) {
      children2 = [...children2].sort(this.sorter.compare.bind(this.sorter));
    }
    return children2;
  }
  dispose() {
    this.disposables.dispose();
  }
};
var CompressibleAsyncDataTreeNodeWrapper = class {
  constructor(node) {
    this.node = node;
  }
  get element() {
    return {
      elements: this.node.element.elements.map((e2) => e2.element),
      incompressible: this.node.element.incompressible
    };
  }
  get children() {
    return this.node.children.map((node) => new CompressibleAsyncDataTreeNodeWrapper(node));
  }
  get depth() {
    return this.node.depth;
  }
  get visibleChildrenCount() {
    return this.node.visibleChildrenCount;
  }
  get visibleChildIndex() {
    return this.node.visibleChildIndex;
  }
  get collapsible() {
    return this.node.collapsible;
  }
  get collapsed() {
    return this.node.collapsed;
  }
  get visible() {
    return this.node.visible;
  }
  get filterData() {
    return this.node.filterData;
  }
};
var CompressibleAsyncDataTreeRenderer = class {
  constructor(renderer, nodeMapper, compressibleNodeMapperProvider, onDidChangeTwistieState) {
    this.renderer = renderer;
    this.nodeMapper = nodeMapper;
    this.compressibleNodeMapperProvider = compressibleNodeMapperProvider;
    this.onDidChangeTwistieState = onDidChangeTwistieState;
    this.renderedNodes = new Map();
    this.disposables = [];
    this.templateId = renderer.templateId;
  }
  renderTemplate(container) {
    const templateData = this.renderer.renderTemplate(container);
    return {templateData};
  }
  renderElement(node, index3, templateData, height) {
    this.renderer.renderElement(this.nodeMapper.map(node), index3, templateData.templateData, height);
  }
  renderCompressedElements(node, index3, templateData, height) {
    this.renderer.renderCompressedElements(this.compressibleNodeMapperProvider().map(node), index3, templateData.templateData, height);
  }
  renderTwistie(element, twistieElement) {
    if (element.slow) {
      addClasses(twistieElement, treeItemLoadingIcon.classNames);
    } else {
      removeClasses(twistieElement, treeItemLoadingIcon.classNames);
    }
    return false;
  }
  disposeElement(node, index3, templateData, height) {
    if (this.renderer.disposeElement) {
      this.renderer.disposeElement(this.nodeMapper.map(node), index3, templateData.templateData, height);
    }
  }
  disposeCompressedElements(node, index3, templateData, height) {
    if (this.renderer.disposeCompressedElements) {
      this.renderer.disposeCompressedElements(this.compressibleNodeMapperProvider().map(node), index3, templateData.templateData, height);
    }
  }
  disposeTemplate(templateData) {
    this.renderer.disposeTemplate(templateData.templateData);
  }
  dispose() {
    this.renderedNodes.clear();
    this.disposables = dispose(this.disposables);
  }
};
function asCompressibleObjectTreeOptions(options) {
  const objectTreeOptions = options && asObjectTreeOptions$1(options);
  return objectTreeOptions && Object.assign(Object.assign({}, objectTreeOptions), {keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, objectTreeOptions.keyboardNavigationLabelProvider), {getCompressedNodeKeyboardNavigationLabel(els) {
    return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(els.map((e2) => e2.element));
  }})});
}
var CompressibleAsyncDataTree = class extends AsyncDataTree {
  constructor(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options = {}) {
    super(user, container, virtualDelegate, renderers, dataSource, options);
    this.compressionDelegate = compressionDelegate;
    this.compressibleNodeMapper = new WeakMapper((node) => new CompressibleAsyncDataTreeNodeWrapper(node));
    this.filter = options.filter;
  }
  createTree(user, container, delegate, renderers, options) {
    const objectTreeDelegate = new ComposedTreeDelegate(delegate);
    const objectTreeRenderers = renderers.map((r3) => new CompressibleAsyncDataTreeRenderer(r3, this.nodeMapper, () => this.compressibleNodeMapper, this._onDidChangeNodeSlowState.event));
    const objectTreeOptions = asCompressibleObjectTreeOptions(options) || {};
    return new CompressibleObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
  }
  asTreeElement(node, viewStateContext) {
    return Object.assign({incompressible: this.compressionDelegate.isIncompressible(node.element)}, super.asTreeElement(node, viewStateContext));
  }
  updateOptions(options = {}) {
    this.tree.updateOptions(options);
  }
  render(node, viewStateContext) {
    if (!this.identityProvider) {
      return super.render(node, viewStateContext);
    }
    const getId2 = (element) => this.identityProvider.getId(element).toString();
    const getUncompressedIds = (nodes) => {
      const result = new Set();
      for (const node2 of nodes) {
        const compressedNode = this.tree.getCompressedTreeNode(node2 === this.root ? null : node2);
        if (!compressedNode.element) {
          continue;
        }
        for (const node3 of compressedNode.element.elements) {
          result.add(getId2(node3.element));
        }
      }
      return result;
    };
    const oldSelection = getUncompressedIds(this.tree.getSelection());
    const oldFocus = getUncompressedIds(this.tree.getFocus());
    super.render(node, viewStateContext);
    const selection2 = this.getSelection();
    let didChangeSelection = false;
    const focus = this.getFocus();
    let didChangeFocus = false;
    const visit = (node2) => {
      const compressedNode = node2.element;
      if (compressedNode) {
        for (let i3 = 0; i3 < compressedNode.elements.length; i3++) {
          const id3 = getId2(compressedNode.elements[i3].element);
          const element = compressedNode.elements[compressedNode.elements.length - 1].element;
          if (oldSelection.has(id3) && selection2.indexOf(element) === -1) {
            selection2.push(element);
            didChangeSelection = true;
          }
          if (oldFocus.has(id3) && focus.indexOf(element) === -1) {
            focus.push(element);
            didChangeFocus = true;
          }
        }
      }
      node2.children.forEach(visit);
    };
    visit(this.tree.getCompressedTreeNode(node === this.root ? null : node));
    if (didChangeSelection) {
      this.setSelection(selection2);
    }
    if (didChangeFocus) {
      this.setFocus(focus);
    }
  }
  processChildren(children2) {
    if (this.filter) {
      children2 = Iterable.filter(children2, (e2) => {
        const result = this.filter.filter(e2, 1);
        const visibility = getVisibility(result);
        if (visibility === 2) {
          throw new Error("Recursive tree visibility not supported in async data compressed trees");
        }
        return visibility === 1;
      });
    }
    return super.processChildren(children2);
  }
};
function getVisibility(filterResult) {
  if (typeof filterResult === "boolean") {
    return filterResult ? 1 : 0;
  } else if (isFilterResult(filterResult)) {
    return getVisibleState(filterResult.visibility);
  } else {
    return getVisibleState(filterResult);
  }
}
var DataTree = class extends AbstractTree {
  constructor(user, container, delegate, renderers, dataSource, options = {}) {
    super(user, container, delegate, renderers, options);
    this.user = user;
    this.dataSource = dataSource;
    this.identityProvider = options.identityProvider;
  }
  createModel(user, view, options) {
    return new ObjectTreeModel(user, view, options);
  }
};
var __decorate$g = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$c = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var IListService = createDecorator("listService");
var ListService = class ListService2 {
  constructor(_themeService) {
    this._themeService = _themeService;
    this.disposables = new DisposableStore();
    this.lists = [];
    this._lastFocusedWidget = void 0;
    this._hasCreatedStyleController = false;
  }
  get lastFocusedList() {
    return this._lastFocusedWidget;
  }
  register(widget, extraContextKeys) {
    if (!this._hasCreatedStyleController) {
      this._hasCreatedStyleController = true;
      const styleController = new DefaultStyleController(createStyleSheet(), "");
      this.disposables.add(attachListStyler(styleController, this._themeService));
    }
    if (this.lists.some((l2) => l2.widget === widget)) {
      throw new Error("Cannot register the same widget multiple times");
    }
    const registeredList = {widget, extraContextKeys};
    this.lists.push(registeredList);
    if (widget.getHTMLElement() === document.activeElement) {
      this._lastFocusedWidget = widget;
    }
    return combinedDisposable(widget.onDidFocus(() => this._lastFocusedWidget = widget), toDisposable(() => this.lists.splice(this.lists.indexOf(registeredList), 1)), widget.onDidDispose(() => {
      this.lists = this.lists.filter((l2) => l2 !== registeredList);
      if (this._lastFocusedWidget === widget) {
        this._lastFocusedWidget = void 0;
      }
    }));
  }
  dispose() {
    this.disposables.dispose();
  }
};
ListService = __decorate$g([
  __param$c(0, IThemeService)
], ListService);
var RawWorkbenchListFocusContextKey = new RawContextKey("listFocus", true);
var WorkbenchListSupportsMultiSelectContextKey = new RawContextKey("listSupportsMultiselect", true);
var WorkbenchListFocusContextKey = ContextKeyExpr.and(RawWorkbenchListFocusContextKey, ContextKeyExpr.not(InputFocusedContextKey));
var WorkbenchListHasSelectionOrFocus = new RawContextKey("listHasSelectionOrFocus", false);
var WorkbenchListDoubleSelection = new RawContextKey("listDoubleSelection", false);
var WorkbenchListMultiSelection = new RawContextKey("listMultiSelection", false);
var WorkbenchListSupportsKeyboardNavigation = new RawContextKey("listSupportsKeyboardNavigation", true);
var WorkbenchListAutomaticKeyboardNavigationKey = "listAutomaticKeyboardNavigation";
var WorkbenchListAutomaticKeyboardNavigation = new RawContextKey(WorkbenchListAutomaticKeyboardNavigationKey, true);
var didBindWorkbenchListAutomaticKeyboardNavigation = false;
function createScopedContextKeyService(contextKeyService, widget) {
  const result = contextKeyService.createScoped(widget.getHTMLElement());
  RawWorkbenchListFocusContextKey.bindTo(result);
  return result;
}
var multiSelectModifierSettingKey = "workbench.list.multiSelectModifier";
var openModeSettingKey = "workbench.list.openMode";
var horizontalScrollingKey = "workbench.list.horizontalScrolling";
var keyboardNavigationSettingKey = "workbench.list.keyboardNavigation";
var automaticKeyboardNavigationSettingKey = "workbench.list.automaticKeyboardNavigation";
var treeIndentKey = "workbench.tree.indent";
var treeRenderIndentGuidesKey = "workbench.tree.renderIndentGuides";
var listSmoothScrolling = "workbench.list.smoothScrolling";
function useAltAsMultipleSelectionModifier(configurationService) {
  return configurationService.getValue(multiSelectModifierSettingKey) === "alt";
}
var MultipleSelectionController = class extends Disposable {
  constructor(configurationService) {
    super();
    this.configurationService = configurationService;
    this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
    this.registerListeners();
  }
  registerListeners() {
    this._register(this.configurationService.onDidChangeConfiguration((e2) => {
      if (e2.affectsConfiguration(multiSelectModifierSettingKey)) {
        this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(this.configurationService);
      }
    }));
  }
  isSelectionSingleChangeEvent(event) {
    if (this.useAltAsMultipleSelectionModifier) {
      return event.browserEvent.altKey;
    }
    return isSelectionSingleChangeEvent(event);
  }
  isSelectionRangeChangeEvent(event) {
    return isSelectionRangeChangeEvent(event);
  }
};
function toWorkbenchListOptions(options, configurationService, keybindingService) {
  const disposables = new DisposableStore();
  const result = Object.assign({}, options);
  if (options.multipleSelectionSupport !== false && !options.multipleSelectionController) {
    const multipleSelectionController = new MultipleSelectionController(configurationService);
    result.multipleSelectionController = multipleSelectionController;
    disposables.add(multipleSelectionController);
  }
  result.keyboardNavigationDelegate = {
    mightProducePrintableCharacter(e2) {
      return keybindingService.mightProducePrintableCharacter(e2);
    }
  };
  result.smoothScrolling = configurationService.getValue(listSmoothScrolling);
  return [result, disposables];
}
var WorkbenchList = class WorkbenchList2 extends List2 {
  constructor(user, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService) {
    const horizontalScrolling = typeof options.horizontalScrolling !== "undefined" ? options.horizontalScrolling : configurationService.getValue(horizontalScrollingKey);
    const [workbenchListOptions, workbenchListOptionsDisposable] = toWorkbenchListOptions(options, configurationService, keybindingService);
    super(user, container, delegate, renderers, Object.assign(Object.assign(Object.assign({keyboardSupport: false}, computeStyles2(themeService.getColorTheme(), defaultListStyles)), workbenchListOptions), {horizontalScrolling}));
    this.disposables.add(workbenchListOptionsDisposable);
    this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
    this.themeService = themeService;
    const listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
    listSupportsMultiSelect.set(!(options.multipleSelectionSupport === false));
    this.listHasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
    this.listDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
    this.listMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
    this.horizontalScrolling = options.horizontalScrolling;
    this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
    this.disposables.add(this.contextKeyService);
    this.disposables.add(listService.register(this));
    if (options.overrideStyles) {
      this.updateStyles(options.overrideStyles);
    }
    this.disposables.add(this.onDidChangeSelection(() => {
      const selection2 = this.getSelection();
      const focus = this.getFocus();
      this.contextKeyService.bufferChangeEvents(() => {
        this.listHasSelectionOrFocus.set(selection2.length > 0 || focus.length > 0);
        this.listMultiSelection.set(selection2.length > 1);
        this.listDoubleSelection.set(selection2.length === 2);
      });
    }));
    this.disposables.add(this.onDidChangeFocus(() => {
      const selection2 = this.getSelection();
      const focus = this.getFocus();
      this.listHasSelectionOrFocus.set(selection2.length > 0 || focus.length > 0);
    }));
    this.disposables.add(configurationService.onDidChangeConfiguration((e2) => {
      if (e2.affectsConfiguration(multiSelectModifierSettingKey)) {
        this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      }
      let options2 = {};
      if (e2.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === void 0) {
        const horizontalScrolling2 = configurationService.getValue(horizontalScrollingKey);
        options2 = Object.assign(Object.assign({}, options2), {horizontalScrolling: horizontalScrolling2});
      }
      if (e2.affectsConfiguration(listSmoothScrolling)) {
        const smoothScrolling = configurationService.getValue(listSmoothScrolling);
        options2 = Object.assign(Object.assign({}, options2), {smoothScrolling});
      }
      if (Object.keys(options2).length > 0) {
        this.updateOptions(options2);
      }
    }));
  }
  updateOptions(options) {
    super.updateOptions(options);
    if (options.overrideStyles) {
      this.updateStyles(options.overrideStyles);
    }
  }
  dispose() {
    super.dispose();
    if (this._styler) {
      this._styler.dispose();
    }
  }
  updateStyles(styles6) {
    if (this._styler) {
      this._styler.dispose();
    }
    this._styler = attachListStyler(this, this.themeService, styles6);
  }
};
WorkbenchList = __decorate$g([
  __param$c(5, IContextKeyService),
  __param$c(6, IListService),
  __param$c(7, IThemeService),
  __param$c(8, IConfigurationService),
  __param$c(9, IKeybindingService)
], WorkbenchList);
var WorkbenchPagedList = class WorkbenchPagedList2 extends PagedList {
  constructor(user, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService) {
    const horizontalScrolling = typeof options.horizontalScrolling !== "undefined" ? options.horizontalScrolling : configurationService.getValue(horizontalScrollingKey);
    const [workbenchListOptions, workbenchListOptionsDisposable] = toWorkbenchListOptions(options, configurationService, keybindingService);
    super(user, container, delegate, renderers, Object.assign(Object.assign(Object.assign({keyboardSupport: false}, computeStyles2(themeService.getColorTheme(), defaultListStyles)), workbenchListOptions), {horizontalScrolling}));
    this.disposables = new DisposableStore();
    this.disposables.add(workbenchListOptionsDisposable);
    this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
    this.horizontalScrolling = options.horizontalScrolling;
    const listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
    listSupportsMultiSelect.set(!(options.multipleSelectionSupport === false));
    this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
    this.disposables.add(this.contextKeyService);
    this.disposables.add(listService.register(this));
    if (options.overrideStyles) {
      this.disposables.add(attachListStyler(this, themeService, options.overrideStyles));
    }
    this.disposables.add(configurationService.onDidChangeConfiguration((e2) => {
      if (e2.affectsConfiguration(multiSelectModifierSettingKey)) {
        this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      }
      let options2 = {};
      if (e2.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === void 0) {
        const horizontalScrolling2 = configurationService.getValue(horizontalScrollingKey);
        options2 = Object.assign(Object.assign({}, options2), {horizontalScrolling: horizontalScrolling2});
      }
      if (e2.affectsConfiguration(listSmoothScrolling)) {
        const smoothScrolling = configurationService.getValue(listSmoothScrolling);
        options2 = Object.assign(Object.assign({}, options2), {smoothScrolling});
      }
      if (Object.keys(options2).length > 0) {
        this.updateOptions(options2);
      }
    }));
  }
  dispose() {
    super.dispose();
    this.disposables.dispose();
  }
};
WorkbenchPagedList = __decorate$g([
  __param$c(5, IContextKeyService),
  __param$c(6, IListService),
  __param$c(7, IThemeService),
  __param$c(8, IConfigurationService),
  __param$c(9, IKeybindingService)
], WorkbenchPagedList);
var ResourceNavigator = class extends Disposable {
  constructor(widget, options) {
    var _a, _b;
    super();
    this.widget = widget;
    this._onDidOpen = new Emitter();
    this.onDidOpen = this._onDidOpen.event;
    this.openOnFocus = (_a = options === null || options === void 0 ? void 0 : options.openOnFocus) !== null && _a !== void 0 ? _a : false;
    this._register(Event.filter(this.widget.onDidChangeSelection, (e2) => e2.browserEvent instanceof KeyboardEvent)((e2) => this.onSelectionFromKeyboard(e2)));
    this._register(this.widget.onPointer((e2) => this.onPointer(e2.browserEvent)));
    this._register(this.widget.onMouseDblClick((e2) => this.onMouseDblClick(e2.browserEvent)));
    if (this.openOnFocus) {
      this._register(Event.filter(this.widget.onDidChangeFocus, (e2) => e2.browserEvent instanceof KeyboardEvent)((e2) => this.onFocusFromKeyboard(e2)));
    }
    if (typeof (options === null || options === void 0 ? void 0 : options.openOnSingleClick) !== "boolean" && (options === null || options === void 0 ? void 0 : options.configurationService)) {
      this.openOnSingleClick = (options === null || options === void 0 ? void 0 : options.configurationService.getValue(openModeSettingKey)) !== "doubleClick";
      this._register(options === null || options === void 0 ? void 0 : options.configurationService.onDidChangeConfiguration(() => {
        this.openOnSingleClick = (options === null || options === void 0 ? void 0 : options.configurationService.getValue(openModeSettingKey)) !== "doubleClick";
      }));
    } else {
      this.openOnSingleClick = (_b = options === null || options === void 0 ? void 0 : options.openOnSingleClick) !== null && _b !== void 0 ? _b : true;
    }
  }
  onFocusFromKeyboard(event) {
    const focus = this.widget.getFocus();
    this.widget.setSelection(focus, event.browserEvent);
    const preserveFocus = typeof event.browserEvent.preserveFocus === "boolean" ? event.browserEvent.preserveFocus : true;
    const pinned = false;
    const sideBySide = false;
    this._open(preserveFocus, pinned, sideBySide, event.browserEvent);
  }
  onSelectionFromKeyboard(event) {
    if (event.elements.length !== 1) {
      return;
    }
    const preserveFocus = typeof event.browserEvent.preserveFocus === "boolean" ? event.browserEvent.preserveFocus : true;
    const pinned = false;
    const sideBySide = false;
    this._open(preserveFocus, pinned, sideBySide, event.browserEvent);
  }
  onPointer(browserEvent) {
    if (!this.openOnSingleClick) {
      return;
    }
    const isDoubleClick = browserEvent.detail === 2;
    if (isDoubleClick) {
      return;
    }
    const isMiddleClick = browserEvent.button === 1;
    const preserveFocus = true;
    const pinned = isMiddleClick;
    const sideBySide = browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey;
    this._open(preserveFocus, pinned, sideBySide, browserEvent);
  }
  onMouseDblClick(browserEvent) {
    if (!browserEvent) {
      return;
    }
    const preserveFocus = false;
    const pinned = true;
    const sideBySide = browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey;
    this._open(preserveFocus, pinned, sideBySide, browserEvent);
  }
  _open(preserveFocus, pinned, sideBySide, browserEvent) {
    this._onDidOpen.fire({
      editorOptions: {
        preserveFocus,
        pinned,
        revealIfVisible: true
      },
      sideBySide,
      element: this.widget.getSelection()[0],
      browserEvent
    });
  }
};
var TreeResourceNavigator = class extends ResourceNavigator {
  constructor(tree, options) {
    super(tree, options);
  }
};
function createKeyboardNavigationEventFilter(container, keybindingService) {
  let inChord = false;
  return (event) => {
    if (inChord) {
      inChord = false;
      return false;
    }
    const result = keybindingService.softDispatch(event, container);
    if (result && result.enterChord) {
      inChord = true;
      return false;
    }
    inChord = false;
    return true;
  };
}
var WorkbenchObjectTree = class WorkbenchObjectTree2 extends ObjectTree {
  constructor(user, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) {
    const {options: treeOptions, getAutomaticKeyboardNavigation, disposable} = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
    super(user, container, delegate, renderers, treeOptions);
    this.disposables.add(disposable);
    this.internals = new WorkbenchTreeInternals(this, options, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
    this.disposables.add(this.internals);
  }
};
WorkbenchObjectTree = __decorate$g([
  __param$c(5, IContextKeyService),
  __param$c(6, IListService),
  __param$c(7, IThemeService),
  __param$c(8, IConfigurationService),
  __param$c(9, IKeybindingService),
  __param$c(10, IAccessibilityService)
], WorkbenchObjectTree);
var WorkbenchCompressibleObjectTree = class WorkbenchCompressibleObjectTree2 extends CompressibleObjectTree {
  constructor(user, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) {
    const {options: treeOptions, getAutomaticKeyboardNavigation, disposable} = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
    super(user, container, delegate, renderers, treeOptions);
    this.disposables.add(disposable);
    this.internals = new WorkbenchTreeInternals(this, options, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
    this.disposables.add(this.internals);
  }
  updateOptions(options = {}) {
    super.updateOptions(options);
    if (options.overrideStyles) {
      this.internals.updateStyleOverrides(options.overrideStyles);
    }
  }
};
WorkbenchCompressibleObjectTree = __decorate$g([
  __param$c(5, IContextKeyService),
  __param$c(6, IListService),
  __param$c(7, IThemeService),
  __param$c(8, IConfigurationService),
  __param$c(9, IKeybindingService),
  __param$c(10, IAccessibilityService)
], WorkbenchCompressibleObjectTree);
var WorkbenchDataTree = class WorkbenchDataTree2 extends DataTree {
  constructor(user, container, delegate, renderers, dataSource, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) {
    const {options: treeOptions, getAutomaticKeyboardNavigation, disposable} = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
    super(user, container, delegate, renderers, dataSource, treeOptions);
    this.disposables.add(disposable);
    this.internals = new WorkbenchTreeInternals(this, options, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
    this.disposables.add(this.internals);
  }
  updateOptions(options = {}) {
    super.updateOptions(options);
    if (options.overrideStyles) {
      this.internals.updateStyleOverrides(options.overrideStyles);
    }
  }
};
WorkbenchDataTree = __decorate$g([
  __param$c(6, IContextKeyService),
  __param$c(7, IListService),
  __param$c(8, IThemeService),
  __param$c(9, IConfigurationService),
  __param$c(10, IKeybindingService),
  __param$c(11, IAccessibilityService)
], WorkbenchDataTree);
var WorkbenchAsyncDataTree = class WorkbenchAsyncDataTree2 extends AsyncDataTree {
  constructor(user, container, delegate, renderers, dataSource, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) {
    const {options: treeOptions, getAutomaticKeyboardNavigation, disposable} = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
    super(user, container, delegate, renderers, dataSource, treeOptions);
    this.disposables.add(disposable);
    this.internals = new WorkbenchTreeInternals(this, options, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
    this.disposables.add(this.internals);
  }
  get onDidOpen() {
    return this.internals.onDidOpen;
  }
  updateOptions(options = {}) {
    super.updateOptions(options);
    if (options.overrideStyles) {
      this.internals.updateStyleOverrides(options.overrideStyles);
    }
  }
};
WorkbenchAsyncDataTree = __decorate$g([
  __param$c(6, IContextKeyService),
  __param$c(7, IListService),
  __param$c(8, IThemeService),
  __param$c(9, IConfigurationService),
  __param$c(10, IKeybindingService),
  __param$c(11, IAccessibilityService)
], WorkbenchAsyncDataTree);
var WorkbenchCompressibleAsyncDataTree = class WorkbenchCompressibleAsyncDataTree2 extends CompressibleAsyncDataTree {
  constructor(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options, contextKeyService, listService, themeService, configurationService, keybindingService, accessibilityService) {
    const {options: treeOptions, getAutomaticKeyboardNavigation, disposable} = workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
    super(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, treeOptions);
    this.disposables.add(disposable);
    this.internals = new WorkbenchTreeInternals(this, options, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
    this.disposables.add(this.internals);
  }
};
WorkbenchCompressibleAsyncDataTree = __decorate$g([
  __param$c(7, IContextKeyService),
  __param$c(8, IListService),
  __param$c(9, IThemeService),
  __param$c(10, IConfigurationService),
  __param$c(11, IKeybindingService),
  __param$c(12, IAccessibilityService)
], WorkbenchCompressibleAsyncDataTree);
function workbenchTreeDataPreamble(container, options, contextKeyService, configurationService, keybindingService, accessibilityService) {
  WorkbenchListSupportsKeyboardNavigation.bindTo(contextKeyService);
  if (!didBindWorkbenchListAutomaticKeyboardNavigation) {
    WorkbenchListAutomaticKeyboardNavigation.bindTo(contextKeyService);
    didBindWorkbenchListAutomaticKeyboardNavigation = true;
  }
  const getAutomaticKeyboardNavigation = () => {
    let automaticKeyboardNavigation = contextKeyService.getContextKeyValue(WorkbenchListAutomaticKeyboardNavigationKey);
    if (automaticKeyboardNavigation) {
      automaticKeyboardNavigation = configurationService.getValue(automaticKeyboardNavigationSettingKey);
    }
    return automaticKeyboardNavigation;
  };
  const accessibilityOn = accessibilityService.isScreenReaderOptimized();
  const keyboardNavigation = accessibilityOn ? "simple" : configurationService.getValue(keyboardNavigationSettingKey);
  const horizontalScrolling = options.horizontalScrolling !== void 0 ? options.horizontalScrolling : configurationService.getValue(horizontalScrollingKey);
  const [workbenchListOptions, disposable] = toWorkbenchListOptions(options, configurationService, keybindingService);
  const additionalScrollHeight = options.additionalScrollHeight;
  return {
    getAutomaticKeyboardNavigation,
    disposable,
    options: Object.assign(Object.assign({
      keyboardSupport: false
    }, workbenchListOptions), {indent: configurationService.getValue(treeIndentKey), renderIndentGuides: configurationService.getValue(treeRenderIndentGuidesKey), smoothScrolling: configurationService.getValue(listSmoothScrolling), automaticKeyboardNavigation: getAutomaticKeyboardNavigation(), simpleKeyboardNavigation: keyboardNavigation === "simple", filterOnType: keyboardNavigation === "filter", horizontalScrolling, keyboardNavigationEventFilter: createKeyboardNavigationEventFilter(container, keybindingService), additionalScrollHeight, hideTwistiesOfChildlessElements: options.hideTwistiesOfChildlessElements, expandOnlyOnDoubleClick: configurationService.getValue(openModeSettingKey) === "doubleClick"})
  };
}
var WorkbenchTreeInternals = class WorkbenchTreeInternals2 {
  constructor(tree, options, getAutomaticKeyboardNavigation, overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService) {
    this.tree = tree;
    this.themeService = themeService;
    this.disposables = [];
    this.contextKeyService = createScopedContextKeyService(contextKeyService, tree);
    const listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
    listSupportsMultiSelect.set(!(options.multipleSelectionSupport === false));
    this.hasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
    this.hasDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
    this.hasMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
    this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
    const interestingContextKeys = new Set();
    interestingContextKeys.add(WorkbenchListAutomaticKeyboardNavigationKey);
    const updateKeyboardNavigation = () => {
      const accessibilityOn = accessibilityService.isScreenReaderOptimized();
      const keyboardNavigation = accessibilityOn ? "simple" : configurationService.getValue(keyboardNavigationSettingKey);
      tree.updateOptions({
        simpleKeyboardNavigation: keyboardNavigation === "simple",
        filterOnType: keyboardNavigation === "filter"
      });
    };
    this.updateStyleOverrides(overrideStyles);
    this.disposables.push(this.contextKeyService, listService.register(tree), tree.onDidChangeSelection(() => {
      const selection2 = tree.getSelection();
      const focus = tree.getFocus();
      this.contextKeyService.bufferChangeEvents(() => {
        this.hasSelectionOrFocus.set(selection2.length > 0 || focus.length > 0);
        this.hasMultiSelection.set(selection2.length > 1);
        this.hasDoubleSelection.set(selection2.length === 2);
      });
    }), tree.onDidChangeFocus(() => {
      const selection2 = tree.getSelection();
      const focus = tree.getFocus();
      this.hasSelectionOrFocus.set(selection2.length > 0 || focus.length > 0);
    }), configurationService.onDidChangeConfiguration((e2) => {
      let newOptions = {};
      if (e2.affectsConfiguration(multiSelectModifierSettingKey)) {
        this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      }
      if (e2.affectsConfiguration(treeIndentKey)) {
        const indent = configurationService.getValue(treeIndentKey);
        newOptions = Object.assign(Object.assign({}, newOptions), {indent});
      }
      if (e2.affectsConfiguration(treeRenderIndentGuidesKey)) {
        const renderIndentGuides = configurationService.getValue(treeRenderIndentGuidesKey);
        newOptions = Object.assign(Object.assign({}, newOptions), {renderIndentGuides});
      }
      if (e2.affectsConfiguration(listSmoothScrolling)) {
        const smoothScrolling = configurationService.getValue(listSmoothScrolling);
        newOptions = Object.assign(Object.assign({}, newOptions), {smoothScrolling});
      }
      if (e2.affectsConfiguration(keyboardNavigationSettingKey)) {
        updateKeyboardNavigation();
      }
      if (e2.affectsConfiguration(automaticKeyboardNavigationSettingKey)) {
        newOptions = Object.assign(Object.assign({}, newOptions), {automaticKeyboardNavigation: getAutomaticKeyboardNavigation()});
      }
      if (e2.affectsConfiguration(horizontalScrollingKey) && options.horizontalScrolling === void 0) {
        const horizontalScrolling = configurationService.getValue(horizontalScrollingKey);
        newOptions = Object.assign(Object.assign({}, newOptions), {horizontalScrolling});
      }
      if (e2.affectsConfiguration(openModeSettingKey)) {
        newOptions = Object.assign(Object.assign({}, newOptions), {expandOnlyOnDoubleClick: configurationService.getValue(openModeSettingKey) === "doubleClick"});
      }
      if (Object.keys(newOptions).length > 0) {
        tree.updateOptions(newOptions);
      }
    }), this.contextKeyService.onDidChangeContext((e2) => {
      if (e2.affectsSome(interestingContextKeys)) {
        tree.updateOptions({automaticKeyboardNavigation: getAutomaticKeyboardNavigation()});
      }
    }), accessibilityService.onDidChangeScreenReaderOptimized(() => updateKeyboardNavigation()));
    this.navigator = new TreeResourceNavigator(tree, Object.assign({configurationService}, options));
    this.disposables.push(this.navigator);
  }
  get onDidOpen() {
    return this.navigator.onDidOpen;
  }
  updateStyleOverrides(overrideStyles) {
    dispose(this.styler);
    this.styler = overrideStyles ? attachListStyler(this.tree, this.themeService, overrideStyles) : Disposable.None;
  }
  dispose() {
    this.disposables = dispose(this.disposables);
    dispose(this.styler);
    this.styler = void 0;
  }
};
WorkbenchTreeInternals = __decorate$g([
  __param$c(4, IContextKeyService),
  __param$c(5, IListService),
  __param$c(6, IThemeService),
  __param$c(7, IConfigurationService),
  __param$c(8, IAccessibilityService)
], WorkbenchTreeInternals);
var configurationRegistry$2 = Registry$1.as(Extensions$1.Configuration);
configurationRegistry$2.registerConfiguration({
  id: "workbench",
  order: 7,
  title: localize("workbenchConfigurationTitle", "Workbench"),
  type: "object",
  properties: {
    [multiSelectModifierSettingKey]: {
      type: "string",
      enum: ["ctrlCmd", "alt"],
      enumDescriptions: [
        localize("multiSelectModifier.ctrlCmd", "Maps to `Control` on Windows and Linux and to `Command` on macOS."),
        localize("multiSelectModifier.alt", "Maps to `Alt` on Windows and Linux and to `Option` on macOS.")
      ],
      default: "ctrlCmd",
      description: localize({
        key: "multiSelectModifier",
        comment: [
          "- `ctrlCmd` refers to a value the setting can take and should not be localized.",
          "- `Control` and `Command` refer to the modifier keys Ctrl or Cmd on the keyboard and can be localized."
        ]
      }, "The modifier to be used to add an item in trees and lists to a multi-selection with the mouse (for example in the explorer, open editors and scm view). The 'Open to Side' mouse gestures - if supported - will adapt such that they do not conflict with the multiselect modifier.")
    },
    [openModeSettingKey]: {
      type: "string",
      enum: ["singleClick", "doubleClick"],
      default: "singleClick",
      description: localize({
        key: "openModeModifier",
        comment: ["`singleClick` and `doubleClick` refers to a value the setting can take and should not be localized."]
      }, "Controls how to open items in trees and lists using the mouse (if supported). For parents with children in trees, this setting will control if a single click expands the parent or a double click. Note that some trees and lists might choose to ignore this setting if it is not applicable. ")
    },
    [horizontalScrollingKey]: {
      type: "boolean",
      default: false,
      description: localize("horizontalScrolling setting", "Controls whether lists and trees support horizontal scrolling in the workbench. Warning: turning on this setting has a performance implication.")
    },
    [treeIndentKey]: {
      type: "number",
      default: 8,
      minimum: 0,
      maximum: 40,
      description: localize("tree indent setting", "Controls tree indentation in pixels.")
    },
    [treeRenderIndentGuidesKey]: {
      type: "string",
      enum: ["none", "onHover", "always"],
      default: "onHover",
      description: localize("render tree indent guides", "Controls whether the tree should render indent guides.")
    },
    [listSmoothScrolling]: {
      type: "boolean",
      default: false,
      description: localize("list smoothScrolling setting", "Controls whether lists and trees have smooth scrolling.")
    },
    [keyboardNavigationSettingKey]: {
      type: "string",
      enum: ["simple", "highlight", "filter"],
      enumDescriptions: [
        localize("keyboardNavigationSettingKey.simple", "Simple keyboard navigation focuses elements which match the keyboard input. Matching is done only on prefixes."),
        localize("keyboardNavigationSettingKey.highlight", "Highlight keyboard navigation highlights elements which match the keyboard input. Further up and down navigation will traverse only the highlighted elements."),
        localize("keyboardNavigationSettingKey.filter", "Filter keyboard navigation will filter out and hide all the elements which do not match the keyboard input.")
      ],
      default: "highlight",
      description: localize("keyboardNavigationSettingKey", "Controls the keyboard navigation style for lists and trees in the workbench. Can be simple, highlight and filter.")
    },
    [automaticKeyboardNavigationSettingKey]: {
      type: "boolean",
      default: true,
      markdownDescription: localize("automatic keyboard navigation setting", "Controls whether keyboard navigation in lists and trees is automatically triggered simply by typing. If set to `false`, keyboard navigation is only triggered when executing the `list.toggleKeyboardNavigation` command, for which you can assign a keyboard shortcut.")
    }
  }
});
var MarkerSeverity$1;
(function(MarkerSeverity2) {
  MarkerSeverity2[MarkerSeverity2["Hint"] = 1] = "Hint";
  MarkerSeverity2[MarkerSeverity2["Info"] = 2] = "Info";
  MarkerSeverity2[MarkerSeverity2["Warning"] = 4] = "Warning";
  MarkerSeverity2[MarkerSeverity2["Error"] = 8] = "Error";
})(MarkerSeverity$1 || (MarkerSeverity$1 = {}));
(function(MarkerSeverity2) {
  function compare2(a2, b2) {
    return b2 - a2;
  }
  MarkerSeverity2.compare = compare2;
  const _displayStrings = Object.create(null);
  _displayStrings[MarkerSeverity2.Error] = localize("sev.error", "Error");
  _displayStrings[MarkerSeverity2.Warning] = localize("sev.warning", "Warning");
  _displayStrings[MarkerSeverity2.Info] = localize("sev.info", "Info");
  function toString5(a2) {
    return _displayStrings[a2] || "";
  }
  MarkerSeverity2.toString = toString5;
  function fromSeverity(severity) {
    switch (severity) {
      case Severity$1.Error:
        return MarkerSeverity2.Error;
      case Severity$1.Warning:
        return MarkerSeverity2.Warning;
      case Severity$1.Info:
        return MarkerSeverity2.Info;
      case Severity$1.Ignore:
        return MarkerSeverity2.Hint;
    }
  }
  MarkerSeverity2.fromSeverity = fromSeverity;
  function toSeverity(severity) {
    switch (severity) {
      case MarkerSeverity2.Error:
        return Severity$1.Error;
      case MarkerSeverity2.Warning:
        return Severity$1.Warning;
      case MarkerSeverity2.Info:
        return Severity$1.Info;
      case MarkerSeverity2.Hint:
        return Severity$1.Ignore;
    }
  }
  MarkerSeverity2.toSeverity = toSeverity;
})(MarkerSeverity$1 || (MarkerSeverity$1 = {}));
var IMarkerData;
(function(IMarkerData2) {
  const emptyString = "";
  function makeKey(markerData) {
    return makeKeyOptionalMessage(markerData, true);
  }
  IMarkerData2.makeKey = makeKey;
  function makeKeyOptionalMessage(markerData, useMessage) {
    let result = [emptyString];
    if (markerData.source) {
      result.push(markerData.source.replace("¦", "\\¦"));
    } else {
      result.push(emptyString);
    }
    if (markerData.code) {
      if (typeof markerData.code === "string") {
        result.push(markerData.code.replace("¦", "\\¦"));
      } else {
        result.push(markerData.code.value.replace("¦", "\\¦"));
      }
    } else {
      result.push(emptyString);
    }
    if (markerData.severity !== void 0 && markerData.severity !== null) {
      result.push(MarkerSeverity$1.toString(markerData.severity));
    } else {
      result.push(emptyString);
    }
    if (markerData.message && useMessage) {
      result.push(markerData.message.replace("¦", "\\¦"));
    } else {
      result.push(emptyString);
    }
    if (markerData.startLineNumber !== void 0 && markerData.startLineNumber !== null) {
      result.push(markerData.startLineNumber.toString());
    } else {
      result.push(emptyString);
    }
    if (markerData.startColumn !== void 0 && markerData.startColumn !== null) {
      result.push(markerData.startColumn.toString());
    } else {
      result.push(emptyString);
    }
    if (markerData.endLineNumber !== void 0 && markerData.endLineNumber !== null) {
      result.push(markerData.endLineNumber.toString());
    } else {
      result.push(emptyString);
    }
    if (markerData.endColumn !== void 0 && markerData.endColumn !== null) {
      result.push(markerData.endColumn.toString());
    } else {
      result.push(emptyString);
    }
    result.push(emptyString);
    return result.join("¦");
  }
  IMarkerData2.makeKeyOptionalMessage = makeKeyOptionalMessage;
})(IMarkerData || (IMarkerData = {}));
var IMarkerService = createDecorator("markerService");
var DoubleResourceMap = class {
  constructor() {
    this._byResource = new ResourceMap();
    this._byOwner = new Map();
  }
  set(resource2, owner, value) {
    let ownerMap = this._byResource.get(resource2);
    if (!ownerMap) {
      ownerMap = new Map();
      this._byResource.set(resource2, ownerMap);
    }
    ownerMap.set(owner, value);
    let resourceMap = this._byOwner.get(owner);
    if (!resourceMap) {
      resourceMap = new ResourceMap();
      this._byOwner.set(owner, resourceMap);
    }
    resourceMap.set(resource2, value);
  }
  get(resource2, owner) {
    let ownerMap = this._byResource.get(resource2);
    return ownerMap === null || ownerMap === void 0 ? void 0 : ownerMap.get(owner);
  }
  delete(resource2, owner) {
    let removedA = false;
    let removedB = false;
    let ownerMap = this._byResource.get(resource2);
    if (ownerMap) {
      removedA = ownerMap.delete(owner);
    }
    let resourceMap = this._byOwner.get(owner);
    if (resourceMap) {
      removedB = resourceMap.delete(resource2);
    }
    if (removedA !== removedB) {
      throw new Error("illegal state");
    }
    return removedA && removedB;
  }
  values(key) {
    var _a, _b, _c, _d;
    if (typeof key === "string") {
      return (_b = (_a = this._byOwner.get(key)) === null || _a === void 0 ? void 0 : _a.values()) !== null && _b !== void 0 ? _b : Iterable.empty();
    }
    if (URI.isUri(key)) {
      return (_d = (_c = this._byResource.get(key)) === null || _c === void 0 ? void 0 : _c.values()) !== null && _d !== void 0 ? _d : Iterable.empty();
    }
    return Iterable.map(Iterable.concat(...this._byOwner.values()), (map2) => map2[1]);
  }
};
var MarkerStats = class {
  constructor(service) {
    this.errors = 0;
    this.infos = 0;
    this.warnings = 0;
    this.unknowns = 0;
    this._data = new ResourceMap();
    this._service = service;
    this._subscription = service.onMarkerChanged(this._update, this);
  }
  dispose() {
    this._subscription.dispose();
  }
  _update(resources) {
    for (const resource2 of resources) {
      const oldStats = this._data.get(resource2);
      if (oldStats) {
        this._substract(oldStats);
      }
      const newStats = this._resourceStats(resource2);
      this._add(newStats);
      this._data.set(resource2, newStats);
    }
  }
  _resourceStats(resource2) {
    const result = {errors: 0, warnings: 0, infos: 0, unknowns: 0};
    if (resource2.scheme === Schemas.inMemory || resource2.scheme === Schemas.walkThrough || resource2.scheme === Schemas.walkThroughSnippet) {
      return result;
    }
    for (const {severity} of this._service.read({resource: resource2})) {
      if (severity === MarkerSeverity$1.Error) {
        result.errors += 1;
      } else if (severity === MarkerSeverity$1.Warning) {
        result.warnings += 1;
      } else if (severity === MarkerSeverity$1.Info) {
        result.infos += 1;
      } else {
        result.unknowns += 1;
      }
    }
    return result;
  }
  _substract(op) {
    this.errors -= op.errors;
    this.warnings -= op.warnings;
    this.infos -= op.infos;
    this.unknowns -= op.unknowns;
  }
  _add(op) {
    this.errors += op.errors;
    this.warnings += op.warnings;
    this.infos += op.infos;
    this.unknowns += op.unknowns;
  }
};
var MarkerService = class {
  constructor() {
    this._onMarkerChanged = new Emitter();
    this.onMarkerChanged = Event.debounce(this._onMarkerChanged.event, MarkerService._debouncer, 0);
    this._data = new DoubleResourceMap();
    this._stats = new MarkerStats(this);
  }
  dispose() {
    this._stats.dispose();
  }
  remove(owner, resources) {
    for (const resource2 of resources || []) {
      this.changeOne(owner, resource2, []);
    }
  }
  changeOne(owner, resource2, markerData) {
    if (isFalsyOrEmpty(markerData)) {
      const removed = this._data.delete(resource2, owner);
      if (removed) {
        this._onMarkerChanged.fire([resource2]);
      }
    } else {
      const markers = [];
      for (const data2 of markerData) {
        const marker = MarkerService._toMarker(owner, resource2, data2);
        if (marker) {
          markers.push(marker);
        }
      }
      this._data.set(resource2, owner, markers);
      this._onMarkerChanged.fire([resource2]);
    }
  }
  static _toMarker(owner, resource2, data2) {
    let {code: code2, severity, message, source: source2, startLineNumber, startColumn, endLineNumber, endColumn, relatedInformation, tags} = data2;
    if (!message) {
      return void 0;
    }
    startLineNumber = startLineNumber > 0 ? startLineNumber : 1;
    startColumn = startColumn > 0 ? startColumn : 1;
    endLineNumber = endLineNumber >= startLineNumber ? endLineNumber : startLineNumber;
    endColumn = endColumn > 0 ? endColumn : startColumn;
    return {
      resource: resource2,
      owner,
      code: code2,
      severity,
      message,
      source: source2,
      startLineNumber,
      startColumn,
      endLineNumber,
      endColumn,
      relatedInformation,
      tags
    };
  }
  read(filter3 = Object.create(null)) {
    let {owner, resource: resource2, severities, take} = filter3;
    if (!take || take < 0) {
      take = -1;
    }
    if (owner && resource2) {
      const data2 = this._data.get(resource2, owner);
      if (!data2) {
        return [];
      } else {
        const result = [];
        for (const marker of data2) {
          if (MarkerService._accept(marker, severities)) {
            const newLen = result.push(marker);
            if (take > 0 && newLen === take) {
              break;
            }
          }
        }
        return result;
      }
    } else if (!owner && !resource2) {
      const result = [];
      for (let markers of this._data.values()) {
        for (let data2 of markers) {
          if (MarkerService._accept(data2, severities)) {
            const newLen = result.push(data2);
            if (take > 0 && newLen === take) {
              return result;
            }
          }
        }
      }
      return result;
    } else {
      const iterable = this._data.values(resource2 !== null && resource2 !== void 0 ? resource2 : owner);
      const result = [];
      for (const markers of iterable) {
        for (const data2 of markers) {
          if (MarkerService._accept(data2, severities)) {
            const newLen = result.push(data2);
            if (take > 0 && newLen === take) {
              return result;
            }
          }
        }
      }
      return result;
    }
  }
  static _accept(marker, severities) {
    return severities === void 0 || (severities & marker.severity) === marker.severity;
  }
  static _debouncer(last2, event) {
    if (!last2) {
      MarkerService._dedupeMap = new ResourceMap();
      last2 = [];
    }
    for (const uri of event) {
      if (!MarkerService._dedupeMap.has(uri)) {
        MarkerService._dedupeMap.set(uri, true);
        last2.push(uri);
      }
    }
    return last2;
  }
};
var IStorageService = createDecorator("storageService");
var WillSaveStateReason;
(function(WillSaveStateReason2) {
  WillSaveStateReason2[WillSaveStateReason2["NONE"] = 0] = "NONE";
  WillSaveStateReason2[WillSaveStateReason2["SHUTDOWN"] = 1] = "SHUTDOWN";
})(WillSaveStateReason || (WillSaveStateReason = {}));
var InMemoryStorageService = class extends Disposable {
  constructor() {
    super(...arguments);
    this._onDidChangeStorage = this._register(new Emitter());
    this._onWillSaveState = this._register(new Emitter());
    this.onWillSaveState = this._onWillSaveState.event;
    this.globalCache = new Map();
    this.workspaceCache = new Map();
  }
  getCache(scope) {
    return scope === 0 ? this.globalCache : this.workspaceCache;
  }
  get(key, scope, fallbackValue) {
    const value = this.getCache(scope).get(key);
    if (isUndefinedOrNull(value)) {
      return fallbackValue;
    }
    return value;
  }
  getBoolean(key, scope, fallbackValue) {
    const value = this.getCache(scope).get(key);
    if (isUndefinedOrNull(value)) {
      return fallbackValue;
    }
    return value === "true";
  }
  getNumber(key, scope, fallbackValue) {
    const value = this.getCache(scope).get(key);
    if (isUndefinedOrNull(value)) {
      return fallbackValue;
    }
    return parseInt(value, 10);
  }
  store(key, value, scope) {
    if (isUndefinedOrNull(value)) {
      return this.remove(key, scope);
    }
    const valueStr = String(value);
    const currentValue = this.getCache(scope).get(key);
    if (currentValue === valueStr) {
      return Promise.resolve();
    }
    this.getCache(scope).set(key, valueStr);
    this._onDidChangeStorage.fire({scope, key});
    return Promise.resolve();
  }
  remove(key, scope) {
    const wasDeleted = this.getCache(scope).delete(key);
    if (!wasDeleted) {
      return Promise.resolve();
    }
    this._onDidChangeStorage.fire({scope, key});
    return Promise.resolve();
  }
};
var __decorate$h = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$d = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var MenuService = class MenuService2 {
  constructor(_commandService) {
    this._commandService = _commandService;
  }
  createMenu(id3, contextKeyService) {
    return new Menu$1(id3, this._commandService, contextKeyService, this);
  }
};
MenuService = __decorate$h([
  __param$d(0, ICommandService)
], MenuService);
var Menu$1 = class Menu2 {
  constructor(_id, _commandService, _contextKeyService, _menuService) {
    this._id = _id;
    this._commandService = _commandService;
    this._contextKeyService = _contextKeyService;
    this._menuService = _menuService;
    this._onDidChange = new Emitter();
    this._dispoables = new DisposableStore();
    this._menuGroups = [];
    this._contextKeys = new Set();
    this._build();
    this._dispoables.add(Event.debounce(Event.filter(MenuRegistry.onDidChangeMenu, (set3) => set3.has(this._id)), () => {
    }, 50)(this._build, this));
    this._dispoables.add(Event.debounce(this._contextKeyService.onDidChangeContext, (last2, event) => last2 || event.affectsSome(this._contextKeys), 50)((e2) => e2 && this._onDidChange.fire(void 0), this));
  }
  dispose() {
    this._dispoables.dispose();
    this._onDidChange.dispose();
  }
  _build() {
    this._menuGroups.length = 0;
    this._contextKeys.clear();
    const menuItems = MenuRegistry.getMenuItems(this._id);
    let group;
    menuItems.sort(Menu2._compareMenuItems);
    for (let item of menuItems) {
      const groupName = item.group || "";
      if (!group || group[0] !== groupName) {
        group = [groupName, []];
        this._menuGroups.push(group);
      }
      group[1].push(item);
      Menu2._fillInKbExprKeys(item.when, this._contextKeys);
      if (isIMenuItem(item) && item.command.precondition) {
        Menu2._fillInKbExprKeys(item.command.precondition, this._contextKeys);
      }
      if (isIMenuItem(item) && item.command.toggled) {
        const toggledExpression = item.command.toggled.condition || item.command.toggled;
        Menu2._fillInKbExprKeys(toggledExpression, this._contextKeys);
      }
    }
    this._onDidChange.fire(this);
  }
  get onDidChange() {
    return this._onDidChange.event;
  }
  getActions(options) {
    const result = [];
    for (let group of this._menuGroups) {
      const [id3, items] = group;
      const activeActions = [];
      for (const item of items) {
        if (this._contextKeyService.contextMatchesRules(item.when)) {
          const action = isIMenuItem(item) ? new MenuItemAction(item.command, item.alt, options, this._contextKeyService, this._commandService) : new SubmenuItemAction(item, this._menuService, this._contextKeyService, options);
          activeActions.push(action);
        }
      }
      if (activeActions.length > 0) {
        result.push([id3, activeActions]);
      }
    }
    return result;
  }
  static _fillInKbExprKeys(exp, set3) {
    if (exp) {
      for (let key of exp.keys()) {
        set3.add(key);
      }
    }
  }
  static _compareMenuItems(a2, b2) {
    let aGroup = a2.group;
    let bGroup = b2.group;
    if (aGroup !== bGroup) {
      if (!aGroup) {
        return 1;
      } else if (!bGroup) {
        return -1;
      }
      if (aGroup === "navigation") {
        return -1;
      } else if (bGroup === "navigation") {
        return 1;
      }
      let value = aGroup.localeCompare(bGroup);
      if (value !== 0) {
        return value;
      }
    }
    let aPrio = a2.order || 0;
    let bPrio = b2.order || 0;
    if (aPrio < bPrio) {
      return -1;
    } else if (aPrio > bPrio) {
      return 1;
    }
    return Menu2._compareTitles(isIMenuItem(a2) ? a2.command.title : a2.title, isIMenuItem(b2) ? b2.command.title : b2.title);
  }
  static _compareTitles(a2, b2) {
    const aStr = typeof a2 === "string" ? a2 : a2.value;
    const bStr = typeof b2 === "string" ? b2 : b2.value;
    return aStr.localeCompare(bStr);
  }
};
Menu$1 = __decorate$h([
  __param$d(1, ICommandService),
  __param$d(2, IContextKeyService),
  __param$d(3, IMenuService)
], Menu$1);
var IMarkerDecorationsService = createDecorator("markerDecorationsService");
var __decorate$i = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$e = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
function MODEL_ID$2(resource2) {
  return resource2.toString();
}
var MarkerDecorations = class extends Disposable {
  constructor(model) {
    super();
    this.model = model;
    this._markersData = new Map();
    this._register(toDisposable(() => {
      this.model.deltaDecorations([...this._markersData.keys()], []);
      this._markersData.clear();
    }));
  }
  update(markers, newDecorations) {
    const oldIds = [...this._markersData.keys()];
    this._markersData.clear();
    const ids = this.model.deltaDecorations(oldIds, newDecorations);
    for (let index3 = 0; index3 < ids.length; index3++) {
      this._markersData.set(ids[index3], markers[index3]);
    }
    return oldIds.length !== 0 || ids.length !== 0;
  }
  getMarker(decoration) {
    return this._markersData.get(decoration.id);
  }
};
var MarkerDecorationsService = class MarkerDecorationsService2 extends Disposable {
  constructor(modelService, _markerService) {
    super();
    this._markerService = _markerService;
    this._onDidChangeMarker = this._register(new Emitter());
    this._markerDecorations = new Map();
    modelService.getModels().forEach((model) => this._onModelAdded(model));
    this._register(modelService.onModelAdded(this._onModelAdded, this));
    this._register(modelService.onModelRemoved(this._onModelRemoved, this));
    this._register(this._markerService.onMarkerChanged(this._handleMarkerChange, this));
  }
  dispose() {
    super.dispose();
    this._markerDecorations.forEach((value) => value.dispose());
    this._markerDecorations.clear();
  }
  getMarker(model, decoration) {
    const markerDecorations = this._markerDecorations.get(MODEL_ID$2(model.uri));
    return markerDecorations ? markerDecorations.getMarker(decoration) || null : null;
  }
  _handleMarkerChange(changedResources) {
    changedResources.forEach((resource2) => {
      const markerDecorations = this._markerDecorations.get(MODEL_ID$2(resource2));
      if (markerDecorations) {
        this._updateDecorations(markerDecorations);
      }
    });
  }
  _onModelAdded(model) {
    const markerDecorations = new MarkerDecorations(model);
    this._markerDecorations.set(MODEL_ID$2(model.uri), markerDecorations);
    this._updateDecorations(markerDecorations);
  }
  _onModelRemoved(model) {
    const markerDecorations = this._markerDecorations.get(MODEL_ID$2(model.uri));
    if (markerDecorations) {
      markerDecorations.dispose();
      this._markerDecorations.delete(MODEL_ID$2(model.uri));
    }
    if (model.uri.scheme === Schemas.inMemory || model.uri.scheme === Schemas.internal || model.uri.scheme === Schemas.vscode) {
      if (this._markerService) {
        this._markerService.read({resource: model.uri}).map((marker) => marker.owner).forEach((owner) => this._markerService.remove(owner, [model.uri]));
      }
    }
  }
  _updateDecorations(markerDecorations) {
    const markers = this._markerService.read({resource: markerDecorations.model.uri, take: 500});
    let newModelDecorations = markers.map((marker) => {
      return {
        range: this._createDecorationRange(markerDecorations.model, marker),
        options: this._createDecorationOption(marker)
      };
    });
    if (markerDecorations.update(markers, newModelDecorations)) {
      this._onDidChangeMarker.fire(markerDecorations.model);
    }
  }
  _createDecorationRange(model, rawMarker) {
    let ret = Range.lift(rawMarker);
    if (rawMarker.severity === MarkerSeverity$1.Hint && !this._hasMarkerTag(rawMarker, 1) && !this._hasMarkerTag(rawMarker, 2)) {
      ret = ret.setEndPosition(ret.startLineNumber, ret.startColumn + 2);
    }
    ret = model.validateRange(ret);
    if (ret.isEmpty()) {
      let word = model.getWordAtPosition(ret.getStartPosition());
      if (word) {
        ret = new Range(ret.startLineNumber, word.startColumn, ret.endLineNumber, word.endColumn);
      } else {
        let maxColumn = model.getLineLastNonWhitespaceColumn(ret.startLineNumber) || model.getLineMaxColumn(ret.startLineNumber);
        if (maxColumn === 1)
          ;
        else if (ret.endColumn >= maxColumn) {
          ret = new Range(ret.startLineNumber, maxColumn - 1, ret.endLineNumber, maxColumn);
        } else {
          ret = new Range(ret.startLineNumber, ret.startColumn, ret.endLineNumber, ret.endColumn + 1);
        }
      }
    } else if (rawMarker.endColumn === Number.MAX_VALUE && rawMarker.startColumn === 1 && ret.startLineNumber === ret.endLineNumber) {
      let minColumn = model.getLineFirstNonWhitespaceColumn(rawMarker.startLineNumber);
      if (minColumn < ret.endColumn) {
        ret = new Range(ret.startLineNumber, minColumn, ret.endLineNumber, ret.endColumn);
        rawMarker.startColumn = minColumn;
      }
    }
    return ret;
  }
  _createDecorationOption(marker) {
    let className;
    let color2 = void 0;
    let zIndex;
    let inlineClassName = void 0;
    let minimap;
    switch (marker.severity) {
      case MarkerSeverity$1.Hint:
        if (this._hasMarkerTag(marker, 2)) {
          className = void 0;
        } else if (this._hasMarkerTag(marker, 1)) {
          className = "squiggly-unnecessary";
        } else {
          className = "squiggly-hint";
        }
        zIndex = 0;
        break;
      case MarkerSeverity$1.Warning:
        className = "squiggly-warning";
        color2 = themeColorFromId(overviewRulerWarning);
        zIndex = 20;
        minimap = {
          color: themeColorFromId(minimapWarning),
          position: MinimapPosition$1.Inline
        };
        break;
      case MarkerSeverity$1.Info:
        className = "squiggly-info";
        color2 = themeColorFromId(overviewRulerInfo);
        zIndex = 10;
        break;
      case MarkerSeverity$1.Error:
      default:
        className = "squiggly-error";
        color2 = themeColorFromId(overviewRulerError);
        zIndex = 30;
        minimap = {
          color: themeColorFromId(minimapError),
          position: MinimapPosition$1.Inline
        };
        break;
    }
    if (marker.tags) {
      if (marker.tags.indexOf(1) !== -1) {
        inlineClassName = "squiggly-inline-unnecessary";
      }
      if (marker.tags.indexOf(2) !== -1) {
        inlineClassName = "squiggly-inline-deprecated";
      }
    }
    return {
      stickiness: 1,
      className,
      showIfCollapsed: true,
      overviewRuler: {
        color: color2,
        position: OverviewRulerLane$1.Right
      },
      minimap,
      zIndex,
      inlineClassName
    };
  }
  _hasMarkerTag(marker, tag) {
    if (marker.tags) {
      return marker.tags.indexOf(tag) >= 0;
    }
    return false;
  }
};
MarkerDecorationsService = __decorate$i([
  __param$e(0, IModelService),
  __param$e(1, IMarkerService)
], MarkerDecorationsService);
var __decorate$j = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$f = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var AccessibilityService = class AccessibilityService2 extends Disposable {
  constructor(_contextKeyService, _configurationService) {
    super();
    this._contextKeyService = _contextKeyService;
    this._configurationService = _configurationService;
    this._accessibilitySupport = 0;
    this._onDidChangeScreenReaderOptimized = new Emitter();
    this._accessibilityModeEnabledContext = CONTEXT_ACCESSIBILITY_MODE_ENABLED.bindTo(this._contextKeyService);
    const updateContextKey = () => this._accessibilityModeEnabledContext.set(this.isScreenReaderOptimized());
    this._register(this._configurationService.onDidChangeConfiguration((e2) => {
      if (e2.affectsConfiguration("editor.accessibilitySupport")) {
        updateContextKey();
        this._onDidChangeScreenReaderOptimized.fire();
      }
    }));
    updateContextKey();
    this.onDidChangeScreenReaderOptimized(() => updateContextKey());
  }
  get onDidChangeScreenReaderOptimized() {
    return this._onDidChangeScreenReaderOptimized.event;
  }
  isScreenReaderOptimized() {
    const config2 = this._configurationService.getValue("editor.accessibilitySupport");
    return config2 === "on" || config2 === "auto" && this._accessibilitySupport === 2;
  }
  getAccessibilitySupport() {
    return this._accessibilitySupport;
  }
};
AccessibilityService = __decorate$j([
  __param$f(0, IContextKeyService),
  __param$f(1, IConfigurationService)
], AccessibilityService);
var __awaiter$8 = function(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var BrowserClipboardService = class {
  constructor() {
    this.mapTextToType = new Map();
    this.findText = "";
  }
  writeText(text, type) {
    return __awaiter$8(this, void 0, void 0, function* () {
      if (type) {
        this.mapTextToType.set(type, text);
        return;
      }
      try {
        return yield navigator.clipboard.writeText(text);
      } catch (error2) {
        console.error(error2);
      }
      const activeElement = document.activeElement;
      const textArea = document.body.appendChild($("textarea", {"aria-hidden": true}));
      textArea.style.height = "1px";
      textArea.style.width = "1px";
      textArea.style.position = "absolute";
      textArea.value = text;
      textArea.focus();
      textArea.select();
      document.execCommand("copy");
      if (activeElement instanceof HTMLElement) {
        activeElement.focus();
      }
      document.body.removeChild(textArea);
      return;
    });
  }
  readText(type) {
    return __awaiter$8(this, void 0, void 0, function* () {
      if (type) {
        return this.mapTextToType.get(type) || "";
      }
      try {
        return yield navigator.clipboard.readText();
      } catch (error2) {
        console.error(error2);
        return "";
      }
    });
  }
  readFindText() {
    return __awaiter$8(this, void 0, void 0, function* () {
      return this.findText;
    });
  }
  writeFindText(text) {
    return __awaiter$8(this, void 0, void 0, function* () {
      this.findText = text;
    });
  }
};
var __decorate$k = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$g = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$9 = function(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function getResourceLabel(resource2) {
  return resource2.scheme === Schemas.file ? resource2.fsPath : resource2.path;
}
var stackElementCounter = 0;
var ResourceStackElement = class {
  constructor(actual, resourceLabel, strResource) {
    this.id = ++stackElementCounter;
    this.type = 0;
    this.actual = actual;
    this.label = actual.label;
    this.resourceLabel = resourceLabel;
    this.strResource = strResource;
    this.resourceLabels = [this.resourceLabel];
    this.strResources = [this.strResource];
    this.isValid = true;
  }
  setValid(isValid) {
    this.isValid = isValid;
  }
  toString() {
    return `[${this.id}] [${this.isValid ? "VALID" : "INVALID"}] ${this.actual}`;
  }
};
var ResourceReasonPair = class {
  constructor(resourceLabel, reason) {
    this.resourceLabel = resourceLabel;
    this.reason = reason;
  }
};
var RemovedResources = class {
  constructor() {
    this.elements = new Map();
  }
  createMessage() {
    const externalRemoval = [];
    const noParallelUniverses = [];
    for (const [, element] of this.elements) {
      const dest = element.reason === 0 ? externalRemoval : noParallelUniverses;
      dest.push(element.resourceLabel);
    }
    let messages = [];
    if (externalRemoval.length > 0) {
      messages.push(localize({key: "externalRemoval", comment: ["{0} is a list of filenames"]}, "The following files have been closed and modified on disk: {0}.", externalRemoval.join(", ")));
    }
    if (noParallelUniverses.length > 0) {
      messages.push(localize({key: "noParallelUniverses", comment: ["{0} is a list of filenames"]}, "The following files have been modified in an incompatible way: {0}.", noParallelUniverses.join(", ")));
    }
    return messages.join("\n");
  }
  get size() {
    return this.elements.size;
  }
  has(strResource) {
    return this.elements.has(strResource);
  }
  set(strResource, value) {
    this.elements.set(strResource, value);
  }
  delete(strResource) {
    return this.elements.delete(strResource);
  }
};
var WorkspaceStackElement = class {
  constructor(actual, resourceLabels, strResources) {
    this.id = ++stackElementCounter;
    this.type = 1;
    this.actual = actual;
    this.label = actual.label;
    this.resourceLabels = resourceLabels;
    this.strResources = strResources;
    this.removedResources = null;
    this.invalidatedResources = null;
  }
  canSplit() {
    return typeof this.actual.split === "function";
  }
  removeResource(resourceLabel, strResource, reason) {
    if (!this.removedResources) {
      this.removedResources = new RemovedResources();
    }
    if (!this.removedResources.has(strResource)) {
      this.removedResources.set(strResource, new ResourceReasonPair(resourceLabel, reason));
    }
  }
  setValid(resourceLabel, strResource, isValid) {
    if (isValid) {
      if (this.invalidatedResources) {
        this.invalidatedResources.delete(strResource);
        if (this.invalidatedResources.size === 0) {
          this.invalidatedResources = null;
        }
      }
    } else {
      if (!this.invalidatedResources) {
        this.invalidatedResources = new RemovedResources();
      }
      if (!this.invalidatedResources.has(strResource)) {
        this.invalidatedResources.set(strResource, new ResourceReasonPair(resourceLabel, 0));
      }
    }
  }
  toString() {
    return `[${this.id}] [${this.invalidatedResources ? "INVALID" : "VALID"}] ${this.actual}`;
  }
};
var ResourceEditStack = class {
  constructor(resourceLabel, strResource) {
    this.resourceLabel = resourceLabel;
    this.strResource = strResource;
    this._past = [];
    this._future = [];
    this.locked = false;
    this.versionId = 1;
  }
  dispose() {
    for (const element of this._past) {
      if (element.type === 1) {
        element.removeResource(this.resourceLabel, this.strResource, 0);
      }
    }
    for (const element of this._future) {
      if (element.type === 1) {
        element.removeResource(this.resourceLabel, this.strResource, 0);
      }
    }
    this.versionId++;
  }
  toString() {
    let result = [];
    result.push(`* ${this.strResource}:`);
    for (let i3 = 0; i3 < this._past.length; i3++) {
      result.push(`   * [UNDO] ${this._past[i3]}`);
    }
    for (let i3 = this._future.length - 1; i3 >= 0; i3--) {
      result.push(`   * [REDO] ${this._future[i3]}`);
    }
    return result.join("\n");
  }
  flushAllElements() {
    this._past = [];
    this._future = [];
    this.versionId++;
  }
  _setElementValidFlag(element, isValid) {
    if (element.type === 1) {
      element.setValid(this.resourceLabel, this.strResource, isValid);
    } else {
      element.setValid(isValid);
    }
  }
  setElementsValidFlag(isValid, filter3) {
    for (const element of this._past) {
      if (filter3(element.actual)) {
        this._setElementValidFlag(element, isValid);
      }
    }
    for (const element of this._future) {
      if (filter3(element.actual)) {
        this._setElementValidFlag(element, isValid);
      }
    }
  }
  pushElement(element) {
    for (const futureElement of this._future) {
      if (futureElement.type === 1) {
        futureElement.removeResource(this.resourceLabel, this.strResource, 1);
      }
    }
    this._future = [];
    if (this._past.length > 0) {
      const lastElement = this._past[this._past.length - 1];
      if (lastElement.type === 0 && !lastElement.isValid) {
        this._past = [];
      }
    }
    this._past.push(element);
    this.versionId++;
  }
  createSnapshot(resource2) {
    const elements = [];
    for (let i3 = 0, len2 = this._past.length; i3 < len2; i3++) {
      elements.push(this._past[i3].id);
    }
    for (let i3 = this._future.length - 1; i3 >= 0; i3--) {
      elements.push(this._future[i3].id);
    }
    return new ResourceEditStackSnapshot(resource2, elements);
  }
  restoreSnapshot(snapshot) {
    const snapshotLength = snapshot.elements.length;
    let isOK = true;
    let snapshotIndex = 0;
    let removePastAfter = -1;
    for (let i3 = 0, len2 = this._past.length; i3 < len2; i3++, snapshotIndex++) {
      const element = this._past[i3];
      if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
        isOK = false;
        removePastAfter = 0;
      }
      if (!isOK && element.type === 1) {
        element.removeResource(this.resourceLabel, this.strResource, 0);
      }
    }
    let removeFutureBefore = -1;
    for (let i3 = this._future.length - 1; i3 >= 0; i3--, snapshotIndex++) {
      const element = this._future[i3];
      if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
        isOK = false;
        removeFutureBefore = i3;
      }
      if (!isOK && element.type === 1) {
        element.removeResource(this.resourceLabel, this.strResource, 0);
      }
    }
    if (removePastAfter !== -1) {
      this._past = this._past.slice(0, removePastAfter);
    }
    if (removeFutureBefore !== -1) {
      this._future = this._future.slice(removeFutureBefore + 1);
    }
    this.versionId++;
  }
  getElements() {
    const past = [];
    const future = [];
    for (const element of this._past) {
      past.push(element.actual);
    }
    for (const element of this._future) {
      future.push(element.actual);
    }
    return {past, future};
  }
  getClosestPastElement() {
    if (this._past.length === 0) {
      return null;
    }
    return this._past[this._past.length - 1];
  }
  getClosestFutureElement() {
    if (this._future.length === 0) {
      return null;
    }
    return this._future[this._future.length - 1];
  }
  hasPastElements() {
    return this._past.length > 0;
  }
  hasFutureElements() {
    return this._future.length > 0;
  }
  splitPastWorkspaceElement(toRemove, individualMap) {
    for (let j = this._past.length - 1; j >= 0; j--) {
      if (this._past[j] === toRemove) {
        if (individualMap.has(this.strResource)) {
          this._past[j] = individualMap.get(this.strResource);
        } else {
          this._past.splice(j, 1);
        }
        break;
      }
    }
    this.versionId++;
  }
  splitFutureWorkspaceElement(toRemove, individualMap) {
    for (let j = this._future.length - 1; j >= 0; j--) {
      if (this._future[j] === toRemove) {
        if (individualMap.has(this.strResource)) {
          this._future[j] = individualMap.get(this.strResource);
        } else {
          this._future.splice(j, 1);
        }
        break;
      }
    }
    this.versionId++;
  }
  moveBackward(element) {
    this._past.pop();
    this._future.push(element);
    this.versionId++;
  }
  moveForward(element) {
    this._future.pop();
    this._past.push(element);
    this.versionId++;
  }
};
var EditStackSnapshot = class {
  constructor(editStacks) {
    this.editStacks = editStacks;
    this._versionIds = [];
    for (let i3 = 0, len2 = this.editStacks.length; i3 < len2; i3++) {
      this._versionIds[i3] = this.editStacks[i3].versionId;
    }
  }
  isValid() {
    for (let i3 = 0, len2 = this.editStacks.length; i3 < len2; i3++) {
      if (this._versionIds[i3] !== this.editStacks[i3].versionId) {
        return false;
      }
    }
    return true;
  }
};
var missingEditStack = new ResourceEditStack("", "");
missingEditStack.locked = true;
var UndoRedoService = class UndoRedoService2 {
  constructor(_dialogService, _notificationService) {
    this._dialogService = _dialogService;
    this._notificationService = _notificationService;
    this._editStacks = new Map();
    this._uriComparisonKeyComputers = [];
  }
  getUriComparisonKey(resource2) {
    for (const uriComparisonKeyComputer of this._uriComparisonKeyComputers) {
      if (uriComparisonKeyComputer[0] === resource2.scheme) {
        return uriComparisonKeyComputer[1].getComparisonKey(resource2);
      }
    }
    return resource2.toString();
  }
  _print(label2) {
    console.log(`------------------------------------`);
    console.log(`AFTER ${label2}: `);
    let str = [];
    for (const element of this._editStacks) {
      str.push(element[1].toString());
    }
    console.log(str.join("\n"));
  }
  pushElement(element) {
    if (element.type === 0) {
      const resourceLabel = getResourceLabel(element.resource);
      const strResource = this.getUriComparisonKey(element.resource);
      this._pushElement(new ResourceStackElement(element, resourceLabel, strResource));
    } else {
      const seen = new Set();
      const resourceLabels = [];
      const strResources = [];
      for (const resource2 of element.resources) {
        const resourceLabel = getResourceLabel(resource2);
        const strResource = this.getUriComparisonKey(resource2);
        if (seen.has(strResource)) {
          continue;
        }
        seen.add(strResource);
        resourceLabels.push(resourceLabel);
        strResources.push(strResource);
      }
      if (resourceLabels.length === 1) {
        this._pushElement(new ResourceStackElement(element, resourceLabels[0], strResources[0]));
      } else {
        this._pushElement(new WorkspaceStackElement(element, resourceLabels, strResources));
      }
    }
  }
  _pushElement(element) {
    for (let i3 = 0, len2 = element.strResources.length; i3 < len2; i3++) {
      const resourceLabel = element.resourceLabels[i3];
      const strResource = element.strResources[i3];
      let editStack;
      if (this._editStacks.has(strResource)) {
        editStack = this._editStacks.get(strResource);
      } else {
        editStack = new ResourceEditStack(resourceLabel, strResource);
        this._editStacks.set(strResource, editStack);
      }
      editStack.pushElement(element);
    }
  }
  getLastElement(resource2) {
    const strResource = this.getUriComparisonKey(resource2);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      if (editStack.hasFutureElements()) {
        return null;
      }
      const closestPastElement = editStack.getClosestPastElement();
      return closestPastElement ? closestPastElement.actual : null;
    }
    return null;
  }
  _splitPastWorkspaceElement(toRemove, ignoreResources) {
    const individualArr = toRemove.actual.split();
    const individualMap = new Map();
    for (const _element of individualArr) {
      const resourceLabel = getResourceLabel(_element.resource);
      const strResource = this.getUriComparisonKey(_element.resource);
      const element = new ResourceStackElement(_element, resourceLabel, strResource);
      individualMap.set(element.strResource, element);
    }
    for (const strResource of toRemove.strResources) {
      if (ignoreResources && ignoreResources.has(strResource)) {
        continue;
      }
      const editStack = this._editStacks.get(strResource);
      editStack.splitPastWorkspaceElement(toRemove, individualMap);
    }
  }
  _splitFutureWorkspaceElement(toRemove, ignoreResources) {
    const individualArr = toRemove.actual.split();
    const individualMap = new Map();
    for (const _element of individualArr) {
      const resourceLabel = getResourceLabel(_element.resource);
      const strResource = this.getUriComparisonKey(_element.resource);
      const element = new ResourceStackElement(_element, resourceLabel, strResource);
      individualMap.set(element.strResource, element);
    }
    for (const strResource of toRemove.strResources) {
      if (ignoreResources && ignoreResources.has(strResource)) {
        continue;
      }
      const editStack = this._editStacks.get(strResource);
      editStack.splitFutureWorkspaceElement(toRemove, individualMap);
    }
  }
  removeElements(resource2) {
    const strResource = typeof resource2 === "string" ? resource2 : this.getUriComparisonKey(resource2);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      editStack.dispose();
      this._editStacks.delete(strResource);
    }
  }
  setElementsValidFlag(resource2, isValid, filter3) {
    const strResource = this.getUriComparisonKey(resource2);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      editStack.setElementsValidFlag(isValid, filter3);
    }
  }
  createSnapshot(resource2) {
    const strResource = this.getUriComparisonKey(resource2);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      return editStack.createSnapshot(resource2);
    }
    return new ResourceEditStackSnapshot(resource2, []);
  }
  restoreSnapshot(snapshot) {
    const strResource = this.getUriComparisonKey(snapshot.resource);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      editStack.restoreSnapshot(snapshot);
      if (!editStack.hasPastElements() && !editStack.hasFutureElements()) {
        editStack.dispose();
        this._editStacks.delete(strResource);
      }
    }
  }
  getElements(resource2) {
    const strResource = this.getUriComparisonKey(resource2);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      return editStack.getElements();
    }
    return {past: [], future: []};
  }
  canUndo(resource2) {
    const strResource = this.getUriComparisonKey(resource2);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      return editStack.hasPastElements();
    }
    return false;
  }
  _onError(err, element) {
    onUnexpectedError(err);
    for (const strResource of element.strResources) {
      this.removeElements(strResource);
    }
    this._notificationService.error(err);
  }
  _acquireLocks(editStackSnapshot) {
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.locked) {
        throw new Error("Cannot acquire edit stack lock");
      }
    }
    for (const editStack of editStackSnapshot.editStacks) {
      editStack.locked = true;
    }
    return () => {
      for (const editStack of editStackSnapshot.editStacks) {
        editStack.locked = false;
      }
    };
  }
  _safeInvokeWithLocks(element, invoke, editStackSnapshot, cleanup2 = Disposable.None) {
    const releaseLocks = this._acquireLocks(editStackSnapshot);
    let result;
    try {
      result = invoke();
    } catch (err) {
      releaseLocks();
      cleanup2.dispose();
      return this._onError(err, element);
    }
    if (result) {
      return result.then(() => {
        releaseLocks();
        cleanup2.dispose();
      }, (err) => {
        releaseLocks();
        cleanup2.dispose();
        return this._onError(err, element);
      });
    } else {
      releaseLocks();
      cleanup2.dispose();
    }
  }
  _invokeWorkspacePrepare(element) {
    return __awaiter$9(this, void 0, void 0, function* () {
      if (typeof element.actual.prepareUndoRedo === "undefined") {
        return Disposable.None;
      }
      const result = element.actual.prepareUndoRedo();
      if (typeof result === "undefined") {
        return Disposable.None;
      }
      return result;
    });
  }
  _invokeResourcePrepare(element, callback) {
    if (element.actual.type !== 1 || typeof element.actual.prepareUndoRedo === "undefined") {
      callback(Disposable.None);
      return;
    }
    const r3 = element.actual.prepareUndoRedo();
    if (!r3) {
      callback(Disposable.None);
      return;
    }
    if (isDisposable(r3)) {
      callback(r3);
      return;
    }
    return r3.then((disposable) => {
      callback(disposable);
    });
  }
  _getAffectedEditStacks(element) {
    const affectedEditStacks = [];
    for (const strResource of element.strResources) {
      affectedEditStacks.push(this._editStacks.get(strResource) || missingEditStack);
    }
    return new EditStackSnapshot(affectedEditStacks);
  }
  _tryToSplitAndUndo(strResource, element, ignoreResources, message) {
    if (element.canSplit()) {
      this._splitPastWorkspaceElement(element, ignoreResources);
      this._notificationService.info(message);
      return new WorkspaceVerificationError(this.undo(strResource));
    } else {
      for (const strResource2 of element.strResources) {
        this.removeElements(strResource2);
      }
      this._notificationService.info(message);
      return new WorkspaceVerificationError();
    }
  }
  _checkWorkspaceUndo(strResource, element, editStackSnapshot, checkInvalidatedResources) {
    if (element.removedResources) {
      return this._tryToSplitAndUndo(strResource, element, element.removedResources, localize({key: "cannotWorkspaceUndo", comment: ["{0} is a label for an operation. {1} is another message."]}, "Could not undo '{0}' across all files. {1}", element.label, element.removedResources.createMessage()));
    }
    if (checkInvalidatedResources && element.invalidatedResources) {
      return this._tryToSplitAndUndo(strResource, element, element.invalidatedResources, localize({key: "cannotWorkspaceUndo", comment: ["{0} is a label for an operation. {1} is another message."]}, "Could not undo '{0}' across all files. {1}", element.label, element.invalidatedResources.createMessage()));
    }
    const cannotUndoDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.getClosestPastElement() !== element) {
        cannotUndoDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotUndoDueToResources.length > 0) {
      return this._tryToSplitAndUndo(strResource, element, null, localize({key: "cannotWorkspaceUndoDueToChanges", comment: ["{0} is a label for an operation. {1} is a list of filenames."]}, "Could not undo '{0}' across all files because changes were made to {1}", element.label, cannotUndoDueToResources.join(", ")));
    }
    const cannotLockDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.locked) {
        cannotLockDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotLockDueToResources.length > 0) {
      return this._tryToSplitAndUndo(strResource, element, null, localize({key: "cannotWorkspaceUndoDueToInProgressUndoRedo", comment: ["{0} is a label for an operation. {1} is a list of filenames."]}, "Could not undo '{0}' across all files because there is already an undo or redo operation running on {1}", element.label, cannotLockDueToResources.join(", ")));
    }
    if (!editStackSnapshot.isValid()) {
      return this._tryToSplitAndUndo(strResource, element, null, localize({key: "cannotWorkspaceUndoDueToInMeantimeUndoRedo", comment: ["{0} is a label for an operation. {1} is a list of filenames."]}, "Could not undo '{0}' across all files because an undo or redo operation occurred in the meantime", element.label));
    }
    return null;
  }
  _workspaceUndo(strResource, element) {
    const affectedEditStacks = this._getAffectedEditStacks(element);
    const verificationError = this._checkWorkspaceUndo(strResource, element, affectedEditStacks, false);
    if (verificationError) {
      return verificationError.returnValue;
    }
    return this._confirmAndExecuteWorkspaceUndo(strResource, element, affectedEditStacks);
  }
  _confirmAndExecuteWorkspaceUndo(strResource, element, editStackSnapshot) {
    return __awaiter$9(this, void 0, void 0, function* () {
      if (element.canSplit()) {
        const result = yield this._dialogService.show(Severity$1.Info, localize("confirmWorkspace", "Would you like to undo '{0}' across all files?", element.label), [
          localize({key: "ok", comment: ["{0} denotes a number that is > 1"]}, "Undo in {0} Files", editStackSnapshot.editStacks.length),
          localize("nok", "Undo this File"),
          localize("cancel", "Cancel")
        ], {
          cancelId: 2
        });
        if (result.choice === 2) {
          return;
        }
        if (result.choice === 1) {
          this._splitPastWorkspaceElement(element, null);
          return this.undo(strResource);
        }
        const verificationError1 = this._checkWorkspaceUndo(strResource, element, editStackSnapshot, false);
        if (verificationError1) {
          return verificationError1.returnValue;
        }
      }
      let cleanup2;
      try {
        cleanup2 = yield this._invokeWorkspacePrepare(element);
      } catch (err) {
        return this._onError(err, element);
      }
      const verificationError2 = this._checkWorkspaceUndo(strResource, element, editStackSnapshot, true);
      if (verificationError2) {
        cleanup2.dispose();
        return verificationError2.returnValue;
      }
      for (const editStack of editStackSnapshot.editStacks) {
        editStack.moveBackward(element);
      }
      return this._safeInvokeWithLocks(element, () => element.actual.undo(), editStackSnapshot, cleanup2);
    });
  }
  _resourceUndo(editStack, element) {
    if (!element.isValid) {
      editStack.flushAllElements();
      return;
    }
    if (editStack.locked) {
      const message = localize({key: "cannotResourceUndoDueToInProgressUndoRedo", comment: ["{0} is a label for an operation."]}, "Could not undo '{0}' because there is already an undo or redo operation running.", element.label);
      this._notificationService.info(message);
      return;
    }
    return this._invokeResourcePrepare(element, (cleanup2) => {
      editStack.moveBackward(element);
      return this._safeInvokeWithLocks(element, () => element.actual.undo(), new EditStackSnapshot([editStack]), cleanup2);
    });
  }
  undo(resource2) {
    const strResource = typeof resource2 === "string" ? resource2 : this.getUriComparisonKey(resource2);
    if (!this._editStacks.has(strResource)) {
      return;
    }
    const editStack = this._editStacks.get(strResource);
    const element = editStack.getClosestPastElement();
    if (!element) {
      return;
    }
    try {
      if (element.type === 1) {
        return this._workspaceUndo(strResource, element);
      } else {
        return this._resourceUndo(editStack, element);
      }
    } finally {
    }
  }
  canRedo(resource2) {
    const strResource = this.getUriComparisonKey(resource2);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      return editStack.hasFutureElements();
    }
    return false;
  }
  _tryToSplitAndRedo(strResource, element, ignoreResources, message) {
    if (element.canSplit()) {
      this._splitFutureWorkspaceElement(element, ignoreResources);
      this._notificationService.info(message);
      return new WorkspaceVerificationError(this.redo(strResource));
    } else {
      for (const strResource2 of element.strResources) {
        this.removeElements(strResource2);
      }
      this._notificationService.info(message);
      return new WorkspaceVerificationError();
    }
  }
  _checkWorkspaceRedo(strResource, element, editStackSnapshot, checkInvalidatedResources) {
    if (element.removedResources) {
      return this._tryToSplitAndRedo(strResource, element, element.removedResources, localize({key: "cannotWorkspaceRedo", comment: ["{0} is a label for an operation. {1} is another message."]}, "Could not redo '{0}' across all files. {1}", element.label, element.removedResources.createMessage()));
    }
    if (checkInvalidatedResources && element.invalidatedResources) {
      return this._tryToSplitAndRedo(strResource, element, element.invalidatedResources, localize({key: "cannotWorkspaceRedo", comment: ["{0} is a label for an operation. {1} is another message."]}, "Could not redo '{0}' across all files. {1}", element.label, element.invalidatedResources.createMessage()));
    }
    const cannotRedoDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.getClosestFutureElement() !== element) {
        cannotRedoDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotRedoDueToResources.length > 0) {
      return this._tryToSplitAndRedo(strResource, element, null, localize({key: "cannotWorkspaceRedoDueToChanges", comment: ["{0} is a label for an operation. {1} is a list of filenames."]}, "Could not redo '{0}' across all files because changes were made to {1}", element.label, cannotRedoDueToResources.join(", ")));
    }
    const cannotLockDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.locked) {
        cannotLockDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotLockDueToResources.length > 0) {
      return this._tryToSplitAndRedo(strResource, element, null, localize({key: "cannotWorkspaceRedoDueToInProgressUndoRedo", comment: ["{0} is a label for an operation. {1} is a list of filenames."]}, "Could not redo '{0}' across all files because there is already an undo or redo operation running on {1}", element.label, cannotLockDueToResources.join(", ")));
    }
    if (!editStackSnapshot.isValid()) {
      return this._tryToSplitAndRedo(strResource, element, null, localize({key: "cannotWorkspaceRedoDueToInMeantimeUndoRedo", comment: ["{0} is a label for an operation. {1} is a list of filenames."]}, "Could not redo '{0}' across all files because an undo or redo operation occurred in the meantime", element.label));
    }
    return null;
  }
  _workspaceRedo(strResource, element) {
    const affectedEditStacks = this._getAffectedEditStacks(element);
    const verificationError = this._checkWorkspaceRedo(strResource, element, affectedEditStacks, false);
    if (verificationError) {
      return verificationError.returnValue;
    }
    return this._executeWorkspaceRedo(strResource, element, affectedEditStacks);
  }
  _executeWorkspaceRedo(strResource, element, editStackSnapshot) {
    return __awaiter$9(this, void 0, void 0, function* () {
      let cleanup2;
      try {
        cleanup2 = yield this._invokeWorkspacePrepare(element);
      } catch (err) {
        return this._onError(err, element);
      }
      const verificationError = this._checkWorkspaceRedo(strResource, element, editStackSnapshot, true);
      if (verificationError) {
        cleanup2.dispose();
        return verificationError.returnValue;
      }
      for (const editStack of editStackSnapshot.editStacks) {
        editStack.moveForward(element);
      }
      return this._safeInvokeWithLocks(element, () => element.actual.redo(), editStackSnapshot, cleanup2);
    });
  }
  _resourceRedo(editStack, element) {
    if (!element.isValid) {
      editStack.flushAllElements();
      return;
    }
    if (editStack.locked) {
      const message = localize({key: "cannotResourceRedoDueToInProgressUndoRedo", comment: ["{0} is a label for an operation."]}, "Could not redo '{0}' because there is already an undo or redo operation running.", element.label);
      this._notificationService.info(message);
      return;
    }
    return this._invokeResourcePrepare(element, (cleanup2) => {
      editStack.moveForward(element);
      return this._safeInvokeWithLocks(element, () => element.actual.redo(), new EditStackSnapshot([editStack]), cleanup2);
    });
  }
  redo(resource2) {
    const strResource = typeof resource2 === "string" ? resource2 : this.getUriComparisonKey(resource2);
    if (!this._editStacks.has(strResource)) {
      return;
    }
    const editStack = this._editStacks.get(strResource);
    const element = editStack.getClosestFutureElement();
    if (!element) {
      return;
    }
    try {
      if (element.type === 1) {
        return this._workspaceRedo(strResource, element);
      } else {
        return this._resourceRedo(editStack, element);
      }
    } finally {
    }
  }
};
UndoRedoService = __decorate$k([
  __param$g(0, IDialogService),
  __param$g(1, INotificationService)
], UndoRedoService);
var WorkspaceVerificationError = class {
  constructor(returnValue) {
    this.returnValue = returnValue;
  }
};
registerSingleton(IUndoRedoService, UndoRedoService);
function __snowpack__injectStyle$v(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$v("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.quick-input-widget {\r\n	font-size: 13px;\r\n}\r\n\r\n.quick-input-widget .monaco-highlighted-label .highlight,\r\n.quick-input-widget .monaco-highlighted-label .highlight {\r\n	color: #0066BF;\r\n}\r\n\r\n.vs-dark .quick-input-widget .monaco-highlighted-label .highlight,\r\n.vs-dark .quick-input-widget .monaco-highlighted-label .highlight {\r\n	color: #0097fb;\r\n}\r\n\r\n.hc-black .quick-input-widget .monaco-highlighted-label .highlight,\r\n.hc-black .quick-input-widget .monaco-highlighted-label .highlight {\r\n	color: #F38518;\r\n}\r\n");
function __snowpack__injectStyle$w(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$w("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.quick-input-widget {\r\n	position: absolute;\r\n	width: 600px;\r\n	z-index: 2000;\r\n	padding-bottom: 6px;\r\n	left: 50%;\r\n	margin-left: -300px;\r\n}\r\n\r\n.quick-input-titlebar {\r\n	display: flex;\r\n}\r\n\r\n.quick-input-left-action-bar {\r\n	display: flex;\r\n	margin-left: 4px;\r\n	flex: 1;\r\n}\r\n\r\n.quick-input-left-action-bar.monaco-action-bar .actions-container {\r\n	justify-content: flex-start;\r\n}\r\n\r\n.quick-input-title {\r\n	padding: 3px 0px;\r\n	text-align: center;\r\n}\r\n\r\n.quick-input-right-action-bar {\r\n	display: flex;\r\n	margin-right: 4px;\r\n	flex: 1;\r\n}\r\n\r\n.quick-input-titlebar .monaco-action-bar .action-label.codicon {\r\n	margin: 0;\r\n	width: 19px;\r\n	height: 100%;\r\n	background-position: center;\r\n	background-repeat: no-repeat;\r\n}\r\n\r\n.quick-input-description {\r\n	margin: 6px;\r\n}\r\n\r\n.quick-input-header {\r\n	display: flex;\r\n	padding: 6px 6px 0px 6px;\r\n	margin-bottom: -2px;\r\n}\r\n\r\n.quick-input-widget.hidden-input .quick-input-header {\r\n	/* reduce margins and paddings when input box hidden */\r\n	padding: 0;\r\n	margin-bottom: 0;\r\n}\r\n\r\n.quick-input-and-message {\r\n	display: flex;\r\n	flex-direction: column;\r\n	flex-grow: 1;\r\n	position: relative;\r\n}\r\n\r\n.quick-input-check-all {\r\n	align-self: center;\r\n	margin: 0;\r\n}\r\n\r\n.quick-input-filter {\r\n	flex-grow: 1;\r\n	display: flex;\r\n	position: relative;\r\n}\r\n\r\n.quick-input-box {\r\n	flex-grow: 1;\r\n}\r\n\r\n.quick-input-widget.show-checkboxes .quick-input-box,\r\n.quick-input-widget.show-checkboxes .quick-input-message {\r\n	margin-left: 5px;\r\n}\r\n\r\n.quick-input-visible-count {\r\n	position: absolute;\r\n	left: -10000px;\r\n}\r\n\r\n.quick-input-count {\r\n	align-self: center;\r\n	position: absolute;\r\n	right: 4px;\r\n	display: flex;\r\n	align-items: center;\r\n}\r\n\r\n.quick-input-count .monaco-count-badge {\r\n	vertical-align: middle;\r\n	padding: 2px 4px;\r\n	border-radius: 2px;\r\n	min-height: auto;\r\n	line-height: normal;\r\n}\r\n\r\n.quick-input-action {\r\n	margin-left: 6px;\r\n}\r\n\r\n.quick-input-action .monaco-text-button {\r\n	font-size: 11px;\r\n	padding: 0 6px;\r\n	display: flex;\r\n	height: 100%;\r\n	align-items: center;\r\n}\r\n\r\n.quick-input-message {\r\n	margin-top: -1px;\r\n	padding: 5px 5px 2px 5px;\r\n}\r\n\r\n.quick-input-progress.monaco-progress-container {\r\n	position: relative;\r\n}\r\n\r\n.quick-input-progress.monaco-progress-container,\r\n.quick-input-progress.monaco-progress-container .progress-bit {\r\n	height: 2px;\r\n}\r\n\r\n.quick-input-list {\r\n	line-height: 22px;\r\n	margin-top: 6px;\r\n}\r\n\r\n.quick-input-widget.hidden-input .quick-input-list {\r\n	margin-top: 0; /* reduce margins when input box hidden */\r\n}\r\n\r\n.quick-input-list .monaco-list {\r\n	overflow: hidden;\r\n	max-height: calc(20 * 22px);\r\n}\r\n\r\n.quick-input-list .quick-input-list-entry {\r\n	box-sizing: border-box;\r\n	overflow: hidden;\r\n	display: flex;\r\n	height: 100%;\r\n	padding: 0 6px;\r\n}\r\n\r\n.quick-input-list .quick-input-list-entry.quick-input-list-separator-border {\r\n	border-top-width: 1px;\r\n	border-top-style: solid;\r\n}\r\n\r\n.quick-input-list .monaco-list-row:first-child .quick-input-list-entry.quick-input-list-separator-border {\r\n	border-top-style: none;\r\n}\r\n\r\n.quick-input-list .quick-input-list-label {\r\n	overflow: hidden;\r\n	display: flex;\r\n	height: 100%;\r\n	flex: 1;\r\n}\r\n\r\n.quick-input-list .quick-input-list-checkbox {\r\n	align-self: center;\r\n	margin: 0;\r\n}\r\n\r\n.quick-input-list .quick-input-list-rows {\r\n	overflow: hidden;\r\n	text-overflow: ellipsis;\r\n	display: flex;\r\n	flex-direction: column;\r\n	height: 100%;\r\n	flex: 1;\r\n	margin-left: 5px;\r\n}\r\n\r\n.quick-input-widget.show-checkboxes .quick-input-list .quick-input-list-rows {\r\n	margin-left: 10px;\r\n}\r\n\r\n.quick-input-widget .quick-input-list .quick-input-list-checkbox {\r\n	display: none;\r\n}\r\n.quick-input-widget.show-checkboxes .quick-input-list .quick-input-list-checkbox {\r\n	display: inline;\r\n}\r\n\r\n.quick-input-list .quick-input-list-rows > .quick-input-list-row {\r\n	display: flex;\r\n	align-items: center;\r\n}\r\n\r\n.quick-input-list .quick-input-list-rows > .quick-input-list-row .monaco-icon-label,\r\n.quick-input-list .quick-input-list-rows > .quick-input-list-row .monaco-icon-label .monaco-icon-label-container > .monaco-icon-name-container {\r\n	flex: 1; /* make sure the icon label grows within the row */\r\n}\r\n\r\n.quick-input-list .quick-input-list-rows > .quick-input-list-row .codicon[class*='codicon-'] {\r\n	vertical-align: sub;\r\n}\r\n\r\n.quick-input-list .quick-input-list-rows .monaco-highlighted-label span {\r\n	opacity: 1;\r\n}\r\n\r\n.quick-input-list .quick-input-list-entry .quick-input-list-entry-keybinding {\r\n	margin-right: 8px; /* separate from the separator label or scrollbar if any */\r\n}\r\n\r\n.quick-input-list .quick-input-list-label-meta {\r\n	opacity: 0.7;\r\n	line-height: normal;\r\n	text-overflow: ellipsis;\r\n	overflow: hidden;\r\n}\r\n\r\n.quick-input-list .monaco-highlighted-label .highlight {\r\n	font-weight: bold;\r\n}\r\n\r\n.quick-input-list .quick-input-list-entry .quick-input-list-separator {\r\n	margin-right: 8px; /* separate from keybindings or actions */\r\n}\r\n\r\n.quick-input-list .quick-input-list-entry-action-bar {\r\n	display: flex;\r\n	flex: 0;\r\n	overflow: visible;\r\n}\r\n\r\n.quick-input-list .quick-input-list-entry-action-bar .action-label {\r\n	/*\r\n	 * By default, actions in the quick input action bar are hidden\r\n	 * until hovered over them or selected.\r\n	 */\r\n	display: none;\r\n}\r\n\r\n.quick-input-list .quick-input-list-entry-action-bar .action-label.codicon {\r\n	margin: 0;\r\n	height: 100%;\r\n	padding: 0 2px;\r\n	vertical-align: middle;\r\n}\r\n\r\n.quick-input-list .quick-input-list-entry-action-bar {\r\n	margin-top: 1px;\r\n}\r\n\r\n.quick-input-list .quick-input-list-entry-action-bar {\r\n	margin-right: 4px; /* separate from scrollbar */\r\n}\r\n\r\n.quick-input-list .quick-input-list-entry-action-bar .action-label.codicon {\r\n	margin-right: 4px; /* separate actions */\r\n}\r\n\r\n.quick-input-list .quick-input-list-entry .quick-input-list-entry-action-bar .action-label.always-visible,\r\n.quick-input-list .quick-input-list-entry:hover .quick-input-list-entry-action-bar .action-label,\r\n.quick-input-list .monaco-list-row.focused .quick-input-list-entry-action-bar .action-label {\r\n	display: flex;\r\n}\r\n");
var NO_KEY_MODS = {ctrlCmd: false, alt: false};
var ItemActivation;
(function(ItemActivation2) {
  ItemActivation2[ItemActivation2["NONE"] = 0] = "NONE";
  ItemActivation2[ItemActivation2["FIRST"] = 1] = "FIRST";
  ItemActivation2[ItemActivation2["SECOND"] = 2] = "SECOND";
  ItemActivation2[ItemActivation2["LAST"] = 3] = "LAST";
})(ItemActivation || (ItemActivation = {}));
var intlFileNameCollatorBaseNumeric = new IdleValue(() => {
  const collator = new Intl.Collator(void 0, {numeric: true, sensitivity: "base"});
  return {
    collator,
    collatorIsNumeric: collator.resolvedOptions().numeric
  };
});
function compareFileNames(one2, other, caseSensitive = false) {
  const a2 = one2 || "";
  const b2 = other || "";
  const result = intlFileNameCollatorBaseNumeric.value.collator.compare(a2, b2);
  if (intlFileNameCollatorBaseNumeric.value.collatorIsNumeric && result === 0 && a2 !== b2) {
    return a2 < b2 ? -1 : 1;
  }
  return result;
}
function compareAnything(one2, other, lookFor) {
  const elementAName = one2.toLowerCase();
  const elementBName = other.toLowerCase();
  const prefixCompare = compareByPrefix(one2, other, lookFor);
  if (prefixCompare) {
    return prefixCompare;
  }
  const elementASuffixMatch = elementAName.endsWith(lookFor);
  const elementBSuffixMatch = elementBName.endsWith(lookFor);
  if (elementASuffixMatch !== elementBSuffixMatch) {
    return elementASuffixMatch ? -1 : 1;
  }
  const r3 = compareFileNames(elementAName, elementBName);
  if (r3 !== 0) {
    return r3;
  }
  return elementAName.localeCompare(elementBName);
}
function compareByPrefix(one2, other, lookFor) {
  const elementAName = one2.toLowerCase();
  const elementBName = other.toLowerCase();
  const elementAPrefixMatch = elementAName.startsWith(lookFor);
  const elementBPrefixMatch = elementBName.startsWith(lookFor);
  if (elementAPrefixMatch !== elementBPrefixMatch) {
    return elementAPrefixMatch ? -1 : 1;
  } else if (elementAPrefixMatch && elementBPrefixMatch) {
    if (elementAName.length < elementBName.length) {
      return -1;
    }
    if (elementAName.length > elementBName.length) {
      return 1;
    }
  }
  return 0;
}
function __snowpack__injectStyle$x(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$x("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n/* ---------- Icon label ---------- */\r\n\r\n.monaco-icon-label {\r\n	display: flex; /* required for icons support :before rule */\r\n	overflow: hidden;\r\n	text-overflow: ellipsis;\r\n}\r\n\r\n.monaco-icon-label::before {\r\n\r\n	/* svg icons rendered as background image */\r\n	background-size: 16px;\r\n	background-position: left center;\r\n	background-repeat: no-repeat;\r\n	padding-right: 6px;\r\n	width: 16px;\r\n	height: 22px;\r\n	line-height: inherit !important;\r\n	display: inline-block;\r\n\r\n	/* fonts icons */\r\n	-webkit-font-smoothing: antialiased;\r\n	-moz-osx-font-smoothing: grayscale;\r\n	vertical-align: top;\r\n\r\n	flex-shrink: 0; /* fix for https://github.com/Microsoft/vscode/issues/13787 */\r\n}\r\n\r\n.monaco-icon-label > .monaco-icon-label-container {\r\n	min-width: 0;\r\n	overflow: hidden;\r\n	text-overflow: ellipsis;\r\n	flex: 1;\r\n}\r\n\r\n.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-name-container > .label-name {\r\n	color: inherit;\r\n	white-space: pre; /* enable to show labels that include multiple whitespaces */\r\n}\r\n\r\n.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-name-container > .label-name > .label-separator {\r\n	margin: 0 2px;\r\n	opacity: 0.5;\r\n}\r\n\r\n.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {\r\n	opacity: .7;\r\n	margin-left: 0.5em;\r\n	font-size: 0.9em;\r\n	white-space: pre; /* enable to show labels that include multiple whitespaces */\r\n}\r\n\r\n.vs .monaco-icon-label > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {\r\n	opacity: .95;\r\n}\r\n\r\n.monaco-icon-label.italic > .monaco-icon-label-container > .monaco-icon-name-container > .label-name,\r\n.monaco-icon-label.italic > .monaco-icon-description-container > .label-description {\r\n	font-style: italic;\r\n}\r\n\r\n.monaco-icon-label.strikethrough > .monaco-icon-label-container > .monaco-icon-name-container > .label-name,\r\n.monaco-icon-label.strikethrough > .monaco-icon-description-container > .label-description {\r\n	text-decoration: line-through;\r\n}\r\n\r\n.monaco-icon-label::after {\r\n	opacity: 0.75;\r\n	font-size: 90%;\r\n	font-weight: 600;\r\n	padding: 0 16px 0 5px;\r\n	text-align: center;\r\n}\r\n\r\n/* make sure selection color wins when a label is being selected */\r\n.monaco-list:focus .selected .monaco-icon-label, /* list */\r\n.monaco-list:focus .selected .monaco-icon-label::after\r\n{\r\n	color: inherit !important;\r\n}\r\n\r\n.monaco-list-row.focused.selected .label-description,\r\n.monaco-list-row.selected .label-description {\r\n	opacity: .8;\r\n}\r\n");
var HighlightedLabel = class {
  constructor(container, supportCodicons) {
    this.supportCodicons = supportCodicons;
    this.text = "";
    this.title = "";
    this.highlights = [];
    this.didEverRender = false;
    this.domNode = document.createElement("span");
    this.domNode.className = "monaco-highlighted-label";
    container.appendChild(this.domNode);
  }
  get element() {
    return this.domNode;
  }
  set(text, highlights = [], title3 = "", escapeNewLines) {
    if (!text) {
      text = "";
    }
    if (escapeNewLines) {
      text = HighlightedLabel.escapeNewLines(text, highlights);
    }
    if (this.didEverRender && this.text === text && this.title === title3 && equals$1(this.highlights, highlights)) {
      return;
    }
    if (!Array.isArray(highlights)) {
      highlights = [];
    }
    this.text = text;
    this.title = title3;
    this.highlights = highlights;
    this.render();
  }
  render() {
    let htmlContent = "";
    let pos = 0;
    for (const highlight of this.highlights) {
      if (highlight.end === highlight.start) {
        continue;
      }
      if (pos < highlight.start) {
        htmlContent += "<span>";
        const substring2 = this.text.substring(pos, highlight.start);
        htmlContent += this.supportCodicons ? renderCodicons(escape3(substring2)) : escape3(substring2);
        htmlContent += "</span>";
        pos = highlight.end;
      }
      if (highlight.extraClasses) {
        htmlContent += `<span class="highlight ${highlight.extraClasses}">`;
      } else {
        htmlContent += `<span class="highlight">`;
      }
      const substring = this.text.substring(highlight.start, highlight.end);
      htmlContent += this.supportCodicons ? renderCodicons(escape3(substring)) : escape3(substring);
      htmlContent += "</span>";
      pos = highlight.end;
    }
    if (pos < this.text.length) {
      htmlContent += "<span>";
      const substring = this.text.substring(pos);
      htmlContent += this.supportCodicons ? renderCodicons(escape3(substring)) : escape3(substring);
      htmlContent += "</span>";
    }
    this.domNode.innerHTML = htmlContent;
    if (this.title) {
      this.domNode.title = this.title;
    } else {
      this.domNode.removeAttribute("title");
    }
    this.didEverRender = true;
  }
  static escapeNewLines(text, highlights) {
    let total = 0;
    let extra = 0;
    return text.replace(/\r\n|\r|\n/g, (match2, offset2) => {
      extra = match2 === "\r\n" ? -1 : 0;
      offset2 += total;
      for (const highlight of highlights) {
        if (highlight.end <= offset2) {
          continue;
        }
        if (highlight.start >= offset2) {
          highlight.start += extra;
        }
        if (highlight.end >= offset2) {
          highlight.end += extra;
        }
      }
      total += extra;
      return "⏎";
    });
  }
};
var FastLabelNode = class {
  constructor(_element) {
    this._element = _element;
  }
  get element() {
    return this._element;
  }
  set textContent(content2) {
    if (this.disposed || content2 === this._textContent) {
      return;
    }
    this._textContent = content2;
    this._element.textContent = content2;
  }
  set className(className) {
    if (this.disposed || className === this._className) {
      return;
    }
    this._className = className;
    this._element.className = className;
  }
  set title(title3) {
    if (this.disposed || title3 === this._title) {
      return;
    }
    this._title = title3;
    if (this._title) {
      this._element.title = title3;
    } else {
      this._element.removeAttribute("title");
    }
  }
  set empty(empty3) {
    if (this.disposed || empty3 === this._empty) {
      return;
    }
    this._empty = empty3;
    this._element.style.marginLeft = empty3 ? "0" : "";
  }
  dispose() {
    this.disposed = true;
  }
};
var IconLabel = class extends Disposable {
  constructor(container, options) {
    super();
    this.domNode = this._register(new FastLabelNode(append(container, $(".monaco-icon-label"))));
    const labelContainer = append(this.domNode.element, $(".monaco-icon-label-container"));
    const nameContainer = append(labelContainer, $("span.monaco-icon-name-container"));
    this.descriptionContainer = this._register(new FastLabelNode(append(labelContainer, $("span.monaco-icon-description-container"))));
    if (options === null || options === void 0 ? void 0 : options.supportHighlights) {
      this.nameNode = new LabelWithHighlights(nameContainer, !!options.supportCodicons);
    } else {
      this.nameNode = new Label2(nameContainer);
    }
    if (options === null || options === void 0 ? void 0 : options.supportDescriptionHighlights) {
      this.descriptionNodeFactory = () => new HighlightedLabel(append(this.descriptionContainer.element, $("span.label-description")), !!options.supportCodicons);
    } else {
      this.descriptionNodeFactory = () => this._register(new FastLabelNode(append(this.descriptionContainer.element, $("span.label-description"))));
    }
  }
  setLabel(label2, description, options) {
    const classes = ["monaco-icon-label"];
    if (options) {
      if (options.extraClasses) {
        classes.push(...options.extraClasses);
      }
      if (options.italic) {
        classes.push("italic");
      }
      if (options.strikethrough) {
        classes.push("strikethrough");
      }
    }
    this.domNode.className = classes.join(" ");
    this.domNode.title = (options === null || options === void 0 ? void 0 : options.title) || "";
    this.nameNode.setLabel(label2, options);
    if (description || this.descriptionNode) {
      if (!this.descriptionNode) {
        this.descriptionNode = this.descriptionNodeFactory();
      }
      if (this.descriptionNode instanceof HighlightedLabel) {
        this.descriptionNode.set(description || "", options ? options.descriptionMatches : void 0);
        if (options === null || options === void 0 ? void 0 : options.descriptionTitle) {
          this.descriptionNode.element.title = options.descriptionTitle;
        } else {
          this.descriptionNode.element.removeAttribute("title");
        }
      } else {
        this.descriptionNode.textContent = description || "";
        this.descriptionNode.title = (options === null || options === void 0 ? void 0 : options.descriptionTitle) || "";
        this.descriptionNode.empty = !description;
      }
    }
  }
};
var Label2 = class {
  constructor(container) {
    this.container = container;
    this.label = void 0;
    this.singleLabel = void 0;
  }
  setLabel(label2, options) {
    if (this.label === label2 && equals$1(this.options, options)) {
      return;
    }
    this.label = label2;
    this.options = options;
    if (typeof label2 === "string") {
      if (!this.singleLabel) {
        this.container.innerText = "";
        removeClass(this.container, "multiple");
        this.singleLabel = append(this.container, $("a.label-name", {id: options === null || options === void 0 ? void 0 : options.domId}));
      }
      this.singleLabel.textContent = label2;
    } else {
      this.container.innerText = "";
      addClass(this.container, "multiple");
      this.singleLabel = void 0;
      for (let i3 = 0; i3 < label2.length; i3++) {
        const l2 = label2[i3];
        const id3 = (options === null || options === void 0 ? void 0 : options.domId) && `${options === null || options === void 0 ? void 0 : options.domId}_${i3}`;
        append(this.container, $("a.label-name", {id: id3, "data-icon-label-count": label2.length, "data-icon-label-index": i3, role: "treeitem"}, l2));
        if (i3 < label2.length - 1) {
          append(this.container, $("span.label-separator", void 0, (options === null || options === void 0 ? void 0 : options.separator) || "/"));
        }
      }
    }
  }
};
function splitMatches(labels, separator, matches2) {
  if (!matches2) {
    return void 0;
  }
  let labelStart = 0;
  return labels.map((label2) => {
    const labelRange = {start: labelStart, end: labelStart + label2.length};
    const result = matches2.map((match2) => Range$1.intersect(labelRange, match2)).filter((range3) => !Range$1.isEmpty(range3)).map(({start: start3, end: end2}) => ({start: start3 - labelStart, end: end2 - labelStart}));
    labelStart = labelRange.end + separator.length;
    return result;
  });
}
var LabelWithHighlights = class {
  constructor(container, supportCodicons) {
    this.container = container;
    this.supportCodicons = supportCodicons;
    this.label = void 0;
    this.singleLabel = void 0;
  }
  setLabel(label2, options) {
    if (this.label === label2 && equals$1(this.options, options)) {
      return;
    }
    this.label = label2;
    this.options = options;
    if (typeof label2 === "string") {
      if (!this.singleLabel) {
        this.container.innerText = "";
        removeClass(this.container, "multiple");
        this.singleLabel = new HighlightedLabel(append(this.container, $("a.label-name", {id: options === null || options === void 0 ? void 0 : options.domId})), this.supportCodicons);
      }
      this.singleLabel.set(label2, options === null || options === void 0 ? void 0 : options.matches, options === null || options === void 0 ? void 0 : options.title, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines);
    } else {
      this.container.innerText = "";
      addClass(this.container, "multiple");
      this.singleLabel = void 0;
      const separator = (options === null || options === void 0 ? void 0 : options.separator) || "/";
      const matches2 = splitMatches(label2, separator, options === null || options === void 0 ? void 0 : options.matches);
      for (let i3 = 0; i3 < label2.length; i3++) {
        const l2 = label2[i3];
        const m2 = matches2 ? matches2[i3] : void 0;
        const id3 = (options === null || options === void 0 ? void 0 : options.domId) && `${options === null || options === void 0 ? void 0 : options.domId}_${i3}`;
        const name = $("a.label-name", {id: id3, "data-icon-label-count": label2.length, "data-icon-label-index": i3, role: "treeitem"});
        const highlightedLabel = new HighlightedLabel(append(this.container, name), this.supportCodicons);
        highlightedLabel.set(l2, m2, options === null || options === void 0 ? void 0 : options.title, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines);
        if (i3 < label2.length - 1) {
          append(name, $("span.label-separator", void 0, separator));
        }
      }
    }
  }
};
var IdGenerator = class {
  constructor(prefix2) {
    this._prefix = prefix2;
    this._lastId = 0;
  }
  nextId() {
    return this._prefix + ++this._lastId;
  }
};
var iconPathToClass = {};
var iconClassGenerator = new IdGenerator("quick-input-button-icon-");
function getIconClass(iconPath) {
  if (!iconPath) {
    return void 0;
  }
  let iconClass;
  const key = iconPath.dark.toString();
  if (iconPathToClass[key]) {
    iconClass = iconPathToClass[key];
  } else {
    iconClass = iconClassGenerator.nextId();
    createCSSRule(`.${iconClass}`, `background-image: ${asCSSUrl(iconPath.light || iconPath.dark)}`);
    createCSSRule(`.vs-dark .${iconClass}, .hc-black .${iconClass}`, `background-image: ${asCSSUrl(iconPath.dark)}`);
    iconPathToClass[key] = iconClass;
  }
  return iconClass;
}
function __snowpack__injectStyle$y(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$y("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-keybinding {\r\n	display: flex;\r\n	align-items: center;\r\n	line-height: 10px;\r\n}\r\n\r\n.monaco-keybinding > .monaco-keybinding-key {\r\n	display: inline-block;\r\n	border: solid 1px rgba(204, 204, 204, 0.4);\r\n	border-bottom-color: rgba(187, 187, 187, 0.4);\r\n	border-radius: 3px;\r\n	box-shadow: inset 0 -1px 0 rgba(187, 187, 187, 0.4);\r\n	background-color: rgba(221, 221, 221, 0.4);\r\n	vertical-align: middle;\r\n	color: #555;\r\n	font-size: 11px;\r\n	padding: 3px 5px;\r\n	margin: 0 2px;\r\n}\r\n\r\n.monaco-keybinding > .monaco-keybinding-key:first-child {\r\n	margin-left: 0;\r\n}\r\n\r\n.monaco-keybinding > .monaco-keybinding-key:last-child {\r\n	margin-right: 0;\r\n}\r\n\r\n.hc-black .monaco-keybinding > .monaco-keybinding-key,\r\n.vs-dark .monaco-keybinding > .monaco-keybinding-key {\r\n	background-color: rgba(128, 128, 128, 0.17);\r\n	color: #ccc;\r\n	border: solid 1px rgba(51, 51, 51, 0.6);\r\n	border-bottom-color: rgba(68, 68, 68, 0.6);\r\n	box-shadow: inset 0 -1px 0 rgba(68, 68, 68, 0.6);\r\n}\r\n\r\n.monaco-keybinding > .monaco-keybinding-key-separator {\r\n	display: inline-block;\r\n}\r\n\r\n.monaco-keybinding > .monaco-keybinding-key-chord-separator {\r\n	width: 6px;\r\n}");
var $$1 = $;
var KeybindingLabel = class {
  constructor(container, os, options) {
    this.os = os;
    this.options = options;
    this.domNode = append(container, $$1(".monaco-keybinding"));
    this.didEverRender = false;
    container.appendChild(this.domNode);
  }
  set(keybinding, matches2) {
    if (this.didEverRender && this.keybinding === keybinding && KeybindingLabel.areSame(this.matches, matches2)) {
      return;
    }
    this.keybinding = keybinding;
    this.matches = matches2;
    this.render();
  }
  render() {
    clearNode(this.domNode);
    if (this.keybinding) {
      let [firstPart, chordPart] = this.keybinding.getParts();
      if (firstPart) {
        this.renderPart(this.domNode, firstPart, this.matches ? this.matches.firstPart : null);
      }
      if (chordPart) {
        append(this.domNode, $$1("span.monaco-keybinding-key-chord-separator", void 0, " "));
        this.renderPart(this.domNode, chordPart, this.matches ? this.matches.chordPart : null);
      }
      this.domNode.title = this.keybinding.getAriaLabel() || "";
    } else if (this.options && this.options.renderUnboundKeybindings) {
      this.renderUnbound(this.domNode);
    }
    this.didEverRender = true;
  }
  renderPart(parent, part, match2) {
    const modifierLabels = UILabelProvider.modifierLabels[this.os];
    if (part.ctrlKey) {
      this.renderKey(parent, modifierLabels.ctrlKey, Boolean(match2 === null || match2 === void 0 ? void 0 : match2.ctrlKey), modifierLabels.separator);
    }
    if (part.shiftKey) {
      this.renderKey(parent, modifierLabels.shiftKey, Boolean(match2 === null || match2 === void 0 ? void 0 : match2.shiftKey), modifierLabels.separator);
    }
    if (part.altKey) {
      this.renderKey(parent, modifierLabels.altKey, Boolean(match2 === null || match2 === void 0 ? void 0 : match2.altKey), modifierLabels.separator);
    }
    if (part.metaKey) {
      this.renderKey(parent, modifierLabels.metaKey, Boolean(match2 === null || match2 === void 0 ? void 0 : match2.metaKey), modifierLabels.separator);
    }
    const keyLabel = part.keyLabel;
    if (keyLabel) {
      this.renderKey(parent, keyLabel, Boolean(match2 === null || match2 === void 0 ? void 0 : match2.keyCode), "");
    }
  }
  renderKey(parent, label2, highlight, separator) {
    append(parent, $$1("span.monaco-keybinding-key" + (highlight ? ".highlight" : ""), void 0, label2));
    if (separator) {
      append(parent, $$1("span.monaco-keybinding-key-separator", void 0, separator));
    }
  }
  renderUnbound(parent) {
    append(parent, $$1("span.monaco-keybinding-key", void 0, localize("unbound", "Unbound")));
  }
  static areSame(a2, b2) {
    if (a2 === b2 || !a2 && !b2) {
      return true;
    }
    return !!a2 && !!b2 && equals$1(a2.firstPart, b2.firstPart) && equals$1(a2.chordPart, b2.chordPart);
  }
};
var __decorate$l = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var $$2 = $;
var ListElement = class {
  constructor(init4) {
    this.hidden = false;
    this._onChecked = new Emitter();
    this.onChecked = this._onChecked.event;
    assign(this, init4);
  }
  get checked() {
    return !!this._checked;
  }
  set checked(value) {
    if (value !== this._checked) {
      this._checked = value;
      this._onChecked.fire(value);
    }
  }
  dispose() {
    this._onChecked.dispose();
  }
};
var ListElementRenderer = class {
  get templateId() {
    return ListElementRenderer.ID;
  }
  renderTemplate(container) {
    const data2 = Object.create(null);
    data2.toDisposeElement = [];
    data2.toDisposeTemplate = [];
    data2.entry = append(container, $$2(".quick-input-list-entry"));
    const label2 = append(data2.entry, $$2("label.quick-input-list-label"));
    data2.toDisposeTemplate.push(addStandardDisposableListener(label2, EventType.CLICK, (e2) => {
      if (!data2.checkbox.offsetParent) {
        e2.preventDefault();
      }
    }));
    data2.checkbox = append(label2, $$2("input.quick-input-list-checkbox"));
    data2.checkbox.type = "checkbox";
    data2.toDisposeTemplate.push(addStandardDisposableListener(data2.checkbox, EventType.CHANGE, (e2) => {
      data2.element.checked = data2.checkbox.checked;
    }));
    const rows = append(label2, $$2(".quick-input-list-rows"));
    const row1 = append(rows, $$2(".quick-input-list-row"));
    const row2 = append(rows, $$2(".quick-input-list-row"));
    data2.label = new IconLabel(row1, {supportHighlights: true, supportDescriptionHighlights: true, supportCodicons: true});
    const keybindingContainer = append(row1, $$2(".quick-input-list-entry-keybinding"));
    data2.keybinding = new KeybindingLabel(keybindingContainer, OS);
    const detailContainer = append(row2, $$2(".quick-input-list-label-meta"));
    data2.detail = new HighlightedLabel(detailContainer, true);
    data2.separator = append(data2.entry, $$2(".quick-input-list-separator"));
    data2.actionBar = new ActionBar(data2.entry);
    data2.actionBar.domNode.classList.add("quick-input-list-entry-action-bar");
    data2.toDisposeTemplate.push(data2.actionBar);
    return data2;
  }
  renderElement(element, index3, data2) {
    data2.toDisposeElement = dispose(data2.toDisposeElement);
    data2.element = element;
    data2.checkbox.checked = element.checked;
    data2.toDisposeElement.push(element.onChecked((checked) => data2.checkbox.checked = checked));
    const {labelHighlights, descriptionHighlights, detailHighlights} = element;
    const options = Object.create(null);
    options.matches = labelHighlights || [];
    options.descriptionTitle = element.saneDescription;
    options.descriptionMatches = descriptionHighlights || [];
    options.extraClasses = element.item.iconClasses;
    options.italic = element.item.italic;
    options.strikethrough = element.item.strikethrough;
    data2.label.setLabel(element.saneLabel, element.saneDescription, options);
    data2.keybinding.set(element.item.keybinding);
    data2.detail.set(element.saneDetail, detailHighlights);
    if (element.separator && element.separator.label) {
      data2.separator.textContent = element.separator.label;
      data2.separator.style.display = "";
    } else {
      data2.separator.style.display = "none";
    }
    if (element.separator) {
      addClass(data2.entry, "quick-input-list-separator-border");
    } else {
      removeClass(data2.entry, "quick-input-list-separator-border");
    }
    data2.actionBar.clear();
    const buttons = element.item.buttons;
    if (buttons && buttons.length) {
      data2.actionBar.push(buttons.map((button2, index4) => {
        let cssClasses = button2.iconClass || (button2.iconPath ? getIconClass(button2.iconPath) : void 0);
        if (button2.alwaysVisible) {
          cssClasses = cssClasses ? `${cssClasses} always-visible` : "always-visible";
        }
        const action = new Action(`id-${index4}`, "", cssClasses, true, () => {
          element.fireButtonTriggered({
            button: button2,
            item: element.item
          });
          return Promise.resolve();
        });
        action.tooltip = button2.tooltip || "";
        return action;
      }), {icon: true, label: false});
      addClass(data2.entry, "has-actions");
    } else {
      removeClass(data2.entry, "has-actions");
    }
  }
  disposeElement(element, index3, data2) {
    data2.toDisposeElement = dispose(data2.toDisposeElement);
  }
  disposeTemplate(data2) {
    data2.toDisposeElement = dispose(data2.toDisposeElement);
    data2.toDisposeTemplate = dispose(data2.toDisposeTemplate);
  }
};
ListElementRenderer.ID = "listelement";
var ListElementDelegate = class {
  getHeight(element) {
    return element.saneDetail ? 44 : 22;
  }
  getTemplateId(element) {
    return ListElementRenderer.ID;
  }
};
var QuickInputListFocus;
(function(QuickInputListFocus2) {
  QuickInputListFocus2[QuickInputListFocus2["First"] = 1] = "First";
  QuickInputListFocus2[QuickInputListFocus2["Second"] = 2] = "Second";
  QuickInputListFocus2[QuickInputListFocus2["Last"] = 3] = "Last";
  QuickInputListFocus2[QuickInputListFocus2["Next"] = 4] = "Next";
  QuickInputListFocus2[QuickInputListFocus2["Previous"] = 5] = "Previous";
  QuickInputListFocus2[QuickInputListFocus2["NextPage"] = 6] = "NextPage";
  QuickInputListFocus2[QuickInputListFocus2["PreviousPage"] = 7] = "PreviousPage";
})(QuickInputListFocus || (QuickInputListFocus = {}));
var QuickInputList = class {
  constructor(parent, id3, options) {
    this.parent = parent;
    this.inputElements = [];
    this.elements = [];
    this.elementsToIndexes = new Map();
    this.matchOnDescription = false;
    this.matchOnDetail = false;
    this.matchOnLabel = true;
    this.sortByLabel = true;
    this._onChangedAllVisibleChecked = new Emitter();
    this.onChangedAllVisibleChecked = this._onChangedAllVisibleChecked.event;
    this._onChangedCheckedCount = new Emitter();
    this.onChangedCheckedCount = this._onChangedCheckedCount.event;
    this._onChangedVisibleCount = new Emitter();
    this.onChangedVisibleCount = this._onChangedVisibleCount.event;
    this._onChangedCheckedElements = new Emitter();
    this.onChangedCheckedElements = this._onChangedCheckedElements.event;
    this._onButtonTriggered = new Emitter();
    this.onButtonTriggered = this._onButtonTriggered.event;
    this._onKeyDown = new Emitter();
    this.onKeyDown = this._onKeyDown.event;
    this._onLeave = new Emitter();
    this.onLeave = this._onLeave.event;
    this._fireCheckedEvents = true;
    this.elementDisposables = [];
    this.disposables = [];
    this.id = id3;
    this.container = append(this.parent, $$2(".quick-input-list"));
    const delegate = new ListElementDelegate();
    const accessibilityProvider = new QuickInputAccessibilityProvider();
    this.list = options.createList("QuickInput", this.container, delegate, [new ListElementRenderer()], {
      identityProvider: {getId: (element) => element.saneLabel},
      setRowLineHeight: false,
      multipleSelectionSupport: false,
      horizontalScrolling: false,
      accessibilityProvider
    });
    this.list.getHTMLElement().id = id3;
    this.disposables.push(this.list);
    this.disposables.push(this.list.onKeyDown((e2) => {
      const event = new StandardKeyboardEvent(e2);
      switch (event.keyCode) {
        case 10:
          this.toggleCheckbox();
          break;
        case 31:
          if (isMacintosh ? e2.metaKey : e2.ctrlKey) {
            this.list.setFocus(range(this.list.length));
          }
          break;
        case 16:
          const focus1 = this.list.getFocus();
          if (focus1.length === 1 && focus1[0] === 0) {
            this._onLeave.fire();
          }
          break;
        case 18:
          const focus2 = this.list.getFocus();
          if (focus2.length === 1 && focus2[0] === this.list.length - 1) {
            this._onLeave.fire();
          }
          break;
      }
      this._onKeyDown.fire(event);
    }));
    this.disposables.push(this.list.onMouseDown((e2) => {
      if (e2.browserEvent.button !== 2) {
        e2.browserEvent.preventDefault();
      }
    }));
    this.disposables.push(addDisposableListener(this.container, EventType.CLICK, (e2) => {
      if (e2.x || e2.y) {
        this._onLeave.fire();
      }
    }));
    this.disposables.push(this.list.onMouseMiddleClick((e2) => {
      this._onLeave.fire();
    }));
    this.disposables.push(this.list.onContextMenu((e2) => {
      if (typeof e2.index === "number") {
        e2.browserEvent.preventDefault();
        this.list.setSelection([e2.index]);
      }
    }));
    this.disposables.push(this._onChangedAllVisibleChecked, this._onChangedCheckedCount, this._onChangedVisibleCount, this._onChangedCheckedElements, this._onButtonTriggered, this._onLeave, this._onKeyDown);
  }
  get onDidChangeFocus() {
    return Event.map(this.list.onDidChangeFocus, (e2) => e2.elements.map((e3) => e3.item));
  }
  get onDidChangeSelection() {
    return Event.map(this.list.onDidChangeSelection, (e2) => ({items: e2.elements.map((e3) => e3.item), event: e2.browserEvent}));
  }
  getAllVisibleChecked() {
    return this.allVisibleChecked(this.elements, false);
  }
  allVisibleChecked(elements, whenNoneVisible = true) {
    for (let i3 = 0, n3 = elements.length; i3 < n3; i3++) {
      const element = elements[i3];
      if (!element.hidden) {
        if (!element.checked) {
          return false;
        } else {
          whenNoneVisible = true;
        }
      }
    }
    return whenNoneVisible;
  }
  getCheckedCount() {
    let count = 0;
    const elements = this.elements;
    for (let i3 = 0, n3 = elements.length; i3 < n3; i3++) {
      if (elements[i3].checked) {
        count++;
      }
    }
    return count;
  }
  getVisibleCount() {
    let count = 0;
    const elements = this.elements;
    for (let i3 = 0, n3 = elements.length; i3 < n3; i3++) {
      if (!elements[i3].hidden) {
        count++;
      }
    }
    return count;
  }
  setAllVisibleChecked(checked) {
    try {
      this._fireCheckedEvents = false;
      this.elements.forEach((element) => {
        if (!element.hidden) {
          element.checked = checked;
        }
      });
    } finally {
      this._fireCheckedEvents = true;
      this.fireCheckedEvents();
    }
  }
  setElements(inputElements) {
    this.elementDisposables = dispose(this.elementDisposables);
    const fireButtonTriggered = (event) => this.fireButtonTriggered(event);
    this.inputElements = inputElements;
    this.elements = inputElements.reduce((result, item, index3) => {
      var _a, _b, _c;
      if (item.type !== "separator") {
        const previous = index3 && inputElements[index3 - 1];
        const saneLabel = item.label && item.label.replace(/\r?\n/g, " ");
        const saneDescription = item.description && item.description.replace(/\r?\n/g, " ");
        const saneDetail = item.detail && item.detail.replace(/\r?\n/g, " ");
        const saneAriaLabel = item.ariaLabel || [saneLabel, saneDescription, saneDetail].map((s2) => s2 && parseCodicons(s2).text).filter((s2) => !!s2).join(", ");
        result.push(new ListElement({
          index: index3,
          item,
          saneLabel,
          saneAriaLabel,
          saneDescription,
          saneDetail,
          labelHighlights: (_a = item.highlights) === null || _a === void 0 ? void 0 : _a.label,
          descriptionHighlights: (_b = item.highlights) === null || _b === void 0 ? void 0 : _b.description,
          detailHighlights: (_c = item.highlights) === null || _c === void 0 ? void 0 : _c.detail,
          checked: false,
          separator: previous && previous.type === "separator" ? previous : void 0,
          fireButtonTriggered
        }));
      }
      return result;
    }, []);
    this.elementDisposables.push(...this.elements);
    this.elementDisposables.push(...this.elements.map((element) => element.onChecked(() => this.fireCheckedEvents())));
    this.elementsToIndexes = this.elements.reduce((map2, element, index3) => {
      map2.set(element.item, index3);
      return map2;
    }, new Map());
    this.list.splice(0, this.list.length);
    this.list.splice(0, this.list.length, this.elements);
    this._onChangedVisibleCount.fire(this.elements.length);
  }
  getFocusedElements() {
    return this.list.getFocusedElements().map((e2) => e2.item);
  }
  setFocusedElements(items) {
    this.list.setFocus(items.filter((item) => this.elementsToIndexes.has(item)).map((item) => this.elementsToIndexes.get(item)));
    if (items.length > 0) {
      const focused = this.list.getFocus()[0];
      if (typeof focused === "number") {
        this.list.reveal(focused);
      }
    }
  }
  getActiveDescendant() {
    return this.list.getHTMLElement().getAttribute("aria-activedescendant");
  }
  setSelectedElements(items) {
    this.list.setSelection(items.filter((item) => this.elementsToIndexes.has(item)).map((item) => this.elementsToIndexes.get(item)));
  }
  getCheckedElements() {
    return this.elements.filter((e2) => e2.checked).map((e2) => e2.item);
  }
  setCheckedElements(items) {
    try {
      this._fireCheckedEvents = false;
      const checked = new Set();
      for (const item of items) {
        checked.add(item);
      }
      for (const element of this.elements) {
        element.checked = checked.has(element.item);
      }
    } finally {
      this._fireCheckedEvents = true;
      this.fireCheckedEvents();
    }
  }
  set enabled(value) {
    this.list.getHTMLElement().style.pointerEvents = value ? "" : "none";
  }
  focus(what) {
    if (!this.list.length) {
      return;
    }
    if (what === QuickInputListFocus.Next && this.list.getFocus()[0] === this.list.length - 1) {
      what = QuickInputListFocus.First;
    }
    if (what === QuickInputListFocus.Previous && this.list.getFocus()[0] === 0) {
      what = QuickInputListFocus.Last;
    }
    if (what === QuickInputListFocus.Second && this.list.length < 2) {
      what = QuickInputListFocus.First;
    }
    switch (what) {
      case QuickInputListFocus.First:
        this.list.focusFirst();
        break;
      case QuickInputListFocus.Second:
        this.list.focusNth(1);
        break;
      case QuickInputListFocus.Last:
        this.list.focusLast();
        break;
      case QuickInputListFocus.Next:
        this.list.focusNext();
        break;
      case QuickInputListFocus.Previous:
        this.list.focusPrevious();
        break;
      case QuickInputListFocus.NextPage:
        this.list.focusNextPage();
        break;
      case QuickInputListFocus.PreviousPage:
        this.list.focusPreviousPage();
        break;
    }
    const focused = this.list.getFocus()[0];
    if (typeof focused === "number") {
      this.list.reveal(focused);
    }
  }
  clearFocus() {
    this.list.setFocus([]);
  }
  domFocus() {
    this.list.domFocus();
  }
  layout(maxHeight) {
    this.list.getHTMLElement().style.maxHeight = maxHeight ? `calc(${Math.floor(maxHeight / 44) * 44}px)` : "";
    this.list.layout();
  }
  filter(query) {
    if (!(this.sortByLabel || this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) {
      this.list.layout();
      return false;
    }
    query = query.trim();
    if (!query || !(this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) {
      this.elements.forEach((element) => {
        element.labelHighlights = void 0;
        element.descriptionHighlights = void 0;
        element.detailHighlights = void 0;
        element.hidden = false;
        const previous = element.index && this.inputElements[element.index - 1];
        element.separator = previous && previous.type === "separator" ? previous : void 0;
      });
    } else {
      this.elements.forEach((element) => {
        const labelHighlights = this.matchOnLabel ? withNullAsUndefined(matchesFuzzyCodiconAware(query, parseCodicons(element.saneLabel))) : void 0;
        const descriptionHighlights = this.matchOnDescription ? withNullAsUndefined(matchesFuzzyCodiconAware(query, parseCodicons(element.saneDescription || ""))) : void 0;
        const detailHighlights = this.matchOnDetail ? withNullAsUndefined(matchesFuzzyCodiconAware(query, parseCodicons(element.saneDetail || ""))) : void 0;
        if (labelHighlights || descriptionHighlights || detailHighlights) {
          element.labelHighlights = labelHighlights;
          element.descriptionHighlights = descriptionHighlights;
          element.detailHighlights = detailHighlights;
          element.hidden = false;
        } else {
          element.labelHighlights = void 0;
          element.descriptionHighlights = void 0;
          element.detailHighlights = void 0;
          element.hidden = !element.item.alwaysShow;
        }
        element.separator = void 0;
      });
    }
    const shownElements = this.elements.filter((element) => !element.hidden);
    if (this.sortByLabel && query) {
      const normalizedSearchValue = query.toLowerCase();
      shownElements.sort((a2, b2) => {
        return compareEntries(a2, b2, normalizedSearchValue);
      });
    }
    this.elementsToIndexes = shownElements.reduce((map2, element, index3) => {
      map2.set(element.item, index3);
      return map2;
    }, new Map());
    this.list.splice(0, this.list.length, shownElements);
    this.list.setFocus([]);
    this.list.layout();
    this._onChangedAllVisibleChecked.fire(this.getAllVisibleChecked());
    this._onChangedVisibleCount.fire(shownElements.length);
    return true;
  }
  toggleCheckbox() {
    try {
      this._fireCheckedEvents = false;
      const elements = this.list.getFocusedElements();
      const allChecked = this.allVisibleChecked(elements);
      for (const element of elements) {
        element.checked = !allChecked;
      }
    } finally {
      this._fireCheckedEvents = true;
      this.fireCheckedEvents();
    }
  }
  display(display) {
    this.container.style.display = display ? "" : "none";
  }
  isDisplayed() {
    return this.container.style.display !== "none";
  }
  dispose() {
    this.elementDisposables = dispose(this.elementDisposables);
    this.disposables = dispose(this.disposables);
  }
  fireCheckedEvents() {
    if (this._fireCheckedEvents) {
      this._onChangedAllVisibleChecked.fire(this.getAllVisibleChecked());
      this._onChangedCheckedCount.fire(this.getCheckedCount());
      this._onChangedCheckedElements.fire(this.getCheckedElements());
    }
  }
  fireButtonTriggered(event) {
    this._onButtonTriggered.fire(event);
  }
  style(styles6) {
    this.list.style(styles6);
  }
};
__decorate$l([
  memoize
], QuickInputList.prototype, "onDidChangeFocus", null);
__decorate$l([
  memoize
], QuickInputList.prototype, "onDidChangeSelection", null);
function compareEntries(elementA, elementB, lookFor) {
  const labelHighlightsA = elementA.labelHighlights || [];
  const labelHighlightsB = elementB.labelHighlights || [];
  if (labelHighlightsA.length && !labelHighlightsB.length) {
    return -1;
  }
  if (!labelHighlightsA.length && labelHighlightsB.length) {
    return 1;
  }
  if (labelHighlightsA.length === 0 && labelHighlightsB.length === 0) {
    return 0;
  }
  return compareAnything(elementA.saneLabel, elementB.saneLabel, lookFor);
}
var QuickInputAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize("quickInput", "Quick Input");
  }
  getAriaLabel(element) {
    return element.saneAriaLabel;
  }
  getWidgetRole() {
    return "listbox";
  }
  getRole() {
    return "option";
  }
};
function __snowpack__injectStyle$z(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$z("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-inputbox {\r\n	position: relative;\r\n	display: block;\r\n	padding: 0;\r\n	box-sizing:	border-box;\r\n\r\n	/* Customizable */\r\n	font-size: inherit;\r\n}\r\n\r\n.monaco-inputbox.idle {\r\n	border: 1px solid transparent;\r\n}\r\n\r\n.monaco-inputbox > .wrapper > .input,\r\n.monaco-inputbox > .wrapper > .mirror {\r\n\r\n	/* Customizable */\r\n	padding: 4px;\r\n}\r\n\r\n.monaco-inputbox > .wrapper {\r\n	position: relative;\r\n	width: 100%;\r\n	height: 100%;\r\n}\r\n\r\n.monaco-inputbox > .wrapper > .input {\r\n	display: inline-block;\r\n	box-sizing:	border-box;\r\n	width: 100%;\r\n	height: 100%;\r\n	line-height: inherit;\r\n	border: none;\r\n	font-family: inherit;\r\n	font-size: inherit;\r\n	resize: none;\r\n	color: inherit;\r\n}\r\n\r\n.monaco-inputbox > .wrapper > input {\r\n	text-overflow: ellipsis;\r\n}\r\n\r\n.monaco-inputbox > .wrapper > textarea.input {\r\n	display: block;\r\n	-ms-overflow-style: none; /* IE 10+: hide scrollbars */\r\n	scrollbar-width: none; /* Firefox: hide scrollbars */\r\n	outline: none;\r\n}\r\n\r\n.monaco-inputbox > .wrapper > textarea.input::-webkit-scrollbar {\r\n	display: none; /* Chrome + Safari: hide scrollbar */\r\n}\r\n\r\n.monaco-inputbox > .wrapper > textarea.input.empty {\r\n	white-space: nowrap;\r\n}\r\n\r\n.monaco-inputbox > .wrapper > .mirror {\r\n	position: absolute;\r\n	display: inline-block;\r\n	width: 100%;\r\n	top: 0;\r\n	left: 0;\r\n	box-sizing: border-box;\r\n	white-space: pre-wrap;\r\n	visibility: hidden;\r\n	word-wrap: break-word;\r\n}\r\n\r\n/* Context view */\r\n\r\n.monaco-inputbox-container {\r\n	text-align: right;\r\n}\r\n\r\n.monaco-inputbox-container .monaco-inputbox-message {\r\n	display: inline-block;\r\n	overflow: hidden;\r\n	text-align: left;\r\n	width: 100%;\r\n	box-sizing:	border-box;\r\n	padding: 0.4em;\r\n	font-size: 12px;\r\n	line-height: 17px;\r\n	min-height: 34px;\r\n	margin-top: -1px;\r\n	word-wrap: break-word;\r\n}\r\n\r\n/* Action bar support */\r\n.monaco-inputbox .monaco-action-bar {\r\n	position: absolute;\r\n	right: 2px;\r\n	top: 4px;\r\n}\r\n\r\n.monaco-inputbox .monaco-action-bar .action-item {\r\n	margin-left: 2px;\r\n}\r\n\r\n.monaco-inputbox .monaco-action-bar .action-item .codicon {\r\n	background-repeat: no-repeat;\r\n	width: 16px;\r\n	height: 16px;\r\n}\r\n");
function renderText(text, options = {}) {
  const element = createElement(options);
  element.textContent = text;
  return element;
}
function renderFormattedText(formattedText, options = {}) {
  const element = createElement(options);
  _renderFormattedText(element, parseFormattedText(formattedText), options.actionHandler);
  return element;
}
function createElement(options) {
  const tagName = options.inline ? "span" : "div";
  const element = document.createElement(tagName);
  if (options.className) {
    element.className = options.className;
  }
  return element;
}
var StringStream = class {
  constructor(source2) {
    this.source = source2;
    this.index = 0;
  }
  eos() {
    return this.index >= this.source.length;
  }
  next() {
    const next = this.peek();
    this.advance();
    return next;
  }
  peek() {
    return this.source[this.index];
  }
  advance() {
    this.index++;
  }
};
function _renderFormattedText(element, treeNode, actionHandler) {
  let child;
  if (treeNode.type === 2) {
    child = document.createTextNode(treeNode.content || "");
  } else if (treeNode.type === 3) {
    child = document.createElement("b");
  } else if (treeNode.type === 4) {
    child = document.createElement("i");
  } else if (treeNode.type === 5 && actionHandler) {
    const a2 = document.createElement("a");
    a2.href = "#";
    actionHandler.disposeables.add(addStandardDisposableListener(a2, "click", (event) => {
      actionHandler.callback(String(treeNode.index), event);
    }));
    child = a2;
  } else if (treeNode.type === 7) {
    child = document.createElement("br");
  } else if (treeNode.type === 1) {
    child = element;
  }
  if (child && element !== child) {
    element.appendChild(child);
  }
  if (child && Array.isArray(treeNode.children)) {
    treeNode.children.forEach((nodeChild) => {
      _renderFormattedText(child, nodeChild, actionHandler);
    });
  }
}
function parseFormattedText(content2) {
  const root4 = {
    type: 1,
    children: []
  };
  let actionViewItemIndex = 0;
  let current = root4;
  const stack2 = [];
  const stream = new StringStream(content2);
  while (!stream.eos()) {
    let next = stream.next();
    const isEscapedFormatType = next === "\\" && formatTagType(stream.peek()) !== 0;
    if (isEscapedFormatType) {
      next = stream.next();
    }
    if (!isEscapedFormatType && isFormatTag(next) && next === stream.peek()) {
      stream.advance();
      if (current.type === 2) {
        current = stack2.pop();
      }
      const type = formatTagType(next);
      if (current.type === type || current.type === 5 && type === 6) {
        current = stack2.pop();
      } else {
        const newCurrent = {
          type,
          children: []
        };
        if (type === 5) {
          newCurrent.index = actionViewItemIndex;
          actionViewItemIndex++;
        }
        current.children.push(newCurrent);
        stack2.push(current);
        current = newCurrent;
      }
    } else if (next === "\n") {
      if (current.type === 2) {
        current = stack2.pop();
      }
      current.children.push({
        type: 7
      });
    } else {
      if (current.type !== 2) {
        const textCurrent = {
          type: 2,
          content: next
        };
        current.children.push(textCurrent);
        stack2.push(current);
        current = textCurrent;
      } else {
        current.content += next;
      }
    }
  }
  if (current.type === 2) {
    current = stack2.pop();
  }
  return root4;
}
function isFormatTag(char) {
  return formatTagType(char) !== 0;
}
function formatTagType(char) {
  switch (char) {
    case "*":
      return 3;
    case "_":
      return 4;
    case "[":
      return 5;
    case "]":
      return 6;
    default:
      return 0;
  }
}
var $$3 = $;
var defaultOpts = {
  inputBackground: Color.fromHex("#3C3C3C"),
  inputForeground: Color.fromHex("#CCCCCC"),
  inputValidationInfoBorder: Color.fromHex("#55AAFF"),
  inputValidationInfoBackground: Color.fromHex("#063B49"),
  inputValidationWarningBorder: Color.fromHex("#B89500"),
  inputValidationWarningBackground: Color.fromHex("#352A05"),
  inputValidationErrorBorder: Color.fromHex("#BE1100"),
  inputValidationErrorBackground: Color.fromHex("#5A1D1D")
};
var InputBox = class extends Widget$1 {
  constructor(container, contextViewProvider, options) {
    super();
    this.state = "idle";
    this.maxHeight = Number.POSITIVE_INFINITY;
    this._onDidChange = this._register(new Emitter());
    this.onDidChange = this._onDidChange.event;
    this._onDidHeightChange = this._register(new Emitter());
    this.onDidHeightChange = this._onDidHeightChange.event;
    this.contextViewProvider = contextViewProvider;
    this.options = options || Object.create(null);
    mixin(this.options, defaultOpts, false);
    this.message = null;
    this.placeholder = this.options.placeholder || "";
    this.ariaLabel = this.options.ariaLabel || "";
    this.inputBackground = this.options.inputBackground;
    this.inputForeground = this.options.inputForeground;
    this.inputBorder = this.options.inputBorder;
    this.inputValidationInfoBorder = this.options.inputValidationInfoBorder;
    this.inputValidationInfoBackground = this.options.inputValidationInfoBackground;
    this.inputValidationInfoForeground = this.options.inputValidationInfoForeground;
    this.inputValidationWarningBorder = this.options.inputValidationWarningBorder;
    this.inputValidationWarningBackground = this.options.inputValidationWarningBackground;
    this.inputValidationWarningForeground = this.options.inputValidationWarningForeground;
    this.inputValidationErrorBorder = this.options.inputValidationErrorBorder;
    this.inputValidationErrorBackground = this.options.inputValidationErrorBackground;
    this.inputValidationErrorForeground = this.options.inputValidationErrorForeground;
    if (this.options.validationOptions) {
      this.validation = this.options.validationOptions.validation;
    }
    this.element = append(container, $$3(".monaco-inputbox.idle"));
    let tagName = this.options.flexibleHeight ? "textarea" : "input";
    let wrapper = append(this.element, $$3(".wrapper"));
    this.input = append(wrapper, $$3(tagName + ".input.empty"));
    this.input.setAttribute("autocorrect", "off");
    this.input.setAttribute("autocapitalize", "off");
    this.input.setAttribute("spellcheck", "false");
    this.onfocus(this.input, () => this.element.classList.add("synthetic-focus"));
    this.onblur(this.input, () => this.element.classList.remove("synthetic-focus"));
    if (this.options.flexibleHeight) {
      this.maxHeight = typeof this.options.flexibleMaxHeight === "number" ? this.options.flexibleMaxHeight : Number.POSITIVE_INFINITY;
      this.mirror = append(wrapper, $$3("div.mirror"));
      this.mirror.innerText = " ";
      this.scrollableElement = new ScrollableElement(this.element, {vertical: 1});
      if (this.options.flexibleWidth) {
        this.input.setAttribute("wrap", "off");
        this.mirror.style.whiteSpace = "pre";
        this.mirror.style.wordWrap = "initial";
      }
      append(container, this.scrollableElement.getDomNode());
      this._register(this.scrollableElement);
      this._register(this.scrollableElement.onScroll((e2) => this.input.scrollTop = e2.scrollTop));
      const onSelectionChange = Event.filter(domEvent(document, "selectionchange"), () => {
        const selection2 = document.getSelection();
        return (selection2 === null || selection2 === void 0 ? void 0 : selection2.anchorNode) === wrapper;
      });
      this._register(onSelectionChange(this.updateScrollDimensions, this));
      this._register(this.onDidHeightChange(this.updateScrollDimensions, this));
    } else {
      this.input.type = this.options.type || "text";
      this.input.setAttribute("wrap", "off");
    }
    if (this.ariaLabel) {
      this.input.setAttribute("aria-label", this.ariaLabel);
    }
    if (this.placeholder) {
      this.setPlaceHolder(this.placeholder);
    }
    this.oninput(this.input, () => this.onValueChange());
    this.onblur(this.input, () => this.onBlur());
    this.onfocus(this.input, () => this.onFocus());
    this.ignoreGesture(this.input);
    setTimeout(() => this.updateMirror(), 0);
    if (this.options.actions) {
      this.actionbar = this._register(new ActionBar(this.element));
      this.actionbar.push(this.options.actions, {icon: true, label: false});
    }
    this.applyStyles();
  }
  onBlur() {
    this._hideMessage();
  }
  onFocus() {
    this._showMessage();
  }
  setPlaceHolder(placeHolder) {
    this.placeholder = placeHolder;
    this.input.setAttribute("placeholder", placeHolder);
    this.input.title = placeHolder;
  }
  setAriaLabel(label2) {
    this.ariaLabel = label2;
    if (label2) {
      this.input.setAttribute("aria-label", this.ariaLabel);
    } else {
      this.input.removeAttribute("aria-label");
    }
  }
  getAriaLabel() {
    return this.ariaLabel;
  }
  get inputElement() {
    return this.input;
  }
  get value() {
    return this.input.value;
  }
  set value(newValue) {
    if (this.input.value !== newValue) {
      this.input.value = newValue;
      this.onValueChange();
    }
  }
  get height() {
    return typeof this.cachedHeight === "number" ? this.cachedHeight : getTotalHeight(this.element);
  }
  focus() {
    this.input.focus();
  }
  blur() {
    this.input.blur();
  }
  hasFocus() {
    return document.activeElement === this.input;
  }
  select(range3 = null) {
    this.input.select();
    if (range3) {
      this.input.setSelectionRange(range3.start, range3.end);
    }
  }
  isSelectionAtEnd() {
    return this.input.selectionEnd === this.input.value.length && this.input.selectionStart === this.input.selectionEnd;
  }
  enable() {
    this.input.removeAttribute("disabled");
  }
  disable() {
    this.blur();
    this.input.disabled = true;
    this._hideMessage();
  }
  get width() {
    return getTotalWidth(this.input);
  }
  set width(width2) {
    if (this.options.flexibleHeight && this.options.flexibleWidth) {
      let horizontalPadding = 0;
      if (this.mirror) {
        const paddingLeft = parseFloat(this.mirror.style.paddingLeft || "") || 0;
        const paddingRight = parseFloat(this.mirror.style.paddingRight || "") || 0;
        horizontalPadding = paddingLeft + paddingRight;
      }
      this.input.style.width = width2 - horizontalPadding + "px";
    } else {
      this.input.style.width = width2 + "px";
    }
    if (this.mirror) {
      this.mirror.style.width = width2 + "px";
    }
  }
  set paddingRight(paddingRight) {
    if (this.options.flexibleHeight && this.options.flexibleWidth) {
      this.input.style.width = `calc(100% - ${paddingRight}px)`;
    } else {
      this.input.style.paddingRight = paddingRight + "px";
    }
    if (this.mirror) {
      this.mirror.style.paddingRight = paddingRight + "px";
    }
  }
  updateScrollDimensions() {
    if (typeof this.cachedContentHeight !== "number" || typeof this.cachedHeight !== "number" || !this.scrollableElement) {
      return;
    }
    const scrollHeight = this.cachedContentHeight;
    const height = this.cachedHeight;
    const scrollTop = this.input.scrollTop;
    this.scrollableElement.setScrollDimensions({scrollHeight, height});
    this.scrollableElement.setScrollPosition({scrollTop});
  }
  showMessage(message, force) {
    this.message = message;
    this.element.classList.remove("idle");
    this.element.classList.remove("info");
    this.element.classList.remove("warning");
    this.element.classList.remove("error");
    this.element.classList.add(this.classForType(message.type));
    const styles6 = this.stylesForType(this.message.type);
    this.element.style.border = styles6.border ? `1px solid ${styles6.border}` : "";
    if (this.hasFocus() || force) {
      this._showMessage();
    }
  }
  hideMessage() {
    this.message = null;
    this.element.classList.remove("info");
    this.element.classList.remove("warning");
    this.element.classList.remove("error");
    this.element.classList.add("idle");
    this._hideMessage();
    this.applyStyles();
  }
  validate() {
    let errorMsg = null;
    if (this.validation) {
      errorMsg = this.validation(this.value);
      if (errorMsg) {
        this.inputElement.setAttribute("aria-invalid", "true");
        this.showMessage(errorMsg);
      } else if (this.inputElement.hasAttribute("aria-invalid")) {
        this.inputElement.removeAttribute("aria-invalid");
        this.hideMessage();
      }
    }
    return !errorMsg;
  }
  stylesForType(type) {
    switch (type) {
      case 1:
        return {border: this.inputValidationInfoBorder, background: this.inputValidationInfoBackground, foreground: this.inputValidationInfoForeground};
      case 2:
        return {border: this.inputValidationWarningBorder, background: this.inputValidationWarningBackground, foreground: this.inputValidationWarningForeground};
      default:
        return {border: this.inputValidationErrorBorder, background: this.inputValidationErrorBackground, foreground: this.inputValidationErrorForeground};
    }
  }
  classForType(type) {
    switch (type) {
      case 1:
        return "info";
      case 2:
        return "warning";
      default:
        return "error";
    }
  }
  _showMessage() {
    if (!this.contextViewProvider || !this.message) {
      return;
    }
    let div;
    let layout3 = () => div.style.width = getTotalWidth(this.element) + "px";
    this.contextViewProvider.showContextView({
      getAnchor: () => this.element,
      anchorAlignment: 1,
      render: (container) => {
        if (!this.message) {
          return null;
        }
        div = append(container, $$3(".monaco-inputbox-container"));
        layout3();
        const renderOptions = {
          inline: true,
          className: "monaco-inputbox-message"
        };
        const spanElement = this.message.formatContent ? renderFormattedText(this.message.content, renderOptions) : renderText(this.message.content, renderOptions);
        spanElement.classList.add(this.classForType(this.message.type));
        const styles6 = this.stylesForType(this.message.type);
        spanElement.style.backgroundColor = styles6.background ? styles6.background.toString() : "";
        spanElement.style.color = styles6.foreground ? styles6.foreground.toString() : "";
        spanElement.style.border = styles6.border ? `1px solid ${styles6.border}` : "";
        append(div, spanElement);
        return null;
      },
      onHide: () => {
        this.state = "closed";
      },
      layout: layout3
    });
    let alertText;
    if (this.message.type === 3) {
      alertText = localize("alertErrorMessage", "Error: {0}", this.message.content);
    } else if (this.message.type === 2) {
      alertText = localize("alertWarningMessage", "Warning: {0}", this.message.content);
    } else {
      alertText = localize("alertInfoMessage", "Info: {0}", this.message.content);
    }
    alert3(alertText);
    this.state = "open";
  }
  _hideMessage() {
    if (!this.contextViewProvider) {
      return;
    }
    if (this.state === "open") {
      this.contextViewProvider.hideContextView();
    }
    this.state = "idle";
  }
  onValueChange() {
    this._onDidChange.fire(this.value);
    this.validate();
    this.updateMirror();
    this.input.classList.toggle("empty", !this.value);
    if (this.state === "open" && this.contextViewProvider) {
      this.contextViewProvider.layout();
    }
  }
  updateMirror() {
    if (!this.mirror) {
      return;
    }
    const value = this.value;
    const lastCharCode = value.charCodeAt(value.length - 1);
    const suffix = lastCharCode === 10 ? " " : "";
    const mirrorTextContent = value + suffix;
    if (mirrorTextContent) {
      this.mirror.textContent = value + suffix;
    } else {
      this.mirror.innerText = " ";
    }
    this.layout();
  }
  style(styles6) {
    this.inputBackground = styles6.inputBackground;
    this.inputForeground = styles6.inputForeground;
    this.inputBorder = styles6.inputBorder;
    this.inputValidationInfoBackground = styles6.inputValidationInfoBackground;
    this.inputValidationInfoForeground = styles6.inputValidationInfoForeground;
    this.inputValidationInfoBorder = styles6.inputValidationInfoBorder;
    this.inputValidationWarningBackground = styles6.inputValidationWarningBackground;
    this.inputValidationWarningForeground = styles6.inputValidationWarningForeground;
    this.inputValidationWarningBorder = styles6.inputValidationWarningBorder;
    this.inputValidationErrorBackground = styles6.inputValidationErrorBackground;
    this.inputValidationErrorForeground = styles6.inputValidationErrorForeground;
    this.inputValidationErrorBorder = styles6.inputValidationErrorBorder;
    this.applyStyles();
  }
  applyStyles() {
    const background = this.inputBackground ? this.inputBackground.toString() : "";
    const foreground2 = this.inputForeground ? this.inputForeground.toString() : "";
    const border = this.inputBorder ? this.inputBorder.toString() : "";
    this.element.style.backgroundColor = background;
    this.element.style.color = foreground2;
    this.input.style.backgroundColor = "inherit";
    this.input.style.color = foreground2;
    this.element.style.borderWidth = border ? "1px" : "";
    this.element.style.borderStyle = border ? "solid" : "";
    this.element.style.borderColor = border;
  }
  layout() {
    if (!this.mirror) {
      return;
    }
    const previousHeight = this.cachedContentHeight;
    this.cachedContentHeight = getTotalHeight(this.mirror);
    if (previousHeight !== this.cachedContentHeight) {
      this.cachedHeight = Math.min(this.cachedContentHeight, this.maxHeight);
      this.input.style.height = this.cachedHeight + "px";
      this._onDidHeightChange.fire(this.cachedContentHeight);
    }
  }
  insertAtCursor(text) {
    const inputElement = this.inputElement;
    const start3 = inputElement.selectionStart;
    const end2 = inputElement.selectionEnd;
    const content2 = inputElement.value;
    if (start3 !== null && end2 !== null) {
      this.value = content2.substr(0, start3) + text + content2.substr(end2);
      inputElement.setSelectionRange(start3 + 1, start3 + 1);
      this.layout();
    }
  }
  dispose() {
    this._hideMessage();
    this.message = null;
    if (this.actionbar) {
      this.actionbar.dispose();
    }
    super.dispose();
  }
};
var $$4 = $;
var QuickInputBox = class extends Disposable {
  constructor(parent) {
    super();
    this.parent = parent;
    this.onKeyDown = (handler) => {
      return addDisposableListener(this.inputBox.inputElement, EventType.KEY_DOWN, (e2) => {
        handler(new StandardKeyboardEvent(e2));
      });
    };
    this.onMouseDown = (handler) => {
      return addDisposableListener(this.inputBox.inputElement, EventType.MOUSE_DOWN, (e2) => {
        handler(new StandardMouseEvent(e2));
      });
    };
    this.onDidChange = (handler) => {
      return this.inputBox.onDidChange(handler);
    };
    this.container = append(this.parent, $$4(".quick-input-box"));
    this.inputBox = this._register(new InputBox(this.container, void 0));
  }
  get value() {
    return this.inputBox.value;
  }
  set value(value) {
    this.inputBox.value = value;
  }
  select(range3 = null) {
    this.inputBox.select(range3);
  }
  isSelectionAtEnd() {
    return this.inputBox.isSelectionAtEnd();
  }
  get placeholder() {
    return this.inputBox.inputElement.getAttribute("placeholder") || "";
  }
  set placeholder(placeholder) {
    this.inputBox.setPlaceHolder(placeholder);
  }
  get ariaLabel() {
    return this.inputBox.getAriaLabel();
  }
  set ariaLabel(ariaLabel) {
    this.inputBox.setAriaLabel(ariaLabel);
  }
  get password() {
    return this.inputBox.inputElement.type === "password";
  }
  set password(password) {
    this.inputBox.inputElement.type = password ? "password" : "text";
  }
  setAttribute(name, value) {
    this.inputBox.inputElement.setAttribute(name, value);
  }
  removeAttribute(name) {
    this.inputBox.inputElement.removeAttribute(name);
  }
  showDecoration(decoration) {
    if (decoration === Severity$1.Ignore) {
      this.inputBox.hideMessage();
    } else {
      this.inputBox.showMessage({type: decoration === Severity$1.Info ? 1 : decoration === Severity$1.Warning ? 2 : 3, content: ""});
    }
  }
  stylesForType(decoration) {
    return this.inputBox.stylesForType(decoration === Severity$1.Info ? 1 : decoration === Severity$1.Warning ? 2 : 3);
  }
  setFocus() {
    this.inputBox.focus();
  }
  layout() {
    this.inputBox.layout();
  }
  style(styles6) {
    this.inputBox.style(styles6);
  }
};
function __snowpack__injectStyle$A(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$A("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-count-badge {\r\n	padding: 3px 6px;\r\n	border-radius: 11px;\r\n	font-size: 11px;\r\n	min-width: 18px;\r\n	min-height: 18px;\r\n	line-height: 11px;\r\n	font-weight: normal;\r\n	text-align: center;\r\n	display: inline-block;\r\n	box-sizing: border-box;\r\n}\r\n\r\n.monaco-count-badge.long {\r\n	padding: 2px 3px;\r\n	border-radius: 2px;\r\n	min-height: auto;\r\n	line-height: normal;\r\n}\r\n");
var defaultOpts$1 = {
  badgeBackground: Color.fromHex("#4D4D4D"),
  badgeForeground: Color.fromHex("#FFFFFF")
};
var CountBadge = class {
  constructor(container, options) {
    this.count = 0;
    this.options = options || Object.create(null);
    mixin(this.options, defaultOpts$1, false);
    this.badgeBackground = this.options.badgeBackground;
    this.badgeForeground = this.options.badgeForeground;
    this.badgeBorder = this.options.badgeBorder;
    this.element = append(container, $(".monaco-count-badge"));
    this.countFormat = this.options.countFormat || "{0}";
    this.titleFormat = this.options.titleFormat || "";
    this.setCount(this.options.count || 0);
  }
  setCount(count) {
    this.count = count;
    this.render();
  }
  setTitleFormat(titleFormat) {
    this.titleFormat = titleFormat;
    this.render();
  }
  render() {
    this.element.textContent = format(this.countFormat, this.count);
    this.element.title = format(this.titleFormat, this.count);
    this.applyStyles();
  }
  style(styles6) {
    this.badgeBackground = styles6.badgeBackground;
    this.badgeForeground = styles6.badgeForeground;
    this.badgeBorder = styles6.badgeBorder;
    this.applyStyles();
  }
  applyStyles() {
    if (this.element) {
      const background = this.badgeBackground ? this.badgeBackground.toString() : "";
      const foreground2 = this.badgeForeground ? this.badgeForeground.toString() : "";
      const border = this.badgeBorder ? this.badgeBorder.toString() : "";
      this.element.style.backgroundColor = background;
      this.element.style.color = foreground2;
      this.element.style.borderWidth = border ? "1px" : "";
      this.element.style.borderStyle = border ? "solid" : "";
      this.element.style.borderColor = border;
    }
  }
};
function __snowpack__injectStyle$B(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$B("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-progress-container {\r\n	width: 100%;\r\n	height: 5px;\r\n	overflow: hidden; /* keep progress bit in bounds */\r\n}\r\n\r\n.monaco-progress-container .progress-bit {\r\n	width: 2%;\r\n	height: 5px;\r\n	position: absolute;\r\n	left: 0;\r\n	display: none;\r\n}\r\n\r\n.monaco-progress-container.active .progress-bit {\r\n	display: inherit;\r\n}\r\n\r\n.monaco-progress-container.discrete .progress-bit {\r\n	left: 0;\r\n	transition: width 100ms linear;\r\n}\r\n\r\n.monaco-progress-container.discrete.done .progress-bit {\r\n	width: 100%;\r\n}\r\n\r\n.monaco-progress-container.infinite .progress-bit {\r\n	animation-name: progress;\r\n	animation-duration: 4s;\r\n	animation-iteration-count: infinite;\r\n	animation-timing-function: linear;\r\n	transform: translate3d(0px, 0px, 0px);\r\n}\r\n\r\n/**\r\n * The progress bit has a width: 2% (1/50) of the parent container. The animation moves it from 0% to 100% of\r\n * that container. Since translateX is relative to the progress bit size, we have to multiple it with\r\n * its relative size to the parent container:\r\n *  50%: 50 * 50 = 2500%\r\n * 100%: 50 * 100 - 50 (do not overflow): 4950%\r\n */\r\n@keyframes progress { from { transform: translateX(0%) scaleX(1) } 50% { transform: translateX(2500%) scaleX(3) } to { transform: translateX(4950%) scaleX(1) } }\r\n");
var css_done = "done";
var css_active = "active";
var css_infinite = "infinite";
var css_discrete = "discrete";
var css_progress_container = "monaco-progress-container";
var css_progress_bit = "progress-bit";
var defaultOpts$2 = {
  progressBarBackground: Color.fromHex("#0E70C0")
};
var ProgressBar = class extends Disposable {
  constructor(container, options) {
    super();
    this.options = options || Object.create(null);
    mixin(this.options, defaultOpts$2, false);
    this.workedVal = 0;
    this.progressBarBackground = this.options.progressBarBackground;
    this._register(this.showDelayedScheduler = new RunOnceScheduler(() => show(this.element), 0));
    this.create(container);
  }
  create(container) {
    this.element = document.createElement("div");
    addClass(this.element, css_progress_container);
    container.appendChild(this.element);
    this.bit = document.createElement("div");
    addClass(this.bit, css_progress_bit);
    this.element.appendChild(this.bit);
    this.applyStyles();
  }
  off() {
    this.bit.style.width = "inherit";
    this.bit.style.opacity = "1";
    removeClasses(this.element, css_active, css_infinite, css_discrete);
    this.workedVal = 0;
    this.totalWork = void 0;
  }
  stop() {
    return this.doDone(false);
  }
  doDone(delayed) {
    addClass(this.element, css_done);
    if (!hasClass(this.element, css_infinite)) {
      this.bit.style.width = "inherit";
      if (delayed) {
        setTimeout(() => this.off(), 200);
      } else {
        this.off();
      }
    } else {
      this.bit.style.opacity = "0";
      if (delayed) {
        setTimeout(() => this.off(), 200);
      } else {
        this.off();
      }
    }
    return this;
  }
  infinite() {
    this.bit.style.width = "2%";
    this.bit.style.opacity = "1";
    removeClasses(this.element, css_discrete, css_done);
    addClasses(this.element, css_active, css_infinite);
    return this;
  }
  getContainer() {
    return this.element;
  }
  style(styles6) {
    this.progressBarBackground = styles6.progressBarBackground;
    this.applyStyles();
  }
  applyStyles() {
    if (this.bit) {
      const background = this.progressBarBackground ? this.progressBarBackground.toString() : "";
      this.bit.style.backgroundColor = background;
    }
  }
};
function __snowpack__injectStyle$C(css2) {
  const headEl = document.head || document.getElementsByTagName("head")[0];
  const styleEl = document.createElement("style");
  styleEl.type = "text/css";
  if (styleEl.styleSheet) {
    styleEl.styleSheet.cssText = css2;
  } else {
    styleEl.appendChild(document.createTextNode(css2));
  }
  headEl.appendChild(styleEl);
}
__snowpack__injectStyle$C("/*---------------------------------------------------------------------------------------------\r\n *  Copyright (c) Microsoft Corporation. All rights reserved.\r\n *  Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\n\r\n.monaco-text-button {\r\n	box-sizing: border-box;\r\n	display: flex;\r\n	width: 100%;\r\n	padding: 4px;\r\n	text-align: center;\r\n	cursor: pointer;\r\n	outline-offset: 2px !important;\r\n	justify-content: center;\r\n	align-items: center;\r\n}\r\n\r\n.monaco-text-button:hover {\r\n	text-decoration: none !important;\r\n}\r\n\r\n.monaco-button.disabled {\r\n	opacity: 0.4;\r\n	cursor: default;\r\n}\r\n\r\n.monaco-button > .codicon {\r\n	margin: 0 0.2em;\r\n	color: inherit !important;\r\n}\r\n");
function renderCodiconsAsElement(text) {
  const elements = new Array();
  let match2;
  let textStart = 0, textStop = 0;
  while ((match2 = renderCodiconsRegex.exec(text)) !== null) {
    textStop = match2.index || 0;
    elements.push(text.substring(textStart, textStop));
    textStart = (match2.index || 0) + match2[0].length;
    const [, escaped, codicon, name, animation] = match2;
    elements.push(escaped ? `$(${codicon})` : $(`span.codicon.codicon-${name}${animation ? `.codicon-animation-${animation}` : ""}`));
  }
  if (textStart < text.length) {
    elements.push(text.substring(textStart));
  }
  return elements;
}
var defaultOptions$1 = {
  buttonBackground: Color.fromHex("#0E639C"),
  buttonHoverBackground: Color.fromHex("#006BB3"),
  buttonForeground: Color.white
};
var Button2 = class extends Disposable {
  constructor(container, options) {
    super();
    this._onDidClick = this._register(new Emitter());
    this.options = options || Object.create(null);
    mixin(this.options, defaultOptions$1, false);
    this.buttonForeground = this.options.buttonForeground;
    this.buttonBackground = this.options.buttonBackground;
    this.buttonHoverBackground = this.options.buttonHoverBackground;
    this.buttonSecondaryForeground = this.options.buttonSecondaryForeground;
    this.buttonSecondaryBackground = this.options.buttonSecondaryBackground;
    this.buttonSecondaryHoverBackground = this.options.buttonSecondaryHoverBackground;
    this.buttonBorder = this.options.buttonBorder;
    this._element = document.createElement("a");
    addClass(this._element, "monaco-button");
    this._element.tabIndex = 0;
    this._element.setAttribute("role", "button");
    container.appendChild(this._element);
    this._register(Gesture.addTarget(this._element));
    [EventType.CLICK, EventType$1.Tap].forEach((eventType) => {
      this._register(addDisposableListener(this._element, eventType, (e2) => {
        if (!this.enabled) {
          EventHelper.stop(e2);
          return;
        }
        this._onDidClick.fire(e2);
      }));
    });
    this._register(addDisposableListener(this._element, EventType.KEY_DOWN, (e2) => {
      const event = new StandardKeyboardEvent(e2);
      let eventHandled = false;
      if (this.enabled && (event.equals(3) || event.equals(10))) {
        this._onDidClick.fire(e2);
        eventHandled = true;
      } else if (event.equals(9)) {
        this._element.blur();
        eventHandled = true;
      }
      if (eventHandled) {
        EventHelper.stop(event, true);
      }
    }));
    this._register(addDisposableListener(this._element, EventType.MOUSE_OVER, (e2) => {
      if (!hasClass(this._element, "disabled")) {
        this.setHoverBackground();
      }
    }));
    this._register(addDisposableListener(this._element, EventType.MOUSE_OUT, (e2) => {
      this.applyStyles();
    }));
    this.focusTracker = this._register(trackFocus(this._element));
    this._register(this.focusTracker.onDidFocus(() => this.setHoverBackground()));
    this._register(this.focusTracker.onDidBlur(() => this.applyStyles()));
    this.applyStyles();
  }
  get onDidClick() {
    return this._onDidClick.event;
  }
  setHoverBackground() {
    let hoverBackground;
    if (this.options.secondary) {
      hoverBackground = this.buttonSecondaryHoverBackground ? this.buttonSecondaryHoverBackground.toString() : null;
    } else {
      hoverBackground = this.buttonHoverBackground ? this.buttonHoverBackground.toString() : null;
    }
    if (hoverBackground) {
      this._element.style.backgroundColor = hoverBackground;
    }
  }
  style(styles6) {
    this.buttonForeground = styles6.buttonForeground;
    this.buttonBackground = styles6.buttonBackground;
    this.buttonHoverBackground = styles6.buttonHoverBackground;
    this.buttonSecondaryForeground = styles6.buttonSecondaryForeground;
    this.buttonSecondaryBackground = styles6.buttonSecondaryBackground;
    this.buttonSecondaryHoverBackground = styles6.buttonSecondaryHoverBackground;
    this.buttonBorder = styles6.buttonBorder;
    this.applyStyles();
  }
  applyStyles() {
    if (this._element) {
      let background, foreground2;
      if (this.options.secondary) {
        foreground2 = this.buttonSecondaryForeground ? this.buttonSecondaryForeground.toString() : "";
        background = this.buttonSecondaryBackground ? this.buttonSecondaryBackground.toString() : "";
      } else {
        foreground2 = this.buttonForeground ? this.buttonForeground.toString() : "";
        background = this.buttonBackground ? this.buttonBackground.toString() : "";
      }
      const border = this.buttonBorder ? this.buttonBorder.toString() : "";
      this._element.style.color = foreground2;
      this._element.style.backgroundColor = background;
      this._element.style.borderWidth = border ? "1px" : "";
      this._element.style.borderStyle = border ? "solid" : "";
      this._element.style.borderColor = border;
    }
  }
  get element() {
    return this._element;
  }
  set label(value) {
    if (!hasClass(this._element, "monaco-text-button")) {
      addClass(this._element, "monaco-text-button");
    }
    if (this.options.supportCodicons) {
      reset(this._element, ...renderCodiconsAsElement(value));
    } else {
      this._element.textContent = value;
    }
    if (typeof this.options.title === "string") {
      this._element.title = this.options.title;
    } else if (this.options.title) {
      this._element.title = value;
    }
  }
  set enabled(value) {
    if (value) {
      removeClass(this._element, "disabled");
      this._element.setAttribute("aria-disabled", String(false));
      this._element.tabIndex = 0;
    } else {
      addClass(this._element, "disabled");
      this._element.setAttribute("aria-disabled", String(true));
      removeTabIndexAndUpdateFocus(this._element);
    }
  }
  get enabled() {
    return !hasClass(this._element, "disabled");
  }
};
var __awaiter$a = function(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var $$5 = $;
var backButtonIcon = registerIcon("quick-input-back", Codicon.arrowLeft);
var backButton = {
  iconClass: backButtonIcon.classNames,
  tooltip: localize("quickInput.back", "Back"),
  handle: -1
};
var QuickInput = class extends Disposable {
  constructor(ui2) {
    super();
    this.ui = ui2;
    this.visible = false;
    this._enabled = true;
    this._busy = false;
    this._ignoreFocusOut = false;
    this._buttons = [];
    this.buttonsUpdated = false;
    this.onDidTriggerButtonEmitter = this._register(new Emitter());
    this.onDidHideEmitter = this._register(new Emitter());
    this.onDisposeEmitter = this._register(new Emitter());
    this.visibleDisposables = this._register(new DisposableStore());
    this.onDidHide = this.onDidHideEmitter.event;
  }
  get title() {
    return this._title;
  }
  set title(title3) {
    this._title = title3;
    this.update();
  }
  get description() {
    return this._description;
  }
  set description(description) {
    this._description = description;
    this.update();
  }
  get step() {
    return this._steps;
  }
  set step(step) {
    this._steps = step;
    this.update();
  }
  get totalSteps() {
    return this._totalSteps;
  }
  set totalSteps(totalSteps) {
    this._totalSteps = totalSteps;
    this.update();
  }
  get enabled() {
    return this._enabled;
  }
  set enabled(enabled) {
    this._enabled = enabled;
    this.update();
  }
  get contextKey() {
    return this._contextKey;
  }
  set contextKey(contextKey) {
    this._contextKey = contextKey;
    this.update();
  }
  get busy() {
    return this._busy;
  }
  set busy(busy) {
    this._busy = busy;
    this.update();
  }
  get ignoreFocusOut() {
    return this._ignoreFocusOut;
  }
  set ignoreFocusOut(ignoreFocusOut) {
    this._ignoreFocusOut = ignoreFocusOut;
    this.update();
  }
  get buttons() {
    return this._buttons;
  }
  set buttons(buttons) {
    this._buttons = buttons;
    this.buttonsUpdated = true;
    this.update();
  }
  show() {
    if (this.visible) {
      return;
    }
    this.visibleDisposables.add(this.ui.onDidTriggerButton((button2) => {
      if (this.buttons.indexOf(button2) !== -1) {
        this.onDidTriggerButtonEmitter.fire(button2);
      }
    }));
    this.ui.show(this);
    this.visible = true;
    this.update();
  }
  hide() {
    if (!this.visible) {
      return;
    }
    this.ui.hide();
  }
  didHide() {
    this.visible = false;
    this.visibleDisposables.clear();
    this.onDidHideEmitter.fire();
  }
  update() {
    if (!this.visible) {
      return;
    }
    const title3 = this.getTitle();
    if (title3 && this.ui.title.textContent !== title3) {
      this.ui.title.textContent = title3;
    } else if (!title3 && this.ui.title.innerHTML !== "&nbsp;") {
      this.ui.title.innerText = " ;";
    }
    const description = this.getDescription();
    if (this.ui.description.textContent !== description) {
      this.ui.description.textContent = description;
    }
    if (this.busy && !this.busyDelay) {
      this.busyDelay = new TimeoutTimer();
      this.busyDelay.setIfNotSet(() => {
        if (this.visible) {
          this.ui.progressBar.infinite();
        }
      }, 800);
    }
    if (!this.busy && this.busyDelay) {
      this.ui.progressBar.stop();
      this.busyDelay.cancel();
      this.busyDelay = void 0;
    }
    if (this.buttonsUpdated) {
      this.buttonsUpdated = false;
      this.ui.leftActionBar.clear();
      const leftButtons = this.buttons.filter((button2) => button2 === backButton);
      this.ui.leftActionBar.push(leftButtons.map((button2, index3) => {
        const action = new Action(`id-${index3}`, "", button2.iconClass || getIconClass(button2.iconPath), true, () => __awaiter$a(this, void 0, void 0, function* () {
          this.onDidTriggerButtonEmitter.fire(button2);
        }));
        action.tooltip = button2.tooltip || "";
        return action;
      }), {icon: true, label: false});
      this.ui.rightActionBar.clear();
      const rightButtons = this.buttons.filter((button2) => button2 !== backButton);
      this.ui.rightActionBar.push(rightButtons.map((button2, index3) => {
        const action = new Action(`id-${index3}`, "", button2.iconClass || getIconClass(button2.iconPath), true, () => __awaiter$a(this, void 0, void 0, function* () {
          this.onDidTriggerButtonEmitter.fire(button2);
        }));
        action.tooltip = button2.tooltip || "";
        return action;
      }), {icon: true, label: false});
    }
    this.ui.ignoreFocusOut = this.ignoreFocusOut;
    this.ui.setEnabled(this.enabled);
    this.ui.setContextKey(this.contextKey);
  }
  getTitle() {
    if (this.title && this.step) {
      return `${this.title} (${this.getSteps()})`;
    }
    if (this.title) {
      return this.title;
    }
    if (this.step) {
      return this.getSteps();
    }
    return "";
  }
  getDescription() {
    return this.description || "";
  }
  getSteps() {
    if (this.step && this.totalSteps) {
      return localize("quickInput.steps", "{0}/{1}", this.step, this.totalSteps);
    }
    if (this.step) {
      return String(this.step);
    }
    return "";
  }
  showMessageDecoration(severity) {
    this.ui.inputBox.showDecoration(severity);
    if (severity === Severity$1.Error) {
      const styles6 = this.ui.inputBox.stylesForType(severity);
      this.ui.message.style.color = styles6.foreground ? `${styles6.foreground}` : "";
      this.ui.message.style.backgroundColor = styles6.background ? `${styles6.background}` : "";
      this.ui.message.style.border = styles6.border ? `1px solid ${styles6.border}` : "";
      this.ui.message.style.paddingBottom = "4px";
    } else {
      this.ui.message.style.color = "";
      this.ui.message.style.backgroundColor = "";
      this.ui.message.style.border = "";
      this.ui.message.style.paddingBottom = "";
    }
  }
  dispose() {
    this.hide();
    this.onDisposeEmitter.fire();
    super.dispose();
  }
};
var QuickPick = class extends QuickInput {
  constructor() {
    super(...arguments);
    this._value = "";
    this.onDidChangeValueEmitter = this._register(new Emitter());
    this.onDidAcceptEmitter = this._register(new Emitter());
    this.onDidCustomEmitter = this._register(new Emitter());
    this._items = [];
    this.itemsUpdated = false;
    this._canSelectMany = false;
    this._canAcceptInBackground = false;
    this._matchOnDescription = false;
    this._matchOnDetail = false;
    this._matchOnLabel = true;
    this._sortByLabel = true;
    this._autoFocusOnList = true;
    this._itemActivation = this.ui.isScreenReaderOptimized() ? ItemActivation.NONE : ItemActivation.FIRST;
    this._activeItems = [];
    this.activeItemsUpdated = false;
    this.activeItemsToConfirm = [];
    this.onDidChangeActiveEmitter = this._register(new Emitter());
    this._selectedItems = [];
    this.selectedItemsUpdated = false;
    this.selectedItemsToConfirm = [];
    this.onDidChangeSelectionEmitter = this._register(new Emitter());
    this.onDidTriggerItemButtonEmitter = this._register(new Emitter());
    this.valueSelectionUpdated = true;
    this._ok = "default";
    this._customButton = false;
    this.filterValue = (value) => value;
    this.onDidChangeValue = this.onDidChangeValueEmitter.event;
    this.onDidAccept = this.onDidAcceptEmitter.event;
    this.onDidChangeActive = this.onDidChangeActiveEmitter.event;
    this.onDidChangeSelection = this.onDidChangeSelectionEmitter.event;
    this.onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event;
  }
  get quickNavigate() {
    return this._quickNavigate;
  }
  set quickNavigate(quickNavigate) {
    this._quickNavigate = quickNavigate;
    this.update();
  }
  get value() {
    return this._value;
  }
  set value(value) {
    this._value = value || "";
    this.update();
  }
  set ariaLabel(ariaLabel) {
    this._ariaLabel = ariaLabel;
    this.update();
  }
  get ariaLabel() {
    return this._ariaLabel;
  }
  get placeholder() {
    return this._placeholder;
  }
  set placeholder(placeholder) {
    this._placeholder = placeholder;
    this.update();
  }
  get items() {
    return this._items;
  }
  set items(items) {
    this._items = items;
    this.itemsUpdated = true;
    this.update();
  }
  get canSelectMany() {
    return this._canSelectMany;
  }
  set canSelectMany(canSelectMany) {
    this._canSelectMany = canSelectMany;
    this.update();
  }
  get canAcceptInBackground() {
    return this._canAcceptInBackground;
  }
  set canAcceptInBackground(canAcceptInBackground) {
    this._canAcceptInBackground = canAcceptInBackground;
  }
  get matchOnDescription() {
    return this._matchOnDescription;
  }
  set matchOnDescription(matchOnDescription) {
    this._matchOnDescription = matchOnDescription;
    this.update();
  }
  get matchOnDetail() {
    return this._matchOnDetail;
  }
  set matchOnDetail(matchOnDetail) {
    this._matchOnDetail = matchOnDetail;
    this.update();
  }
  get matchOnLabel() {
    return this._matchOnLabel;
  }
  set matchOnLabel(matchOnLabel) {
    this._matchOnLabel = matchOnLabel;
    this.update();
  }
  get sortByLabel() {
    return this._sortByLabel;
  }
  set sortByLabel(sortByLabel) {
    this._sortByLabel = sortByLabel;
    this.update();
  }
  get autoFocusOnList() {
    return this._autoFocusOnList;
  }
  set autoFocusOnList(autoFocusOnList) {
    this._autoFocusOnList = autoFocusOnList;
    this.update();
  }
  get itemActivation() {
    return this._itemActivation;
  }
  set itemActivation(itemActivation) {
    this._itemActivation = itemActivation;
  }
  get activeItems() {
    return this._activeItems;
  }
  set activeItems(activeItems) {
    this._activeItems = activeItems;
    this.activeItemsUpdated = true;
    this.update();
  }
  get selectedItems() {
    return this._selectedItems;
  }
  set selectedItems(selectedItems) {
    this._selectedItems = selectedItems;
    this.selectedItemsUpdated = true;
    this.update();
  }
  get keyMods() {
    if (this._quickNavigate) {
      return NO_KEY_MODS;
    }
    return this.ui.keyMods;
  }
  set valueSelection(valueSelection) {
    this._valueSelection = valueSelection;
    this.valueSelectionUpdated = true;
    this.update();
  }
  get validationMessage() {
    return this._validationMessage;
  }
  set validationMessage(validationMessage) {
    this._validationMessage = validationMessage;
    this.update();
  }
  get customButton() {
    return this._customButton;
  }
  set customButton(showCustomButton) {
    this._customButton = showCustomButton;
    this.update();
  }
  get customLabel() {
    return this._customButtonLabel;
  }
  set customLabel(label2) {
    this._customButtonLabel = label2;
    this.update();
  }
  get customHover() {
    return this._customButtonHover;
  }
  set customHover(hover) {
    this._customButtonHover = hover;
    this.update();
  }
  get ok() {
    return this._ok;
  }
  set ok(showOkButton) {
    this._ok = showOkButton;
    this.update();
  }
  get hideInput() {
    return !!this._hideInput;
  }
  set hideInput(hideInput) {
    this._hideInput = hideInput;
    this.update();
  }
  trySelectFirst() {
    if (this.autoFocusOnList) {
      if (!this.canSelectMany) {
        this.ui.list.focus(QuickInputListFocus.First);
      }
    }
  }
  show() {
    if (!this.visible) {
      this.visibleDisposables.add(this.ui.inputBox.onDidChange((value) => {
        if (value === this.value) {
          return;
        }
        this._value = value;
        const didFilter = this.ui.list.filter(this.filterValue(this.ui.inputBox.value));
        if (didFilter) {
          this.trySelectFirst();
        }
        this.onDidChangeValueEmitter.fire(value);
      }));
      this.visibleDisposables.add(this.ui.inputBox.onMouseDown((event) => {
        if (!this.autoFocusOnList) {
          this.ui.list.clearFocus();
        }
      }));
      this.visibleDisposables.add((this._hideInput ? this.ui.list : this.ui.inputBox).onKeyDown((event) => {
        switch (event.keyCode) {
          case 18:
            this.ui.list.focus(QuickInputListFocus.Next);
            if (this.canSelectMany) {
              this.ui.list.domFocus();
            }
            EventHelper.stop(event, true);
            break;
          case 16:
            if (this.ui.list.getFocusedElements().length) {
              this.ui.list.focus(QuickInputListFocus.Previous);
            } else {
              this.ui.list.focus(QuickInputListFocus.Last);
            }
            if (this.canSelectMany) {
              this.ui.list.domFocus();
            }
            EventHelper.stop(event, true);
            break;
          case 12:
            this.ui.list.focus(QuickInputListFocus.NextPage);
            if (this.canSelectMany) {
              this.ui.list.domFocus();
            }
            EventHelper.stop(event, true);
            break;
          case 11:
            this.ui.list.focus(QuickInputListFocus.PreviousPage);
            if (this.canSelectMany) {
              this.ui.list.domFocus();
            }
            EventHelper.stop(event, true);
            break;
          case 17:
            if (!this._canAcceptInBackground) {
              return;
            }
            if (!this.ui.inputBox.isSelectionAtEnd()) {
              return;
            }
            if (this.activeItems[0]) {
              this._selectedItems = [this.activeItems[0]];
              this.onDidChangeSelectionEmitter.fire(this.selectedItems);
              this.onDidAcceptEmitter.fire({inBackground: true});
            }
            break;
          case 14:
            if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
              this.ui.list.focus(QuickInputListFocus.First);
              EventHelper.stop(event, true);
            }
            break;
          case 13:
            if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
              this.ui.list.focus(QuickInputListFocus.Last);
              EventHelper.stop(event, true);
            }
            break;
        }
      }));
      this.visibleDisposables.add(this.ui.onDidAccept(() => {
        if (!this.canSelectMany && this.activeItems[0]) {
          this._selectedItems = [this.activeItems[0]];
          this.onDidChangeSelectionEmitter.fire(this.selectedItems);
        }
        this.onDidAcceptEmitter.fire({inBackground: false});
      }));
      this.visibleDisposables.add(this.ui.onDidCustom(() => {
        this.onDidCustomEmitter.fire();
      }));
      this.visibleDisposables.add(this.ui.list.onDidChangeFocus((focusedItems) => {
        if (this.activeItemsUpdated) {
          return;
        }
        if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a2, b2) => a2 === b2)) {
          return;
        }
        this._activeItems = focusedItems;
        this.onDidChangeActiveEmitter.fire(focusedItems);
      }));
      this.visibleDisposables.add(this.ui.list.onDidChangeSelection(({items: selectedItems, event}) => {
        if (this.canSelectMany) {
          if (selectedItems.length) {
            this.ui.list.setSelectedElements([]);
          }
          return;
        }
        if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a2, b2) => a2 === b2)) {
          return;
        }
        this._selectedItems = selectedItems;
        this.onDidChangeSelectionEmitter.fire(selectedItems);
        if (selectedItems.length) {
          this.onDidAcceptEmitter.fire({inBackground: event instanceof MouseEvent && event.button === 1});
        }
      }));
      this.visibleDisposables.add(this.ui.list.onChangedCheckedElements((checkedItems) => {
        if (!this.canSelectMany) {
          return;
        }
        if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a2, b2) => a2 === b2)) {
          return;
        }
        this._selectedItems = checkedItems;
        this.onDidChangeSelectionEmitter.fire(checkedItems);
      }));
      this.visibleDisposables.add(this.ui.list.onButtonTriggered((event) => this.onDidTriggerItemButtonEmitter.fire(event)));
      this.visibleDisposables.add(this.registerQuickNavigation());
      this.valueSelectionUpdated = true;
    }
    super.show();
  }
  registerQuickNavigation() {
    return addDisposableListener(this.ui.container, EventType.KEY_UP, (e2) => {
      if (this.canSelectMany || !this._quickNavigate) {
        return;
      }
      const keyboardEvent = new StandardKeyboardEvent(e2);
      const keyCode = keyboardEvent.keyCode;
      const quickNavKeys = this._quickNavigate.keybindings;
      const wasTriggerKeyPressed = quickNavKeys.some((k2) => {
        const [firstPart, chordPart] = k2.getParts();
        if (chordPart) {
          return false;
        }
        if (firstPart.shiftKey && keyCode === 4) {
          if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) {
            return false;
          }
          return true;
        }
        if (firstPart.altKey && keyCode === 6) {
          return true;
        }
        if (firstPart.ctrlKey && keyCode === 5) {
          return true;
        }
        if (firstPart.metaKey && keyCode === 57) {
          return true;
        }
        return false;
      });
      if (wasTriggerKeyPressed) {
        if (this.activeItems[0]) {
          this._selectedItems = [this.activeItems[0]];
          this.onDidChangeSelectionEmitter.fire(this.selectedItems);
          this.onDidAcceptEmitter.fire({inBackground: false});
        }
        this._quickNavigate = void 0;
      }
    });
  }
  update() {
    if (!this.visible) {
      return;
    }
    let hideInput = false;
    let inputShownJustForScreenReader = false;
    if (!!this._hideInput && this._items.length > 0) {
      if (this.ui.isScreenReaderOptimized()) {
        inputShownJustForScreenReader = true;
      } else {
        hideInput = true;
      }
    }
    toggleClass(this.ui.container, "hidden-input", hideInput);
    const visibilities = {
      title: !!this.title || !!this.step || !!this.buttons.length,
      description: !!this.description,
      checkAll: this.canSelectMany,
      inputBox: !hideInput,
      progressBar: !hideInput,
      visibleCount: true,
      count: this.canSelectMany,
      ok: this.ok === "default" ? this.canSelectMany : this.ok,
      list: true,
      message: !!this.validationMessage,
      customButton: this.customButton
    };
    this.ui.setVisibilities(visibilities);
    super.update();
    if (this.ui.inputBox.value !== this.value) {
      this.ui.inputBox.value = this.value;
    }
    if (this.valueSelectionUpdated) {
      this.valueSelectionUpdated = false;
      this.ui.inputBox.select(this._valueSelection && {start: this._valueSelection[0], end: this._valueSelection[1]});
    }
    if (this.ui.inputBox.placeholder !== (this.placeholder || "")) {
      this.ui.inputBox.placeholder = this.placeholder || "";
    }
    if (inputShownJustForScreenReader) {
      this.ui.inputBox.ariaLabel = "";
    } else {
      const ariaLabel = this.ariaLabel || this.placeholder || QuickPick.DEFAULT_ARIA_LABEL;
      if (this.ui.inputBox.ariaLabel !== ariaLabel) {
        this.ui.inputBox.ariaLabel = ariaLabel;
      }
    }
    this.ui.list.matchOnDescription = this.matchOnDescription;
    this.ui.list.matchOnDetail = this.matchOnDetail;
    this.ui.list.matchOnLabel = this.matchOnLabel;
    this.ui.list.sortByLabel = this.sortByLabel;
    if (this.itemsUpdated) {
      this.itemsUpdated = false;
      this.ui.list.setElements(this.items);
      this.ui.list.filter(this.filterValue(this.ui.inputBox.value));
      this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked();
      this.ui.visibleCount.setCount(this.ui.list.getVisibleCount());
      this.ui.count.setCount(this.ui.list.getCheckedCount());
      switch (this._itemActivation) {
        case ItemActivation.NONE:
          this._itemActivation = ItemActivation.FIRST;
          break;
        case ItemActivation.SECOND:
          this.ui.list.focus(QuickInputListFocus.Second);
          this._itemActivation = ItemActivation.FIRST;
          break;
        case ItemActivation.LAST:
          this.ui.list.focus(QuickInputListFocus.Last);
          this._itemActivation = ItemActivation.FIRST;
          break;
        default:
          this.trySelectFirst();
          break;
      }
    }
    if (this.ui.container.classList.contains("show-checkboxes") !== !!this.canSelectMany) {
      if (this.canSelectMany) {
        this.ui.list.clearFocus();
      } else {
        this.trySelectFirst();
      }
    }
    if (this.activeItemsUpdated) {
      this.activeItemsUpdated = false;
      this.activeItemsToConfirm = this._activeItems;
      this.ui.list.setFocusedElements(this.activeItems);
      if (this.activeItemsToConfirm === this._activeItems) {
        this.activeItemsToConfirm = null;
      }
    }
    if (this.selectedItemsUpdated) {
      this.selectedItemsUpdated = false;
      this.selectedItemsToConfirm = this._selectedItems;
      if (this.canSelectMany) {
        this.ui.list.setCheckedElements(this.selectedItems);
      } else {
        this.ui.list.setSelectedElements(this.selectedItems);
      }
      if (this.selectedItemsToConfirm === this._selectedItems) {
        this.selectedItemsToConfirm = null;
      }
    }
    if (this.validationMessage) {
      this.ui.message.textContent = this.validationMessage;
      this.showMessageDecoration(Severity$1.Error);
    } else {
      this.ui.message.textContent = null;
      this.showMessageDecoration(Severity$1.Ignore);
    }
    this.ui.customButton.label = this.customLabel || "";
    this.ui.customButton.element.title = this.customHover || "";
    this.ui.setComboboxAccessibility(true);
    if (!visibilities.inputBox) {
      this.ui.list.domFocus();
    }
  }
};
QuickPick.DEFAULT_ARIA_LABEL = localize("quickInputBox.ariaLabel", "Type to narrow down results.");
var QuickInputController = class extends Disposable {
  constructor(options) {
    super();
    this.options = options;
    this.comboboxAccessibility = false;
    this.enabled = true;
    this.onDidAcceptEmitter = this._register(new Emitter());
    this.onDidCustomEmitter = this._register(new Emitter());
    this.onDidTriggerButtonEmitter = this._register(new Emitter());
    this.keyMods = {ctrlCmd: false, alt: false};
    this.controller = null;
    this.onShowEmitter = this._register(new Emitter());
    this.onShow = this.onShowEmitter.event;
    this.onHideEmitter = this._register(new Emitter());
    this.onHide = this.onHideEmitter.event;
    this.idPrefix = options.idPrefix;
    this.parentElement = options.container;
    this.styles = options.styles;
    this.registerKeyModsListeners();
  }
  registerKeyModsListeners() {
    const listener = (e2) => {
      this.keyMods.ctrlCmd = e2.ctrlKey || e2.metaKey;
      this.keyMods.alt = e2.altKey;
    };
    this._register(addDisposableListener(window, EventType.KEY_DOWN, listener, true));
    this._register(addDisposableListener(window, EventType.KEY_UP, listener, true));
    this._register(addDisposableListener(window, EventType.MOUSE_DOWN, listener, true));
  }
  getUI() {
    if (this.ui) {
      return this.ui;
    }
    const container = append(this.parentElement, $$5(".quick-input-widget.show-file-icons"));
    container.tabIndex = -1;
    container.style.display = "none";
    const styleSheet = createStyleSheet(container);
    const titleBar = append(container, $$5(".quick-input-titlebar"));
    const leftActionBar = this._register(new ActionBar(titleBar));
    leftActionBar.domNode.classList.add("quick-input-left-action-bar");
    const title3 = append(titleBar, $$5(".quick-input-title"));
    const rightActionBar = this._register(new ActionBar(titleBar));
    rightActionBar.domNode.classList.add("quick-input-right-action-bar");
    const description = append(container, $$5(".quick-input-description"));
    const headerContainer = append(container, $$5(".quick-input-header"));
    const checkAll = append(headerContainer, $$5("input.quick-input-check-all"));
    checkAll.type = "checkbox";
    this._register(addStandardDisposableListener(checkAll, EventType.CHANGE, (e2) => {
      const checked = checkAll.checked;
      list3.setAllVisibleChecked(checked);
    }));
    this._register(addDisposableListener(checkAll, EventType.CLICK, (e2) => {
      if (e2.x || e2.y) {
        inputBox.setFocus();
      }
    }));
    const extraContainer = append(headerContainer, $$5(".quick-input-and-message"));
    const filterContainer = append(extraContainer, $$5(".quick-input-filter"));
    const inputBox = this._register(new QuickInputBox(filterContainer));
    inputBox.setAttribute("aria-describedby", `${this.idPrefix}message`);
    const visibleCountContainer = append(filterContainer, $$5(".quick-input-visible-count"));
    visibleCountContainer.setAttribute("aria-live", "polite");
    visibleCountContainer.setAttribute("aria-atomic", "true");
    const visibleCount = new CountBadge(visibleCountContainer, {countFormat: localize({key: "quickInput.visibleCount", comment: ["This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers."]}, "{0} Results")});
    const countContainer = append(filterContainer, $$5(".quick-input-count"));
    countContainer.setAttribute("aria-live", "polite");
    const count = new CountBadge(countContainer, {countFormat: localize({key: "quickInput.countSelected", comment: ["This tells the user how many items are selected in a list of items to select from. The items can be anything."]}, "{0} Selected")});
    const okContainer = append(headerContainer, $$5(".quick-input-action"));
    const ok3 = new Button2(okContainer);
    ok3.label = localize("ok", "OK");
    this._register(ok3.onDidClick((e2) => {
      this.onDidAcceptEmitter.fire();
    }));
    const customButtonContainer = append(headerContainer, $$5(".quick-input-action"));
    const customButton = new Button2(customButtonContainer);
    customButton.label = localize("custom", "Custom");
    this._register(customButton.onDidClick((e2) => {
      this.onDidCustomEmitter.fire();
    }));
    const message = append(extraContainer, $$5(`#${this.idPrefix}message.quick-input-message`));
    const progressBar = new ProgressBar(container);
    addClass(progressBar.getContainer(), "quick-input-progress");
    const list3 = this._register(new QuickInputList(container, this.idPrefix + "list", this.options));
    this._register(list3.onChangedAllVisibleChecked((checked) => {
      checkAll.checked = checked;
    }));
    this._register(list3.onChangedVisibleCount((c3) => {
      visibleCount.setCount(c3);
    }));
    this._register(list3.onChangedCheckedCount((c3) => {
      count.setCount(c3);
    }));
    this._register(list3.onLeave(() => {
      setTimeout(() => {
        inputBox.setFocus();
        if (this.controller instanceof QuickPick && this.controller.canSelectMany) {
          list3.clearFocus();
        }
      }, 0);
    }));
    this._register(list3.onDidChangeFocus(() => {
      if (this.comboboxAccessibility) {
        this.getUI().inputBox.setAttribute("aria-activedescendant", this.getUI().list.getActiveDescendant() || "");
      }
    }));
    const focusTracker = trackFocus(container);
    this._register(focusTracker);
    this._register(addDisposableListener(container, EventType.FOCUS, (e2) => {
      this.previousFocusElement = e2.relatedTarget instanceof HTMLElement ? e2.relatedTarget : void 0;
    }, true));
    this._register(focusTracker.onDidBlur(() => {
      if (!this.getUI().ignoreFocusOut && !this.options.ignoreFocusOut()) {
        this.hide();
      }
      this.previousFocusElement = void 0;
    }));
    this._register(addDisposableListener(container, EventType.FOCUS, (e2) => {
      inputBox.setFocus();
    }));
    this._register(addDisposableListener(container, EventType.KEY_DOWN, (e2) => {
      const event = new StandardKeyboardEvent(e2);
      switch (event.keyCode) {
        case 3:
          EventHelper.stop(e2, true);
          this.onDidAcceptEmitter.fire();
          break;
        case 9:
          EventHelper.stop(e2, true);
          this.hide();
          break;
        case 2:
          if (!event.altKey && !event.ctrlKey && !event.metaKey) {
            const selectors = [".action-label.codicon"];
            if (container.classList.contains("show-checkboxes")) {
              selectors.push("input");
            } else {
              selectors.push("input[type=text]");
            }
            if (this.getUI().list.isDisplayed()) {
              selectors.push(".monaco-list");
            }
            const stops = container.querySelectorAll(selectors.join(", "));
            if (event.shiftKey && event.target === stops[0]) {
              EventHelper.stop(e2, true);
              stops[stops.length - 1].focus();
            } else if (!event.shiftKey && event.target === stops[stops.length - 1]) {
              EventHelper.stop(e2, true);
              stops[0].focus();
            }
          }
          break;
      }
    }));
    this.ui = {
      container,
      styleSheet,
      leftActionBar,
      titleBar,
      title: title3,
      description,
      rightActionBar,
      checkAll,
      filterContainer,
      inputBox,
      visibleCountContainer,
      visibleCount,
      countContainer,
      count,
      okContainer,
      ok: ok3,
      message,
      customButtonContainer,
      customButton,
      progressBar,
      list: list3,
      onDidAccept: this.onDidAcceptEmitter.event,
      onDidCustom: this.onDidCustomEmitter.event,
      onDidTriggerButton: this.onDidTriggerButtonEmitter.event,
      ignoreFocusOut: false,
      keyMods: this.keyMods,
      isScreenReaderOptimized: () => this.options.isScreenReaderOptimized(),
      show: (controller) => this.show(controller),
      hide: () => this.hide(),
      setVisibilities: (visibilities) => this.setVisibilities(visibilities),
      setComboboxAccessibility: (enabled) => this.setComboboxAccessibility(enabled),
      setEnabled: (enabled) => this.setEnabled(enabled),
      setContextKey: (contextKey) => this.options.setContextKey(contextKey)
    };
    this.updateStyles();
    return this.ui;
  }
  pick(picks, options = {}, token2 = CancellationToken.None) {
    return new Promise((doResolve, reject) => {
      let resolve2 = (result) => {
        resolve2 = doResolve;
        if (options.onKeyMods) {
          options.onKeyMods(input.keyMods);
        }
        doResolve(result);
      };
      if (token2.isCancellationRequested) {
        resolve2(void 0);
        return;
      }
      const input = this.createQuickPick();
      let activeItem;
      const disposables = [
        input,
        input.onDidAccept(() => {
          if (input.canSelectMany) {
            resolve2(input.selectedItems.slice());
            input.hide();
          } else {
            const result = input.activeItems[0];
            if (result) {
              resolve2(result);
              input.hide();
            }
          }
        }),
        input.onDidChangeActive((items) => {
          const focused = items[0];
          if (focused && options.onDidFocus) {
            options.onDidFocus(focused);
          }
        }),
        input.onDidChangeSelection((items) => {
          if (!input.canSelectMany) {
            const result = items[0];
            if (result) {
              resolve2(result);
              input.hide();
            }
          }
        }),
        input.onDidTriggerItemButton((event) => options.onDidTriggerItemButton && options.onDidTriggerItemButton(Object.assign(Object.assign({}, event), {removeItem: () => {
          const index3 = input.items.indexOf(event.item);
          if (index3 !== -1) {
            const items = input.items.slice();
            items.splice(index3, 1);
            input.items = items;
          }
        }}))),
        input.onDidChangeValue((value) => {
          if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) {
            input.activeItems = [activeItem];
          }
        }),
        token2.onCancellationRequested(() => {
          input.hide();
        }),
        input.onDidHide(() => {
          dispose(disposables);
          resolve2(void 0);
        })
      ];
      input.canSelectMany = !!options.canPickMany;
      input.placeholder = options.placeHolder;
      input.ignoreFocusOut = !!options.ignoreFocusLost;
      input.matchOnDescription = !!options.matchOnDescription;
      input.matchOnDetail = !!options.matchOnDetail;
      input.matchOnLabel = options.matchOnLabel === void 0 || options.matchOnLabel;
      input.autoFocusOnList = options.autoFocusOnList === void 0 || options.autoFocusOnList;
      input.quickNavigate = options.quickNavigate;
      input.contextKey = options.contextKey;
      input.busy = true;
      Promise.all([picks, options.activeItem]).then(([items, _activeItem]) => {
        activeItem = _activeItem;
        input.busy = false;
        input.items = items;
        if (input.canSelectMany) {
          input.selectedItems = items.filter((item) => item.type !== "separator" && item.picked);
        }
        if (activeItem) {
          input.activeItems = [activeItem];
        }
      });
      input.show();
      Promise.resolve(picks).then(void 0, (err) => {
        reject(err);
        input.hide();
      });
    });
  }
  createQuickPick() {
    const ui2 = this.getUI();
    return new QuickPick(ui2);
  }
  show(controller) {
    const ui2 = this.getUI();
    this.onShowEmitter.fire();
    const oldController = this.controller;
    this.controller = controller;
    if (oldController) {
      oldController.didHide();
    }
    this.setEnabled(true);
    ui2.leftActionBar.clear();
    ui2.title.textContent = "";
    ui2.description.textContent = "";
    ui2.rightActionBar.clear();
    ui2.checkAll.checked = false;
    ui2.inputBox.placeholder = "";
    ui2.inputBox.password = false;
    ui2.inputBox.showDecoration(Severity$1.Ignore);
    ui2.visibleCount.setCount(0);
    ui2.count.setCount(0);
    ui2.message.textContent = "";
    ui2.progressBar.stop();
    ui2.list.setElements([]);
    ui2.list.matchOnDescription = false;
    ui2.list.matchOnDetail = false;
    ui2.list.matchOnLabel = true;
    ui2.list.sortByLabel = true;
    ui2.ignoreFocusOut = false;
    this.setComboboxAccessibility(false);
    ui2.inputBox.ariaLabel = "";
    const backKeybindingLabel = this.options.backKeybindingLabel();
    backButton.tooltip = backKeybindingLabel ? localize("quickInput.backWithKeybinding", "Back ({0})", backKeybindingLabel) : localize("quickInput.back", "Back");
    ui2.container.style.display = "";
    this.updateLayout();
    ui2.inputBox.setFocus();
  }
  setVisibilities(visibilities) {
    const ui2 = this.getUI();
    ui2.title.style.display = visibilities.title ? "" : "none";
    ui2.description.style.display = visibilities.description ? "" : "none";
    ui2.checkAll.style.display = visibilities.checkAll ? "" : "none";
    ui2.filterContainer.style.display = visibilities.inputBox ? "" : "none";
    ui2.visibleCountContainer.style.display = visibilities.visibleCount ? "" : "none";
    ui2.countContainer.style.display = visibilities.count ? "" : "none";
    ui2.okContainer.style.display = visibilities.ok ? "" : "none";
    ui2.customButtonContainer.style.display = visibilities.customButton ? "" : "none";
    ui2.message.style.display = visibilities.message ? "" : "none";
    ui2.progressBar.getContainer().style.display = visibilities.progressBar ? "" : "none";
    ui2.list.display(!!visibilities.list);
    ui2.container.classList[visibilities.checkAll ? "add" : "remove"]("show-checkboxes");
    this.updateLayout();
  }
  setComboboxAccessibility(enabled) {
    if (enabled !== this.comboboxAccessibility) {
      const ui2 = this.getUI();
      this.comboboxAccessibility = enabled;
      if (this.comboboxAccessibility) {
        ui2.inputBox.setAttribute("role", "combobox");
        ui2.inputBox.setAttribute("aria-haspopup", "true");
        ui2.inputBox.setAttribute("aria-autocomplete", "list");
        ui2.inputBox.setAttribute("aria-activedescendant", ui2.list.getActiveDescendant() || "");
      } else {
        ui2.inputBox.removeAttribute("role");
        ui2.inputBox.removeAttribute("aria-haspopup");
        ui2.inputBox.removeAttribute("aria-autocomplete");
        ui2.inputBox.removeAttribute("aria-activedescendant");
      }
    }
  }
  setEnabled(enabled) {
    if (enabled !== this.enabled) {
      this.enabled = enabled;
      for (const item of this.getUI().leftActionBar.viewItems) {
        item.getAction().enabled = enabled;
      }
      for (const item of this.getUI().rightActionBar.viewItems) {
        item.getAction().enabled = enabled;
      }
      this.getUI().checkAll.disabled = !enabled;
      this.getUI().ok.enabled = enabled;
      this.getUI().list.enabled = enabled;
    }
  }
  hide() {
    var _a;
    const controller = this.controller;
    if (controller) {
      const focusChanged = !((_a = this.ui) === null || _a === void 0 ? void 0 : _a.container.contains(document.activeElement));
      this.controller = null;
      this.onHideEmitter.fire();
      this.getUI().container.style.display = "none";
      if (!focusChanged) {
        if (this.previousFocusElement && this.previousFocusElement.offsetParent) {
          this.previousFocusElement.focus();
          this.previousFocusElement = void 0;
        } else {
          this.options.returnFocus();
        }
      }
      controller.didHide();
    }
  }
  layout(dimension, titleBarOffset) {
    this.dimension = dimension;
    this.titleBarOffset = titleBarOffset;
    this.updateLayout();
  }
  updateLayout() {
    if (this.ui) {
      this.ui.container.style.top = `${this.titleBarOffset}px`;
      const style = this.ui.container.style;
      const width2 = Math.min(this.dimension.width * 0.62, QuickInputController.MAX_WIDTH);
      style.width = width2 + "px";
      style.marginLeft = "-" + width2 / 2 + "px";
      this.ui.inputBox.layout();
      this.ui.list.layout(this.dimension && this.dimension.height * 0.4);
    }
  }
  applyStyles(styles6) {
    this.styles = styles6;
    this.updateStyles();
  }
  updateStyles() {
    if (this.ui) {
      const {quickInputTitleBackground: quickInputTitleBackground2, quickInputBackground: quickInputBackground2, quickInputForeground: quickInputForeground2, contrastBorder: contrastBorder2, widgetShadow: widgetShadow2} = this.styles.widget;
      this.ui.titleBar.style.backgroundColor = quickInputTitleBackground2 ? quickInputTitleBackground2.toString() : "";
      this.ui.container.style.backgroundColor = quickInputBackground2 ? quickInputBackground2.toString() : "";
      this.ui.container.style.color = quickInputForeground2 ? quickInputForeground2.toString() : "";
      this.ui.container.style.border = contrastBorder2 ? `1px solid ${contrastBorder2}` : "";
      this.ui.container.style.boxShadow = widgetShadow2 ? `0 5px 8px ${widgetShadow2}` : "";
      this.ui.inputBox.style(this.styles.inputBox);
      this.ui.count.style(this.styles.countBadge);
      this.ui.ok.style(this.styles.button);
      this.ui.customButton.style(this.styles.button);
      this.ui.progressBar.style(this.styles.progressBar);
      this.ui.list.style(this.styles.list);
      const content2 = [];
      if (this.styles.list.listInactiveFocusForeground) {
        content2.push(`.monaco-list .monaco-list-row.focused { color:  ${this.styles.list.listInactiveFocusForeground}; }`);
        content2.push(`.monaco-list .monaco-list-row.focused:hover { color:  ${this.styles.list.listInactiveFocusForeground}; }`);
      }
      if (this.styles.list.pickerGroupBorder) {
        content2.push(`.quick-input-list .quick-input-list-entry { border-top-color:  ${this.styles.list.pickerGroupBorder}; }`);
      }
      if (this.styles.list.pickerGroupForeground) {
        content2.push(`.quick-input-list .quick-input-list-separator { color:  ${this.styles.list.pickerGroupForeground}; }`);
      }
      const newStyles = content2.join("\n");
      if (newStyles !== this.ui.styleSheet.innerHTML) {
        this.ui.styleSheet.innerHTML = newStyles;
      }
    }
  }
};
QuickInputController.MAX_WIDTH = 600;
var IQuickInputService = createDecorator("quickInputService");
var DefaultQuickAccessFilterValue;
(function(DefaultQuickAccessFilterValue2) {
  DefaultQuickAccessFilterValue2[DefaultQuickAccessFilterValue2["PRESERVE"] = 0] = "PRESERVE";
  DefaultQuickAccessFilterValue2[DefaultQuickAccessFilterValue2["LAST"] = 1] = "LAST";
})(DefaultQuickAccessFilterValue || (DefaultQuickAccessFilterValue = {}));
var Extensions$7 = {
  Quickaccess: "workbench.contributions.quickaccess"
};
var QuickAccessRegistry = class {
  constructor() {
    this.providers = [];
    this.defaultProvider = void 0;
  }
  registerQuickAccessProvider(provider) {
    if (provider.prefix.length === 0) {
      this.defaultProvider = provider;
    } else {
      this.providers.push(provider);
    }
    this.providers.sort((providerA, providerB) => providerB.prefix.length - providerA.prefix.length);
    return toDisposable(() => {
      this.providers.splice(this.providers.indexOf(provider), 1);
      if (this.defaultProvider === provider) {
        this.defaultProvider = void 0;
      }
    });
  }
  getQuickAccessProviders() {
    return coalesce([this.defaultProvider, ...this.providers]);
  }
  getQuickAccessProvider(prefix2) {
    const result = prefix2 ? this.providers.find((provider) => prefix2.startsWith(provider.prefix)) || void 0 : void 0;
    return result || this.defaultProvider;
  }
};
Registry$1.add(Extensions$7.Quickaccess, new QuickAccessRegistry());
var __decorate$m = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$h = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var QuickAccessController = class QuickAccessController2 extends Disposable {
  constructor(quickInputService, instantiationService) {
    super();
    this.quickInputService = quickInputService;
    this.instantiationService = instantiationService;
    this.registry = Registry$1.as(Extensions$7.Quickaccess);
    this.mapProviderToDescriptor = new Map();
    this.lastAcceptedPickerValues = new Map();
    this.visibleQuickAccess = void 0;
  }
  show(value = "", options) {
    var _a;
    const [provider, descriptor] = this.getOrInstantiateProvider(value);
    const visibleQuickAccess = this.visibleQuickAccess;
    const visibleDescriptor = visibleQuickAccess === null || visibleQuickAccess === void 0 ? void 0 : visibleQuickAccess.descriptor;
    if (visibleQuickAccess && descriptor && visibleDescriptor === descriptor) {
      if (value !== descriptor.prefix && !(options === null || options === void 0 ? void 0 : options.preserveValue)) {
        visibleQuickAccess.picker.value = value;
      }
      this.adjustValueSelection(visibleQuickAccess.picker, descriptor, options);
      return;
    }
    if (descriptor && !(options === null || options === void 0 ? void 0 : options.preserveValue)) {
      let newValue = void 0;
      if (visibleQuickAccess && visibleDescriptor && visibleDescriptor !== descriptor) {
        const newValueCandidateWithoutPrefix = visibleQuickAccess.value.substr(visibleDescriptor.prefix.length);
        if (newValueCandidateWithoutPrefix) {
          newValue = `${descriptor.prefix}${newValueCandidateWithoutPrefix}`;
        }
      }
      if (!newValue) {
        const defaultFilterValue = provider === null || provider === void 0 ? void 0 : provider.defaultFilterValue;
        if (defaultFilterValue === DefaultQuickAccessFilterValue.LAST) {
          newValue = this.lastAcceptedPickerValues.get(descriptor);
        } else if (typeof defaultFilterValue === "string") {
          newValue = `${descriptor.prefix}${defaultFilterValue}`;
        }
      }
      if (typeof newValue === "string") {
        value = newValue;
      }
    }
    const disposables = new DisposableStore();
    const picker = disposables.add(this.quickInputService.createQuickPick());
    picker.value = value;
    this.adjustValueSelection(picker, descriptor, options);
    picker.placeholder = descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder;
    picker.quickNavigate = options === null || options === void 0 ? void 0 : options.quickNavigateConfiguration;
    picker.hideInput = !!picker.quickNavigate && !visibleQuickAccess;
    if (typeof (options === null || options === void 0 ? void 0 : options.itemActivation) === "number" || (options === null || options === void 0 ? void 0 : options.quickNavigateConfiguration)) {
      picker.itemActivation = (_a = options === null || options === void 0 ? void 0 : options.itemActivation) !== null && _a !== void 0 ? _a : ItemActivation.SECOND;
    }
    picker.contextKey = descriptor === null || descriptor === void 0 ? void 0 : descriptor.contextKey;
    picker.filterValue = (value2) => value2.substring(descriptor ? descriptor.prefix.length : 0);
    if (descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder) {
      picker.ariaLabel = descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder;
    }
    const cancellationToken = this.registerPickerListeners(picker, provider, descriptor, value, disposables);
    if (provider) {
      disposables.add(provider.provide(picker, cancellationToken));
    }
    picker.show();
  }
  adjustValueSelection(picker, descriptor, options) {
    var _a;
    let valueSelection;
    if (options === null || options === void 0 ? void 0 : options.preserveValue) {
      valueSelection = [picker.value.length, picker.value.length];
    } else {
      valueSelection = [(_a = descriptor === null || descriptor === void 0 ? void 0 : descriptor.prefix.length) !== null && _a !== void 0 ? _a : 0, picker.value.length];
    }
    picker.valueSelection = valueSelection;
  }
  registerPickerListeners(picker, provider, descriptor, value, disposables) {
    const visibleQuickAccess = this.visibleQuickAccess = {picker, descriptor, value};
    disposables.add(toDisposable(() => {
      if (visibleQuickAccess === this.visibleQuickAccess) {
        this.visibleQuickAccess = void 0;
      }
    }));
    disposables.add(picker.onDidChangeValue((value2) => {
      const [providerForValue] = this.getOrInstantiateProvider(value2);
      if (providerForValue !== provider) {
        this.show(value2, {preserveValue: true});
      } else {
        visibleQuickAccess.value = value2;
      }
    }));
    if (descriptor) {
      disposables.add(picker.onDidAccept(() => {
        this.lastAcceptedPickerValues.set(descriptor, picker.value);
      }));
    }
    const cts = disposables.add(new CancellationTokenSource());
    once$1(picker.onDidHide)(() => {
      if (picker.selectedItems.length === 0) {
        cts.cancel();
      }
      disposables.dispose();
    });
    return cts.token;
  }
  getOrInstantiateProvider(value) {
    const providerDescriptor = this.registry.getQuickAccessProvider(value);
    if (!providerDescriptor) {
      return [void 0, void 0];
    }
    let provider = this.mapProviderToDescriptor.get(providerDescriptor);
    if (!provider) {
      provider = this.instantiationService.createInstance(providerDescriptor.ctor);
      this.mapProviderToDescriptor.set(providerDescriptor, provider);
    }
    return [provider, providerDescriptor];
  }
};
QuickAccessController = __decorate$m([
  __param$h(0, IQuickInputService),
  __param$h(1, IInstantiationService)
], QuickAccessController);
var __decorate$n = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$i = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var QuickInputService = class QuickInputService2 extends Themable {
  constructor(instantiationService, contextKeyService, themeService, accessibilityService, layoutService) {
    super(themeService);
    this.instantiationService = instantiationService;
    this.contextKeyService = contextKeyService;
    this.accessibilityService = accessibilityService;
    this.layoutService = layoutService;
    this.contexts = new Map();
  }
  get controller() {
    if (!this._controller) {
      this._controller = this._register(this.createController());
    }
    return this._controller;
  }
  get quickAccess() {
    if (!this._quickAccess) {
      this._quickAccess = this._register(this.instantiationService.createInstance(QuickAccessController));
    }
    return this._quickAccess;
  }
  createController(host = this.layoutService, options) {
    var _a, _b;
    const defaultOptions3 = {
      idPrefix: "quickInput_",
      container: host.container,
      ignoreFocusOut: () => false,
      isScreenReaderOptimized: () => this.accessibilityService.isScreenReaderOptimized(),
      backKeybindingLabel: () => void 0,
      setContextKey: (id3) => this.setContextKey(id3),
      returnFocus: () => host.focus(),
      createList: (user, container, delegate, renderers, options2) => this.instantiationService.createInstance(WorkbenchList, user, container, delegate, renderers, options2),
      styles: this.computeStyles()
    };
    const controller = this._register(new QuickInputController(Object.assign(Object.assign({}, defaultOptions3), options)));
    controller.layout(host.dimension, (_b = (_a = host.offset) === null || _a === void 0 ? void 0 : _a.top) !== null && _b !== void 0 ? _b : 0);
    this._register(host.onLayout((dimension) => {
      var _a2, _b2;
      return controller.layout(dimension, (_b2 = (_a2 = host.offset) === null || _a2 === void 0 ? void 0 : _a2.top) !== null && _b2 !== void 0 ? _b2 : 0);
    }));
    this._register(controller.onShow(() => this.resetContextKeys()));
    this._register(controller.onHide(() => this.resetContextKeys()));
    return controller;
  }
  setContextKey(id3) {
    let key;
    if (id3) {
      key = this.contexts.get(id3);
      if (!key) {
        key = new RawContextKey(id3, false).bindTo(this.contextKeyService);
        this.contexts.set(id3, key);
      }
    }
    if (key && key.get()) {
      return;
    }
    this.resetContextKeys();
    if (key) {
      key.set(true);
    }
  }
  resetContextKeys() {
    this.contexts.forEach((context2) => {
      if (context2.get()) {
        context2.reset();
      }
    });
  }
  pick(picks, options = {}, token2 = CancellationToken.None) {
    return this.controller.pick(picks, options, token2);
  }
  createQuickPick() {
    return this.controller.createQuickPick();
  }
  updateStyles() {
    this.controller.applyStyles(this.computeStyles());
  }
  computeStyles() {
    return {
      widget: Object.assign({}, computeStyles2(this.theme, {
        quickInputBackground,
        quickInputForeground,
        quickInputTitleBackground,
        contrastBorder,
        widgetShadow
      })),
      inputBox: computeStyles2(this.theme, {
        inputForeground,
        inputBackground,
        inputBorder,
        inputValidationInfoBackground,
        inputValidationInfoForeground,
        inputValidationInfoBorder,
        inputValidationWarningBackground,
        inputValidationWarningForeground,
        inputValidationWarningBorder,
        inputValidationErrorBackground,
        inputValidationErrorForeground,
        inputValidationErrorBorder
      }),
      countBadge: computeStyles2(this.theme, {
        badgeBackground,
        badgeForeground,
        badgeBorder: contrastBorder
      }),
      button: computeStyles2(this.theme, {
        buttonForeground,
        buttonBackground,
        buttonHoverBackground,
        buttonBorder: contrastBorder
      }),
      progressBar: computeStyles2(this.theme, {
        progressBarBackground
      }),
      list: computeStyles2(this.theme, {
        listBackground: quickInputBackground,
        listInactiveFocusForeground: listFocusForeground,
        listInactiveFocusBackground: listFocusBackground,
        listFocusOutline: activeContrastBorder,
        listInactiveFocusOutline: activeContrastBorder,
        pickerGroupBorder,
        pickerGroupForeground
      })
    };
  }
};
QuickInputService = __decorate$n([
  __param$i(0, IInstantiationService),
  __param$i(1, IContextKeyService),
  __param$i(2, IThemeService),
  __param$i(3, IAccessibilityService),
  __param$i(4, ILayoutService)
], QuickInputService);
var __decorate$o = function(decorators, target, key, desc) {
  var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r3 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d2 = decorators[i3])
        r3 = (c3 < 3 ? d2(r3) : c3 > 3 ? d2(target, key, r3) : d2(target, key)) || r3;
  return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3;
};
var __param$j = function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var EditorScopedQuickInputServiceImpl = class EditorScopedQuickInputServiceImpl2 extends QuickInputService {
  constructor(editor2, instantiationService, contextKeyService, themeService, accessibilityService, layoutService) {
    super(instantiationService, contextKeyService, themeService, accessibilityService, layoutService);
    this.host = void 0;
    const contribution = QuickInputEditorContribution.get(editor2);
    this.host = {
      _serviceBrand: void 0,
      get container() {
        return contribution.widget.getDomNode();
      },
      get dimension() {
        return editor2.getLayoutInfo();
      },
      get onLayout() {
        return editor2.onDidLayoutChange;
      },
      focus: () => editor2.focus()
    };
  }
  createController() {
    return super.createController(this.host);
  }
};
EditorScopedQuickInputServiceImpl = __decorate$o([
  __param$j(1, IInstantiationService),
  __param$j(2, IContextKeyService),
  __param$j(3, IThemeService),
  __param$j(4, IAccessibilityService),
  __param$j(5, ILayoutService)
], EditorScopedQuickInputServiceImpl);
var StandaloneQuickInputServiceImpl = class StandaloneQuickInputServiceImpl2 {
  constructor(instantiationService, codeEditorService) {
    this.instantiationService = instantiationService;
    this.codeEditorService = codeEditorService;
    this.mapEditorToService = new Map();
  }
  get activeService() {
    const editor2 = this.codeEditorService.getFocusedCodeEditor();
    if (!editor2) {
      throw new Error("Quick input service needs a focused editor to work.");
    }
    let quickInputService = this.mapEditorToService.get(editor2);
    if (!quickInputService) {
      const newQuickInputService = quickInputService = this.instantiationService.createInstance(EditorScopedQuickInputServiceImpl, editor2);
      this.mapEditorToService.set(editor2, quickInputService);
      once$1(editor2.onDidDispose)(() => {
        newQuickInputService.dispose();
        this.mapEditorToService.delete(editor2);
      });
    }
    return quickInputService;
  }
  get quickAccess() {
    return this.activeService.quickAccess;
  }
  pick(picks, options = {}, token2 = CancellationToken.None) {
    return this.activeService.pick(picks, options, token2);
  }
  createQuickPick() {
    return this.activeService.createQuickPick();
  }
};
StandaloneQuickInputServiceImpl = __decorate$o([
  __param$j(0, IInstantiationService),
  __param$j(1, ICodeEditorService)
], StandaloneQuickInputServiceImpl);
var QuickInputEditorContribution = class {
  constructor(editor2) {
    this.editor = editor2;
    this.widget = new QuickInputEditorWidget(this.editor);
  }
  static get(editor2) {
    return editor2.getContribution(QuickInputEditorContribution.ID);
  }
  dispose() {
    this.widget.dispose();
  }
};
QuickInputEditorContribution.ID = "editor.controller.quickInput";
var QuickInputEditorWidget = class {
  constructor(codeEditor2) {
    this.codeEditor = codeEditor2;
    this.domNode = document.createElement("div");
    this.codeEditor.addOverlayWidget(this);
  }
  getId() {
    return QuickInputEditorWidget.ID;
  }
  getDomNode() {
    return this.domNode;
  }
  getPosition() {
    return {preference: 2};
  }
  dispose() {
    this.codeEditor.removeOverlayWidget(this);
  }
};
QuickInputEditorWidget.ID = "editor.contrib.quickInputWidget";
registerEditorContribution(QuickInputEditorContribution.ID, QuickInputEditorContribution);
var IStorageKeysSyncRegistryService = createDecorator("IStorageKeysSyncRegistryService");
var StorageKeysSyncRegistryService = class extends Disposable {
  constructor() {
    super();
    this._storageKeys = new Map();
    this._onDidChangeStorageKeys = this._register(new Emitter());
    this._register(toDisposable(() => this._storageKeys.clear()));
  }
  get storageKeys() {
    return [...this._storageKeys.values()];
  }
  registerStorageKey(storageKey) {
    if (!this._storageKeys.has(storageKey.key)) {
      this._storageKeys.set(storageKey.key, storageKey);
      this._onDidChangeStorageKeys.fire(this.storageKeys);
    }
  }
};
var StaticServices;
(function(StaticServices2) {
  const _serviceCollection = new ServiceCollection();
  class LazyStaticService {
    constructor(serviceId, factory) {
      this._serviceId = serviceId;
      this._factory = factory;
      this._value = null;
    }
    get id() {
      return this._serviceId;
    }
    get(overrides) {
      if (!this._value) {
        if (overrides) {
          this._value = overrides[this._serviceId.toString()];
        }
        if (!this._value) {
          this._value = this._factory(overrides);
        }
        if (!this._value) {
          throw new Error("Service " + this._serviceId + " is missing!");
        }
        _serviceCollection.set(this._serviceId, this._value);
      }
      return this._value;
    }
  }
  StaticServices2.LazyStaticService = LazyStaticService;
  let _all = [];
  function define2(serviceId, factory) {
    let r3 = new LazyStaticService(serviceId, factory);
    _all.push(r3);
    return r3;
  }
  function init4(overrides) {
    let result = new ServiceCollection();
    for (const [id3, descriptor] of getSingletonServiceDescriptors()) {
      result.set(id3, descriptor);
    }
    for (let serviceId in overrides) {
      if (overrides.hasOwnProperty(serviceId)) {
        result.set(createDecorator(serviceId), overrides[serviceId]);
      }
    }
    _all.forEach((service) => result.set(service.id, service.get(overrides)));
    let instantiationService = new InstantiationService(result, true);
    result.set(IInstantiationService, instantiationService);
    return [result, instantiationService];
  }
  StaticServices2.init = init4;
  StaticServices2.instantiationService = define2(IInstantiationService, () => new InstantiationService(_serviceCollection, true));
  const configurationServiceImpl = new SimpleConfigurationService();
  StaticServices2.configurationService = define2(IConfigurationService, () => configurationServiceImpl);
  StaticServices2.resourceConfigurationService = define2(ITextResourceConfigurationService, () => new SimpleResourceConfigurationService(configurationServiceImpl));
  StaticServices2.resourcePropertiesService = define2(ITextResourcePropertiesService, () => new SimpleResourcePropertiesService(configurationServiceImpl));
  StaticServices2.contextService = define2(IWorkspaceContextService, () => new SimpleWorkspaceContextService());
  StaticServices2.labelService = define2(ILabelService, () => new SimpleUriLabelService());
  StaticServices2.telemetryService = define2(ITelemetryService, () => new StandaloneTelemetryService());
  StaticServices2.dialogService = define2(IDialogService, () => new SimpleDialogService());
  StaticServices2.notificationService = define2(INotificationService, () => new SimpleNotificationService());
  StaticServices2.markerService = define2(IMarkerService, () => new MarkerService());
  StaticServices2.modeService = define2(IModeService, (o) => new ModeServiceImpl());
  StaticServices2.standaloneThemeService = define2(IStandaloneThemeService, () => new StandaloneThemeServiceImpl());
  StaticServices2.logService = define2(ILogService, () => new ConsoleLogService());
  StaticServices2.undoRedoService = define2(IUndoRedoService, (o) => new UndoRedoService(StaticServices2.dialogService.get(o), StaticServices2.notificationService.get(o)));
  StaticServices2.modelService = define2(IModelService, (o) => new ModelServiceImpl(StaticServices2.configurationService.get(o), StaticServices2.resourcePropertiesService.get(o), StaticServices2.standaloneThemeService.get(o), StaticServices2.logService.get(o), StaticServices2.undoRedoService.get(o)));
  StaticServices2.markerDecorationsService = define2(IMarkerDecorationsService, (o) => new MarkerDecorationsService(StaticServices2.modelService.get(o), StaticServices2.markerService.get(o)));
  StaticServices2.codeEditorService = define2(ICodeEditorService, (o) => new StandaloneCodeEditorServiceImpl(StaticServices2.standaloneThemeService.get(o)));
  StaticServices2.editorProgressService = define2(IEditorProgressService, () => new SimpleEditorProgressService());
  StaticServices2.storageService = define2(IStorageService, () => new InMemoryStorageService());
  StaticServices2.storageSyncService = define2(IStorageKeysSyncRegistryService, () => new StorageKeysSyncRegistryService());
  StaticServices2.editorWorkerService = define2(IEditorWorkerService, (o) => new EditorWorkerServiceImpl(StaticServices2.modelService.get(o), StaticServices2.resourceConfigurationService.get(o), StaticServices2.logService.get(o)));
})(StaticServices || (StaticServices = {}));
var DynamicStandaloneServices = class extends Disposable {
  constructor(domElement, overrides) {
    super();
    const [_serviceCollection, _instantiationService] = StaticServices.init(overrides);
    this._serviceCollection = _serviceCollection;
    this._instantiationService = _instantiationService;
    const configurationService = this.get(IConfigurationService);
    const notificationService = this.get(INotificationService);
    const telemetryService = this.get(ITelemetryService);
    const themeService = this.get(IThemeService);
    const logService = this.get(ILogService);
    let ensure = (serviceId, factory) => {
      let value = null;
      if (overrides) {
        value = overrides[serviceId.toString()];
      }
      if (!value) {
        value = factory();
      }
      this._serviceCollection.set(serviceId, value);
      return value;
    };
    let contextKeyService = ensure(IContextKeyService, () => this._register(new ContextKeyService(configurationService)));
    ensure(IAccessibilityService, () => new AccessibilityService(contextKeyService, configurationService));
    ensure(IListService, () => new ListService(themeService));
    let commandService = ensure(ICommandService, () => new StandaloneCommandService(this._instantiationService));
    let keybindingService = ensure(IKeybindingService, () => this._register(new StandaloneKeybindingService(contextKeyService, commandService, telemetryService, notificationService, logService, domElement)));
    let layoutService = ensure(ILayoutService, () => new SimpleLayoutService(StaticServices.codeEditorService.get(ICodeEditorService), domElement));
    ensure(IQuickInputService, () => new StandaloneQuickInputServiceImpl(_instantiationService, StaticServices.codeEditorService.get(ICodeEditorService)));
    let contextViewService = ensure(IContextViewService, () => this._register(new ContextViewService(layoutService)));
    ensure(IClipboardService, () => new BrowserClipboardService());
    ensure(IContextMenuService, () => {
      const contextMenuService = new ContextMenuService(telemetryService, notificationService, contextViewService, keybindingService, themeService);
      contextMenuService.configure({blockMouse: false});
      return this._register(contextMenuService);
    });
    ensure(IMenuService, () => new MenuService(commandService));
    ensure(IBulkEditService, () => new SimpleBulkEditService(StaticServices.modelService.get(IModelService)));
  }
  get(serviceId) {
    let r3 = this._serviceCollection.get(serviceId);
    if (!r3) {
      throw new Error("Missing service " + serviceId);
    }
    return r3;
  }
  set(serviceId, instance2) {
    this._serviceCollection.set(serviceId, instance2);
  }
  has(serviceId) {
    return this._serviceCollection.has(serviceId);
  }
};
function withAllStandaloneServices(domElement, override, callback) {
  let services = new DynamicStandaloneServices(domElement, override);
  let simpleEditorModelResolverService = null;
  if (!services.has(ITextModelService)) {
    simpleEditorModelResolverService = new SimpleEditorModelResolverService(StaticServices.modelService.get());
    services.set(ITextModelService, simpleEditorModelResolverService);
  }
  if (!services.has(IOpenerService)) {
    services.set(IOpenerService, new OpenerService(services.get(ICodeEditorService), services.get(ICommandService)));
  }
  let result = callback(services);
  if (simpleEditorModelResolverService) {
    simpleEditorModelResolverService.setEditor(result);
  }
  return result;
}
function create(domElement, options, override) {
  return withAllStandaloneServices(domElement, override || {}, (services) => {
    return new StandaloneEditor(domElement, options, services, services.get(IInstantiationService), services.get(ICodeEditorService), services.get(ICommandService), services.get(IContextKeyService), services.get(IKeybindingService), services.get(IContextViewService), services.get(IStandaloneThemeService), services.get(INotificationService), services.get(IConfigurationService), services.get(IAccessibilityService));
  });
}
function onDidCreateEditor(listener) {
  return StaticServices.codeEditorService.get().onCodeEditorAdd((editor2) => {
    listener(editor2);
  });
}
function createDiffEditor(domElement, options, override) {
  return withAllStandaloneServices(domElement, override || {}, (services) => {
    return new StandaloneDiffEditor(domElement, options, services, services.get(IInstantiationService), services.get(IContextKeyService), services.get(IKeybindingService), services.get(IContextViewService), services.get(IEditorWorkerService), services.get(ICodeEditorService), services.get(IStandaloneThemeService), services.get(INotificationService), services.get(IConfigurationService), services.get(IContextMenuService), services.get(IEditorProgressService), services.get(IClipboardService));
  });
}
function createDiffNavigator(diffEditor, opts) {
  return new DiffNavigator(diffEditor, opts);
}
function doCreateModel(value, languageSelection, uri) {
  return StaticServices.modelService.get().createModel(value, languageSelection, uri);
}
function createModel(value, language, uri) {
  value = value || "";
  if (!language) {
    let firstLF = value.indexOf("\n");
    let firstLine = value;
    if (firstLF !== -1) {
      firstLine = value.substring(0, firstLF);
    }
    return doCreateModel(value, StaticServices.modeService.get().createByFilepathOrFirstLine(uri || null, firstLine), uri);
  }
  return doCreateModel(value, StaticServices.modeService.get().create(language), uri);
}
function setModelLanguage(model, languageId) {
  StaticServices.modelService.get().setMode(model, StaticServices.modeService.get().create(languageId));
}
function setModelMarkers(model, owner, markers) {
  if (model) {
    StaticServices.markerService.get().changeOne(owner, model.uri, markers);
  }
}
function getModelMarkers(filter3) {
  return StaticServices.markerService.get().read(filter3);
}
function getModel(uri) {
  return StaticServices.modelService.get().getModel(uri);
}
function getModels() {
  return StaticServices.modelService.get().getModels();
}
function onDidCreateModel(listener) {
  return StaticServices.modelService.get().onModelAdded(listener);
}
function onWillDisposeModel(listener) {
  return StaticServices.modelService.get().onModelRemoved(listener);
}
function onDidChangeModelLanguage(listener) {
  return StaticServices.modelService.get().onModelModeChanged((e2) => {
    listener({
      model: e2.model,
      oldLanguage: e2.oldModeId
    });
  });
}
function createWebWorker$1(opts) {
  return createWebWorker(StaticServices.modelService.get(), opts);
}
function colorizeElement(domNode, options) {
  const themeService = StaticServices.standaloneThemeService.get();
  themeService.registerEditorContainer(domNode);
  return Colorizer.colorizeElement(themeService, StaticServices.modeService.get(), domNode, options);
}
function colorize(text, languageId, options) {
  const themeService = StaticServices.standaloneThemeService.get();
  themeService.registerEditorContainer(document.body);
  return Colorizer.colorize(StaticServices.modeService.get(), text, languageId, options);
}
function colorizeModelLine(model, lineNumber, tabSize = 4) {
  const themeService = StaticServices.standaloneThemeService.get();
  themeService.registerEditorContainer(document.body);
  return Colorizer.colorizeModelLine(model, lineNumber, tabSize);
}
function getSafeTokenizationSupport(language) {
  let tokenizationSupport = TokenizationRegistry.get(language);
  if (tokenizationSupport) {
    return tokenizationSupport;
  }
  return {
    getInitialState: () => NULL_STATE,
    tokenize: (line, state, deltaOffset) => nullTokenize(language, line, state, deltaOffset)
  };
}
function tokenize(text, languageId) {
  let modeService = StaticServices.modeService.get();
  modeService.triggerMode(languageId);
  let tokenizationSupport = getSafeTokenizationSupport(languageId);
  let lines = text.split(/\r\n|\r|\n/);
  let result = [];
  let state = tokenizationSupport.getInitialState();
  for (let i3 = 0, len2 = lines.length; i3 < len2; i3++) {
    let line = lines[i3];
    let tokenizationResult = tokenizationSupport.tokenize(line, state, 0);
    result[i3] = tokenizationResult.tokens;
    state = tokenizationResult.endState;
  }
  return result;
}
function defineTheme(themeName, themeData) {
  StaticServices.standaloneThemeService.get().defineTheme(themeName, themeData);
}
function setTheme(themeName) {
  StaticServices.standaloneThemeService.get().setTheme(themeName);
}
function remeasureFonts() {
  clearAllFontInfos();
}
function createMonacoEditorAPI() {
  return {
    create,
    onDidCreateEditor,
    createDiffEditor,
    createDiffNavigator,
    createModel,
    setModelLanguage,
    setModelMarkers,
    getModelMarkers,
    getModels,
    getModel,
    onDidCreateModel,
    onWillDisposeModel,
    onDidChangeModelLanguage,
    createWebWorker: createWebWorker$1,
    colorizeElement,
    colorize,
    colorizeModelLine,
    tokenize,
    defineTheme,
    setTheme,
    remeasureFonts,
    AccessibilitySupport,
    ContentWidgetPositionPreference,
    CursorChangeReason,
    DefaultEndOfLine,
    EditorAutoIndentStrategy,
    EditorOption,
    EndOfLinePreference,
    EndOfLineSequence,
    MinimapPosition,
    MouseTargetType,
    OverlayWidgetPositionPreference,
    OverviewRulerLane,
    RenderLineNumbersType,
    RenderMinimap,
    ScrollbarVisibility,
    ScrollType,
    TextEditorCursorBlinkingStyle,
    TextEditorCursorStyle: TextEditorCursorStyle$1,
    TrackedRangeStickiness,
    WrappingIndent,
    ConfigurationChangedEvent,
    BareFontInfo,
    FontInfo,
    TextModelResolvedOptions,
    FindMatch,
    EditorType,
    EditorOptions
  };
}
function isArrayOf(elemType, obj) {
  if (!obj) {
    return false;
  }
  if (!Array.isArray(obj)) {
    return false;
  }
  for (const el of obj) {
    if (!elemType(el)) {
      return false;
    }
  }
  return true;
}
function bool(prop, defValue) {
  if (typeof prop === "boolean") {
    return prop;
  }
  return defValue;
}
function string(prop, defValue) {
  if (typeof prop === "string") {
    return prop;
  }
  return defValue;
}
function arrayToHash(array2) {
  const result = {};
  for (const e2 of array2) {
    result[e2] = true;
  }
  return result;
}
function createKeywordMatcher(arr, caseInsensitive = false) {
  if (caseInsensitive) {
    arr = arr.map(function(x2) {
      return x2.toLowerCase();
    });
  }
  const hash2 = arrayToHash(arr);
  if (caseInsensitive) {
    return function(word) {
      return hash2[word.toLowerCase()] !== void 0 && hash2.hasOwnProperty(word.toLowerCase());
    };
  } else {
    return function(word) {
      return hash2[word] !== void 0 && hash2.hasOwnProperty(word);
    };
  }
}
function compileRegExp(lexer, str) {
  let n3 = 0;
  while (str.indexOf("@") >= 0 && n3 < 5) {
    n3++;
    str = str.replace(/@(\w+)/g, function(s2, attr2) {
      let sub = "";
      if (typeof lexer[attr2] === "string") {
        sub = lexer[attr2];
      } else if (lexer[attr2] && lexer[attr2] instanceof RegExp) {
        sub = lexer[attr2].source;
      } else {
        if (lexer[attr2] === void 0) {
          throw createError3(lexer, "language definition does not contain attribute '" + attr2 + "', used at: " + str);
        } else {
          throw createError3(lexer, "attribute reference '" + attr2 + "' must be a string, used at: " + str);
        }
      }
      return empty(sub) ? "" : "(?:" + sub + ")";
    });
  }
  let flags2 = (lexer.ignoreCase ? "i" : "") + (lexer.unicode ? "u" : "");
  return new RegExp(str, flags2);
}
function selectScrutinee(id3, matches2, state, num) {
  if (num < 0) {
    return id3;
  }
  if (num < matches2.length) {
    return matches2[num];
  }
  if (num >= 100) {
    num = num - 100;
    let parts = state.split(".");
    parts.unshift(state);
    if (num < parts.length) {
      return parts[num];
    }
  }
  return null;
}
function createGuard(lexer, ruleName, tkey, val) {
  let scrut = -1;
  let oppat = tkey;
  let matches2 = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
  if (matches2) {
    if (matches2[3]) {
      scrut = parseInt(matches2[3]);
      if (matches2[2]) {
        scrut = scrut + 100;
      }
    }
    oppat = matches2[4];
  }
  let op = "~";
  let pat = oppat;
  if (!oppat || oppat.length === 0) {
    op = "!=";
    pat = "";
  } else if (/^\w*$/.test(pat)) {
    op = "==";
  } else {
    matches2 = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
    if (matches2) {
      op = matches2[1];
      pat = matches2[2];
    }
  }
  let tester;
  if ((op === "~" || op === "!~") && /^(\w|\|)*$/.test(pat)) {
    let inWords = createKeywordMatcher(pat.split("|"), lexer.ignoreCase);
    tester = function(s2) {
      return op === "~" ? inWords(s2) : !inWords(s2);
    };
  } else if (op === "@" || op === "!@") {
    let words2 = lexer[pat];
    if (!words2) {
      throw createError3(lexer, "the @ match target '" + pat + "' is not defined, in rule: " + ruleName);
    }
    if (!isArrayOf(function(elem) {
      return typeof elem === "string";
    }, words2)) {
      throw createError3(lexer, "the @ match target '" + pat + "' must be an array of strings, in rule: " + ruleName);
    }
    let inWords = createKeywordMatcher(words2, lexer.ignoreCase);
    tester = function(s2) {
      return op === "@" ? inWords(s2) : !inWords(s2);
    };
  } else if (op === "~" || op === "!~") {
    if (pat.indexOf("$") < 0) {
      let re2 = compileRegExp(lexer, "^" + pat + "$");
      tester = function(s2) {
        return op === "~" ? re2.test(s2) : !re2.test(s2);
      };
    } else {
      tester = function(s2, id3, matches3, state) {
        let re2 = compileRegExp(lexer, "^" + substituteMatches(lexer, pat, id3, matches3, state) + "$");
        return re2.test(s2);
      };
    }
  } else {
    if (pat.indexOf("$") < 0) {
      let patx = fixCase(lexer, pat);
      tester = function(s2) {
        return op === "==" ? s2 === patx : s2 !== patx;
      };
    } else {
      let patx = fixCase(lexer, pat);
      tester = function(s2, id3, matches3, state, eos) {
        let patexp = substituteMatches(lexer, patx, id3, matches3, state);
        return op === "==" ? s2 === patexp : s2 !== patexp;
      };
    }
  }
  if (scrut === -1) {
    return {
      name: tkey,
      value: val,
      test: function(id3, matches3, state, eos) {
        return tester(id3, id3, matches3, state, eos);
      }
    };
  } else {
    return {
      name: tkey,
      value: val,
      test: function(id3, matches3, state, eos) {
        let scrutinee = selectScrutinee(id3, matches3, state, scrut);
        return tester(!scrutinee ? "" : scrutinee, id3, matches3, state, eos);
      }
    };
  }
}
function compileAction(lexer, ruleName, action) {
  if (!action) {
    return {token: ""};
  } else if (typeof action === "string") {
    return action;
  } else if (action.token || action.token === "") {
    if (typeof action.token !== "string") {
      throw createError3(lexer, "a 'token' attribute must be of type string, in rule: " + ruleName);
    } else {
      let newAction = {token: action.token};
      if (action.token.indexOf("$") >= 0) {
        newAction.tokenSubst = true;
      }
      if (typeof action.bracket === "string") {
        if (action.bracket === "@open") {
          newAction.bracket = 1;
        } else if (action.bracket === "@close") {
          newAction.bracket = -1;
        } else {
          throw createError3(lexer, "a 'bracket' attribute must be either '@open' or '@close', in rule: " + ruleName);
        }
      }
      if (action.next) {
        if (typeof action.next !== "string") {
          throw createError3(lexer, "the next state must be a string value in rule: " + ruleName);
        } else {
          let next = action.next;
          if (!/^(@pop|@push|@popall)$/.test(next)) {
            if (next[0] === "@") {
              next = next.substr(1);
            }
            if (next.indexOf("$") < 0) {
              if (!stateExists(lexer, substituteMatches(lexer, next, "", [], ""))) {
                throw createError3(lexer, "the next state '" + action.next + "' is not defined in rule: " + ruleName);
              }
            }
          }
          newAction.next = next;
        }
      }
      if (typeof action.goBack === "number") {
        newAction.goBack = action.goBack;
      }
      if (typeof action.switchTo === "string") {
        newAction.switchTo = action.switchTo;
      }
      if (typeof action.log === "string") {
        newAction.log = action.log;
      }
      if (typeof action.nextEmbedded === "string") {
        newAction.nextEmbedded = action.nextEmbedded;
        lexer.usesEmbedded = true;
      }
      return newAction;
    }
  } else if (Array.isArray(action)) {
    let results = [];
    for (let i3 = 0, len2 = action.length; i3 < len2; i3++) {
      results[i3] = compileAction(lexer, ruleName, action[i3]);
    }
    return {group: results};
  } else if (action.cases) {
    let cases = [];
    for (let tkey in action.cases) {
      if (action.cases.hasOwnProperty(tkey)) {
        const val = compileAction(lexer, ruleName, action.cases[tkey]);
        if (tkey === "@default" || tkey === "@" || tkey === "") {
          cases.push({test: void 0, value: val, name: tkey});
        } else if (tkey === "@eos") {
          cases.push({test: function(id3, matches2, state, eos) {
            return eos;
          }, value: val, name: tkey});
        } else {
          cases.push(createGuard(lexer, ruleName, tkey, val));
        }
      }
    }
    const def = lexer.defaultToken;
    return {
      test: function(id3, matches2, state, eos) {
        for (const _case of cases) {
          const didmatch = !_case.test || _case.test(id3, matches2, state, eos);
          if (didmatch) {
            return _case.value;
          }
        }
        return def;
      }
    };
  } else {
    throw createError3(lexer, "an action must be a string, an object with a 'token' or 'cases' attribute, or an array of actions; in rule: " + ruleName);
  }
}
var Rule = class {
  constructor(name) {
    this.regex = new RegExp("");
    this.action = {token: ""};
    this.matchOnlyAtLineStart = false;
    this.name = "";
    this.name = name;
  }
  setRegex(lexer, re2) {
    let sregex;
    if (typeof re2 === "string") {
      sregex = re2;
    } else if (re2 instanceof RegExp) {
      sregex = re2.source;
    } else {
      throw createError3(lexer, "rules must start with a match string or regular expression: " + this.name);
    }
    this.matchOnlyAtLineStart = sregex.length > 0 && sregex[0] === "^";
    this.name = this.name + ": " + sregex;
    this.regex = compileRegExp(lexer, "^(?:" + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ")");
  }
  setAction(lexer, act) {
    this.action = compileAction(lexer, this.name, act);
  }
};
function compile2(languageId, json2) {
  if (!json2 || typeof json2 !== "object") {
    throw new Error("Monarch: expecting a language definition object");
  }
  let lexer = {};
  lexer.languageId = languageId;
  lexer.noThrow = false;
  lexer.maxStack = 100;
  lexer.start = typeof json2.start === "string" ? json2.start : null;
  lexer.ignoreCase = bool(json2.ignoreCase, false);
  lexer.unicode = bool(json2.unicode, false);
  lexer.tokenPostfix = string(json2.tokenPostfix, "." + lexer.languageId);
  lexer.defaultToken = string(json2.defaultToken, "source");
  lexer.usesEmbedded = false;
  let lexerMin = json2;
  lexerMin.languageId = languageId;
  lexerMin.ignoreCase = lexer.ignoreCase;
  lexerMin.unicode = lexer.unicode;
  lexerMin.noThrow = lexer.noThrow;
  lexerMin.usesEmbedded = lexer.usesEmbedded;
  lexerMin.stateNames = json2.tokenizer;
  lexerMin.defaultToken = lexer.defaultToken;
  function addRules(state, newrules, rules) {
    for (const rule of rules) {
      let include = rule.include;
      if (include) {
        if (typeof include !== "string") {
          throw createError3(lexer, "an 'include' attribute must be a string at: " + state);
        }
        if (include[0] === "@") {
          include = include.substr(1);
        }
        if (!json2.tokenizer[include]) {
          throw createError3(lexer, "include target '" + include + "' is not defined at: " + state);
        }
        addRules(state + "." + include, newrules, json2.tokenizer[include]);
      } else {
        const newrule = new Rule(state);
        if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
          newrule.setRegex(lexerMin, rule[0]);
          if (rule.length >= 3) {
            if (typeof rule[1] === "string") {
              newrule.setAction(lexerMin, {token: rule[1], next: rule[2]});
            } else if (typeof rule[1] === "object") {
              const rule1 = rule[1];
              rule1.next = rule[2];
              newrule.setAction(lexerMin, rule1);
            } else {
              throw createError3(lexer, "a next state as the last element of a rule can only be given if the action is either an object or a string, at: " + state);
            }
          } else {
            newrule.setAction(lexerMin, rule[1]);
          }
        } else {
          if (!rule.regex) {
            throw createError3(lexer, "a rule must either be an array, or an object with a 'regex' or 'include' field at: " + state);
          }
          if (rule.name) {
            if (typeof rule.name === "string") {
              newrule.name = rule.name;
            }
          }
          if (rule.matchOnlyAtStart) {
            newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
          }
          newrule.setRegex(lexerMin, rule.regex);
          newrule.setAction(lexerMin, rule.action);
        }
        newrules.push(newrule);
      }
    }
  }
  if (!json2.tokenizer || typeof json2.tokenizer !== "object") {
    throw createError3(lexer, "a language definition must define the 'tokenizer' attribute as an object");
  }
  lexer.tokenizer = [];
  for (let key in json2.tokenizer) {
    if (json2.tokenizer.hasOwnProperty(key)) {
      if (!lexer.start) {
        lexer.start = key;
      }
      const rules = json2.tokenizer[key];
      lexer.tokenizer[key] = new Array();
      addRules("tokenizer." + key, lexer.tokenizer[key], rules);
    }
  }
  lexer.usesEmbedded = lexerMin.usesEmbedded;
  if (json2.brackets) {
    if (!Array.isArray(json2.brackets)) {
      throw createError3(lexer, "the 'brackets' attribute must be defined as an array");
    }
  } else {
    json2.brackets = [
      {open: "{", close: "}", token: "delimiter.curly"},
      {open: "[", close: "]", token: "delimiter.square"},
      {open: "(", close: ")", token: "delimiter.parenthesis"},
      {open: "<", close: ">", token: "delimiter.angle"}
    ];
  }
  let brackets = [];
  for (let el of json2.brackets) {
    let desc = el;
    if (desc && Array.isArray(desc) && desc.length === 3) {
      desc = {token: desc[2], open: desc[0], close: desc[1]};
    }
    if (desc.open === desc.close) {
      throw createError3(lexer, "open and close brackets in a 'brackets' attribute must be different: " + desc.open + "\n hint: use the 'bracket' attribute if matching on equal brackets is required.");
    }
    if (typeof desc.open === "string" && typeof desc.token === "string" && typeof desc.close === "string") {
      brackets.push({
        token: desc.token + lexer.tokenPostfix,
        open: fixCase(lexer, desc.open),
        close: fixCase(lexer, desc.close)
      });
    } else {
      throw createError3(lexer, "every element in the 'brackets' array must be a '{open,close,token}' object or array");
    }
  }
  lexer.brackets = brackets;
  lexer.noThrow = true;
  return lexer;
}
function register$1(language) {
  ModesRegistry.registerLanguage(language);
}
function getLanguages() {
  let result = [];
  result = result.concat(ModesRegistry.getLanguages());
  return result;
}
function getEncodedLanguageId(languageId) {
  let lid = StaticServices.modeService.get().getLanguageIdentifier(languageId);
  return lid ? lid.id : 0;
}
function onLanguage(languageId, callback) {
  let disposable = StaticServices.modeService.get().onDidCreateMode((mode) => {
    if (mode.getId() === languageId) {
      disposable.dispose();
      callback();
    }
  });
  return disposable;
}
function setLanguageConfiguration(languageId, configuration) {
  let languageIdentifier = StaticServices.modeService.get().getLanguageIdentifier(languageId);
  if (!languageIdentifier) {
    throw new Error(`Cannot set configuration for unknown language ${languageId}`);
  }
  return LanguageConfigurationRegistry.register(languageIdentifier, configuration);
}
var EncodedTokenizationSupport2Adapter = class {
  constructor(actual) {
    this._actual = actual;
  }
  getInitialState() {
    return this._actual.getInitialState();
  }
  tokenize(line, state, offsetDelta) {
    throw new Error("Not supported!");
  }
  tokenize2(line, state) {
    let result = this._actual.tokenizeEncoded(line, state);
    return new TokenizationResult2(result.tokens, result.endState);
  }
};
var TokenizationSupport2Adapter = class {
  constructor(standaloneThemeService, languageIdentifier, actual) {
    this._standaloneThemeService = standaloneThemeService;
    this._languageIdentifier = languageIdentifier;
    this._actual = actual;
  }
  getInitialState() {
    return this._actual.getInitialState();
  }
  _toClassicTokens(tokens, language, offsetDelta) {
    let result = [];
    let previousStartIndex = 0;
    for (let i3 = 0, len2 = tokens.length; i3 < len2; i3++) {
      const t5 = tokens[i3];
      let startIndex = t5.startIndex;
      if (i3 === 0) {
        startIndex = 0;
      } else if (startIndex < previousStartIndex) {
        startIndex = previousStartIndex;
      }
      result[i3] = new Token(startIndex + offsetDelta, t5.scopes, language);
      previousStartIndex = startIndex;
    }
    return result;
  }
  tokenize(line, state, offsetDelta) {
    let actualResult = this._actual.tokenize(line, state);
    let tokens = this._toClassicTokens(actualResult.tokens, this._languageIdentifier.language, offsetDelta);
    let endState;
    if (actualResult.endState.equals(state)) {
      endState = state;
    } else {
      endState = actualResult.endState;
    }
    return new TokenizationResult(tokens, endState);
  }
  _toBinaryTokens(tokens, offsetDelta) {
    const languageId = this._languageIdentifier.id;
    const tokenTheme = this._standaloneThemeService.getColorTheme().tokenTheme;
    let result = [], resultLen = 0;
    let previousStartIndex = 0;
    for (let i3 = 0, len2 = tokens.length; i3 < len2; i3++) {
      const t5 = tokens[i3];
      const metadata = tokenTheme.match(languageId, t5.scopes);
      if (resultLen > 0 && result[resultLen - 1] === metadata) {
        continue;
      }
      let startIndex = t5.startIndex;
      if (i3 === 0) {
        startIndex = 0;
      } else if (startIndex < previousStartIndex) {
        startIndex = previousStartIndex;
      }
      result[resultLen++] = startIndex + offsetDelta;
      result[resultLen++] = metadata;
      previousStartIndex = startIndex;
    }
    let actualResult = new Uint32Array(resultLen);
    for (let i3 = 0; i3 < resultLen; i3++) {
      actualResult[i3] = result[i3];
    }
    return actualResult;
  }
  tokenize2(line, state, offsetDelta) {
    let actualResult = this._actual.tokenize(line, state);
    let tokens = this._toBinaryTokens(actualResult.tokens, offsetDelta);
    let endState;
    if (actualResult.endState.equals(state)) {
      endState = state;
    } else {
      endState = actualResult.endState;
    }
    return new TokenizationResult2(tokens, endState);
  }
};
function isEncodedTokensProvider(provider) {
  return "tokenizeEncoded" in provider;
}
function isThenable$1(obj) {
  return obj && typeof obj.then === "function";
}
function setTokensProvider(languageId, provider) {
  let languageIdentifier = StaticServices.modeService.get().getLanguageIdentifier(languageId);
  if (!languageIdentifier) {
    throw new Error(`Cannot set tokens provider for unknown language ${languageId}`);
  }
  const create3 = (provider2) => {
    if (isEncodedTokensProvider(provider2)) {
      return new EncodedTokenizationSupport2Adapter(provider2);
    } else {
      return new TokenizationSupport2Adapter(StaticServices.standaloneThemeService.get(), languageIdentifier, provider2);
    }
  };
  if (isThenable$1(provider)) {
    return TokenizationRegistry.registerPromise(languageId, provider.then((provider2) => create3(provider2)));
  }
  return TokenizationRegistry.register(languageId, create3(provider));
}
function setMonarchTokensProvider(languageId, languageDef) {
  const create3 = (languageDef2) => {
    return createTokenizationSupport(StaticServices.modeService.get(), StaticServices.standaloneThemeService.get(), languageId, compile2(languageId, languageDef2));
  };
  if (isThenable$1(languageDef)) {
    return TokenizationRegistry.registerPromise(languageId, languageDef.then((languageDef2) => create3(languageDef2)));
  }
  return TokenizationRegistry.register(languageId, create3(languageDef));
}
function registerReferenceProvider(languageId, provider) {
  return ReferenceProviderRegistry.register(languageId, provider);
}
function registerRenameProvider(languageId, provider) {
  return RenameProviderRegistry.register(languageId, provider);
}
function registerSignatureHelpProvider(languageId, provider) {
  return SignatureHelpProviderRegistry.register(languageId, provider);
}
function registerHoverProvider(languageId, provider) {
  return HoverProviderRegistry.register(languageId, {
    provideHover: (model, position2, token2) => {
      let word = model.getWordAtPosition(position2);
      return Promise.resolve(provider.provideHover(model, position2, token2)).then((value) => {
        if (!value) {
          return void 0;
        }
        if (!value.range && word) {
          value.range = new Range(position2.lineNumber, word.startColumn, position2.lineNumber, word.endColumn);
        }
        if (!value.range) {
          value.range = new Range(position2.lineNumber, position2.column, position2.lineNumber, position2.column);
        }
        return value;
      });
    }
  });
}
function registerDocumentSymbolProvider(languageId, provider) {
  return DocumentSymbolProviderRegistry.register(languageId, provider);
}
function registerDocumentHighlightProvider(languageId, provider) {
  return DocumentHighlightProviderRegistry.register(languageId, provider);
}
function registerOnTypeRenameProvider(languageId, provider) {
  return OnTypeRenameProviderRegistry.register(languageId, provider);
}
function registerDefinitionProvider(languageId, provider) {
  return DefinitionProviderRegistry.register(languageId, provider);
}
function registerImplementationProvider(languageId, provider) {
  return ImplementationProviderRegistry.register(languageId, provider);
}
function registerTypeDefinitionProvider(languageId, provider) {
  return TypeDefinitionProviderRegistry.register(languageId, provider);
}
function registerCodeLensProvider(languageId, provider) {
  return CodeLensProviderRegistry.register(languageId, provider);
}
function registerCodeActionProvider(languageId, provider) {
  return CodeActionProviderRegistry.register(languageId, {
    provideCodeActions: (model, range3, context2, token2) => {
      let markers = StaticServices.markerService.get().read({resource: model.uri}).filter((m2) => {
        return Range.areIntersectingOrTouching(m2, range3);
      });
      return provider.provideCodeActions(model, range3, {markers, only: context2.only}, token2);
    }
  });
}
function registerDocumentFormattingEditProvider(languageId, provider) {
  return DocumentFormattingEditProviderRegistry.register(languageId, provider);
}
function registerDocumentRangeFormattingEditProvider(languageId, provider) {
  return DocumentRangeFormattingEditProviderRegistry.register(languageId, provider);
}
function registerOnTypeFormattingEditProvider(languageId, provider) {
  return OnTypeFormattingEditProviderRegistry.register(languageId, provider);
}
function registerLinkProvider(languageId, provider) {
  return LinkProviderRegistry.register(languageId, provider);
}
function registerCompletionItemProvider(languageId, provider) {
  return CompletionProviderRegistry.register(languageId, provider);
}
function registerColorProvider(languageId, provider) {
  return ColorProviderRegistry.register(languageId, provider);
}
function registerFoldingRangeProvider(languageId, provider) {
  return FoldingRangeProviderRegistry.register(languageId, provider);
}
function registerDeclarationProvider(languageId, provider) {
  return DeclarationProviderRegistry.register(languageId, provider);
}
function registerSelectionRangeProvider(languageId, provider) {
  return SelectionRangeRegistry.register(languageId, provider);
}
function registerDocumentSemanticTokensProvider(languageId, provider) {
  return DocumentSemanticTokensProviderRegistry.register(languageId, provider);
}
function registerDocumentRangeSemanticTokensProvider(languageId, provider) {
  return DocumentRangeSemanticTokensProviderRegistry.register(languageId, provider);
}
function createMonacoLanguagesAPI() {
  return {
    register: register$1,
    getLanguages,
    onLanguage,
    getEncodedLanguageId,
    setLanguageConfiguration,
    setTokensProvider,
    setMonarchTokensProvider,
    registerReferenceProvider,
    registerRenameProvider,
    registerCompletionItemProvider,
    registerSignatureHelpProvider,
    registerHoverProvider,
    registerDocumentSymbolProvider,
    registerDocumentHighlightProvider,
    registerOnTypeRenameProvider,
    registerDefinitionProvider,
    registerImplementationProvider,
    registerTypeDefinitionProvider,
    registerCodeLensProvider,
    registerCodeActionProvider,
    registerDocumentFormattingEditProvider,
    registerDocumentRangeFormattingEditProvider,
    registerOnTypeFormattingEditProvider,
    registerLinkProvider,
    registerColorProvider,
    registerFoldingRangeProvider,
    registerDeclarationProvider,
    registerSelectionRangeProvider,
    registerDocumentSemanticTokensProvider,
    registerDocumentRangeSemanticTokensProvider,
    DocumentHighlightKind,
    CompletionItemKind,
    CompletionItemTag,
    CompletionItemInsertTextRule,
    SymbolKind,
    SymbolTag,
    IndentAction,
    CompletionTriggerKind,
    SignatureHelpTriggerKind,
    FoldingRangeKind
  };
}
var global$1 = self;
EditorOptions.wrappingIndent.defaultValue = 0;
EditorOptions.glyphMargin.defaultValue = false;
EditorOptions.autoIndent.defaultValue = 3;
EditorOptions.overviewRulerLanes.defaultValue = 2;
var api = createMonacoBaseAPI();
api.editor = createMonacoEditorAPI();
api.languages = createMonacoLanguagesAPI();
var CancellationTokenSource$1 = api.CancellationTokenSource;
var Emitter$1 = api.Emitter;
var KeyCode$1 = api.KeyCode;
var KeyMod$1 = api.KeyMod;
var Position$1 = api.Position;
var Range$2 = api.Range;
var Selection$1 = api.Selection;
var SelectionDirection$1 = api.SelectionDirection;
var MarkerSeverity$2 = api.MarkerSeverity;
var MarkerTag$1 = api.MarkerTag;
var Uri$1 = api.Uri;
var Token$1 = api.Token;
var editor = api.editor;
var languages = api.languages;
global$1.monaco = api;
if (typeof global$1.require !== "undefined" && typeof global$1.require.config === "function") {
  global$1.require.config({
    ignoreDuplicateModules: [
      "vscode-languageserver-types",
      "vscode-languageserver-types/main",
      "vscode-languageserver-textdocument",
      "vscode-languageserver-textdocument/main",
      "vscode-nls",
      "vscode-nls/vscode-nls",
      "jsonc-parser",
      "jsonc-parser/main",
      "vscode-uri",
      "vscode-uri/index",
      "vs/basic-languages/typescript/typescript"
    ]
  });
}
var monaco = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  CancellationTokenSource: CancellationTokenSource$1,
  Emitter: Emitter$1,
  KeyCode: KeyCode$1,
  KeyMod: KeyMod$1,
  Position: Position$1,
  Range: Range$2,
  Selection: Selection$1,
  SelectionDirection: SelectionDirection$1,
  MarkerSeverity: MarkerSeverity$2,
  MarkerTag: MarkerTag$1,
  Uri: Uri$1,
  Token: Token$1,
  editor,
  languages
});
function processSize(size2) {
  return !/^\d+$/.test(size2) ? size2 : size2 + "px";
}
function noop4() {
}
var __extends = function() {
  var extendStatics = function(d2, b2) {
    extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
      d3.__proto__ = b3;
    } || function(d3, b3) {
      for (var p2 in b3)
        if (Object.prototype.hasOwnProperty.call(b3, p2))
          d3[p2] = b3[p2];
    };
    return extendStatics(d2, b2);
  };
  return function(d2, b2) {
    extendStatics(d2, b2);
    function __() {
      this.constructor = d2;
    }
    d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
  };
}();
var __assign = function() {
  __assign = Object.assign || function(t5) {
    for (var s2, i3 = 1, n3 = arguments.length; i3 < n3; i3++) {
      s2 = arguments[i3];
      for (var p2 in s2)
        if (Object.prototype.hasOwnProperty.call(s2, p2))
          t5[p2] = s2[p2];
    }
    return t5;
  };
  return __assign.apply(this, arguments);
};
var MonacoDiffEditor = function(_super) {
  __extends(MonacoDiffEditor2, _super);
  function MonacoDiffEditor2(props) {
    var _this = _super.call(this, props) || this;
    _this.assignRef = function(component) {
      _this.containerElement = component;
    };
    _this.containerElement = void 0;
    return _this;
  }
  MonacoDiffEditor2.prototype.componentDidMount = function() {
    this.initMonaco();
  };
  MonacoDiffEditor2.prototype.componentDidUpdate = function(prevProps) {
    var _a = this.props, language = _a.language, theme = _a.theme, height = _a.height, options = _a.options, width2 = _a.width;
    var _b = this.editor.getModel(), original = _b.original, modified = _b.modified;
    if (this.props.original !== original.getValue()) {
      original.setValue(this.props.original);
    }
    if (this.props.value != null && this.props.value !== modified.getValue()) {
      this.__prevent_trigger_change_event = true;
      this.editor.modifiedEditor.pushUndoStop();
      modified.pushEditOperations([], [
        {
          range: modified.getFullModelRange(),
          text: this.props.value
        }
      ]);
      this.editor.modifiedEditor.pushUndoStop();
      this.__prevent_trigger_change_event = false;
    }
    if (prevProps.language !== language) {
      editor.setModelLanguage(original, language);
      editor.setModelLanguage(modified, language);
    }
    if (prevProps.theme !== theme) {
      editor.setTheme(theme);
    }
    if (this.editor && (width2 !== prevProps.width || height !== prevProps.height)) {
      this.editor.layout();
    }
    if (prevProps.options !== options) {
      this.editor.updateOptions(options);
    }
  };
  MonacoDiffEditor2.prototype.componentWillUnmount = function() {
    this.destroyMonaco();
  };
  MonacoDiffEditor2.prototype.editorWillMount = function() {
    var editorWillMount = this.props.editorWillMount;
    var options = editorWillMount(monaco);
    return options || {};
  };
  MonacoDiffEditor2.prototype.editorDidMount = function(editor2) {
    var _this = this;
    this.props.editorDidMount(editor2, monaco);
    var modified = editor2.getModel().modified;
    this._subscription = modified.onDidChangeContent(function(event) {
      if (!_this.__prevent_trigger_change_event) {
        _this.props.onChange(modified.getValue(), event);
      }
    });
  };
  MonacoDiffEditor2.prototype.initModels = function(value, original) {
    var language = this.props.language;
    var originalModel = editor.createModel(original, language);
    var modifiedModel = editor.createModel(value, language);
    this.editor.setModel({
      original: originalModel,
      modified: modifiedModel
    });
  };
  MonacoDiffEditor2.prototype.initMonaco = function() {
    var value = this.props.value != null ? this.props.value : this.props.defaultValue;
    var _a = this.props, original = _a.original, theme = _a.theme, options = _a.options, overrideServices = _a.overrideServices;
    if (this.containerElement) {
      this.editorWillMount();
      this.editor = editor.createDiffEditor(this.containerElement, __assign(__assign({}, options), theme ? {theme} : {}), overrideServices);
      this.initModels(value, original);
      this.editorDidMount(this.editor);
    }
  };
  MonacoDiffEditor2.prototype.destroyMonaco = function() {
    if (this.editor) {
      this.editor.dispose();
      var _a = this.editor.getModel(), original = _a.original, modified = _a.modified;
      if (original) {
        original.dispose();
      }
      if (modified) {
        modified.dispose();
      }
    }
    if (this._subscription) {
      this._subscription.dispose();
    }
  };
  MonacoDiffEditor2.prototype.render = function() {
    var _a = this.props, width2 = _a.width, height = _a.height;
    var fixedWidth = processSize(width2);
    var fixedHeight = processSize(height);
    var style = {
      width: fixedWidth,
      height: fixedHeight
    };
    return react.createElement("div", {ref: this.assignRef, style, className: "react-monaco-editor-container"});
  };
  MonacoDiffEditor2.propTypes = {
    width: propTypes.oneOfType([propTypes.string, propTypes.number]),
    height: propTypes.oneOfType([propTypes.string, propTypes.number]),
    original: propTypes.string,
    value: propTypes.string,
    defaultValue: propTypes.string,
    language: propTypes.string,
    theme: propTypes.string,
    options: propTypes.object,
    overrideServices: propTypes.object,
    editorDidMount: propTypes.func,
    editorWillMount: propTypes.func,
    onChange: propTypes.func
  };
  MonacoDiffEditor2.defaultProps = {
    width: "100%",
    height: "100%",
    original: null,
    value: null,
    defaultValue: "",
    language: "javascript",
    theme: null,
    options: {},
    overrideServices: {},
    editorDidMount: noop4,
    editorWillMount: noop4,
    onChange: noop4
  };
  return MonacoDiffEditor2;
}(react.Component);
var __extends$1 = function() {
  var extendStatics = function(d2, b2) {
    extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d3, b3) {
      d3.__proto__ = b3;
    } || function(d3, b3) {
      for (var p2 in b3)
        if (Object.prototype.hasOwnProperty.call(b3, p2))
          d3[p2] = b3[p2];
    };
    return extendStatics(d2, b2);
  };
  return function(d2, b2) {
    extendStatics(d2, b2);
    function __() {
      this.constructor = d2;
    }
    d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
  };
}();
var __assign$1 = function() {
  __assign$1 = Object.assign || function(t5) {
    for (var s2, i3 = 1, n3 = arguments.length; i3 < n3; i3++) {
      s2 = arguments[i3];
      for (var p2 in s2)
        if (Object.prototype.hasOwnProperty.call(s2, p2))
          t5[p2] = s2[p2];
    }
    return t5;
  };
  return __assign$1.apply(this, arguments);
};
var __rest3 = function(s2, e2) {
  var t5 = {};
  for (var p2 in s2)
    if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
      t5[p2] = s2[p2];
  if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i3 = 0, p2 = Object.getOwnPropertySymbols(s2); i3 < p2.length; i3++) {
      if (e2.indexOf(p2[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i3]))
        t5[p2[i3]] = s2[p2[i3]];
    }
  return t5;
};
var MonacoEditor = function(_super) {
  __extends$1(MonacoEditor2, _super);
  function MonacoEditor2(props) {
    var _this = _super.call(this, props) || this;
    _this.assignRef = function(component) {
      _this.containerElement = component;
    };
    _this.containerElement = void 0;
    return _this;
  }
  MonacoEditor2.prototype.componentDidMount = function() {
    this.initMonaco();
  };
  MonacoEditor2.prototype.componentDidUpdate = function(prevProps) {
    var _a = this.props, value = _a.value, language = _a.language, theme = _a.theme, height = _a.height, options = _a.options, width2 = _a.width;
    var editor$1 = this.editor;
    var model = editor$1.getModel();
    if (this.props.value != null && this.props.value !== model.getValue()) {
      this.__prevent_trigger_change_event = true;
      this.editor.pushUndoStop();
      model.pushEditOperations([], [
        {
          range: model.getFullModelRange(),
          text: value
        }
      ]);
      this.editor.pushUndoStop();
      this.__prevent_trigger_change_event = false;
    }
    if (prevProps.language !== language) {
      editor.setModelLanguage(model, language);
    }
    if (prevProps.theme !== theme) {
      editor.setTheme(theme);
    }
    if (editor$1 && (width2 !== prevProps.width || height !== prevProps.height)) {
      editor$1.layout();
    }
    if (prevProps.options !== options) {
      var _model = options.model, optionsWithoutModel = __rest3(options, ["model"]);
      editor$1.updateOptions(optionsWithoutModel);
    }
  };
  MonacoEditor2.prototype.componentWillUnmount = function() {
    this.destroyMonaco();
  };
  MonacoEditor2.prototype.destroyMonaco = function() {
    if (this.editor) {
      this.editor.dispose();
      var model = this.editor.getModel();
      if (model) {
        model.dispose();
      }
    }
    if (this._subscription) {
      this._subscription.dispose();
    }
  };
  MonacoEditor2.prototype.initMonaco = function() {
    var value = this.props.value != null ? this.props.value : this.props.defaultValue;
    var _a = this.props, language = _a.language, theme = _a.theme, overrideServices = _a.overrideServices;
    if (this.containerElement) {
      var options = __assign$1(__assign$1({}, this.props.options), this.editorWillMount());
      this.editor = editor.create(this.containerElement, __assign$1(__assign$1({
        value,
        language
      }, options), theme ? {theme} : {}), overrideServices);
      this.editorDidMount(this.editor);
    }
  };
  MonacoEditor2.prototype.editorWillMount = function() {
    var editorWillMount = this.props.editorWillMount;
    var options = editorWillMount(monaco);
    return options || {};
  };
  MonacoEditor2.prototype.editorDidMount = function(editor2) {
    var _this = this;
    this.props.editorDidMount(editor2, monaco);
    this._subscription = editor2.onDidChangeModelContent(function(event) {
      if (!_this.__prevent_trigger_change_event) {
        _this.props.onChange(editor2.getValue(), event);
      }
    });
  };
  MonacoEditor2.prototype.render = function() {
    var _a = this.props, width2 = _a.width, height = _a.height;
    var fixedWidth = processSize(width2);
    var fixedHeight = processSize(height);
    var style = {
      width: fixedWidth,
      height: fixedHeight
    };
    return react.createElement("div", {ref: this.assignRef, style, className: "react-monaco-editor-container"});
  };
  MonacoEditor2.propTypes = {
    width: propTypes.oneOfType([propTypes.string, propTypes.number]),
    height: propTypes.oneOfType([propTypes.string, propTypes.number]),
    value: propTypes.string,
    defaultValue: propTypes.string,
    language: propTypes.string,
    theme: propTypes.string,
    options: propTypes.object,
    overrideServices: propTypes.object,
    editorDidMount: propTypes.func,
    editorWillMount: propTypes.func,
    onChange: propTypes.func
  };
  MonacoEditor2.defaultProps = {
    width: "100%",
    height: "100%",
    value: null,
    defaultValue: "",
    language: "javascript",
    theme: null,
    options: {},
    overrideServices: {},
    editorDidMount: noop4,
    editorWillMount: noop4,
    onChange: noop4
  };
  return MonacoEditor2;
}(react.Component);
var UploadIconConfig = {
  name: "UploadIcon",
  height: 512,
  width: 512,
  svgPath: "M296 384h-80c-13.3 0-24-10.7-24-24V192h-87.7c-17.8 0-26.7-21.5-14.1-34.1L242.3 5.7c7.5-7.5 19.8-7.5 27.3 0l152.2 152.2c12.6 12.6 3.7 34.1-14.1 34.1H320v168c0 13.3-10.7 24-24 24zm216-8v112c0 13.3-10.7 24-24 24H24c-13.3 0-24-10.7-24-24V376c0-13.3 10.7-24 24-24h136v8c0 30.9 25.1 56 56 56h80c30.9 0 56-25.1 56-56v-8h136c13.3 0 24 10.7 24 24zm-124 88c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20zm64 0c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20z",
  yOffset: 0,
  xOffset: 0
};
var UploadIcon = createIcon(UploadIconConfig);
var DownloadIconConfig = {
  name: "DownloadIcon",
  height: 512,
  width: 512,
  svgPath: "M216 0h80c13.3 0 24 10.7 24 24v168h87.7c17.8 0 26.7 21.5 14.1 34.1L269.7 378.3c-7.5 7.5-19.8 7.5-27.3 0L90.1 226.1c-12.6-12.6-3.7-34.1 14.1-34.1H192V24c0-13.3 10.7-24 24-24zm296 376v112c0 13.3-10.7 24-24 24H24c-13.3 0-24-10.7-24-24V376c0-13.3 10.7-24 24-24h146.7l49 49c20.1 20.1 52.5 20.1 72.6 0l49-49H488c13.3 0 24 10.7 24 24zm-124 88c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20zm64 0c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20z",
  yOffset: 0,
  xOffset: 0
};
var DownloadIcon = createIcon(DownloadIconConfig);
var CodeIconConfig = {
  name: "CodeIcon",
  height: 512,
  width: 640,
  svgPath: "M278.9 511.5l-61-17.7c-6.4-1.8-10-8.5-8.2-14.9L346.2 8.7c1.8-6.4 8.5-10 14.9-8.2l61 17.7c6.4 1.8 10 8.5 8.2 14.9L293.8 503.3c-1.9 6.4-8.5 10.1-14.9 8.2zm-114-112.2l43.5-46.4c4.6-4.9 4.3-12.7-.8-17.2L117 256l90.6-79.7c5.1-4.5 5.5-12.3.8-17.2l-43.5-46.4c-4.5-4.8-12.1-5.1-17-.5L3.8 247.2c-5.1 4.7-5.1 12.8 0 17.5l144.1 135.1c4.9 4.6 12.5 4.4 17-.5zm327.2.6l144.1-135.1c5.1-4.7 5.1-12.8 0-17.5L492.1 112.1c-4.8-4.5-12.4-4.3-17 .5L431.6 159c-4.6 4.9-4.3 12.7.8 17.2L523 256l-90.6 79.7c-5.1 4.5-5.5 12.3-.8 17.2l43.5 46.4c4.5 4.9 12.1 5.1 17 .6z",
  yOffset: 0,
  xOffset: 0
};
var CodeIcon = createIcon(CodeIconConfig);
var CodeEditorContext = react.createContext(null);
var Language;
(function(Language2) {
  Language2["abap"] = "abap";
  Language2["aes"] = "aes";
  Language2["apex"] = "apex";
  Language2["azcli"] = "azcli";
  Language2["bat"] = "bat";
  Language2["bicep"] = "bicep";
  Language2["c"] = "c";
  Language2["cameligo"] = "cameligo";
  Language2["clojure"] = "clojure";
  Language2["coffeescript"] = "coffeescript";
  Language2["cpp"] = "cpp";
  Language2["csharp"] = "csharp";
  Language2["csp"] = "csp";
  Language2["css"] = "css";
  Language2["dart"] = "dart";
  Language2["dockerfile"] = "dockerfile";
  Language2["ecl"] = "ecl";
  Language2["elixir"] = "elixir";
  Language2["fsharp"] = "fsharp";
  Language2["go"] = "go";
  Language2["graphql"] = "graphql";
  Language2["handlebars"] = "handlebars";
  Language2["hcl"] = "hcl";
  Language2["html"] = "html";
  Language2["ini"] = "ini";
  Language2["java"] = "java";
  Language2["javascript"] = "javascript";
  Language2["json"] = "json";
  Language2["julia"] = "julia";
  Language2["kotlin"] = "kotlin";
  Language2["less"] = "less";
  Language2["lexon"] = "lexon";
  Language2["liquid"] = "liquid";
  Language2["lua"] = "lua";
  Language2["m3"] = "m3";
  Language2["markdown"] = "markdown";
  Language2["mips"] = "mips";
  Language2["msdax"] = "msdax";
  Language2["mysql"] = "mysql";
  Language2["objective-c"] = "objective-c";
  Language2["pascal"] = "pascal";
  Language2["pascaligo"] = "pascaligo";
  Language2["perl"] = "perl";
  Language2["pgsql"] = "pgsql";
  Language2["php"] = "php";
  Language2["plaintext"] = "plaintext";
  Language2["postiats"] = "postiats";
  Language2["powerquery"] = "powerquery";
  Language2["powershell"] = "powershell";
  Language2["pug"] = "pug";
  Language2["python"] = "python";
  Language2["r"] = "r";
  Language2["razor"] = "razor";
  Language2["redis"] = "redis";
  Language2["redshift"] = "redshift";
  Language2["restructuredtext"] = "restructuredtext";
  Language2["ruby"] = "ruby";
  Language2["rust"] = "rust";
  Language2["sb"] = "sb";
  Language2["scala"] = "scala";
  Language2["scheme"] = "scheme";
  Language2["scss"] = "scss";
  Language2["shell"] = "shell";
  Language2["sol"] = "sol";
  Language2["sql"] = "sql";
  Language2["st"] = "st";
  Language2["swift"] = "swift";
  Language2["systemverilog"] = "systemverilog";
  Language2["tcl"] = "tcl";
  Language2["twig"] = "twig";
  Language2["typescript"] = "typescript";
  Language2["vb"] = "vb";
  Language2["verilog"] = "verilog";
  Language2["xml"] = "xml";
  Language2["yaml"] = "yaml";
})(Language || (Language = {}));
var CodeEditor = class extends react.Component {
  constructor(props) {
    super(props);
    this.editor = null;
    this.wrapperRef = react.createRef();
    this.ref = react.createRef();
    this.timer = null;
    this.observer = () => {
    };
    this.onChange = (value, event) => {
      if (this.props.onChange) {
        this.props.onChange(value, event);
      }
      this.setState({value});
    };
    this.handleResize = () => {
      if (this.editor) {
        this.editor.layout();
      }
    };
    this.handleGlobalKeys = (event) => {
      var _a;
      if (this.wrapperRef.current === document.activeElement && (event.key === "ArrowDown" || event.key === " ")) {
        (_a = this.editor) === null || _a === void 0 ? void 0 : _a.focus();
        event.preventDefault();
      }
    };
    this.editorDidMount = (editor2, monaco2) => {
      editor2.addCommand(monaco2.KeyMod.Shift | monaco2.KeyCode.Tab, () => this.wrapperRef.current.focus());
      Array.from(document.getElementsByClassName("monaco-editor")).forEach((editorElement) => editorElement.removeAttribute("role"));
      this.props.onEditorDidMount(editor2, monaco2);
      this.editor = editor2;
    };
    this.handleFileChange = (value, filename) => {
      this.setState({
        value,
        filename
      });
    };
    this.handleFileReadStarted = () => this.setState({isLoading: true});
    this.handleFileReadFinished = () => this.setState({isLoading: false});
    this.onDropAccepted = (acceptedFiles) => {
      if (acceptedFiles.length > 0) {
        const fileHandle = acceptedFiles[0];
        this.handleFileChange("", fileHandle.name);
        this.handleFileReadStarted();
        this.readFile(fileHandle).then((data2) => {
          this.handleFileReadFinished();
          this.handleFileChange(data2, fileHandle.name);
        }).catch((error2) => {
          console.error("error", error2);
          this.handleFileReadFinished();
          this.handleFileChange("", "");
        });
      }
    };
    this.onDropRejected = (rejectedFiles) => {
      if (rejectedFiles.length > 0) {
        console.error("There was an error accepting that dropped file");
      }
    };
    this.copyCode = () => {
      var _a;
      if (this.timer) {
        window.clearTimeout(this.timer);
        this.setState({copied: false});
      }
      (_a = this.editor) === null || _a === void 0 ? void 0 : _a.focus();
      document.execCommand("copy");
      this.setState({copied: true}, () => {
        this.timer = window.setTimeout(() => {
          this.setState({copied: false});
          this.timer = null;
        }, 2500);
      });
    };
    this.download = () => {
      const {value} = this.state;
      const element = document.createElement("a");
      const file = new Blob([value], {type: "text"});
      element.href = URL.createObjectURL(file);
      element.download = `${this.props.downloadFileName}.${CodeEditor.getExtensionFromLanguage(this.props.language)}`;
      document.body.appendChild(element);
      element.click();
    };
    this.toggleEmptyState = () => {
      this.setState({showEmptyState: false});
    };
    this.state = {
      value: this.props.code,
      filename: "",
      isLoading: false,
      showEmptyState: true,
      copied: false
    };
  }
  static getExtensionFromLanguage(language) {
    switch (language) {
      case Language.shell:
        return "sh";
      case Language.ruby:
        return "rb";
      case Language.perl:
        return "pl";
      case Language.python:
        return "py";
      case Language.mysql:
        return "sql";
      case Language.javascript:
        return "js";
      case Language.typescript:
        return "ts";
      case Language.markdown:
        return "md";
      case Language.plaintext:
        return "txt";
      default:
        return language.toString();
    }
  }
  componentDidUpdate(prevProps) {
    const {code: code2} = this.props;
    if (prevProps.code !== code2) {
      this.setState({value: code2});
    }
  }
  componentDidMount() {
    document.addEventListener("keydown", this.handleGlobalKeys);
    this.observer = getResizeObserver(this.ref.current, this.handleResize);
    this.handleResize();
  }
  componentWillUnmount() {
    document.removeEventListener("keydown", this.handleGlobalKeys);
    this.observer();
  }
  readFile(fileHandle) {
    return new Promise((resolve2, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve2(reader.result);
      reader.onerror = () => reject(reader.error);
      reader.readAsText(fileHandle);
    });
  }
  render() {
    const {value, isLoading, showEmptyState, copied} = this.state;
    const {isDarkTheme, height, width: width2, className, isCopyEnabled, copyButtonSuccessTooltipText, isReadOnly, isUploadEnabled, isLanguageLabelVisible, copyButtonAriaLabel, copyButtonToolTipText, uploadButtonAriaLabel, uploadButtonToolTipText, downloadButtonAriaLabel, downloadButtonToolTipText, toolTipDelay, toolTipCopyExitDelay, toolTipMaxWidth, toolTipPosition, isLineNumbersVisible, isDownloadEnabled, language, emptyState: providedEmptyState, emptyStateTitle, emptyStateBody, emptyStateButton, emptyStateLink, customControls, isMinimapVisible, showEditor, options: optionsProp, overrideServices} = this.props;
    const options = Object.assign({readOnly: isReadOnly, cursorStyle: "line", lineNumbers: isLineNumbersVisible ? "on" : "off", tabIndex: -1, minimap: {
      enabled: isMinimapVisible
    }}, optionsProp);
    return react.createElement(Dropzone, {multiple: false, onDropAccepted: this.onDropAccepted, onDropRejected: this.onDropRejected}, ({getRootProps, getInputProps, isDragActive, open: open2}) => {
      const emptyState2 = providedEmptyState || (isUploadEnabled ? react.createElement(EmptyState, {variant: EmptyStateVariant.small}, react.createElement(EmptyStateIcon, {icon: CodeIcon}), react.createElement(Title, {headingLevel: "h4", size: "lg"}, emptyStateTitle), react.createElement(EmptyStateBody, null, emptyStateBody), react.createElement(Button, {variant: "primary", onClick: open2}, emptyStateButton), react.createElement(EmptyStateSecondaryActions, null, react.createElement(Button, {variant: "link", onClick: this.toggleEmptyState}, emptyStateLink))) : react.createElement(EmptyState, {variant: EmptyStateVariant.small}, react.createElement(EmptyStateIcon, {icon: CodeIcon}), react.createElement(Title, {headingLevel: "h4", size: "lg"}, emptyStateTitle), react.createElement(Button, {variant: "primary", onClick: this.toggleEmptyState}, emptyStateLink)));
      const editorHeader = react.createElement("div", {className: css(styles4.codeEditorHeader)}, (isCopyEnabled || isDownloadEnabled || isUploadEnabled || customControls) && react.createElement("div", {className: css(styles4.codeEditorControls)}, isCopyEnabled && (!showEmptyState || !!value) && react.createElement(Tooltip, {trigger: "mouseenter", content: react.createElement("div", null, copied ? copyButtonSuccessTooltipText : copyButtonToolTipText), exitDelay: copied ? toolTipCopyExitDelay : toolTipDelay, entryDelay: toolTipDelay, maxWidth: toolTipMaxWidth, position: toolTipPosition}, react.createElement(Button, {onClick: this.copyCode, variant: "control", "aria-label": copyButtonAriaLabel}, react.createElement(CopyIcon, null))), isUploadEnabled && react.createElement(Tooltip, {trigger: "mouseenter focus click", content: react.createElement("div", null, uploadButtonToolTipText), entryDelay: toolTipDelay, exitDelay: toolTipDelay, maxWidth: toolTipMaxWidth, position: toolTipPosition}, react.createElement(Button, {onClick: open2, variant: "control", "aria-label": uploadButtonAriaLabel}, react.createElement(UploadIcon, null))), isDownloadEnabled && (!showEmptyState || !!value) && react.createElement(Tooltip, {trigger: "mouseenter focus click", content: react.createElement("div", null, downloadButtonToolTipText), entryDelay: toolTipDelay, exitDelay: toolTipDelay, maxWidth: toolTipMaxWidth, position: toolTipPosition}, react.createElement(Button, {onClick: this.download, variant: "control", "aria-label": downloadButtonAriaLabel}, react.createElement(DownloadIcon, null))), customControls && react.createElement(CodeEditorContext.Provider, {value: {code: value}}, customControls)), isLanguageLabelVisible && react.createElement("div", {className: css(styles4.codeEditorTab)}, react.createElement("span", {className: css(styles4.codeEditorTabIcon)}, react.createElement(CodeIcon, null)), react.createElement("span", {className: css(styles4.codeEditorTabText)}, language.toUpperCase())));
      const editor2 = react.createElement("div", {className: css(styles4.codeEditorCode), ref: this.wrapperRef, tabIndex: 0}, react.createElement(MonacoEditor, {height, width: width2, language, value, options, overrideServices, onChange: this.onChange, editorDidMount: this.editorDidMount, theme: isDarkTheme ? "vs-dark" : "vs-light"}));
      return react.createElement("div", {className: css(styles4.codeEditor, isReadOnly && styles4.modifiers.readOnly, className), ref: this.ref}, isUploadEnabled || providedEmptyState ? react.createElement("div", Object.assign({}, getRootProps({
        onClick: (event) => event.preventDefault()
      }), {className: `pf-c-file-upload ${isDragActive && "pf-m-drag-hover"} ${isLoading && "pf-m-loading"}`}), editorHeader, react.createElement("div", {className: css(styles4.codeEditorMain)}, react.createElement("input", Object.assign({}, getInputProps())), (showEmptyState || providedEmptyState) && !value ? emptyState2 : editor2)) : react.createElement(react.Fragment, null, editorHeader, showEditor && react.createElement("div", {className: css(styles4.codeEditorMain)}, editor2)));
    });
  }
};
CodeEditor.displayName = "CodeEditor";
CodeEditor.defaultProps = {
  className: "",
  code: "",
  onEditorDidMount: () => {
  },
  language: Language.plaintext,
  isDarkTheme: false,
  height: "",
  width: "",
  isLineNumbersVisible: true,
  isReadOnly: false,
  isLanguageLabelVisible: false,
  loading: "",
  emptyState: "",
  emptyStateTitle: "Start editing",
  emptyStateBody: "Drag and drop a file or upload one.",
  emptyStateButton: "Browse",
  emptyStateLink: "Start from scratch",
  downloadFileName: Date.now().toString(),
  isUploadEnabled: false,
  isDownloadEnabled: false,
  isCopyEnabled: false,
  copyButtonAriaLabel: "Copy code to clipboard",
  uploadButtonAriaLabel: "Upload code",
  downloadButtonAriaLabel: "Download code",
  copyButtonToolTipText: "Copy to clipboard",
  uploadButtonToolTipText: "Upload",
  downloadButtonToolTipText: "Download",
  copyButtonSuccessTooltipText: "Content added to clipboard",
  toolTipCopyExitDelay: 1600,
  toolTipDelay: 300,
  toolTipMaxWidth: "100px",
  toolTipPosition: "top",
  customControls: null,
  isMinimapVisible: false,
  showEditor: true,
  options: {},
  overrideServices: {}
};

// build/components/json-file-upload/FileUploadForm.js
var FileUploadForm = ({
  id: id3,
  onChange,
  helpText = "common-help:helpFileUpload",
  unWrap = false,
  language,
  extension,
  ...rest
}) => {
  const {t: t5} = useTranslation();
  const defaultUpload = {
    value: "",
    filename: "",
    isLoading: false,
    modal: false
  };
  const [fileUpload2, setFileUpload] = useState(defaultUpload);
  const removeDialog = () => setFileUpload({...fileUpload2, modal: false});
  const handleChange = (value, filename, event) => {
    if (event.nativeEvent instanceof MouseEvent && !(event.nativeEvent instanceof DragEvent)) {
      setFileUpload({...fileUpload2, modal: true});
    } else {
      setFileUpload({
        ...fileUpload2,
        value: value.toString(),
        filename
      });
      if (value) {
        onChange(value.toString());
      }
    }
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, fileUpload2.modal && /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    title: t5("clearFile"),
    isOpen: true,
    onClose: removeDialog,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        key: "confirm",
        variant: "primary",
        onClick: () => {
          setFileUpload(defaultUpload);
          onChange("");
        }
      }, t5("clear")),
      /* @__PURE__ */ react.createElement(Button, {
        key: "cancel",
        variant: "link",
        onClick: removeDialog
      }, t5("cancel"))
    ]
  }, t5("clearFileExplain")), unWrap && /* @__PURE__ */ react.createElement(FileUpload, {
    id: id3,
    ...rest,
    type: "text",
    value: fileUpload2.value,
    filename: fileUpload2.filename,
    onChange: handleChange,
    onReadStarted: () => setFileUpload({...fileUpload2, isLoading: true}),
    onReadFinished: () => setFileUpload({...fileUpload2, isLoading: false}),
    isLoading: fileUpload2.isLoading,
    dropzoneProps: {
      accept: extension
    }
  }), !unWrap && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("resourceFile"),
    fieldId: id3,
    helperText: t5(helpText)
  }, /* @__PURE__ */ react.createElement(FileUpload, {
    id: id3,
    ...rest,
    type: "text",
    value: fileUpload2.value,
    filename: fileUpload2.filename,
    onChange: handleChange,
    onReadStarted: () => setFileUpload({...fileUpload2, isLoading: true}),
    onReadFinished: () => setFileUpload({...fileUpload2, isLoading: false}),
    isLoading: fileUpload2.isLoading,
    hideDefaultPreview: true
  }, !rest.hideDefaultPreview && /* @__PURE__ */ react.createElement(CodeEditor, {
    isLineNumbersVisible: true,
    code: fileUpload2.value,
    language,
    height: "128px",
    onChange: (value, event) => handleChange(value || "", fileUpload2.filename, event),
    isReadOnly: !rest.allowEditingUploadedText
  }))));
};

// build/components/json-file-upload/JsonFileUpload.js
var JsonFileUpload = ({onChange, ...props}) => {
  const handleChange = (value) => {
    try {
      onChange(JSON.parse(value));
    } catch (error2) {
      onChange({});
      console.warn("Invalid json, ignoring value using {}");
    }
  };
  return /* @__PURE__ */ react.createElement(FileUploadForm, {
    ...props,
    language: Language.json,
    extension: ".json",
    onChange: handleChange
  });
};

// build/components/external-link/FormattedLink.js
var FormattedLink = ({
  title: title3,
  href,
  isInline,
  ...rest
}) => {
  return /* @__PURE__ */ react.createElement("a", {
    href,
    target: "_blank",
    rel: "noreferrer noopener",
    className: isInline ? "pf-m-link pf-m-inline" : "",
    ...rest
  }, title3 ? title3 : href, " ", href?.startsWith("http") && /* @__PURE__ */ react.createElement(ExternalLinkAltIcon, null));
};
var formattedLinkTableCell = () => (data2) => {
  return data2 ? /* @__PURE__ */ react.createElement(FormattedLink, {
    href: data2.toString()
  }) : void 0;
};

// build/components/view-header/ViewHeader.js
var ViewHeader = ({
  actionsDropdownId,
  className,
  titleKey,
  badges,
  isDropdownDisabled,
  subKey,
  subKeyLinkProps,
  dropdownItems,
  lowerDropdownMenuTitle,
  lowerDropdownItems,
  isEnabled = true,
  onToggle,
  divider: divider2 = true,
  helpTextKey
}) => {
  const {t: t5} = useTranslation();
  const {enabled} = useHelp();
  const [isDropdownOpen, setDropdownOpen] = useState(false);
  const [isLowerDropdownOpen, setIsLowerDropdownOpen] = useState(false);
  const onDropdownToggle = () => {
    setDropdownOpen(!isDropdownOpen);
  };
  const onLowerDropdownToggle = () => {
    setIsLowerDropdownOpen(!isLowerDropdownOpen);
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(Level, {
    hasGutter: true
  }, /* @__PURE__ */ react.createElement(LevelItem, null, /* @__PURE__ */ react.createElement(Level, null, /* @__PURE__ */ react.createElement(LevelItem, null, /* @__PURE__ */ react.createElement(TextContent, {
    className: "pf-u-mr-sm"
  }, /* @__PURE__ */ react.createElement(Text, {
    className,
    component: "h1"
  }, t5(titleKey)))), badges && /* @__PURE__ */ react.createElement(LevelItem, null, badges.map((badge2, index3) => /* @__PURE__ */ react.createElement(Fragment, {
    key: index3
  }, !isValidElement(badge2.text) && /* @__PURE__ */ react.createElement(Fragment, {
    key: badge2.text
  }, /* @__PURE__ */ react.createElement(Badge, {
    "data-testid": badge2.id,
    isRead: badge2.readonly
  }, badge2.text), " "), isValidElement(badge2.text) && badge2.text, " "))))), /* @__PURE__ */ react.createElement(LevelItem, null, /* @__PURE__ */ react.createElement(Toolbar, {
    className: "pf-u-p-0"
  }, /* @__PURE__ */ react.createElement(ToolbarContent, null, onToggle && /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Switch, {
    id: `${titleKey}-switch`,
    label: t5("common:enabled"),
    labelOff: t5("common:disabled"),
    className: "pf-u-mr-lg",
    isChecked: isEnabled,
    onChange: (value) => {
      onToggle(value);
    }
  }), helpTextKey && /* @__PURE__ */ react.createElement(HelpItem, {
    helpText: t5(helpTextKey),
    fieldLabelId: `${titleKey}-switch`
  })), dropdownItems && /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Dropdown, {
    position: DropdownPosition.right,
    toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
      isDisabled: isDropdownDisabled,
      id: actionsDropdownId,
      onToggle: onDropdownToggle
    }, t5("common:action")),
    isOpen: isDropdownOpen,
    dropdownItems,
    "data-testid": "action-dropdown"
  })))))), enabled && /* @__PURE__ */ react.createElement(TextContent, {
    id: "view-header-subkey"
  }, /* @__PURE__ */ react.createElement(Text, null, react.isValidElement(subKey) ? subKey : subKey ? t5(subKey) : "", subKeyLinkProps && /* @__PURE__ */ react.createElement(FormattedLink, {
    ...subKeyLinkProps,
    isInline: true,
    className: "pf-u-ml-md"
  }))), lowerDropdownItems && /* @__PURE__ */ react.createElement(Dropdown, {
    className: "keycloak__user-federation__dropdown",
    toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
      onToggle: () => onLowerDropdownToggle(),
      isPrimary: true,
      id: "ufToggleId"
    }, t5(lowerDropdownMenuTitle)),
    isOpen: isLowerDropdownOpen,
    dropdownItems: lowerDropdownItems
  })), divider2 && /* @__PURE__ */ react.createElement(Divider, {
    component: "div"
  }));
};

// build/realm/routes/AddRealm.js
var AddRealmRoute = {
  path: "/:realm/add-realm",
  component: lazy(() => Promise.resolve().then(() => require_NewRealmForm())),
  breadcrumb: (t5) => t5("realm:createRealm"),
  access: "manage-realm"
};
var toAddRealm = (params) => ({
  pathname: generatePath(AddRealmRoute.path, params)
});

// build/components/realm-selector/RealmSelector.js
var RealmSelector = () => {
  const {realm: realm2} = useRealm();
  const {realms: realms2} = useRealms();
  const {whoAmI: whoAmI2} = useWhoAmI();
  const [open2, setOpen] = useState(false);
  const [search2, setSearch] = useState("");
  const history = useHistory();
  const {t: t5} = useTranslation("common");
  const recentUsed = new RecentUsed();
  const all2 = recentUsed.used.filter((r3) => r3 !== realm2).map((name) => {
    return {name, used: true};
  }).concat(realms2.filter((r3) => !recentUsed.used.includes(r3.realm)).map((r3) => {
    return {name: r3.realm, used: false};
  }));
  const filteredItems = useMemo(() => {
    if (search2 === "") {
      return void 0;
    }
    return all2.filter((r3) => r3.name.toLowerCase().includes(search2.toLowerCase()));
  }, [search2, all2]);
  const RealmText = ({value}) => /* @__PURE__ */ react.createElement(Split, {
    className: "keycloak__realm_selector__list-item-split"
  }, /* @__PURE__ */ react.createElement(SplitItem, {
    isFilled: true
  }, toUpperCase(value)), /* @__PURE__ */ react.createElement(SplitItem, null, value === realm2 && /* @__PURE__ */ react.createElement(CheckIcon, null)));
  const AddRealm = () => /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "add-realm",
    component: "div",
    isBlock: true,
    onClick: () => {
      history.push(toAddRealm({realm: realm2}));
      setOpen(!open2);
    }
  }, t5("createRealm"));
  const selectRealm = (realm22) => {
    setOpen(!open2);
    history.push(toDashboard({realm: realm22}));
  };
  const dropdownItems = realms2.map((r3) => /* @__PURE__ */ react.createElement(DropdownItem, {
    key: `realm-dropdown-item-${r3.realm}`,
    onClick: () => {
      selectRealm(r3.realm);
    }
  }, /* @__PURE__ */ react.createElement(RealmText, {
    value: r3.realm
  })));
  const addRealmComponent = /* @__PURE__ */ react.createElement(react.Fragment, {
    key: "Add Realm"
  }, whoAmI2.canCreateRealm() && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Divider, {
    key: "divider"
  }), /* @__PURE__ */ react.createElement(DropdownItem, {
    key: "add"
  }, /* @__PURE__ */ react.createElement(AddRealm, null))));
  return /* @__PURE__ */ react.createElement(react.Fragment, null, realms2.length > 5 && /* @__PURE__ */ react.createElement(ContextSelector, {
    "data-testid": "realmSelector",
    toggleText: toUpperCase(realm2),
    isOpen: open2,
    screenReaderLabel: toUpperCase(realm2),
    onToggle: () => setOpen(!open2),
    onSelect: (_23, r3) => {
      let element;
      if (Array.isArray(r3)) {
        element = r3[0];
      } else {
        element = r3;
      }
      const value = element.props.value;
      if (value) {
        selectRealm(value);
      }
    },
    searchInputValue: search2,
    onSearchInputChange: (value) => setSearch(value),
    className: "keycloak__realm_selector__context_selector",
    footer: /* @__PURE__ */ react.createElement(ContextSelectorItem, {
      key: "add"
    }, /* @__PURE__ */ react.createElement(AddRealm, null))
  }, (filteredItems || all2).map((item) => /* @__PURE__ */ react.createElement(ContextSelectorItem, {
    key: item.name
  }, /* @__PURE__ */ react.createElement(RealmText, {
    value: item.name
  }), " ", item.used && /* @__PURE__ */ react.createElement(Label, null, t5("recent"))))), realms2.length <= 5 && /* @__PURE__ */ react.createElement(Dropdown, {
    id: "realm-select",
    "data-testid": "realmSelector",
    className: "keycloak__realm_selector__dropdown",
    isOpen: open2,
    toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
      "data-testid": "realmSelectorToggle",
      onToggle: () => setOpen(!open2),
      className: "keycloak__realm_selector_dropdown__toggle"
    }, toUpperCase(realm2)),
    dropdownItems: [...dropdownItems, addRealmComponent]
  }));
};

// build/_snowpack/pkg/common/_baseIsEqual-c84a3118.js
function listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}
var _listCacheClear = listCacheClear;
function eq(value, other) {
  return value === other || value !== value && other !== other;
}
var eq_1 = eq;
function assocIndexOf(array2, key) {
  var length = array2.length;
  while (length--) {
    if (eq_1(array2[length][0], key)) {
      return length;
    }
  }
  return -1;
}
var _assocIndexOf = assocIndexOf;
var arrayProto = Array.prototype;
var splice2 = arrayProto.splice;
function listCacheDelete(key) {
  var data2 = this.__data__, index3 = _assocIndexOf(data2, key);
  if (index3 < 0) {
    return false;
  }
  var lastIndex = data2.length - 1;
  if (index3 == lastIndex) {
    data2.pop();
  } else {
    splice2.call(data2, index3, 1);
  }
  --this.size;
  return true;
}
var _listCacheDelete = listCacheDelete;
function listCacheGet(key) {
  var data2 = this.__data__, index3 = _assocIndexOf(data2, key);
  return index3 < 0 ? void 0 : data2[index3][1];
}
var _listCacheGet = listCacheGet;
function listCacheHas(key) {
  return _assocIndexOf(this.__data__, key) > -1;
}
var _listCacheHas = listCacheHas;
function listCacheSet(key, value) {
  var data2 = this.__data__, index3 = _assocIndexOf(data2, key);
  if (index3 < 0) {
    ++this.size;
    data2.push([key, value]);
  } else {
    data2[index3][1] = value;
  }
  return this;
}
var _listCacheSet = listCacheSet;
function ListCache(entries) {
  var index3 = -1, length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index3 < length) {
    var entry = entries[index3];
    this.set(entry[0], entry[1]);
  }
}
ListCache.prototype.clear = _listCacheClear;
ListCache.prototype["delete"] = _listCacheDelete;
ListCache.prototype.get = _listCacheGet;
ListCache.prototype.has = _listCacheHas;
ListCache.prototype.set = _listCacheSet;
var _ListCache = ListCache;
function stackClear() {
  this.__data__ = new _ListCache();
  this.size = 0;
}
var _stackClear = stackClear;
function stackDelete(key) {
  var data2 = this.__data__, result = data2["delete"](key);
  this.size = data2.size;
  return result;
}
var _stackDelete = stackDelete;
function stackGet(key) {
  return this.__data__.get(key);
}
var _stackGet = stackGet;
function stackHas(key) {
  return this.__data__.has(key);
}
var _stackHas = stackHas;
var freeGlobal2 = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
var _freeGlobal = freeGlobal2;
var freeSelf2 = typeof self == "object" && self && self.Object === Object && self;
var root2 = _freeGlobal || freeSelf2 || Function("return this")();
var _root = root2;
var Symbol2 = _root.Symbol;
var _Symbol = Symbol2;
var objectProto2 = Object.prototype;
var hasOwnProperty3 = objectProto2.hasOwnProperty;
var nativeObjectToString = objectProto2.toString;
var symToStringTag = _Symbol ? _Symbol.toStringTag : void 0;
function getRawTag(value) {
  var isOwn = hasOwnProperty3.call(value, symToStringTag), tag = value[symToStringTag];
  try {
    value[symToStringTag] = void 0;
    var unmasked = true;
  } catch (e2) {
  }
  var result = nativeObjectToString.call(value);
  if (unmasked) {
    if (isOwn) {
      value[symToStringTag] = tag;
    } else {
      delete value[symToStringTag];
    }
  }
  return result;
}
var _getRawTag = getRawTag;
var objectProto$1 = Object.prototype;
var nativeObjectToString$1 = objectProto$1.toString;
function objectToString2(value) {
  return nativeObjectToString$1.call(value);
}
var _objectToString = objectToString2;
var nullTag = "[object Null]";
var undefinedTag = "[object Undefined]";
var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : void 0;
function baseGetTag(value) {
  if (value == null) {
    return value === void 0 ? undefinedTag : nullTag;
  }
  return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value);
}
var _baseGetTag = baseGetTag;
function isObject4(value) {
  var type = typeof value;
  return value != null && (type == "object" || type == "function");
}
var isObject_1 = isObject4;
var asyncTag = "[object AsyncFunction]";
var funcTag = "[object Function]";
var genTag = "[object GeneratorFunction]";
var proxyTag = "[object Proxy]";
function isFunction4(value) {
  if (!isObject_1(value)) {
    return false;
  }
  var tag = _baseGetTag(value);
  return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var isFunction_1 = isFunction4;
var coreJsData = _root["__core-js_shared__"];
var _coreJsData = coreJsData;
var maskSrcKey = function() {
  var uid2 = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || "");
  return uid2 ? "Symbol(src)_1." + uid2 : "";
}();
function isMasked(func) {
  return !!maskSrcKey && maskSrcKey in func;
}
var _isMasked = isMasked;
var funcProto = Function.prototype;
var funcToString = funcProto.toString;
function toSource(func) {
  if (func != null) {
    try {
      return funcToString.call(func);
    } catch (e2) {
    }
    try {
      return func + "";
    } catch (e2) {
    }
  }
  return "";
}
var _toSource = toSource;
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
var reIsHostCtor = /^\[object .+?Constructor\]$/;
var funcProto$1 = Function.prototype;
var objectProto$2 = Object.prototype;
var funcToString$1 = funcProto$1.toString;
var hasOwnProperty$12 = objectProto$2.hasOwnProperty;
var reIsNative = RegExp("^" + funcToString$1.call(hasOwnProperty$12).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
function baseIsNative(value) {
  if (!isObject_1(value) || _isMasked(value)) {
    return false;
  }
  var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
  return pattern.test(_toSource(value));
}
var _baseIsNative = baseIsNative;
function getValue(object, key) {
  return object == null ? void 0 : object[key];
}
var _getValue = getValue;
function getNative(object, key) {
  var value = _getValue(object, key);
  return _baseIsNative(value) ? value : void 0;
}
var _getNative = getNative;
var Map2 = _getNative(_root, "Map");
var _Map = Map2;
var nativeCreate = _getNative(Object, "create");
var _nativeCreate = nativeCreate;
function hashClear() {
  this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  this.size = 0;
}
var _hashClear = hashClear;
function hashDelete(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}
var _hashDelete = hashDelete;
var HASH_UNDEFINED = "__lodash_hash_undefined__";
var objectProto$3 = Object.prototype;
var hasOwnProperty$22 = objectProto$3.hasOwnProperty;
function hashGet(key) {
  var data2 = this.__data__;
  if (_nativeCreate) {
    var result = data2[key];
    return result === HASH_UNDEFINED ? void 0 : result;
  }
  return hasOwnProperty$22.call(data2, key) ? data2[key] : void 0;
}
var _hashGet = hashGet;
var objectProto$4 = Object.prototype;
var hasOwnProperty$32 = objectProto$4.hasOwnProperty;
function hashHas(key) {
  var data2 = this.__data__;
  return _nativeCreate ? data2[key] !== void 0 : hasOwnProperty$32.call(data2, key);
}
var _hashHas = hashHas;
var HASH_UNDEFINED$1 = "__lodash_hash_undefined__";
function hashSet(key, value) {
  var data2 = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data2[key] = _nativeCreate && value === void 0 ? HASH_UNDEFINED$1 : value;
  return this;
}
var _hashSet = hashSet;
function Hash(entries) {
  var index3 = -1, length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index3 < length) {
    var entry = entries[index3];
    this.set(entry[0], entry[1]);
  }
}
Hash.prototype.clear = _hashClear;
Hash.prototype["delete"] = _hashDelete;
Hash.prototype.get = _hashGet;
Hash.prototype.has = _hashHas;
Hash.prototype.set = _hashSet;
var _Hash = Hash;
function mapCacheClear() {
  this.size = 0;
  this.__data__ = {
    hash: new _Hash(),
    map: new (_Map || _ListCache)(),
    string: new _Hash()
  };
}
var _mapCacheClear = mapCacheClear;
function isKeyable(value) {
  var type = typeof value;
  return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
var _isKeyable = isKeyable;
function getMapData(map2, key) {
  var data2 = map2.__data__;
  return _isKeyable(key) ? data2[typeof key == "string" ? "string" : "hash"] : data2.map;
}
var _getMapData = getMapData;
function mapCacheDelete(key) {
  var result = _getMapData(this, key)["delete"](key);
  this.size -= result ? 1 : 0;
  return result;
}
var _mapCacheDelete = mapCacheDelete;
function mapCacheGet(key) {
  return _getMapData(this, key).get(key);
}
var _mapCacheGet = mapCacheGet;
function mapCacheHas(key) {
  return _getMapData(this, key).has(key);
}
var _mapCacheHas = mapCacheHas;
function mapCacheSet(key, value) {
  var data2 = _getMapData(this, key), size2 = data2.size;
  data2.set(key, value);
  this.size += data2.size == size2 ? 0 : 1;
  return this;
}
var _mapCacheSet = mapCacheSet;
function MapCache(entries) {
  var index3 = -1, length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index3 < length) {
    var entry = entries[index3];
    this.set(entry[0], entry[1]);
  }
}
MapCache.prototype.clear = _mapCacheClear;
MapCache.prototype["delete"] = _mapCacheDelete;
MapCache.prototype.get = _mapCacheGet;
MapCache.prototype.has = _mapCacheHas;
MapCache.prototype.set = _mapCacheSet;
var _MapCache = MapCache;
var LARGE_ARRAY_SIZE = 200;
function stackSet(key, value) {
  var data2 = this.__data__;
  if (data2 instanceof _ListCache) {
    var pairs = data2.__data__;
    if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
      pairs.push([key, value]);
      this.size = ++data2.size;
      return this;
    }
    data2 = this.__data__ = new _MapCache(pairs);
  }
  data2.set(key, value);
  this.size = data2.size;
  return this;
}
var _stackSet = stackSet;
function Stack3(entries) {
  var data2 = this.__data__ = new _ListCache(entries);
  this.size = data2.size;
}
Stack3.prototype.clear = _stackClear;
Stack3.prototype["delete"] = _stackDelete;
Stack3.prototype.get = _stackGet;
Stack3.prototype.has = _stackHas;
Stack3.prototype.set = _stackSet;
var _Stack = Stack3;
var defineProperty2 = function() {
  try {
    var func = _getNative(Object, "defineProperty");
    func({}, "", {});
    return func;
  } catch (e2) {
  }
}();
var _defineProperty5 = defineProperty2;
function baseAssignValue(object, key, value) {
  if (key == "__proto__" && _defineProperty5) {
    _defineProperty5(object, key, {
      configurable: true,
      enumerable: true,
      value,
      writable: true
    });
  } else {
    object[key] = value;
  }
}
var _baseAssignValue = baseAssignValue;
function assignMergeValue(object, key, value) {
  if (value !== void 0 && !eq_1(object[key], value) || value === void 0 && !(key in object)) {
    _baseAssignValue(object, key, value);
  }
}
var _assignMergeValue = assignMergeValue;
function createBaseFor(fromRight) {
  return function(object, iteratee, keysFunc) {
    var index3 = -1, iterable = Object(object), props = keysFunc(object), length = props.length;
    while (length--) {
      var key = props[fromRight ? length : ++index3];
      if (iteratee(iterable[key], key, iterable) === false) {
        break;
      }
    }
    return object;
  };
}
var _createBaseFor = createBaseFor;
var baseFor = _createBaseFor();
var _baseFor = baseFor;
var _cloneBuffer = createCommonjsModule(function(module2, exports2) {
  var freeExports = exports2 && !exports2.nodeType && exports2;
  var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
  var moduleExports = freeModule && freeModule.exports === freeExports;
  var Buffer2 = moduleExports ? _root.Buffer : void 0, allocUnsafe = Buffer2 ? Buffer2.allocUnsafe : void 0;
  function cloneBuffer(buffer, isDeep) {
    if (isDeep) {
      return buffer.slice();
    }
    var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
    buffer.copy(result);
    return result;
  }
  module2.exports = cloneBuffer;
});
var Uint8Array2 = _root.Uint8Array;
var _Uint8Array = Uint8Array2;
function cloneArrayBuffer(arrayBuffer) {
  var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
  return result;
}
var _cloneArrayBuffer = cloneArrayBuffer;
function cloneTypedArray(typedArray, isDeep) {
  var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
var _cloneTypedArray = cloneTypedArray;
function copyArray(source2, array2) {
  var index3 = -1, length = source2.length;
  array2 || (array2 = Array(length));
  while (++index3 < length) {
    array2[index3] = source2[index3];
  }
  return array2;
}
var _copyArray = copyArray;
var objectCreate = Object.create;
var baseCreate = function() {
  function object() {
  }
  return function(proto) {
    if (!isObject_1(proto)) {
      return {};
    }
    if (objectCreate) {
      return objectCreate(proto);
    }
    object.prototype = proto;
    var result = new object();
    object.prototype = void 0;
    return result;
  };
}();
var _baseCreate = baseCreate;
function overArg(func, transform3) {
  return function(arg) {
    return func(transform3(arg));
  };
}
var _overArg = overArg;
var getPrototype = _overArg(Object.getPrototypeOf, Object);
var _getPrototype = getPrototype;
var objectProto$5 = Object.prototype;
function isPrototype(value) {
  var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto$5;
  return value === proto;
}
var _isPrototype = isPrototype;
function initCloneObject(object) {
  return typeof object.constructor == "function" && !_isPrototype(object) ? _baseCreate(_getPrototype(object)) : {};
}
var _initCloneObject = initCloneObject;
function isObjectLike2(value) {
  return value != null && typeof value == "object";
}
var isObjectLike_1 = isObjectLike2;
var argsTag = "[object Arguments]";
function baseIsArguments(value) {
  return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
}
var _baseIsArguments = baseIsArguments;
var objectProto$6 = Object.prototype;
var hasOwnProperty$4 = objectProto$6.hasOwnProperty;
var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;
var isArguments = _baseIsArguments(function() {
  return arguments;
}()) ? _baseIsArguments : function(value) {
  return isObjectLike_1(value) && hasOwnProperty$4.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
};
var isArguments_1 = isArguments;
var isArray2 = Array.isArray;
var isArray_1 = isArray2;
var MAX_SAFE_INTEGER = 9007199254740991;
function isLength(value) {
  return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
var isLength_1 = isLength;
function isArrayLike(value) {
  return value != null && isLength_1(value.length) && !isFunction_1(value);
}
var isArrayLike_1 = isArrayLike;
function isArrayLikeObject(value) {
  return isObjectLike_1(value) && isArrayLike_1(value);
}
var isArrayLikeObject_1 = isArrayLikeObject;
function stubFalse() {
  return false;
}
var stubFalse_1 = stubFalse;
var isBuffer_1 = createCommonjsModule(function(module2, exports2) {
  var freeExports = exports2 && !exports2.nodeType && exports2;
  var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
  var moduleExports = freeModule && freeModule.exports === freeExports;
  var Buffer2 = moduleExports ? _root.Buffer : void 0;
  var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0;
  var isBuffer3 = nativeIsBuffer || stubFalse_1;
  module2.exports = isBuffer3;
});
var objectTag = "[object Object]";
var funcProto$2 = Function.prototype;
var objectProto$7 = Object.prototype;
var funcToString$2 = funcProto$2.toString;
var hasOwnProperty$5 = objectProto$7.hasOwnProperty;
var objectCtorString = funcToString$2.call(Object);
function isPlainObject2(value) {
  if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag) {
    return false;
  }
  var proto = _getPrototype(value);
  if (proto === null) {
    return true;
  }
  var Ctor = hasOwnProperty$5.call(proto, "constructor") && proto.constructor;
  return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString;
}
var isPlainObject_1 = isPlainObject2;
var argsTag$1 = "[object Arguments]";
var arrayTag = "[object Array]";
var boolTag = "[object Boolean]";
var dateTag = "[object Date]";
var errorTag = "[object Error]";
var funcTag$1 = "[object Function]";
var mapTag = "[object Map]";
var numberTag = "[object Number]";
var objectTag$1 = "[object Object]";
var regexpTag = "[object RegExp]";
var setTag = "[object Set]";
var stringTag = "[object String]";
var weakMapTag = "[object WeakMap]";
var arrayBufferTag = "[object ArrayBuffer]";
var dataViewTag = "[object DataView]";
var float32Tag = "[object Float32Array]";
var float64Tag = "[object Float64Array]";
var int8Tag = "[object Int8Array]";
var int16Tag = "[object Int16Array]";
var int32Tag = "[object Int32Array]";
var uint8Tag = "[object Uint8Array]";
var uint8ClampedTag = "[object Uint8ClampedArray]";
var uint16Tag = "[object Uint16Array]";
var uint32Tag = "[object Uint32Array]";
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
function baseIsTypedArray(value) {
  return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
}
var _baseIsTypedArray = baseIsTypedArray;
function baseUnary(func) {
  return function(value) {
    return func(value);
  };
}
var _baseUnary = baseUnary;
var _nodeUtil = createCommonjsModule(function(module2, exports2) {
  var freeExports = exports2 && !exports2.nodeType && exports2;
  var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
  var moduleExports = freeModule && freeModule.exports === freeExports;
  var freeProcess = moduleExports && _freeGlobal.process;
  var nodeUtil = function() {
    try {
      var types2 = freeModule && freeModule.require && freeModule.require("util").types;
      if (types2) {
        return types2;
      }
      return freeProcess && freeProcess.binding && freeProcess.binding("util");
    } catch (e2) {
    }
  }();
  module2.exports = nodeUtil;
});
var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
var isTypedArray_1 = isTypedArray;
function safeGet(object, key) {
  if (key === "constructor" && typeof object[key] === "function") {
    return;
  }
  if (key == "__proto__") {
    return;
  }
  return object[key];
}
var _safeGet = safeGet;
var objectProto$8 = Object.prototype;
var hasOwnProperty$6 = objectProto$8.hasOwnProperty;
function assignValue(object, key, value) {
  var objValue = object[key];
  if (!(hasOwnProperty$6.call(object, key) && eq_1(objValue, value)) || value === void 0 && !(key in object)) {
    _baseAssignValue(object, key, value);
  }
}
var _assignValue = assignValue;
function copyObject(source2, props, object, customizer) {
  var isNew = !object;
  object || (object = {});
  var index3 = -1, length = props.length;
  while (++index3 < length) {
    var key = props[index3];
    var newValue = customizer ? customizer(object[key], source2[key], key, object, source2) : void 0;
    if (newValue === void 0) {
      newValue = source2[key];
    }
    if (isNew) {
      _baseAssignValue(object, key, newValue);
    } else {
      _assignValue(object, key, newValue);
    }
  }
  return object;
}
var _copyObject = copyObject;
function baseTimes(n3, iteratee) {
  var index3 = -1, result = Array(n3);
  while (++index3 < n3) {
    result[index3] = iteratee(index3);
  }
  return result;
}
var _baseTimes = baseTimes;
var MAX_SAFE_INTEGER$1 = 9007199254740991;
var reIsUint = /^(?:0|[1-9]\d*)$/;
function isIndex(value, length) {
  var type = typeof value;
  length = length == null ? MAX_SAFE_INTEGER$1 : length;
  return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
}
var _isIndex = isIndex;
var objectProto$9 = Object.prototype;
var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
function arrayLikeKeys(value, inherited) {
  var isArr = isArray_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes(value.length, String) : [], length = result.length;
  for (var key in value) {
    if ((inherited || hasOwnProperty$7.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || _isIndex(key, length)))) {
      result.push(key);
    }
  }
  return result;
}
var _arrayLikeKeys = arrayLikeKeys;
function nativeKeysIn(object) {
  var result = [];
  if (object != null) {
    for (var key in Object(object)) {
      result.push(key);
    }
  }
  return result;
}
var _nativeKeysIn = nativeKeysIn;
var objectProto$a = Object.prototype;
var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
function baseKeysIn(object) {
  if (!isObject_1(object)) {
    return _nativeKeysIn(object);
  }
  var isProto = _isPrototype(object), result = [];
  for (var key in object) {
    if (!(key == "constructor" && (isProto || !hasOwnProperty$8.call(object, key)))) {
      result.push(key);
    }
  }
  return result;
}
var _baseKeysIn = baseKeysIn;
function keysIn(object) {
  return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
}
var keysIn_1 = keysIn;
function toPlainObject(value) {
  return _copyObject(value, keysIn_1(value));
}
var toPlainObject_1 = toPlainObject;
function baseMergeDeep(object, source2, key, srcIndex, mergeFunc, customizer, stack2) {
  var objValue = _safeGet(object, key), srcValue = _safeGet(source2, key), stacked = stack2.get(srcValue);
  if (stacked) {
    _assignMergeValue(object, key, stacked);
    return;
  }
  var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source2, stack2) : void 0;
  var isCommon = newValue === void 0;
  if (isCommon) {
    var isArr = isArray_1(srcValue), isBuff = !isArr && isBuffer_1(srcValue), isTyped = !isArr && !isBuff && isTypedArray_1(srcValue);
    newValue = srcValue;
    if (isArr || isBuff || isTyped) {
      if (isArray_1(objValue)) {
        newValue = objValue;
      } else if (isArrayLikeObject_1(objValue)) {
        newValue = _copyArray(objValue);
      } else if (isBuff) {
        isCommon = false;
        newValue = _cloneBuffer(srcValue, true);
      } else if (isTyped) {
        isCommon = false;
        newValue = _cloneTypedArray(srcValue, true);
      } else {
        newValue = [];
      }
    } else if (isPlainObject_1(srcValue) || isArguments_1(srcValue)) {
      newValue = objValue;
      if (isArguments_1(objValue)) {
        newValue = toPlainObject_1(objValue);
      } else if (!isObject_1(objValue) || isFunction_1(objValue)) {
        newValue = _initCloneObject(srcValue);
      }
    } else {
      isCommon = false;
    }
  }
  if (isCommon) {
    stack2.set(srcValue, newValue);
    mergeFunc(newValue, srcValue, srcIndex, customizer, stack2);
    stack2["delete"](srcValue);
  }
  _assignMergeValue(object, key, newValue);
}
var _baseMergeDeep = baseMergeDeep;
function baseMerge(object, source2, srcIndex, customizer, stack2) {
  if (object === source2) {
    return;
  }
  _baseFor(source2, function(srcValue, key) {
    stack2 || (stack2 = new _Stack());
    if (isObject_1(srcValue)) {
      _baseMergeDeep(object, source2, key, srcIndex, baseMerge, customizer, stack2);
    } else {
      var newValue = customizer ? customizer(_safeGet(object, key), srcValue, key + "", object, source2, stack2) : void 0;
      if (newValue === void 0) {
        newValue = srcValue;
      }
      _assignMergeValue(object, key, newValue);
    }
  }, keysIn_1);
}
var _baseMerge = baseMerge;
function identity(value) {
  return value;
}
var identity_1 = identity;
function apply(func, thisArg, args) {
  switch (args.length) {
    case 0:
      return func.call(thisArg);
    case 1:
      return func.call(thisArg, args[0]);
    case 2:
      return func.call(thisArg, args[0], args[1]);
    case 3:
      return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}
var _apply = apply;
var nativeMax = Math.max;
function overRest(func, start3, transform3) {
  start3 = nativeMax(start3 === void 0 ? func.length - 1 : start3, 0);
  return function() {
    var args = arguments, index3 = -1, length = nativeMax(args.length - start3, 0), array2 = Array(length);
    while (++index3 < length) {
      array2[index3] = args[start3 + index3];
    }
    index3 = -1;
    var otherArgs = Array(start3 + 1);
    while (++index3 < start3) {
      otherArgs[index3] = args[index3];
    }
    otherArgs[start3] = transform3(array2);
    return _apply(func, this, otherArgs);
  };
}
var _overRest = overRest;
function constant(value) {
  return function() {
    return value;
  };
}
var constant_1 = constant;
var baseSetToString = !_defineProperty5 ? identity_1 : function(func, string2) {
  return _defineProperty5(func, "toString", {
    configurable: true,
    enumerable: false,
    value: constant_1(string2),
    writable: true
  });
};
var _baseSetToString = baseSetToString;
var HOT_COUNT = 800;
var HOT_SPAN = 16;
var nativeNow = Date.now;
function shortOut(func) {
  var count = 0, lastCalled = 0;
  return function() {
    var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled);
    lastCalled = stamp;
    if (remaining > 0) {
      if (++count >= HOT_COUNT) {
        return arguments[0];
      }
    } else {
      count = 0;
    }
    return func.apply(void 0, arguments);
  };
}
var _shortOut = shortOut;
var setToString = _shortOut(_baseSetToString);
var _setToString = setToString;
function baseRest(func, start3) {
  return _setToString(_overRest(func, start3, identity_1), func + "");
}
var _baseRest = baseRest;
function isIterateeCall(value, index3, object) {
  if (!isObject_1(object)) {
    return false;
  }
  var type = typeof index3;
  if (type == "number" ? isArrayLike_1(object) && _isIndex(index3, object.length) : type == "string" && index3 in object) {
    return eq_1(object[index3], value);
  }
  return false;
}
var _isIterateeCall = isIterateeCall;
function createAssigner(assigner) {
  return _baseRest(function(object, sources) {
    var index3 = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : void 0, guard = length > 2 ? sources[2] : void 0;
    customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : void 0;
    if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
      customizer = length < 3 ? void 0 : customizer;
      length = 1;
    }
    object = Object(object);
    while (++index3 < length) {
      var source2 = sources[index3];
      if (source2) {
        assigner(object, source2, index3, customizer);
      }
    }
    return object;
  });
}
var _createAssigner = createAssigner;
var HASH_UNDEFINED$2 = "__lodash_hash_undefined__";
function setCacheAdd(value) {
  this.__data__.set(value, HASH_UNDEFINED$2);
  return this;
}
var _setCacheAdd = setCacheAdd;
function setCacheHas(value) {
  return this.__data__.has(value);
}
var _setCacheHas = setCacheHas;
function SetCache(values2) {
  var index3 = -1, length = values2 == null ? 0 : values2.length;
  this.__data__ = new _MapCache();
  while (++index3 < length) {
    this.add(values2[index3]);
  }
}
SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
SetCache.prototype.has = _setCacheHas;
var _SetCache = SetCache;
function arraySome(array2, predicate) {
  var index3 = -1, length = array2 == null ? 0 : array2.length;
  while (++index3 < length) {
    if (predicate(array2[index3], index3, array2)) {
      return true;
    }
  }
  return false;
}
var _arraySome = arraySome;
function cacheHas(cache3, key) {
  return cache3.has(key);
}
var _cacheHas = cacheHas;
var COMPARE_PARTIAL_FLAG = 1;
var COMPARE_UNORDERED_FLAG = 2;
function equalArrays(array2, other, bitmask, customizer, equalFunc, stack2) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array2.length, othLength = other.length;
  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
    return false;
  }
  var arrStacked = stack2.get(array2);
  var othStacked = stack2.get(other);
  if (arrStacked && othStacked) {
    return arrStacked == other && othStacked == array2;
  }
  var index3 = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : void 0;
  stack2.set(array2, other);
  stack2.set(other, array2);
  while (++index3 < arrLength) {
    var arrValue = array2[index3], othValue = other[index3];
    if (customizer) {
      var compared = isPartial ? customizer(othValue, arrValue, index3, other, array2, stack2) : customizer(arrValue, othValue, index3, array2, other, stack2);
    }
    if (compared !== void 0) {
      if (compared) {
        continue;
      }
      result = false;
      break;
    }
    if (seen) {
      if (!_arraySome(other, function(othValue2, othIndex) {
        if (!_cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack2))) {
          return seen.push(othIndex);
        }
      })) {
        result = false;
        break;
      }
    } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack2))) {
      result = false;
      break;
    }
  }
  stack2["delete"](array2);
  stack2["delete"](other);
  return result;
}
var _equalArrays = equalArrays;
function mapToArray(map2) {
  var index3 = -1, result = Array(map2.size);
  map2.forEach(function(value, key) {
    result[++index3] = [key, value];
  });
  return result;
}
var _mapToArray = mapToArray;
function setToArray(set3) {
  var index3 = -1, result = Array(set3.size);
  set3.forEach(function(value) {
    result[++index3] = value;
  });
  return result;
}
var _setToArray = setToArray;
var COMPARE_PARTIAL_FLAG$1 = 1;
var COMPARE_UNORDERED_FLAG$1 = 2;
var boolTag$1 = "[object Boolean]";
var dateTag$1 = "[object Date]";
var errorTag$1 = "[object Error]";
var mapTag$1 = "[object Map]";
var numberTag$1 = "[object Number]";
var regexpTag$1 = "[object RegExp]";
var setTag$1 = "[object Set]";
var stringTag$1 = "[object String]";
var symbolTag2 = "[object Symbol]";
var arrayBufferTag$1 = "[object ArrayBuffer]";
var dataViewTag$1 = "[object DataView]";
var symbolProto2 = _Symbol ? _Symbol.prototype : void 0;
var symbolValueOf = symbolProto2 ? symbolProto2.valueOf : void 0;
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack2) {
  switch (tag) {
    case dataViewTag$1:
      if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
        return false;
      }
      object = object.buffer;
      other = other.buffer;
    case arrayBufferTag$1:
      if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
        return false;
      }
      return true;
    case boolTag$1:
    case dateTag$1:
    case numberTag$1:
      return eq_1(+object, +other);
    case errorTag$1:
      return object.name == other.name && object.message == other.message;
    case regexpTag$1:
    case stringTag$1:
      return object == other + "";
    case mapTag$1:
      var convert = _mapToArray;
    case setTag$1:
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
      convert || (convert = _setToArray);
      if (object.size != other.size && !isPartial) {
        return false;
      }
      var stacked = stack2.get(object);
      if (stacked) {
        return stacked == other;
      }
      bitmask |= COMPARE_UNORDERED_FLAG$1;
      stack2.set(object, other);
      var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack2);
      stack2["delete"](object);
      return result;
    case symbolTag2:
      if (symbolValueOf) {
        return symbolValueOf.call(object) == symbolValueOf.call(other);
      }
  }
  return false;
}
var _equalByTag = equalByTag;
function arrayPush(array2, values2) {
  var index3 = -1, length = values2.length, offset2 = array2.length;
  while (++index3 < length) {
    array2[offset2 + index3] = values2[index3];
  }
  return array2;
}
var _arrayPush = arrayPush;
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
}
var _baseGetAllKeys = baseGetAllKeys;
function arrayFilter(array2, predicate) {
  var index3 = -1, length = array2 == null ? 0 : array2.length, resIndex = 0, result = [];
  while (++index3 < length) {
    var value = array2[index3];
    if (predicate(value, index3, array2)) {
      result[resIndex++] = value;
    }
  }
  return result;
}
var _arrayFilter = arrayFilter;
function stubArray() {
  return [];
}
var stubArray_1 = stubArray;
var objectProto$b = Object.prototype;
var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable;
var nativeGetSymbols = Object.getOwnPropertySymbols;
var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) {
  if (object == null) {
    return [];
  }
  object = Object(object);
  return _arrayFilter(nativeGetSymbols(object), function(symbol) {
    return propertyIsEnumerable$1.call(object, symbol);
  });
};
var _getSymbols = getSymbols;
var nativeKeys = _overArg(Object.keys, Object);
var _nativeKeys = nativeKeys;
var objectProto$c = Object.prototype;
var hasOwnProperty$9 = objectProto$c.hasOwnProperty;
function baseKeys(object) {
  if (!_isPrototype(object)) {
    return _nativeKeys(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (hasOwnProperty$9.call(object, key) && key != "constructor") {
      result.push(key);
    }
  }
  return result;
}
var _baseKeys = baseKeys;
function keys(object) {
  return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
}
var keys_1 = keys;
function getAllKeys(object) {
  return _baseGetAllKeys(object, keys_1, _getSymbols);
}
var _getAllKeys = getAllKeys;
var COMPARE_PARTIAL_FLAG$2 = 1;
var objectProto$d = Object.prototype;
var hasOwnProperty$a = objectProto$d.hasOwnProperty;
function equalObjects(object, other, bitmask, customizer, equalFunc, stack2) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, objProps = _getAllKeys(object), objLength = objProps.length, othProps = _getAllKeys(other), othLength = othProps.length;
  if (objLength != othLength && !isPartial) {
    return false;
  }
  var index3 = objLength;
  while (index3--) {
    var key = objProps[index3];
    if (!(isPartial ? key in other : hasOwnProperty$a.call(other, key))) {
      return false;
    }
  }
  var objStacked = stack2.get(object);
  var othStacked = stack2.get(other);
  if (objStacked && othStacked) {
    return objStacked == other && othStacked == object;
  }
  var result = true;
  stack2.set(object, other);
  stack2.set(other, object);
  var skipCtor = isPartial;
  while (++index3 < objLength) {
    key = objProps[index3];
    var objValue = object[key], othValue = other[key];
    if (customizer) {
      var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack2) : customizer(objValue, othValue, key, object, other, stack2);
    }
    if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack2) : compared)) {
      result = false;
      break;
    }
    skipCtor || (skipCtor = key == "constructor");
  }
  if (result && !skipCtor) {
    var objCtor = object.constructor, othCtor = other.constructor;
    if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
      result = false;
    }
  }
  stack2["delete"](object);
  stack2["delete"](other);
  return result;
}
var _equalObjects = equalObjects;
var DataView2 = _getNative(_root, "DataView");
var _DataView = DataView2;
var Promise2 = _getNative(_root, "Promise");
var _Promise = Promise2;
var Set2 = _getNative(_root, "Set");
var _Set = Set2;
var WeakMap2 = _getNative(_root, "WeakMap");
var _WeakMap = WeakMap2;
var mapTag$2 = "[object Map]";
var objectTag$2 = "[object Object]";
var promiseTag = "[object Promise]";
var setTag$2 = "[object Set]";
var weakMapTag$1 = "[object WeakMap]";
var dataViewTag$2 = "[object DataView]";
var dataViewCtorString = _toSource(_DataView);
var mapCtorString = _toSource(_Map);
var promiseCtorString = _toSource(_Promise);
var setCtorString = _toSource(_Set);
var weakMapCtorString = _toSource(_WeakMap);
var getTag = _baseGetTag;
if (_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2 || _Map && getTag(new _Map()) != mapTag$2 || _Promise && getTag(_Promise.resolve()) != promiseTag || _Set && getTag(new _Set()) != setTag$2 || _WeakMap && getTag(new _WeakMap()) != weakMapTag$1) {
  getTag = function(value) {
    var result = _baseGetTag(value), Ctor = result == objectTag$2 ? value.constructor : void 0, ctorString = Ctor ? _toSource(Ctor) : "";
    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString:
          return dataViewTag$2;
        case mapCtorString:
          return mapTag$2;
        case promiseCtorString:
          return promiseTag;
        case setCtorString:
          return setTag$2;
        case weakMapCtorString:
          return weakMapTag$1;
      }
    }
    return result;
  };
}
var _getTag = getTag;
var COMPARE_PARTIAL_FLAG$3 = 1;
var argsTag$2 = "[object Arguments]";
var arrayTag$1 = "[object Array]";
var objectTag$3 = "[object Object]";
var objectProto$e = Object.prototype;
var hasOwnProperty$b = objectProto$e.hasOwnProperty;
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack2) {
  var objIsArr = isArray_1(object), othIsArr = isArray_1(other), objTag = objIsArr ? arrayTag$1 : _getTag(object), othTag = othIsArr ? arrayTag$1 : _getTag(other);
  objTag = objTag == argsTag$2 ? objectTag$3 : objTag;
  othTag = othTag == argsTag$2 ? objectTag$3 : othTag;
  var objIsObj = objTag == objectTag$3, othIsObj = othTag == objectTag$3, isSameTag = objTag == othTag;
  if (isSameTag && isBuffer_1(object)) {
    if (!isBuffer_1(other)) {
      return false;
    }
    objIsArr = true;
    objIsObj = false;
  }
  if (isSameTag && !objIsObj) {
    stack2 || (stack2 = new _Stack());
    return objIsArr || isTypedArray_1(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack2) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack2);
  }
  if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
    var objIsWrapped = objIsObj && hasOwnProperty$b.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty$b.call(other, "__wrapped__");
    if (objIsWrapped || othIsWrapped) {
      var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
      stack2 || (stack2 = new _Stack());
      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack2);
    }
  }
  if (!isSameTag) {
    return false;
  }
  stack2 || (stack2 = new _Stack());
  return _equalObjects(object, other, bitmask, customizer, equalFunc, stack2);
}
var _baseIsEqualDeep = baseIsEqualDeep;
function baseIsEqual(value, other, bitmask, customizer, stack2) {
  if (value === other) {
    return true;
  }
  if (value == null || other == null || !isObjectLike_1(value) && !isObjectLike_1(other)) {
    return value !== value && other !== other;
  }
  return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack2);
}
var _baseIsEqual = baseIsEqual;

// build/_snowpack/pkg/@patternfly/react-table.js
var handleArrows = (event, navigableElements, isActiveElement = (element) => document.activeElement.contains(element), getFocusableElement = (element) => element, validSiblingTags = ["A", "BUTTON", "INPUT"], noVerticalArrowHandling = false, noHorizontalArrowHandling = false, updateTabIndex = true, onlyTraverseSiblings = true) => {
  const activeElement = document.activeElement;
  const key = event.key;
  let moveTarget = null;
  if (!noVerticalArrowHandling) {
    if (["ArrowUp", "ArrowDown"].includes(key)) {
      event.preventDefault();
      event.stopImmediatePropagation();
      let currentIndex = -1;
      navigableElements.forEach((element, index3) => {
        if (isActiveElement(element)) {
          let increment = 0;
          while (!moveTarget && increment < navigableElements.length && increment * -1 < navigableElements.length) {
            key === "ArrowUp" ? increment-- : increment++;
            currentIndex = index3 + increment;
            if (currentIndex >= navigableElements.length) {
              currentIndex = 0;
            }
            if (currentIndex < 0) {
              currentIndex = navigableElements.length - 1;
            }
            moveTarget = getFocusableElement(navigableElements[currentIndex]);
          }
        }
      });
    }
  }
  if (!noHorizontalArrowHandling) {
    if (["ArrowLeft", "ArrowRight"].includes(key)) {
      event.preventDefault();
      event.stopImmediatePropagation();
      let currentIndex = -1;
      navigableElements.forEach((element, index3) => {
        if (isActiveElement(element)) {
          const activeRow = navigableElements[index3].querySelectorAll(validSiblingTags.join(","));
          if (!activeRow.length || onlyTraverseSiblings) {
            let nextSibling = activeElement;
            while (nextSibling) {
              nextSibling = key === "ArrowLeft" ? nextSibling.previousElementSibling : nextSibling.nextElementSibling;
              if (nextSibling) {
                if (validSiblingTags.includes(nextSibling.tagName)) {
                  moveTarget = nextSibling;
                  break;
                }
              }
            }
          } else {
            activeRow.forEach((focusableElement, index4) => {
              if (event.target === focusableElement) {
                const increment = key === "ArrowLeft" ? -1 : 1;
                currentIndex = index4 + increment;
                if (currentIndex >= activeRow.length) {
                  currentIndex = 0;
                }
                if (currentIndex < 0) {
                  currentIndex = activeRow.length - 1;
                }
                moveTarget = activeRow[currentIndex];
              }
            });
          }
        }
      });
    }
  }
  if (moveTarget) {
    if (updateTabIndex) {
      activeElement.tabIndex = -1;
      moveTarget.tabIndex = 0;
    }
    moveTarget.focus();
  }
};
var setTabIndex = (options) => {
  if (options && options.length > 0) {
    options.forEach((option) => {
      option.tabIndex = -1;
    });
    options[0].tabIndex = 0;
  }
};
var Bullseye = (_a) => {
  var {children: children2 = null, className = "", component = "div"} = _a, props = __rest(_a, ["children", "className", "component"]);
  const Component = component;
  return react.createElement(Component, Object.assign({className: css(styles2.bullseye, className)}, props), children2);
};
Bullseye.displayName = "Bullseye";
var ArrowsAltVIconConfig = {
  name: "ArrowsAltVIcon",
  height: 512,
  width: 256,
  svgPath: "M214.059 377.941H168V134.059h46.059c21.382 0 32.09-25.851 16.971-40.971L144.971 7.029c-9.373-9.373-24.568-9.373-33.941 0L24.971 93.088c-15.119 15.119-4.411 40.971 16.971 40.971H88v243.882H41.941c-21.382 0-32.09 25.851-16.971 40.971l86.059 86.059c9.373 9.373 24.568 9.373 33.941 0l86.059-86.059c15.12-15.119 4.412-40.971-16.97-40.971z",
  yOffset: 0,
  xOffset: 0
};
var ArrowsAltVIcon = createIcon(ArrowsAltVIconConfig);
var EllipsisHIconConfig = {
  name: "EllipsisHIcon",
  height: 512,
  width: 512,
  svgPath: "M328 256c0 39.8-32.2 72-72 72s-72-32.2-72-72 32.2-72 72-72 72 32.2 72 72zm104-72c-39.8 0-72 32.2-72 72s32.2 72 72 72 72-32.2 72-72-32.2-72-72-72zm-352 0c-39.8 0-72 32.2-72 72s32.2 72 72 72 72-32.2 72-72-32.2-72-72-72z",
  yOffset: 0,
  xOffset: 0
};
var EllipsisHIcon = createIcon(EllipsisHIconConfig);
var LongArrowAltDownIconConfig = {
  name: "LongArrowAltDownIcon",
  height: 512,
  width: 256,
  svgPath: "M168 345.941V44c0-6.627-5.373-12-12-12h-56c-6.627 0-12 5.373-12 12v301.941H41.941c-21.382 0-32.09 25.851-16.971 40.971l86.059 86.059c9.373 9.373 24.569 9.373 33.941 0l86.059-86.059c15.119-15.119 4.411-40.971-16.971-40.971H168z",
  yOffset: 0,
  xOffset: 0
};
var LongArrowAltDownIcon = createIcon(LongArrowAltDownIconConfig);
var LongArrowAltUpIconConfig = {
  name: "LongArrowAltUpIcon",
  height: 512,
  width: 256,
  svgPath: "M88 166.059V468c0 6.627 5.373 12 12 12h56c6.627 0 12-5.373 12-12V166.059h46.059c21.382 0 32.09-25.851 16.971-40.971l-86.059-86.059c-9.373-9.373-24.569-9.373-33.941 0l-86.059 86.059c-15.119 15.119-4.411 40.971 16.971 40.971H88z",
  yOffset: 0,
  xOffset: 0
};
var LongArrowAltUpIcon = createIcon(LongArrowAltUpIconConfig);
var table = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    modifiers: {
      hidden: "pf-m-hidden",
      hiddenOnSm: "pf-m-hidden-on-sm",
      visibleOnSm: "pf-m-visible-on-sm",
      hiddenOnMd: "pf-m-hidden-on-md",
      visibleOnMd: "pf-m-visible-on-md",
      hiddenOnLg: "pf-m-hidden-on-lg",
      visibleOnLg: "pf-m-visible-on-lg",
      hiddenOnXl: "pf-m-hidden-on-xl",
      visibleOnXl: "pf-m-visible-on-xl",
      hiddenOn_2xl: "pf-m-hidden-on-2xl",
      visibleOn_2xl: "pf-m-visible-on-2xl",
      fixed: "pf-m-fixed",
      stickyHeader: "pf-m-sticky-header",
      ghostRow: "pf-m-ghost-row",
      center: "pf-m-center",
      help: "pf-m-help",
      favorite: "pf-m-favorite",
      borderRight: "pf-m-border-right",
      borderLeft: "pf-m-border-left",
      nestedColumnHeader: "pf-m-nested-column-header",
      truncate: "pf-m-truncate",
      wrap: "pf-m-wrap",
      nowrap: "pf-m-nowrap",
      fitContent: "pf-m-fit-content",
      breakWord: "pf-m-break-word",
      noBorderRows: "pf-m-no-border-rows",
      expanded: "pf-m-expanded",
      hoverable: "pf-m-hoverable",
      selected: "pf-m-selected",
      firstCellOffsetReset: "pf-m-first-cell-offset-reset",
      dragOver: "pf-m-drag-over",
      favorited: "pf-m-favorited",
      noPadding: "pf-m-no-padding",
      compact: "pf-m-compact",
      width_10: "pf-m-width-10",
      width_15: "pf-m-width-15",
      width_20: "pf-m-width-20",
      width_25: "pf-m-width-25",
      width_30: "pf-m-width-30",
      width_35: "pf-m-width-35",
      width_40: "pf-m-width-40",
      width_45: "pf-m-width-45",
      width_50: "pf-m-width-50",
      width_60: "pf-m-width-60",
      width_70: "pf-m-width-70",
      width_80: "pf-m-width-80",
      width_90: "pf-m-width-90",
      width_100: "pf-m-width-100"
    },
    table: "pf-c-table",
    tableAction: "pf-c-table__action",
    tableButton: "pf-c-table__button",
    tableButtonContent: "pf-c-table__button-content",
    tableCheck: "pf-c-table__check",
    tableColumnHelp: "pf-c-table__column-help",
    tableColumnHelpAction: "pf-c-table__column-help-action",
    tableCompoundExpansionToggle: "pf-c-table__compound-expansion-toggle",
    tableControlRow: "pf-c-table__control-row",
    tableDraggable: "pf-c-table__draggable",
    tableExpandableRow: "pf-c-table__expandable-row",
    tableExpandableRowContent: "pf-c-table__expandable-row-content",
    tableFavorite: "pf-c-table__favorite",
    tableIcon: "pf-c-table__icon",
    tableIconInline: "pf-c-table__icon-inline",
    tableInlineEditAction: "pf-c-table__inline-edit-action",
    tableSort: "pf-c-table__sort",
    tableSortIndicator: "pf-c-table__sort-indicator",
    tableSubhead: "pf-c-table__subhead",
    tableText: "pf-c-table__text",
    tableToggle: "pf-c-table__toggle",
    tableToggleIcon: "pf-c-table__toggle-icon"
  };
});
var styles5 = /* @__PURE__ */ getDefaultExportFromCjs(table);
var tableGrid = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    button: "pf-c-button",
    modifiers: {
      grid: "pf-m-grid",
      compact: "pf-m-compact",
      expanded: "pf-m-expanded",
      selected: "pf-m-selected",
      noPadding: "pf-m-no-padding",
      hoverable: "pf-m-hoverable",
      nowrap: "pf-m-nowrap",
      fitContent: "pf-m-fit-content",
      truncate: "pf-m-truncate",
      gridMd: "pf-m-grid-md",
      gridLg: "pf-m-grid-lg",
      gridXl: "pf-m-grid-xl",
      grid_2xl: "pf-m-grid-2xl"
    },
    table: "pf-c-table",
    tableAction: "pf-c-table__action",
    tableButton: "pf-c-table__button",
    tableCheck: "pf-c-table__check",
    tableCompoundExpansionToggle: "pf-c-table__compound-expansion-toggle",
    tableExpandableRow: "pf-c-table__expandable-row",
    tableExpandableRowContent: "pf-c-table__expandable-row-content",
    tableFavorite: "pf-c-table__favorite",
    tableIcon: "pf-c-table__icon",
    tableInlineEditAction: "pf-c-table__inline-edit-action",
    tableText: "pf-c-table__text",
    tableToggle: "pf-c-table__toggle",
    tableToggleIcon: "pf-c-table__toggle-icon"
  };
});
var stylesGrid2 = /* @__PURE__ */ getDefaultExportFromCjs(tableGrid);
var tableTreeView = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    dropdown: "pf-c-dropdown",
    modifiers: {
      treeView: "pf-m-tree-view",
      treeViewGrid: "pf-m-tree-view-grid",
      treeViewDetailsExpanded: "pf-m-tree-view-details-expanded",
      treeViewGridMd: "pf-m-tree-view-grid-md",
      treeViewGridLg: "pf-m-tree-view-grid-lg",
      treeViewGridXl: "pf-m-tree-view-grid-xl",
      treeViewGrid_2xl: "pf-m-tree-view-grid-2xl"
    },
    table: "pf-c-table",
    tableAction: "pf-c-table__action",
    tableCheck: "pf-c-table__check",
    tableToggle: "pf-c-table__toggle",
    tableToggleIcon: "pf-c-table__toggle-icon",
    tableTreeViewDetailsToggle: "pf-c-table__tree-view-details-toggle",
    tableTreeViewIcon: "pf-c-table__tree-view-icon",
    tableTreeViewMain: "pf-c-table__tree-view-main",
    tableTreeViewText: "pf-c-table__tree-view-text",
    tableTreeViewTitleCell: "pf-c-table__tree-view-title-cell",
    tableTreeViewTitleHeaderCell: "pf-c-table__tree-view-title-header-cell"
  };
});
var stylesTreeView = /* @__PURE__ */ getDefaultExportFromCjs(tableTreeView);
var hasCompoundParentsExpanded = (parentId2, compoundParent, rows) => {
  for (const i3 of rows) {
    if (rows[parentId2].hasOwnProperty("parent")) {
      parentId2 = rows[parentId2].parent;
    } else {
      return rows[parentId2].cells[compoundParent].props.isOpen;
    }
  }
  return false;
};
var hasParentsExpanded = (parentId2, rows) => {
  for (const i3 of rows) {
    if (rows[parentId2].hasOwnProperty("parent")) {
      parentId2 = rows[parentId2].parent;
    } else {
      return rows[parentId2].isOpen;
    }
  }
  return false;
};
var isRowExpanded = (row, rows) => {
  if (row.parent !== void 0) {
    if (row.hasOwnProperty("compoundParent")) {
      return hasCompoundParentsExpanded(row.parent, row.compoundParent, rows);
    }
    return hasParentsExpanded(row.parent, rows) && rows[row.parent].isOpen;
  }
  return void 0;
};
var camelize2 = (s2) => s2.toUpperCase().replace("-", "").replace("_", "");
var toCamel2 = (s2) => s2.replace(/([-_][a-z])/gi, camelize2);
function capitalize4(input) {
  return input[0].toUpperCase() + input.substring(1);
}
var TableGridBreakpoint;
(function(TableGridBreakpoint2) {
  TableGridBreakpoint2["none"] = "";
  TableGridBreakpoint2["grid"] = "grid";
  TableGridBreakpoint2["gridMd"] = "grid-md";
  TableGridBreakpoint2["gridLg"] = "grid-lg";
  TableGridBreakpoint2["gridXl"] = "grid-xl";
  TableGridBreakpoint2["grid2xl"] = "grid-2xl";
})(TableGridBreakpoint || (TableGridBreakpoint = {}));
var TableVariant;
(function(TableVariant2) {
  TableVariant2["compact"] = "compact";
})(TableVariant || (TableVariant = {}));
var TableComposableBase = (_a) => {
  var _b, _c;
  var {children: children2, className, variant, borders = true, isStickyHeader = false, gridBreakPoint = TableGridBreakpoint.gridMd, "aria-label": ariaLabel, role = "grid", innerRef, ouiaId, ouiaSafe = true, isTreeTable = false, isNested = false, nestedHeaderColumnSpans} = _a, props = __rest(_a, ["children", "className", "variant", "borders", "isStickyHeader", "gridBreakPoint", "aria-label", "role", "innerRef", "ouiaId", "ouiaSafe", "isTreeTable", "isNested", "nestedHeaderColumnSpans"]);
  const tableRef = innerRef || react.useRef(null);
  react.useEffect(() => {
    document.addEventListener("keydown", handleKeys);
    if (tableRef && tableRef.current && tableRef.current.classList.contains("pf-m-tree-view")) {
      const tbody = tableRef.current.querySelector("tbody");
      tbody && setTabIndex(Array.from(tbody.querySelectorAll("button, a, input")));
    }
    return function cleanup2() {
      document.removeEventListener("keydown", handleKeys);
    };
  }, [tableRef, tableRef.current]);
  const ouiaProps = useOUIAProps("Table", ouiaId, ouiaSafe);
  const grid2 = (_b = stylesGrid2.modifiers) === null || _b === void 0 ? void 0 : _b[toCamel2(gridBreakPoint || "").replace(/-?2xl/, "_2xl")];
  const breakPointPrefix = `treeView${gridBreakPoint.charAt(0).toUpperCase() + gridBreakPoint.slice(1)}`;
  const treeGrid = (_c = stylesTreeView.modifiers) === null || _c === void 0 ? void 0 : _c[toCamel2(breakPointPrefix || "").replace(/-?2xl/, "_2xl")];
  const handleKeys = (event) => {
    if (isNested || !(tableRef && tableRef.current && tableRef.current.classList.contains("pf-m-tree-view")) || tableRef && tableRef.current !== event.target.closest(".pf-c-table:not(.pf-m-nested)")) {
      return;
    }
    const activeElement = document.activeElement;
    const key = event.key;
    const rows = Array.from(tableRef.current.querySelectorAll("tbody tr")).filter((el) => !el.classList.contains("pf-m-disabled") && !el.hidden);
    if (key === "Space" || key === "Enter") {
      activeElement.click();
      event.preventDefault();
    }
    const getFocusableElement = (element) => element.querySelectorAll("button:not(:disabled), input:not(:disabled), a:not(:disabled)")[0];
    handleArrows(event, rows, (element) => element === activeElement.closest("tr"), getFocusableElement, ["button", "input", "a"], void 0, false, true, false);
  };
  return react.createElement("table", Object.assign({"aria-label": ariaLabel, role, className: css(className, styles5.table, isTreeTable ? treeGrid : grid2, styles5.modifiers[variant], !borders && styles5.modifiers.noBorderRows, isStickyHeader && styles5.modifiers.stickyHeader, isTreeTable && stylesTreeView.modifiers.treeView, isNested && "pf-m-nested"), ref: tableRef}, isTreeTable && {role: "treegrid"}, ouiaProps, props), nestedHeaderColumnSpans && nestedHeaderColumnSpans.map((span, index3) => {
    if (span === 1) {
      return react.createElement("col", {key: index3});
    } else {
      return react.createElement("colgroup", {key: index3, span});
    }
  }), children2);
};
var TableComposable = react.forwardRef((props, ref) => react.createElement(TableComposableBase, Object.assign({}, props, {innerRef: ref})));
TableComposable.displayName = "TableComposable";
var TheadBase = (_a) => {
  var {children: children2, className, noWrap = false, innerRef, hasNestedHeader} = _a, props = __rest(_a, ["children", "className", "noWrap", "innerRef", "hasNestedHeader"]);
  return react.createElement("thead", Object.assign({className: css(className, noWrap && styles5.modifiers.nowrap, hasNestedHeader && styles5.modifiers.nestedColumnHeader), ref: innerRef}, props), children2);
};
var Thead = react.forwardRef((props, ref) => react.createElement(TheadBase, Object.assign({}, props, {innerRef: ref})));
Thead.displayName = "Thead";
var TbodyBase = (_a) => {
  var {children: children2, className, isExpanded, innerRef} = _a, props = __rest(_a, ["children", "className", "isExpanded", "innerRef"]);
  return react.createElement("tbody", Object.assign({role: "rowgroup", className: css(className, isExpanded && styles5.modifiers.expanded), ref: innerRef}, props), children2);
};
var Tbody = react.forwardRef((props, ref) => react.createElement(TbodyBase, Object.assign({}, props, {innerRef: ref})));
Tbody.displayName = "Tbody";
var TrBase = (_a) => {
  var {children: children2, className, isExpanded, isEditable, isHidden: isHidden3 = false, isHoverable = false, isRowSelected = false, innerRef, ouiaId, ouiaSafe = true, resetOffset = false, onRowClick} = _a, props = __rest(_a, ["children", "className", "isExpanded", "isEditable", "isHidden", "isHoverable", "isRowSelected", "innerRef", "ouiaId", "ouiaSafe", "resetOffset", "onRowClick"]);
  const ouiaProps = useOUIAProps("TableRow", ouiaId, ouiaSafe);
  let onKeyDown = null;
  if (onRowClick) {
    onKeyDown = (e2) => {
      if (e2.key === "Enter" || e2.key === " ") {
        onRowClick(e2);
        e2.preventDefault();
      }
    };
  }
  return react.createElement("tr", Object.assign({className: css(className, isExpanded !== void 0 && styles5.tableExpandableRow, isExpanded && styles5.modifiers.expanded, isEditable && inlineStyles.modifiers.inlineEditable, isHoverable && styles5.modifiers.hoverable, isRowSelected && styles5.modifiers.selected, resetOffset && styles5.modifiers.firstCellOffsetReset), hidden: isHidden3 || isExpanded !== void 0 && !isExpanded}, isHoverable && {tabIndex: 0}, {ref: innerRef}, onRowClick && {onClick: onRowClick, onKeyDown}, ouiaProps, props), children2);
};
var Tr = react.forwardRef((props, ref) => react.createElement(TrBase, Object.assign({}, props, {innerRef: ref})));
Tr.displayName = "Tr";
var tableScrollable = createCommonjsModule(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = {
    modifiers: {
      borderRight: "pf-m-border-right",
      borderLeft: "pf-m-border-left",
      stickyHeader: "pf-m-sticky-header"
    },
    scrollInnerWrapper: "pf-c-scroll-inner-wrapper",
    scrollOuterWrapper: "pf-c-scroll-outer-wrapper",
    table: "pf-c-table",
    tableStickyColumn: "pf-c-table__sticky-column"
  };
});
var styles$14 = /* @__PURE__ */ getDefaultExportFromCjs(tableScrollable);
var TableTextVariant;
(function(TableTextVariant2) {
  TableTextVariant2["div"] = "div";
  TableTextVariant2["nav"] = "nav";
})(TableTextVariant || (TableTextVariant = {}));
var WrapModifier;
(function(WrapModifier2) {
  WrapModifier2["wrap"] = "wrap";
  WrapModifier2["nowrap"] = "nowrap";
  WrapModifier2["truncate"] = "truncate";
  WrapModifier2["breakWord"] = "breakWord";
  WrapModifier2["fitContent"] = "fitContent";
})(WrapModifier || (WrapModifier = {}));
var TableText = (_a) => {
  var {children: children2 = null, className = "", variant = "span", wrapModifier = null, tooltip: tooltipProp = "", tooltipProps = {}, onMouseEnter: onMouseEnterProp = () => {
  }} = _a, props = __rest(_a, ["children", "className", "variant", "wrapModifier", "tooltip", "tooltipProps", "onMouseEnter"]);
  const Component = variant;
  const [tooltip2, setTooltip] = react.useState("");
  const onMouseEnter = (event) => {
    if (event.target.offsetWidth < event.target.scrollWidth) {
      setTooltip(tooltipProp || event.target.innerText);
    } else {
      setTooltip("");
    }
    onMouseEnterProp(event);
  };
  const text = react.createElement(Component, Object.assign({onMouseEnter, className: css(className, wrapModifier && styles5.modifiers[wrapModifier], styles5.tableText)}, props), children2);
  return tooltip2 !== "" ? react.createElement(Tooltip, Object.assign({content: tooltip2, isVisible: true}, tooltipProps), text) : text;
};
TableText.displayName = "TableText";
var HeaderCellInfoWrapper = ({children: children2, info: info2, className, variant = "tooltip", popoverProps, tooltipProps, ariaLabel}) => react.createElement("div", {className: css(styles5.tableColumnHelp, className)}, typeof children2 === "string" ? react.createElement(TableText, null, children2) : children2, react.createElement("span", {className: css(styles5.tableColumnHelpAction)}, variant === "tooltip" ? react.createElement(Tooltip, Object.assign({content: info2}, tooltipProps), react.createElement(Button, {variant: "plain", "aria-label": ariaLabel || typeof info2 === "string" && info2 || "More info"}, react.createElement(HelpIcon, {noVerticalAlign: true}))) : react.createElement(Popover, Object.assign({bodyContent: info2}, popoverProps), react.createElement(Button, {variant: "plain", "aria-label": ariaLabel || typeof info2 === "string" && info2 || "More info"}, react.createElement(HelpIcon, {noVerticalAlign: true})))));
HeaderCellInfoWrapper.displayName = "HeaderCellInfoWrapper";
var info = ({tooltip: tooltip2, tooltipProps, popover: popover2, popoverProps, className, ariaLabel}) => {
  const infoObj = (value) => ({
    className: styles5.modifiers.help,
    children: tooltip2 ? react.createElement(HeaderCellInfoWrapper, {variant: "tooltip", info: tooltip2, tooltipProps, ariaLabel, className}, value) : react.createElement(HeaderCellInfoWrapper, {variant: "popover", info: popover2, popoverProps, ariaLabel, className}, value)
  });
  return infoObj;
};
var SortByDirection;
(function(SortByDirection2) {
  SortByDirection2["asc"] = "asc";
  SortByDirection2["desc"] = "desc";
})(SortByDirection || (SortByDirection = {}));
var SortColumn = (_a) => {
  var {children: children2 = null, className = "", isSortedBy = false, onSort = null, sortDirection = "", type = "button"} = _a, props = __rest(_a, ["children", "className", "isSortedBy", "onSort", "sortDirection", "type"]);
  let SortedByIcon;
  if (isSortedBy) {
    SortedByIcon = sortDirection === SortByDirection.asc ? LongArrowAltUpIcon : LongArrowAltDownIcon;
  } else {
    SortedByIcon = ArrowsAltVIcon;
  }
  return react.createElement("button", Object.assign({}, props, {type, className: css(className, styles5.tableButton), onClick: (event) => onSort && onSort(event)}), react.createElement("div", {className: css(className, styles5.tableButtonContent)}, react.createElement(TableText, null, children2), react.createElement("span", {className: css(styles5.tableSortIndicator)}, react.createElement(SortedByIcon, null))));
};
SortColumn.displayName = "SortColumn";
var sortableFavorites = (sort2) => () => sortable(react.createElement(StarIcon, {"aria-hidden": true}), {
  columnIndex: sort2.columnIndex,
  className: styles5.modifiers.favorite,
  ariaLabel: "Sort favorites",
  column: {
    extraParams: {
      sortBy: sort2.sortBy,
      onSort: sort2 === null || sort2 === void 0 ? void 0 : sort2.onSort
    }
  }
});
var sortable = (label2, {columnIndex, column, property: property2, className, ariaLabel}) => {
  const {extraParams: {sortBy: sortBy3, onSort}} = column;
  const extraData = {
    columnIndex,
    column,
    property: property2
  };
  const isSortedBy = sortBy3 && columnIndex === sortBy3.index;
  function sortClicked(event) {
    let reversedDirection;
    if (!isSortedBy) {
      reversedDirection = sortBy3.defaultDirection ? sortBy3.defaultDirection : SortByDirection.asc;
    } else {
      reversedDirection = sortBy3.direction === SortByDirection.asc ? SortByDirection.desc : SortByDirection.asc;
    }
    onSort && onSort(event, columnIndex, reversedDirection, extraData);
  }
  return {
    className: css(styles5.tableSort, isSortedBy && styles5.modifiers.selected, className),
    "aria-sort": isSortedBy ? `${sortBy3.direction}ending` : "none",
    children: react.createElement(SortColumn, {isSortedBy, sortDirection: isSortedBy ? sortBy3.direction : "", onSort: sortClicked, "aria-label": ariaLabel}, label2)
  };
};
var RowSelectVariant;
(function(RowSelectVariant2) {
  RowSelectVariant2["radio"] = "radio";
  RowSelectVariant2["checkbox"] = "checkbox";
})(RowSelectVariant || (RowSelectVariant = {}));
var SelectColumn = (_a) => {
  var {
    children: children2 = null,
    className,
    onSelect = null,
    selectVariant
  } = _a, props = __rest(_a, ["children", "className", "onSelect", "selectVariant"]);
  return react.createElement(react.Fragment, null, react.createElement("input", Object.assign({}, props, {type: selectVariant, onChange: onSelect})), children2);
};
SelectColumn.displayName = "SelectColumn";
var selectable = (label2, {rowIndex, columnIndex, rowData, column, property: property2}) => {
  const {extraParams: {onSelect, selectVariant, allRowsSelected, isHeaderSelectDisabled}} = column;
  const extraData = {
    rowIndex,
    columnIndex,
    column,
    property: property2
  };
  if (rowData && rowData.hasOwnProperty("parent") && !rowData.showSelect && !rowData.fullWidth) {
    return {
      component: "td",
      isVisible: true
    };
  }
  const rowId = rowIndex !== void 0 ? rowIndex : -1;
  function selectClick(event) {
    const selected = rowIndex === void 0 ? event.currentTarget.checked : rowData && !rowData.selected;
    onSelect && onSelect(event, selected, rowId, rowData, extraData);
  }
  const customProps = Object.assign(Object.assign(Object.assign({}, rowId !== -1 ? {
    checked: rowData && !!rowData.selected,
    "aria-label": `Select row ${rowIndex}`
  } : {
    checked: allRowsSelected,
    "aria-label": "Select all rows"
  }), rowData && (rowData.disableCheckbox || rowData.disableSelection) && {
    disabled: true,
    className: checkStyles.checkInput
  }), !rowData && isHeaderSelectDisabled && {disabled: true});
  let selectName = "check-all";
  if (rowId !== -1 && selectVariant === RowSelectVariant.checkbox) {
    selectName = `checkrow${rowIndex}`;
  } else if (rowId !== -1) {
    selectName = "radioGroup";
  }
  return {
    className: css(styles5.tableCheck),
    component: "td",
    isVisible: !rowData || !rowData.fullWidth,
    children: react.createElement(SelectColumn, Object.assign({}, customProps, {selectVariant, onSelect: selectClick, name: selectName}), label2)
  };
};
var cellWidth = (width2) => () => ({
  className: css(styles5.modifiers[typeof width2 === "number" ? `width_${width2}` : `width${capitalize4(width2)}`])
});
var visibilityModifiers = [
  "hidden",
  "hiddenOnSm",
  "hiddenOnMd",
  "hiddenOnLg",
  "hiddenOnXl",
  "hiddenOn_2xl",
  "visibleOnSm",
  "visibleOnMd",
  "visibleOnLg",
  "visibleOnXl",
  "visibleOn_2xl"
];
var Visibility = visibilityModifiers.filter((key) => styles5.modifiers[key]).reduce((acc, curr) => {
  const key2 = curr.replace("_2xl", "2Xl");
  acc[key2] = styles5.modifiers[curr];
  return acc;
}, {});
var classNames = (...classes) => () => ({
  className: css(...classes)
});
var mergeWith = _createAssigner(function(object, source2, srcIndex, customizer) {
  _baseMerge(object, source2, srcIndex, customizer);
});
var mergeWith_1 = mergeWith;
function mergeProps2(...props) {
  const firstProps = props[0];
  const restProps = props.slice(1);
  if (!restProps.length) {
    return mergeWith_1({}, firstProps);
  }
  return mergeWith_1(mergeWith_1({}, firstProps), ...restProps, (a2, b2, key) => {
    if (key === "children") {
      if (a2 && b2) {
        return react.cloneElement(a2, {
          children: b2
        });
      }
      return Object.assign(Object.assign({}, b2), a2);
    }
    if (key === "className") {
      return css(a2, b2);
    }
    return void 0;
  });
}
var ThBase = (_a) => {
  var {children: children2, className, component = "th", dataLabel, scope = "col", textCenter = false, sort: sort2 = null, modifier, select: select3 = null, tooltip: tooltip2 = "", onMouseEnter: onMouseEnterProp = () => {
  }, width: width2, visibility, innerRef, info: infoProps, isStickyColumn = false, hasRightBorder = false, stickyMinWidth = "120px", stickyLeftOffset, isSubheader = false} = _a, props = __rest(_a, ["children", "className", "component", "dataLabel", "scope", "textCenter", "sort", "modifier", "select", "tooltip", "onMouseEnter", "width", "visibility", "innerRef", "info", "isStickyColumn", "hasRightBorder", "stickyMinWidth", "stickyLeftOffset", "isSubheader"]);
  const [showTooltip, setShowTooltip] = react.useState(false);
  const onMouseEnter = (event) => {
    if (event.target.offsetWidth < event.target.scrollWidth) {
      !showTooltip && setShowTooltip(true);
    } else {
      showTooltip && setShowTooltip(false);
    }
    onMouseEnterProp(event);
  };
  let sortParams = null;
  if (sort2) {
    if (sort2.isFavorites) {
      sortParams = sortableFavorites({
        onSort: sort2 === null || sort2 === void 0 ? void 0 : sort2.onSort,
        columnIndex: sort2.columnIndex,
        sortBy: sort2.sortBy
      })();
    } else {
      sortParams = sortable(children2, {
        columnIndex: sort2.columnIndex,
        column: {
          extraParams: {
            sortBy: sort2.sortBy,
            onSort: sort2 === null || sort2 === void 0 ? void 0 : sort2.onSort
          }
        }
      });
    }
  }
  const selectParams = select3 ? selectable(children2, {
    column: {
      extraParams: {
        onSelect: select3 === null || select3 === void 0 ? void 0 : select3.onSelect,
        selectVariant: "checkbox",
        allRowsSelected: select3.isSelected,
        isHeaderSelectDisabled: !!select3.isHeaderSelectDisabled
      }
    }
  }) : null;
  const widthParams = width2 ? cellWidth(width2)() : null;
  const visibilityParams = visibility ? classNames(...visibility.map((vis) => Visibility[vis]))() : null;
  let transformedChildren = (sortParams === null || sortParams === void 0 ? void 0 : sortParams.children) || (selectParams === null || selectParams === void 0 ? void 0 : selectParams.children) || children2;
  let infoParams = null;
  if (infoProps) {
    infoParams = info(infoProps)(transformedChildren);
    transformedChildren = infoParams.children;
  }
  const merged = mergeProps2(sortParams, selectParams, widthParams, visibilityParams, infoParams);
  const {
    children: mergedChildren = null,
    isVisible = null,
    className: mergedClassName = "",
    component: MergedComponent = component
  } = merged, mergedProps = __rest(merged, ["children", "isVisible", "className", "component"]);
  const cell = react.createElement(MergedComponent, Object.assign({"data-label": dataLabel, onMouseEnter: tooltip2 !== null ? onMouseEnter : onMouseEnterProp, scope: component === "th" && children2 ? scope : null, ref: innerRef, className: css(className, textCenter && styles5.modifiers.center, isSubheader && styles5.tableSubhead, isStickyColumn && styles$14.tableStickyColumn, hasRightBorder && styles$14.modifiers.borderRight, modifier && styles5.modifiers[modifier], mergedClassName)}, mergedProps, props, isStickyColumn && {
    style: Object.assign({"--pf-c-table__sticky-column--MinWidth": stickyMinWidth ? stickyMinWidth : void 0, "--pf-c-table__sticky-column--Left": stickyLeftOffset ? stickyLeftOffset : void 0}, props.style)
  }), transformedChildren);
  const canDefault = tooltip2 === "" ? typeof children2 === "string" : true;
  return tooltip2 !== null && canDefault && showTooltip ? react.createElement(Tooltip, {content: tooltip2 || tooltip2 === "" && children2, isVisible: true}, cell) : cell;
};
var Th2 = react.forwardRef((props, ref) => react.createElement(ThBase, Object.assign({}, props, {innerRef: ref})));
Th2.displayName = "Th";
var ActionsColumn = class extends react.Component {
  constructor(props) {
    super(props);
    this.toggleRef = react.createRef();
    this.onToggle = (isOpen) => {
      this.setState({
        isOpen
      });
    };
    this.onClick = (event, onClick) => {
      const {rowData, extraData} = this.props;
      if (onClick) {
        event.preventDefault();
        onClick(event, extraData && extraData.rowIndex, rowData, extraData);
      }
    };
    this.state = {
      isOpen: false
    };
  }
  render() {
    const {isOpen} = this.state;
    const {items, children: children2, dropdownPosition, dropdownDirection, isDisabled, rowData, actionsToggle} = this.props;
    const actionsToggleClone = actionsToggle ? actionsToggle({onToggle: this.onToggle, isOpen, isDisabled}) : react.createElement(KebabToggle, {isDisabled, onToggle: this.onToggle});
    return react.createElement(react.Fragment, null, items.filter((item) => item.isOutsideDropdown).map((_a, key) => {
      var {title: title3, itemKey, onClick, isOutsideDropdown} = _a, props = __rest(_a, ["title", "itemKey", "onClick", "isOutsideDropdown"]);
      return typeof title3 === "string" ? react.createElement(Button, Object.assign({onClick: (event) => this.onClick(event, onClick)}, props, {isDisabled, key: itemKey || `outside_dropdown_${key}`, "data-key": itemKey || `outside_dropdown_${key}`}), title3) : react.cloneElement(title3, Object.assign({onClick, isDisabled}, props));
    }), react.createElement(Dropdown, Object.assign({toggle: actionsToggleClone, position: dropdownPosition, direction: dropdownDirection, isOpen, dropdownItems: items.filter((item) => !item.isOutsideDropdown).map((_a, key) => {
      var {title: title3, itemKey, onClick, isSeparator} = _a, props = __rest(_a, ["title", "itemKey", "onClick", "isSeparator"]);
      return isSeparator ? react.createElement(DropdownSeparator, Object.assign({}, props, {key: itemKey || key, "data-key": itemKey || key})) : react.createElement(DropdownItem, Object.assign({component: "button", onClick: (event) => {
        this.onClick(event, onClick);
        this.onToggle(!isOpen);
      }}, props, {key: itemKey || key, "data-key": itemKey || key}), title3);
    }), isPlain: true}, rowData && rowData.actionProps)), children2);
  }
};
ActionsColumn.displayName = "ActionsColumn";
ActionsColumn.defaultProps = {
  children: null,
  items: [],
  dropdownPosition: DropdownPosition.right,
  dropdownDirection: DropdownDirection.down,
  rowData: {},
  extraData: {}
};
var resolveOrDefault = (resolver, defaultValue, rowData, extraData) => typeof resolver === "function" ? resolver(rowData, extraData) : defaultValue;
var cellActions = (actions2, actionResolver, areActionsDisabled) => (label2, {rowData, column, rowIndex, columnIndex, column: {extraParams: {dropdownPosition, dropdownDirection, actionsToggle}}, property: property2}) => {
  const extraData = {
    rowIndex,
    columnIndex,
    column,
    property: property2
  };
  const resolvedActions = resolveOrDefault(actionResolver, actions2, rowData, extraData);
  const resolvedIsDisabled = resolveOrDefault(areActionsDisabled, rowData && rowData.disableActions, rowData, extraData);
  const renderProps = resolvedActions && resolvedActions.length > 0 ? {
    children: react.createElement(ActionsColumn, {items: resolvedActions, dropdownPosition, dropdownDirection, isDisabled: resolvedIsDisabled, rowData, extraData, actionsToggle}, label2)
  } : {};
  return Object.assign({className: css(styles5.tableAction), style: {width: "auto", paddingRight: 0}, isVisible: true}, renderProps);
};
var CollapseColumn = (_a) => {
  var {className = "", children: children2 = null, isOpen, onToggle} = _a, props = __rest(_a, ["className", "children", "isOpen", "onToggle"]);
  return react.createElement(react.Fragment, null, isOpen !== void 0 && react.createElement(Button, Object.assign({className: css(className, isOpen && styles5.modifiers.expanded)}, props, {variant: "plain", "aria-label": "Details", onClick: onToggle, "aria-expanded": isOpen}), react.createElement("div", {className: css(styles5.tableToggleIcon)}, react.createElement(AngleDownIcon, null))), children2);
};
CollapseColumn.displayName = "CollapseColumn";
var ExpandableRowContent = (_a) => {
  var {children: children2 = null} = _a, props = __rest(_a, ["children"]);
  return react.createElement("div", Object.assign({}, props, {className: css(styles5.tableExpandableRowContent)}), children2);
};
ExpandableRowContent.displayName = "ExpandableRowContent";
var collapsible = (value, {rowIndex, columnIndex, rowData, column, property: property2}) => {
  const {extraParams: {onCollapse, rowLabeledBy = "simple-node", expandId = "expand-toggle"}} = column;
  const extraData = {
    rowIndex,
    columnIndex,
    column,
    property: property2
  };
  function onToggle(event) {
    onCollapse && onCollapse(event, rowIndex, rowData && !rowData.isOpen, rowData, extraData);
  }
  return {
    className: rowData.isOpen !== void 0 && css(styles5.tableToggle),
    isVisible: !rowData.fullWidth,
    children: react.createElement(CollapseColumn, {"aria-labelledby": `${rowLabeledBy}${rowIndex} ${expandId}${rowIndex}`, onToggle, id: expandId + rowIndex, isOpen: rowData && rowData.isOpen}, value)
  };
};
var expandable = (value, {rowData}) => rowData && rowData.hasOwnProperty("parent") ? react.createElement(ExpandableRowContent, null, value) : value;
var expandedRow = (colSpan) => {
  const expandedRowFormatter = (value, {columnIndex, rowIndex, rowData, column: {extraParams: {contentId = "expanded-content"}}}) => value && rowData.hasOwnProperty("parent") && {
    colSpan: !rowData.cells || rowData.cells.length === 1 ? colSpan + !!rowData.fullWidth : 1,
    id: contentId + rowIndex + (columnIndex ? "-" + columnIndex : ""),
    className: rowData.noPadding && css(styles5.modifiers.noPadding)
  };
  return expandedRowFormatter;
};
var compoundExpand = (value, {rowIndex, columnIndex, rowData, column, property: property2}) => {
  if (!value) {
    return null;
  }
  const {title: title3, props} = value;
  const {extraParams: {onExpand}} = column;
  const extraData = {
    rowIndex,
    columnIndex,
    column,
    property: property2
  };
  function onToggle(event) {
    onExpand && onExpand(event, rowIndex, columnIndex, props.isOpen, rowData, extraData);
  }
  return {
    className: css(styles5.tableCompoundExpansionToggle, props.isOpen && styles5.modifiers.expanded),
    children: props.isOpen !== void 0 && react.createElement("button", {type: "button", className: css(styles5.tableButton), onClick: onToggle, "aria-expanded": props.isOpen, "aria-controls": props.ariaControls}, react.createElement(TableText, null, title3))
  };
};
var FavoritesCell = (_a) => {
  var {className = "", onFavorite, isFavorited, rowIndex} = _a, props = __rest(_a, ["className", "onFavorite", "isFavorited", "rowIndex"]);
  const ariaProps = rowIndex === void 0 ? {} : {
    id: `favorites-button-${rowIndex}`,
    "aria-labelledby": `favorites-button-${rowIndex}`
  };
  return react.createElement(Button, Object.assign({variant: "plain", className, type: "button", "aria-label": isFavorited ? "Starred" : "Not starred", onClick: onFavorite}, ariaProps, props), react.createElement(StarIcon, {"aria-hidden": true}));
};
FavoritesCell.displayName = "FavoritesCell";
var favoritable = (value, {rowIndex, columnIndex, rowData, column, property: property2}) => {
  const {extraParams: {onFavorite}} = column;
  const extraData = {
    rowIndex,
    columnIndex,
    column,
    property: property2
  };
  if (rowData && rowData.hasOwnProperty("parent") && !rowData.fullWidth) {
    return {
      component: "td",
      isVisible: true
    };
  }
  function favoritesClick(event) {
    onFavorite && onFavorite(event, rowData && !rowData.favorited, rowIndex, rowData, extraData);
  }
  const additionalProps = rowData.favoritesProps || {};
  return {
    className: css(styles5.tableFavorite, rowData && rowData.favorited && styles5.modifiers.favorited),
    isVisible: !rowData || !rowData.fullWidth,
    children: react.createElement(FavoritesCell, Object.assign({rowIndex, onFavorite: favoritesClick, isFavorited: rowData && rowData.favorited}, additionalProps))
  };
};
var DraggableCell = (_a) => {
  var {className, onClick, "aria-label": ariaLabel, id: id3} = _a, props = __rest(_a, ["className", "onClick", "aria-label", "id"]);
  return react.createElement(Button, Object.assign({id: id3, variant: "plain", className, type: "button", "aria-label": ariaLabel || `Draggable row draggable button`, onClick}, props), react.createElement(GripVerticalIcon, {"aria-hidden": true}));
};
DraggableCell.displayName = "DraggableCell";
var draggable = (value, {rowData}) => {
  const {id: id3} = rowData;
  return {
    className: "",
    children: react.createElement(DraggableCell, {id: id3})
  };
};
var treeRow = (onCollapse, onCheckChange, onToggleRowDetails) => (value, {rowIndex, rowData}) => {
  const {isExpanded, isDetailsExpanded, "aria-level": level2, "aria-setsize": setsize, toggleAriaLabel, checkAriaLabel, showDetailsAriaLabel, isChecked, checkboxId, icon} = rowData.props;
  const content2 = value.title || value;
  const text = react.createElement("div", {className: css(stylesTreeView.tableTreeViewText), key: "tree-view-text"}, icon && react.createElement("span", {className: css(stylesTreeView.tableTreeViewIcon), key: "tree-view-text-icon"}, icon), react.createElement("span", {className: "pf-c-table__text", key: "table-text"}, content2));
  const onChange = (isChecked2, event) => {
    onCheckChange(event, isChecked2, rowIndex, content2, rowData);
  };
  return {
    component: "th",
    className: "pf-c-table__tree-view-title-cell",
    children: level2 !== void 0 ? react.createElement("div", {className: css(stylesTreeView.tableTreeViewMain)}, setsize > 0 && react.createElement("span", {className: css(stylesTreeView.tableToggle), key: "table-toggle"}, react.createElement(Button, {variant: "plain", onClick: (event) => onCollapse && onCollapse(event, rowIndex, content2, rowData), className: css(isExpanded && styles5.modifiers.expanded), "aria-expanded": isExpanded, "aria-label": toggleAriaLabel || `${isExpanded ? "Collapse" : "Expand"} row ${rowIndex}`}, react.createElement("div", {className: css(stylesTreeView.tableToggleIcon)}, react.createElement(AngleDownIcon, {"aria-hidden": "true"})))), !!onCheckChange && react.createElement("span", {className: css(stylesTreeView.tableCheck), key: "table-check"}, react.createElement(Checkbox, {id: checkboxId || `checkbox_${rowIndex}`, "aria-label": checkAriaLabel || `Row ${rowIndex} checkbox`, isChecked, onChange})), text, !!onToggleRowDetails && react.createElement("span", {className: css(stylesTreeView.tableTreeViewDetailsToggle), key: "view-details-toggle"}, react.createElement(Button, {variant: "plain", "aria-expanded": isDetailsExpanded, "aria-label": showDetailsAriaLabel || "Show row details", onClick: (event) => onToggleRowDetails && onToggleRowDetails(event, rowIndex, content2, rowData)}, react.createElement("span", {className: "pf-c-table__details-toggle-icon"}, react.createElement(EllipsisHIcon, {"aria-hidden": true}))))) : text
  };
};
var TdBase = (_a) => {
  var {children: children2, className, component = "td", dataLabel, textCenter = false, modifier, select: select3 = null, actions: actions2 = null, expand = null, treeRow: treeRowProp = null, compoundExpand: compoundExpandProp = null, noPadding, width: width2, visibility, innerRef, favorites = null, draggableRow: draggableRowProp = null} = _a, props = __rest(_a, ["children", "className", "component", "dataLabel", "textCenter", "modifier", "select", "actions", "expand", "treeRow", "compoundExpand", "noPadding", "width", "visibility", "innerRef", "favorites", "draggableRow"]);
  const selectParams = select3 ? selectable(children2, {
    rowIndex: select3.rowIndex,
    rowData: {
      selected: select3.isSelected,
      disableSelection: select3 === null || select3 === void 0 ? void 0 : select3.disable,
      props: select3 === null || select3 === void 0 ? void 0 : select3.props
    },
    column: {
      extraParams: {
        onSelect: select3 === null || select3 === void 0 ? void 0 : select3.onSelect,
        selectVariant: select3.variant || "checkbox"
      }
    }
  }) : null;
  const favoriteParams = favorites ? favoritable(null, {
    rowIndex: favorites === null || favorites === void 0 ? void 0 : favorites.rowIndex,
    rowData: {
      favorited: favorites.isFavorited,
      favoritesProps: favorites === null || favorites === void 0 ? void 0 : favorites.props
    },
    column: {
      extraParams: {
        onFavorite: favorites === null || favorites === void 0 ? void 0 : favorites.onFavorite
      }
    }
  }) : null;
  const draggableParams = draggableRowProp !== null ? draggable(null, {
    rowData: {
      id: draggableRowProp.id
    }
  }) : null;
  const actionParamsFunc = actions2 ? cellActions(actions2.items, null, null) : null;
  const actionParams = actionParamsFunc ? actionParamsFunc(null, {
    rowData: {
      disableActions: actions2 === null || actions2 === void 0 ? void 0 : actions2.disable
    },
    column: {
      extraParams: {
        dropdownPosition: actions2 === null || actions2 === void 0 ? void 0 : actions2.dropdownPosition,
        dropdownDirection: actions2 === null || actions2 === void 0 ? void 0 : actions2.dropdownDirection,
        actionsToggle: actions2 === null || actions2 === void 0 ? void 0 : actions2.actionsToggle
      }
    }
  }) : null;
  const expandableParams = expand !== null ? collapsible(null, {
    rowIndex: expand.rowIndex,
    columnIndex: expand === null || expand === void 0 ? void 0 : expand.columnIndex,
    rowData: {
      isOpen: expand.isExpanded
    },
    column: {
      extraParams: {
        onCollapse: expand === null || expand === void 0 ? void 0 : expand.onToggle
      }
    }
  }) : null;
  const compoundParams = compoundExpandProp !== null ? compoundExpand({
    title: children2,
    props: {
      isOpen: compoundExpandProp.isExpanded
    }
  }, {
    column: {
      extraParams: {
        onExpand: compoundExpandProp === null || compoundExpandProp === void 0 ? void 0 : compoundExpandProp.onToggle
      }
    }
  }) : null;
  const widthParams = width2 ? cellWidth(width2)() : null;
  const visibilityParams = visibility ? classNames(...visibility.map((vis) => Visibility[vis]))() : null;
  const treeRowParams = treeRowProp !== null ? treeRow(treeRowProp.onCollapse, treeRowProp.onCheckChange, treeRowProp.onToggleRowDetails)({
    title: children2
  }, {
    rowIndex: treeRowProp.rowIndex,
    rowData: {
      props: treeRowProp.props
    }
  }) : null;
  const merged = mergeProps2(selectParams, actionParams, expandableParams, compoundParams, widthParams, visibilityParams, favoriteParams, treeRowParams, draggableParams);
  const {
    isVisible = null,
    children: mergedChildren = null,
    className: mergedClassName = "",
    component: MergedComponent = component
  } = merged, mergedProps = __rest(merged, ["isVisible", "children", "className", "component"]);
  const treeTableTitleCell = className && className.includes("pf-c-table__tree-view-title-cell") || mergedClassName && mergedClassName.includes("pf-c-table__tree-view-title-cell");
  return react.createElement(MergedComponent, Object.assign({}, !treeTableTitleCell && {"data-label": dataLabel}, {className: css(className, textCenter && styles5.modifiers.center, noPadding && styles5.modifiers.noPadding, styles5.modifiers[modifier], draggableParams && styles5.tableDraggable, mergedClassName), ref: innerRef}, mergedProps, props), mergedChildren || children2);
};
var Td2 = react.forwardRef((props, ref) => react.createElement(TdBase, Object.assign({}, props, {innerRef: ref})));
Td2.displayName = "Td";
var TableDefaults = {
  renderers: {
    table: TableComposable,
    header: {
      wrapper: Thead,
      row: Tr,
      cell: Th2
    },
    body: {
      wrapper: Tbody,
      row: Tr,
      cell: Td2
    }
  }
};
var ProviderContext = react.createContext({
  columns: null,
  renderers: null
});
var Provider = class extends react.Component {
  render() {
    const _a = this.props, {columns, renderers, components: components3, children: children2} = _a, props = __rest(_a, ["columns", "renderers", "components", "children"]);
    let finalRenderers = renderers;
    if (components3) {
      console.warn("`components` have been deprecated in favor of `renderers` and will be removed in the next major version, please rename!");
      finalRenderers = components3;
    }
    const provider = react.createElement(renderers.table || TableDefaults.renderers.table, props, children2);
    return react.createElement(ProviderContext.Provider, {value: {
      columns,
      renderers: {
        table: finalRenderers.table || TableDefaults.renderers.table,
        header: Object.assign(Object.assign({}, TableDefaults.renderers.header), finalRenderers.header),
        body: Object.assign(Object.assign({}, TableDefaults.renderers.body), finalRenderers.body)
      }
    }}, provider);
  }
};
Provider.displayName = "Provider";
Provider.defaultProps = {
  renderers: TableDefaults.renderers
};
function evaluateFormatters(formatters) {
  return (value, extra) => formatters.reduce((parameters, formatter) => ({
    value: formatter(parameters.value, parameters.extra),
    extra
  }), {value, extra}).value;
}
function evaluateTransforms(transforms = [], value, extraParameters = {}) {
  if (transforms.length === 0) {
    return {};
  }
  return mergeProps2(...transforms.map((transform3) => transform3(value, extraParameters)));
}
var HeaderRow = ({rowData, rowIndex, renderers, onRow = () => ({})}) => react.createElement(renderers.row, onRow(rowData, {rowIndex}), rowData.map((column, columnIndex) => {
  const {property: property2, header = {}, props = {}} = column;
  const evaluatedProperty = property2 || header && header.property;
  const {label: label2, transforms = [], formatters = [], info: info2 = {}} = header;
  const extraParameters = {
    columnIndex,
    property: evaluatedProperty,
    column
  };
  const transformedProps = evaluateTransforms(transforms, label2, extraParameters);
  if (!transformedProps) {
    console.warn("Table.Header - Failed to receive a transformed result");
  }
  let cellNode;
  const {tooltip: tooltip2, tooltipProps, popover: popover2, popoverProps, ariaLabel, className} = info2;
  if (tooltip2) {
    cellNode = react.createElement(HeaderCellInfoWrapper, {variant: "tooltip", info: tooltip2, tooltipProps, ariaLabel, className}, transformedProps.children || evaluateFormatters(formatters)(label2, extraParameters));
  } else if (popover2) {
    cellNode = react.createElement(HeaderCellInfoWrapper, {variant: "popover", info: popover2, popoverProps, ariaLabel, className}, transformedProps.children || evaluateFormatters(formatters)(label2, extraParameters));
  } else {
    cellNode = transformedProps.children || evaluateFormatters(formatters)(label2, extraParameters);
  }
  return react.createElement(renderers.cell, Object.assign({key: `${columnIndex}-header`}, mergeProps2(props, header && header.props, transformedProps)), cellNode);
}));
HeaderRow.displayName = "HeaderRow";
var BaseHeader = class extends react.Component {
  render() {
    const _a = this.props, {children: children2, headerRows, onRow, renderers, columns} = _a, props = __rest(_a, ["children", "headerRows", "onRow", "renderers", "columns"]);
    return react.createElement(renderers.header.wrapper, props, [
      (headerRows || [columns]).map((rowData, rowIndex) => react.createElement(HeaderRow, {
        key: `${rowIndex}-header-row`,
        renderers: renderers.header,
        onRow,
        rowData,
        rowIndex
      }))
    ].concat(children2));
  }
};
var Header2 = (props) => react.createElement(ProviderContext.Consumer, null, ({columns, renderers}) => react.createElement(BaseHeader, Object.assign({columns, renderers}, props)));
function isEqual3(value, other) {
  return _baseIsEqual(value, other);
}
var isEqual_1 = isEqual3;
function resolveRowKey({rowData, rowIndex, rowKey}) {
  if (typeof rowKey === "function") {
    return `${rowKey({rowData, rowIndex})}-row`;
  }
  if (rowData[rowKey] === 0) {
    return `${rowData[rowKey]}-row`;
  }
  return `${rowData[rowKey] || rowIndex}-row`;
}
function isEqualWith(value, other, customizer) {
  customizer = typeof customizer == "function" ? customizer : void 0;
  var result = customizer ? customizer(value, other) : void 0;
  return result === void 0 ? _baseIsEqual(value, other, void 0, customizer) : !!result;
}
var isEqualWith_1 = isEqualWith;
function columnsAreEqual(oldColumns, newColumns) {
  return isEqualWith_1(oldColumns, newColumns, (a2, b2) => {
    if (typeof a2 === "function" && typeof b2 === "function") {
      return a2 === b2;
    }
    return void 0;
  });
}
var BodyRow = class extends react.Component {
  shouldComponentUpdate(nextProps) {
    const {columns, rowData} = this.props;
    const {renderers} = nextProps;
    if (renderers && renderers.row && renderers.row.shouldComponentUpdate) {
      if (typeof renderers.row.shouldComponentUpdate === "function") {
        return renderers.row.shouldComponentUpdate.call(this, nextProps, {}, {});
      }
      return true;
    }
    return !(columnsAreEqual(columns, nextProps.columns) && isEqual_1(rowData, nextProps.rowData));
  }
  render() {
    const {columns, renderers, onRow, rowKey, rowIndex, rowData} = this.props;
    return react.createElement(renderers.row, onRow(rowData, {rowIndex, rowKey}), columns.map((column, columnIndex) => {
      const {property: property2, cell, props} = column;
      const evaluatedProperty = property2 || cell && cell.property;
      const {transforms = [], formatters = []} = cell || {};
      const extraParameters = {
        columnIndex,
        property: evaluatedProperty,
        column,
        rowData,
        rowIndex,
        rowKey
      };
      const transformed = evaluateTransforms(transforms, rowData[evaluatedProperty], extraParameters);
      if (!transformed) {
        console.warn("Table.Body - Failed to receive a transformed result");
      }
      let additionalFormaters = [];
      if (rowData[evaluatedProperty]) {
        additionalFormaters = rowData[evaluatedProperty].formatters;
      }
      return react.createElement(renderers.cell, Object.assign({key: `col-${columnIndex}-row-${rowIndex}`}, mergeProps2(props, cell && cell.props, transformed)), !rowData.fullWidth && transformed.children || evaluateFormatters([...formatters, ...additionalFormaters])(rowData[`_${evaluatedProperty}`] || rowData[evaluatedProperty], extraParameters));
    }));
  }
};
BodyRow.displayName = "BodyRow";
BodyRow.defaultProps = {
  onRow: (...args) => ({})
};
var BaseBody = class extends react.Component {
  constructor() {
    super(...arguments);
    this.omitOnRow = (props) => {
      const ret = __rest(props, ["onRow"]);
      return ret;
    };
  }
  shouldComponentUpdate(nextProps) {
    const {renderers} = nextProps;
    if (renderers && renderers.body && renderers.body.wrapper && renderers.body.wrapper.shouldComponentUpdate) {
      if (typeof renderers.body.wrapper.shouldComponentUpdate === "function") {
        return renderers.body.wrapper.shouldComponentUpdate.call(this, nextProps, {}, {});
      }
      return true;
    }
    return !isEqual_1(this.omitOnRow(this.props), this.omitOnRow(nextProps));
  }
  render() {
    const _a = this.props, {onRow, rows, rowKey, columns, renderers} = _a, props = __rest(_a, ["onRow", "rows", "rowKey", "columns", "renderers"]);
    const children2 = rows.map((rowData, index3) => {
      const key = resolveRowKey({rowData, rowIndex: index3, rowKey});
      return react.createElement(BodyRow, {
        key,
        renderers: renderers.body,
        onRow,
        rowKey: key,
        rowIndex: index3,
        rowData,
        columns
      });
    });
    return react.createElement(renderers.body.wrapper, props, children2);
  }
};
BaseBody.defaultProps = {
  onRow: (...args) => ({})
};
var Body = (props) => react.createElement(ProviderContext.Consumer, null, ({columns, renderers}) => react.createElement(BaseBody, Object.assign({columns, renderers}, props)));
var BodyCell = (_a) => {
  var {
    "data-label": dataLabel = "",
    className = "",
    colSpan,
    component = "td",
    isVisible,
    parentId: parentId2,
    textCenter = false,
    tooltip: tooltipProp = "",
    onMouseEnter: onMouseEnterProp = () => {
    },
    children: children2,
    errorText,
    isValid,
    isOpen,
    ariaControls,
    editableValue,
    editableSelectProps,
    options,
    isSelectOpen,
    value,
    name
  } = _a, props = __rest(_a, ["data-label", "className", "colSpan", "component", "isVisible", "parentId", "textCenter", "tooltip", "onMouseEnter", "children", "errorText", "isValid", "isOpen", "ariaControls", "editableValue", "editableSelectProps", "options", "isSelectOpen", "value", "name"]);
  const [tooltip2, setTooltip] = react.useState("");
  const onMouseEnter = (event) => {
    if (event.target.offsetWidth < event.target.scrollWidth) {
      if (tooltipProp) {
        setTooltip(tooltipProp);
      } else if (typeof children2 === "string") {
        setTooltip(children2);
      }
    } else {
      setTooltip("");
    }
    onMouseEnterProp(event);
  };
  let isEmptyStateCell = false;
  if (children2) {
    isEmptyStateCell = children2.type === Bullseye && children2.props.children && children2.props.children.type === EmptyState || children2.type === EmptyState;
  }
  const cell = react.createElement(Td2, Object.assign({className, component, dataLabel: dataLabel && parentId2 == null && !isEmptyStateCell ? dataLabel : null, onMouseEnter, textCenter, colSpan}, props), children2);
  const bodyCell = tooltip2 !== "" ? react.createElement(Tooltip, {content: tooltip2, isVisible: true}, cell) : cell;
  return parentId2 !== void 0 && colSpan === void 0 || !isVisible ? null : bodyCell;
};
BodyCell.displayName = "BodyCell";
var HeaderCell = (_a) => {
  var {
    className = "",
    component = "th",
    scope = "",
    textCenter = false,
    tooltip: tooltip2 = "",
    onMouseEnter = () => {
    },
    children: children2,
    isVisible,
    dataLabel = ""
  } = _a, props = __rest(_a, ["className", "component", "scope", "textCenter", "tooltip", "onMouseEnter", "children", "isVisible", "dataLabel"]);
  return react.createElement(Th2, Object.assign({}, props, {scope, tooltip: tooltip2, onMouseEnter, textCenter, component, className}), children2);
};
HeaderCell.displayName = "HeaderCell";
var RowWrapper = class extends react.Component {
  constructor(props) {
    super(props);
    this.handleScroll = (event) => {
      if (!this._unmounted) {
        this.props.onScroll(event);
      }
    };
    this.handleResize = (event) => {
      if (!this._unmounted) {
        this.props.onResize(event);
      }
    };
    if (props.onScroll) {
      this.handleScroll = debounce(this.handleScroll, 100);
    }
    if (props.onResize) {
      this.handleResize = debounce(this.handleResize, 100);
    }
  }
  componentDidMount() {
    this._unmounted = false;
    if (canUseDOM) {
      if (this.props.onScroll) {
        window.addEventListener("scroll", this.handleScroll);
      }
      if (this.props.onResize) {
        window.addEventListener("resize", this.handleResize);
      }
    }
  }
  componentWillUnmount() {
    this._unmounted = true;
    if (canUseDOM) {
      if (this.props.onScroll) {
        window.removeEventListener("scroll", this.handleScroll);
      }
      if (this.props.onResize) {
        window.removeEventListener("resize", this.handleResize);
      }
    }
  }
  render() {
    const _a = this.props, {
      onScroll,
      onResize,
      row: {isExpanded, isEditable, isHoverable, isRowSelected},
      rowProps,
      trRef,
      className,
      ouiaId
    } = _a, props = __rest(_a, ["onScroll", "onResize", "row", "rowProps", "trRef", "className", "ouiaId"]);
    return react.createElement(Tr, Object.assign({}, props, {ref: trRef, isExpanded, isEditable, className, ouiaId, isHoverable, isRowSelected}));
  }
};
RowWrapper.displayName = "RowWrapper";
RowWrapper.defaultProps = {
  className: "",
  row: {
    isOpen: void 0,
    isExpanded: void 0,
    isHeightAuto: void 0,
    isEditable: void 0
  },
  rowProps: null
};
var emptyTD = () => ({
  component: "td"
});
var scopeColTransformer = () => ({
  scope: "col"
});
var emptyCol = (label2) => Object.assign({}, label2 ? {} : {scope: ""});
var parentId = (_value, {rowData}) => ({
  parentId: rowData.parent
});
var mapProps = (_label, {property: property2, rowData}) => Object.assign({}, rowData[property2] && rowData[property2].props);
var EditColumn = (_a) => {
  var {
    onClick = null,
    className = "",
    editing,
    valid,
    saveAriaLabel,
    cancelAriaLabel,
    editAriaLabel
  } = _a, props = __rest(_a, ["onClick", "className", "editing", "valid", "saveAriaLabel", "cancelAriaLabel", "editAriaLabel"]);
  return react.createElement(react.Fragment, null, react.createElement("div", {className: css(inlineStyles.inlineEditGroup, inlineStyles.modifiers.iconGroup, "pf-m-action-group")}, react.createElement("div", {className: css(inlineStyles.inlineEditAction)}, react.createElement(Button, Object.assign({"aria-label": saveAriaLabel}, props, {onClick: (e2) => onClick(e2, "save"), variant: "plain"}), react.createElement(CheckIcon, null))), react.createElement("div", {className: css(inlineStyles.inlineEditAction)}, react.createElement(Button, Object.assign({"aria-label": cancelAriaLabel}, props, {onClick: (e2) => onClick(e2, "cancel"), variant: "plain"}), react.createElement(TimesIcon, null)))), react.createElement("div", {className: css(inlineStyles.inlineEditAction, inlineStyles.modifiers.enableEditable)}, react.createElement(Button, Object.assign({"aria-label": editAriaLabel}, props, {onClick: (e2) => onClick(e2, "edit"), variant: "plain"}), react.createElement(PencilAltIcon, null))));
};
EditColumn.displayName = "EditColumn";
var editable = (label2, {rowIndex, rowData, column}) => {
  const {extraParams: {onRowEdit}} = column;
  const toggleEditMode = (event, type) => {
    let validationErrors = {};
    if (type === "save") {
      validationErrors = rowData.rowEditValidationRules && rowData.rowEditValidationRules.reduce((acc, rule) => {
        const invalidCells = rowData.cells.filter((cellData) => {
          const testValue = cellData.props.editableValue === "" ? "" : cellData.props.editableValue || cellData.props.value;
          let failedValidation = false;
          if (Array.isArray(testValue) && testValue.length) {
            failedValidation = testValue.reduce((hasInvalidSelection, el) => {
              if (hasInvalidSelection === true) {
                return true;
              }
              return !rule.validator(el);
            }, failedValidation);
          } else if (Array.isArray(testValue) && !testValue.length) {
            failedValidation = !rule.validator("");
          } else {
            failedValidation = !rule.validator(testValue);
          }
          if (failedValidation) {
            cellData.props.isValid = false;
          }
          return failedValidation;
        });
        if (invalidCells.length) {
          acc[rule.name] = invalidCells.map((cell) => cell.props.name);
        }
        return acc;
      }, {});
    }
    onRowEdit(event, type, rowData && rowData.isEditable, rowIndex, validationErrors);
  };
  function getAriaLabelTxt(identifier, actionType) {
    let result;
    switch (actionType) {
      case "cancel":
        result = `Cancel row edits for row ${identifier}`;
        break;
      case "save":
        result = `Save row edits for row ${identifier}`;
        break;
      default:
        result = `Place row ${identifier} in edit mode`;
    }
    return result;
  }
  return {
    className: styles5.tableInlineEditAction,
    component: "td",
    isVisible: true,
    children: react.createElement(EditColumn, {saveAriaLabel: rowData && rowData.rowSaveBtnAriaLabel && rowData.rowSaveBtnAriaLabel(rowIndex) || getAriaLabelTxt(rowIndex, "save"), cancelAriaLabel: rowData && rowData.rowCancelBtnAriaLabel && rowData.rowCancelBtnAriaLabel(rowIndex) || getAriaLabelTxt(rowIndex, "cancel"), editAriaLabel: rowData && rowData.rowEditBtnAriaLabel && rowData.rowEditBtnAriaLabel(rowIndex) || getAriaLabelTxt(rowIndex, "edit"), valid: rowData && rowData.isValid, editing: rowData && rowData.isEditable, onClick: toggleEditMode})
  };
};
var wrappable = () => ({
  className: styles5.modifiers.wrap
});
var defaultTitle = (data2) => data2 && data2.hasOwnProperty("title") ? data2.title : data2;
var generateHeader = ({transforms: origTransforms, formatters: origFormatters, columnTransforms, header}, title3) => Object.assign(Object.assign({}, header), {label: title3, transforms: [
  scopeColTransformer,
  emptyCol,
  ...origTransforms || [],
  ...columnTransforms || [],
  ...header && header.hasOwnProperty("transforms") ? header.transforms : []
], formatters: [...origFormatters || [], ...header && header.hasOwnProperty("formatters") ? header.formatters : []]});
var generateCell = ({cellFormatters, cellTransforms, columnTransforms, cell}, extra) => Object.assign(Object.assign({}, cell), {transforms: [
  ...cellTransforms || [],
  ...columnTransforms || [],
  ...cell && cell.hasOwnProperty("transforms") ? cell.transforms : [],
  mapProps
], formatters: [
  defaultTitle,
  ...cellFormatters || [],
  ...cell && cell.hasOwnProperty("formatters") ? cell.formatters : []
]});
var mapHeader = (column, extra, key, ...props) => {
  const title3 = column.hasOwnProperty("title") ? column.title : column;
  let dataLabel = `column-${key}`;
  if (column.hasOwnProperty("dataLabel")) {
    dataLabel = column.dataLabel;
  } else if (typeof title3 === "string") {
    dataLabel = title3;
  }
  return {
    property: typeof title3 === "string" && title3.toLowerCase().trim().replace(/\s/g, "-") || `column-${key}`,
    extraParams: extra,
    data: column.data,
    header: generateHeader(column, title3),
    cell: generateCell(column),
    props: Object.assign(Object.assign({"data-label": dataLabel, "data-key": key}, column.hasOwnProperty("props") ? column.props : {}), props)
  };
};
var selectableTransforms = ({onSelect, canSelectAll}) => [
  ...onSelect ? [
    {
      title: "",
      transforms: canSelectAll && [selectable] || null,
      cellTransforms: [selectable]
    }
  ] : []
];
var favoritesTransforms = ({onFavorite, onSort, sortBy: sortBy3, canSortFavorites, firstUserColumnIndex}) => [
  ...onFavorite ? [
    {
      title: "",
      transforms: onSort && canSortFavorites ? [
        sortableFavorites({
          onSort,
          columnIndex: firstUserColumnIndex - 1,
          sortBy: sortBy3
        })
      ] : [emptyTD],
      cellTransforms: [favoritable]
    }
  ] : []
];
var actionsTransforms = ({actions: actions2, actionResolver, areActionsDisabled}) => [
  ...actionResolver || actions2 ? [
    {
      title: "",
      transforms: [emptyTD],
      cellTransforms: [cellActions(actions2, actionResolver, areActionsDisabled)]
    }
  ] : []
];
var collapsibleTransforms = (header, {onCollapse}) => [
  ...onCollapse ? [
    {
      title: "",
      transforms: [emptyTD],
      cellTransforms: [collapsible, expandedRow(header.length)]
    }
  ] : []
];
var addAdditionalCellTranforms = (cell, additional) => Object.assign(Object.assign({}, cell.hasOwnProperty("title") ? cell : {title: cell}), {cellTransforms: [...cell.hasOwnProperty("cellTransforms") ? cell.cellTransforms : [], additional]});
var expandContent = (header, extra) => {
  if (!extra.onCollapse && !extra.onExpand) {
    return header;
  }
  return header.map((cell) => {
    const parentIdCell = addAdditionalCellTranforms(cell, parentId);
    return addAdditionalCellTranforms(parentIdCell, expandedRow(header.length));
  });
};
var mapOpenedRows = (rows, children2) => rows.reduce((acc, curr, key) => {
  if (curr.hasOwnProperty("parent")) {
    const parent = acc.length > 0 && acc[acc.length - 1];
    if (parent) {
      acc[acc.length - 1].rows = [...acc[acc.length - 1].rows, children2[key]];
      if (curr.hasOwnProperty("compoundParent")) {
        acc[acc.length - 1].isOpen = acc[acc.length - 1].rows.some((oneRow) => oneRow.props.rowData.cells.some((oneCell) => oneCell.props && oneCell.props.isOpen));
      }
    }
  } else {
    acc = [...acc, Object.assign(Object.assign({}, curr), {rows: [children2[key]]})];
  }
  return acc;
}, []);
var rowEditTransforms = ({onRowEdit}) => [
  ...onRowEdit ? [
    {
      title: "",
      cellTransforms: [editable]
    }
  ] : []
];
var calculateColumns = (headerRows, extra) => headerRows && [
  ...collapsibleTransforms(headerRows, extra),
  ...selectableTransforms(extra),
  ...favoritesTransforms(extra),
  ...expandContent(headerRows, extra),
  ...rowEditTransforms(extra),
  ...actionsTransforms(extra)
].map((oneCol, key) => Object.assign({}, mapHeader(oneCol, extra, key)));
var BodyWrapper = (_a) => {
  var {
    mappedRows,
    tbodyRef,
    rows = [],
    onCollapse,
    headerRows
  } = _a, props = __rest(_a, ["mappedRows", "tbodyRef", "rows", "onCollapse", "headerRows"]);
  if (mappedRows && mappedRows.some((row) => row.hasOwnProperty("parent"))) {
    return react.createElement(react.Fragment, null, mapOpenedRows(mappedRows, props.children).map((oneRow, key) => react.createElement(Tbody, Object.assign({}, props, {isExpanded: oneRow.isOpen, key: `tbody-${key}`, ref: tbodyRef}), oneRow.rows)));
  }
  return react.createElement(Tbody, Object.assign({}, props, {ref: tbodyRef}));
};
BodyWrapper.displayName = "BodyWrapper";
var TableContext = react.createContext({
  headerData: null,
  headerRows: null,
  rows: []
});
var TreeRowWrapper = (_a) => {
  var {
    className,
    rowProps,
    row
  } = _a, props = __rest(_a, ["className", "rowProps", "row"]);
  const {"aria-level": level2, "aria-posinset": posinset, "aria-setsize": setsize, isExpanded, isDetailsExpanded, isHidden: isHidden3} = row.props;
  return react.createElement(Tr, Object.assign({"aria-level": level2, "aria-posinset": posinset, "aria-setsize": setsize, "aria-expanded": !!isExpanded, isHidden: isHidden3, className: css(className, isExpanded && styles5.modifiers.expanded, isDetailsExpanded && stylesTreeView.modifiers.treeViewDetailsExpanded)}, props));
};
TreeRowWrapper.displayName = "TreeRowWrapper";
var Table = class extends react.Component {
  constructor() {
    super(...arguments);
    this.state = {
      ouiaStateId: getDefaultOUIAId(Table.displayName)
    };
    this.isSelected = (row) => row.selected === true;
    this.areAllRowsSelected = (rows) => {
      if (rows === void 0 || rows.length === 0) {
        return false;
      }
      return rows.every((row) => this.isSelected(row) || row.disableSelection || row.hasOwnProperty("parent") && !row.showSelect);
    };
  }
  render() {
    const _a = this.props, {"aria-label": ariaLabel, caption, header, onSort, onSelect, canSelectAll, isHeaderSelectDisabled, selectVariant, sortBy: sortBy3, children: children2, actions: actions2, actionResolver, areActionsDisabled, onCollapse, onExpand, onRowEdit, rowLabeledBy, dropdownPosition, dropdownDirection, actionsToggle, contentId, expandId, variant, rows, cells, bodyWrapper, rowWrapper, role, borders, onFavorite, canSortFavorites} = _a, props = __rest(_a, ["aria-label", "caption", "header", "onSort", "onSelect", "canSelectAll", "isHeaderSelectDisabled", "selectVariant", "sortBy", "children", "actions", "actionResolver", "areActionsDisabled", "onCollapse", "onExpand", "onRowEdit", "rowLabeledBy", "dropdownPosition", "dropdownDirection", "actionsToggle", "contentId", "expandId", "variant", "rows", "cells", "bodyWrapper", "rowWrapper", "role", "borders", "onFavorite", "canSortFavorites"]);
    if (!ariaLabel && !caption && !header && role !== "presentation") {
      console.error("Table: Specify at least one of: header, caption, aria-label");
    }
    const headerData = calculateColumns(cells, {
      sortBy: sortBy3,
      onSort,
      onSelect,
      canSelectAll: selectVariant === RowSelectVariant.radio ? false : canSelectAll,
      isHeaderSelectDisabled,
      selectVariant,
      allRowsSelected: onSelect ? this.areAllRowsSelected(rows) : false,
      actions: actions2,
      actionResolver,
      areActionsDisabled,
      onCollapse,
      onRowEdit,
      onExpand,
      rowLabeledBy,
      expandId,
      contentId,
      dropdownPosition,
      dropdownDirection,
      actionsToggle,
      onFavorite,
      canSortFavorites,
      firstUserColumnIndex: [onCollapse, onSelect, onFavorite].filter((callback) => callback).length
    });
    const table2 = react.createElement(TableContext.Provider, {value: {
      headerData,
      headerRows: null,
      rows
    }}, header, react.createElement(Provider, Object.assign({}, props, {"aria-label": ariaLabel, renderers: {
      body: {
        wrapper: bodyWrapper || BodyWrapper,
        row: rowWrapper || (this.props.isTreeTable ? TreeRowWrapper : RowWrapper),
        cell: BodyCell
      },
      header: {
        cell: HeaderCell
      }
    }, columns: headerData, role, variant, borders}), caption && react.createElement("caption", null, caption), children2));
    if (onRowEdit) {
      return react.createElement("form", {className: css(inlineStyles.inlineEdit)}, table2);
    }
    return table2;
  }
};
Table.displayName = "Table";
Table.hasWarnBeta = false;
Table.defaultProps = {
  children: null,
  className: "",
  variant: null,
  borders: true,
  rowLabeledBy: "simple-node",
  expandId: "expandable-toggle",
  contentId: "expanded-content",
  dropdownPosition: DropdownPosition.right,
  dropdownDirection: DropdownDirection.down,
  header: void 0,
  caption: void 0,
  "aria-label": void 0,
  gridBreakPoint: TableGridBreakpoint.gridMd,
  role: "grid",
  canSelectAll: true,
  isHeaderSelectDisabled: false,
  selectVariant: "checkbox",
  ouiaSafe: true,
  isStickyHeader: false,
  canSortFavorites: true,
  isTreeTable: false,
  isNested: false
};
var flagVisibility = (rows) => {
  const visibleRows = rows.filter((oneRow) => !oneRow.parent || oneRow.isExpanded);
  if (visibleRows.length > 0) {
    visibleRows[0].isFirstVisible = true;
    visibleRows[visibleRows.length - 1].isLastVisible = true;
  }
};
var ContextBody = class extends react.Component {
  constructor() {
    super(...arguments);
    this.onRow = (row, rowProps) => {
      const {onRowClick, onRow} = this.props;
      const extendedRowProps = Object.assign(Object.assign({}, rowProps), onRow ? onRow(row, rowProps) : {});
      return {
        row,
        rowProps: extendedRowProps,
        onClick: (event) => {
          const computedData = {
            isInput: event.target.tagName === "INPUT",
            isButton: event.target.tagName === "BUTTON"
          };
          onRowClick(event, row, rowProps, computedData);
        },
        onKeyDown: (event) => {
          if (event.key === "Enter" || event.key === " ") {
            const computedData = {
              isInput: event.target.tagName === "INPUT",
              isButton: event.target.tagName === "BUTTON"
            };
            onRowClick(event, row, rowProps, computedData);
            if (!computedData.isInput) {
              event.preventDefault();
            }
          }
        }
      };
    };
    this.mapCells = (headerData, row, rowKey) => {
      const {firstUserColumnIndex} = headerData[0].extraParams;
      const isFullWidth = row && row.fullWidth;
      let additionalColsIndexShift = isFullWidth ? 0 : firstUserColumnIndex;
      return Object.assign({}, row && (row.cells || row).reduce((acc, cell, cellIndex) => {
        const isCellObject = cell === Object(cell);
        const isCellFunction = cell && typeof cell.title === "function";
        let formatters = [];
        if (isCellObject && cell.formatters) {
          formatters = cell.formatters;
        } else if (isFullWidth && cellIndex < firstUserColumnIndex) {
          formatters = headerData[firstUserColumnIndex].cell.formatters;
        }
        let mappedCellTitle = cell;
        if (isCellObject && isCellFunction) {
          mappedCellTitle = cell.title(cell.props.value, rowKey, cellIndex, cell.props);
        } else if (isCellObject) {
          mappedCellTitle = cell.title;
        }
        const mappedCell = {
          [headerData[cellIndex + additionalColsIndexShift].property]: {
            title: mappedCellTitle,
            formatters,
            props: Object.assign({isVisible: true}, isCellObject ? cell.props : null)
          }
        };
        if (isCellObject && cell.props && cell.props.colSpan) {
          additionalColsIndexShift += cell.props.colSpan - 1;
        }
        return Object.assign(Object.assign({}, acc), mappedCell);
      }, {secretTableRowKeyId: row.id !== void 0 ? row.id : rowKey}));
    };
  }
  render() {
    const _a = this.props, {className, headerData, rows, rowKey, children: children2, onRowClick} = _a, props = __rest(_a, ["className", "headerData", "rows", "rowKey", "children", "onRowClick"]);
    let mappedRows;
    if (headerData.length > 0) {
      mappedRows = rows.map((oneRow, oneRowKey) => Object.assign(Object.assign(Object.assign({}, oneRow), this.mapCells(headerData, oneRow, oneRowKey)), {isExpanded: isRowExpanded(oneRow, rows), isHeightAuto: oneRow.heightAuto || false, isFirst: oneRowKey === 0, isLast: oneRowKey === rows.length - 1, isFirstVisible: false, isLastVisible: false}));
      flagVisibility(mappedRows);
    }
    return react.createElement(react.Fragment, null, mappedRows && react.createElement(Body, Object.assign({}, props, {mappedRows, rows: mappedRows, onRow: this.onRow, rowKey, className})));
  }
};
var TableBody = (_a) => {
  var {
    className = "",
    children: children2 = null,
    rowKey = "secretTableRowKeyId",
    onRow = (...args) => ({}),
    onRowClick = (event, row, rowProps, computedData) => void 0
  } = _a, props = __rest(_a, ["className", "children", "rowKey", "onRow", "onRowClick"]);
  return react.createElement(TableContext.Consumer, null, (_a2) => {
    var {headerData = [], rows = []} = _a2, rest = __rest(_a2, ["headerData", "rows"]);
    return react.createElement(ContextBody, Object.assign({headerData, rows, onRow, className, rowKey, onRowClick}, props, rest), children2);
  });
};
var ContextHeader = (_a) => {
  var {className = "", headerRows = void 0} = _a, props = __rest(_a, ["className", "headerRows"]);
  return react.createElement(Header2, Object.assign({}, props, {headerRows, className}));
};
var TableHeader = (_a) => {
  var props = __rest(_a, []);
  return react.createElement(TableContext.Consumer, null, ({headerRows}) => react.createElement(ContextHeader, Object.assign({}, props, {headerRows})));
};
TableHeader.displayName = "TableHeader";

// build/components/table-toolbar/TableToolbar.js
var TableToolbar = ({
  toolbarItem,
  subToolbar,
  toolbarItemFooter,
  children: children2,
  searchTypeComponent,
  inputGroupName,
  inputGroupPlaceholder,
  inputGroupOnChange,
  inputGroupOnEnter
}) => {
  const {t: t5} = useTranslation();
  const [searchValue, setSearchValue] = useState("");
  const onSearch = () => {
    if (searchValue !== "") {
      setSearchValue(searchValue);
      inputGroupOnEnter?.(searchValue);
    } else {
      setSearchValue("");
      inputGroupOnEnter?.("");
    }
  };
  const handleKeyDown = (e2) => {
    if (e2.key === "Enter") {
      onSearch();
    }
  };
  const handleInputChange = (value, event) => {
    inputGroupOnChange?.(value, event);
    setSearchValue(value);
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Toolbar, null, /* @__PURE__ */ react.createElement(ToolbarContent, null, inputGroupName && /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(InputGroup, null, searchTypeComponent, inputGroupPlaceholder && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(TextInput, {
    name: inputGroupName,
    id: inputGroupName,
    type: "search",
    "aria-label": t5("search"),
    placeholder: inputGroupPlaceholder,
    onChange: handleInputChange,
    onKeyDown: handleKeyDown
  }), /* @__PURE__ */ react.createElement(Button, {
    variant: ButtonVariant.control,
    "aria-label": t5("search"),
    onClick: onSearch
  }, /* @__PURE__ */ react.createElement(SearchIcon, null))))), toolbarItem)), subToolbar && /* @__PURE__ */ react.createElement(Toolbar, null, /* @__PURE__ */ react.createElement(ToolbarContent, null, subToolbar)), /* @__PURE__ */ react.createElement(Divider, null), children2, /* @__PURE__ */ react.createElement(Toolbar, null, toolbarItemFooter));
};

// build/components/table-toolbar/PaginatingTableToolbar.js
var PaginatingTableToolbar = ({
  count,
  first: first2,
  max: max2,
  onNextClick,
  onPreviousClick,
  onPerPageSelect,
  searchTypeComponent,
  toolbarItem,
  subToolbar,
  children: children2,
  inputGroupName,
  inputGroupPlaceholder,
  inputGroupOnChange,
  inputGroupOnEnter
}) => {
  const page2 = Math.round(first2 / max2);
  const pagination2 = (variant = "top") => /* @__PURE__ */ react.createElement(Pagination, {
    isCompact: true,
    toggleTemplate: ({firstIndex: firstIndex2, lastIndex}) => /* @__PURE__ */ react.createElement("b", null, firstIndex2, " - ", lastIndex),
    itemCount: count + page2 * max2,
    page: page2 + 1,
    perPage: max2,
    onNextClick: (_23, p2) => onNextClick((p2 - 1) * max2),
    onPreviousClick: (_23, p2) => onPreviousClick((p2 - 1) * max2),
    onPerPageSelect: (_23, m2, f2) => onPerPageSelect(f2 - 1, m2),
    variant
  });
  return /* @__PURE__ */ react.createElement(TableToolbar, {
    searchTypeComponent,
    toolbarItem: /* @__PURE__ */ react.createElement(react.Fragment, null, toolbarItem, count !== 0 && /* @__PURE__ */ react.createElement(ToolbarItem, {
      variant: "pagination"
    }, pagination2())),
    subToolbar,
    toolbarItemFooter: count !== 0 ? /* @__PURE__ */ react.createElement(ToolbarItem, null, pagination2("bottom")) : null,
    inputGroupName,
    inputGroupPlaceholder,
    inputGroupOnChange,
    inputGroupOnEnter
  }, children2);
};

// build/components/list-empty-state/ListEmptyState.js
var ListEmptyState = ({
  message,
  instructions,
  onPrimaryAction,
  hasIcon = true,
  isSearchVariant,
  primaryActionText,
  secondaryActions,
  icon
}) => {
  return /* @__PURE__ */ react.createElement(EmptyState, {
    "data-testid": "empty-state",
    variant: "large"
  }, hasIcon && isSearchVariant ? /* @__PURE__ */ react.createElement(EmptyStateIcon, {
    icon: SearchIcon
  }) : hasIcon && /* @__PURE__ */ react.createElement(EmptyStateIcon, {
    icon: icon ? icon : PlusCircleIcon
  }), /* @__PURE__ */ react.createElement(Title, {
    headingLevel: "h1",
    size: "lg"
  }, message), /* @__PURE__ */ react.createElement(EmptyStateBody, null, instructions), primaryActionText && /* @__PURE__ */ react.createElement(Button, {
    "data-testid": `${message.replace(/\W+/g, "-").toLowerCase()}-empty-action`,
    variant: "primary",
    onClick: onPrimaryAction
  }, primaryActionText), secondaryActions && /* @__PURE__ */ react.createElement(EmptyStateSecondaryActions, null, secondaryActions.map((action) => /* @__PURE__ */ react.createElement(Button, {
    key: action.text,
    variant: action.type || ButtonVariant.secondary,
    onClick: action.onClick
  }, action.text))));
};

// build/components/table-toolbar/KeycloakDataTable.js
function DataTable({
  columns,
  rows,
  actions: actions2,
  actionResolver,
  ariaLabelKey,
  onSelect,
  onCollapse,
  canSelectAll,
  isNotCompact,
  isRadio: isRadio3,
  ...props
}) {
  const {t: t5} = useTranslation();
  return /* @__PURE__ */ react.createElement(Table, {
    ...props,
    variant: isNotCompact ? void 0 : TableVariant.compact,
    onSelect: onSelect ? (_23, isSelected, rowIndex) => onSelect(isSelected, rowIndex) : void 0,
    onCollapse: onCollapse ? (_23, rowIndex, isOpen) => onCollapse(isOpen, rowIndex) : void 0,
    selectVariant: isRadio3 ? "radio" : "checkbox",
    canSelectAll,
    cells: columns.map((column) => {
      return {...column, title: t5(column.displayKey || column.name)};
    }),
    rows,
    actions: actions2,
    actionResolver,
    "aria-label": t5(ariaLabelKey)
  }, /* @__PURE__ */ react.createElement(TableHeader, null), /* @__PURE__ */ react.createElement(TableBody, null));
}
function KeycloakDataTable({
  ariaLabelKey,
  searchPlaceholderKey,
  isPaginated = false,
  onSelect,
  canSelectAll = false,
  isNotCompact,
  isRadio: isRadio3,
  detailColumns,
  isRowDisabled,
  loader,
  columns,
  actions: actions2,
  actionResolver,
  searchTypeComponent,
  toolbarItem,
  subToolbar,
  emptyState: emptyState2,
  icon,
  isSearching = false,
  ...props
}) {
  const {t: t5} = useTranslation();
  const [selected, setSelected] = useState([]);
  const [rows, setRows] = useState();
  const [unPaginatedData, setUnPaginatedData] = useState();
  const [loading, setLoading] = useState(false);
  const [max2, setMax] = useState(10);
  const [first2, setFirst] = useState(0);
  const [search2, setSearch] = useState("");
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const renderCell = (columns2, value) => {
    return columns2.map((col) => {
      if (col.cellRenderer) {
        return {title: col.cellRenderer(value)};
      }
      return lodash.get(value, col.name);
    });
  };
  const convertToColumns = (data22) => {
    const isDetailColumnsEnabled = (value) => detailColumns?.[0]?.enabled?.(value);
    return data22.map((value, index3) => {
      const disabledRow = isRowDisabled ? isRowDisabled(value) : false;
      const row = [
        {
          data: value,
          disableSelection: disabledRow,
          disableActions: disabledRow,
          selected: !!selected.find((v2) => lodash.get(v2, "id") === lodash.get(value, "id")),
          isOpen: isDetailColumnsEnabled(value) ? false : void 0,
          cells: renderCell(columns, value)
        }
      ];
      if (isDetailColumnsEnabled(value)) {
        row.push({
          parent: index3 * 2,
          cells: renderCell(detailColumns, value)
        });
      }
      return row;
    }).flat();
  };
  const getNodeText = (node) => {
    if (["string", "number"].includes(typeof node)) {
      return node.toString();
    }
    if (node instanceof Array) {
      return node.map(getNodeText).join("");
    }
    if (typeof node === "object") {
      return getNodeText(isValidElement(node.title) ? node.title.props?.children : node.title);
    }
    return "";
  };
  const filteredData = useMemo(() => search2 === "" || isPaginated ? void 0 : convertToColumns(unPaginatedData || []).filter((row) => row.cells.some((cell) => cell && getNodeText(cell).toLowerCase().includes(search2.toLowerCase()))), [search2]);
  useEffect(() => {
    if (canSelectAll) {
      const checkboxes = document.getElementsByClassName("pf-c-table__check").item(0);
      if (checkboxes) {
        const checkAllCheckbox = checkboxes.children.item(0);
        checkAllCheckbox.indeterminate = selected.length > 0 && selected.length < (filteredData || rows).length;
      }
    }
  }, [selected]);
  useFetch(async () => {
    setLoading(true);
    return unPaginatedData || await loader(first2, max2 + 1, search2);
  }, (data22) => {
    if (!isPaginated) {
      setUnPaginatedData(data22);
      data22 = data22.slice(first2, first2 + max2 + 1);
    }
    const result = convertToColumns(data22);
    setRows(result);
    setLoading(false);
  }, [key, first2, max2, search2]);
  const convertAction = () => actions2 && lodash.cloneDeep(actions2).map((action, index3) => {
    delete action.onRowClick;
    action.onClick = async (_23, rowIndex) => {
      const result = await actions2[index3].onRowClick((filteredData || rows)[rowIndex].data);
      if (result) {
        if (!isPaginated) {
          setSearch("");
        }
        refresh();
      }
    };
    return action;
  });
  const Loading = () => /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
  const _onSelect = (isSelected, rowIndex) => {
    const data22 = filteredData || rows;
    if (rowIndex === -1) {
      setRows(data22.map((row) => {
        row.selected = isSelected;
        return row;
      }));
    } else {
      data22[rowIndex].selected = isSelected;
      setRows([...rows]);
    }
    const difference = lodash.differenceBy(selected, data22.map((row) => row.data), "id");
    const selectedRows = [
      ...difference,
      ...data22.filter((row) => row.selected).map((row) => row.data)
    ];
    setSelected(selectedRows);
    onSelect(selectedRows);
  };
  const onCollapse = (isOpen, rowIndex) => {
    data2[rowIndex].isOpen = isOpen;
    setRows([...data2]);
  };
  const data2 = filteredData || rows;
  const noData = !data2 || data2.length === 0;
  const searching = search2 !== "" || isSearching;
  const maxRows = detailColumns ? max2 * 2 : max2;
  const rowLength = detailColumns ? (data2?.length || 0) / 2 : data2?.length || 0;
  return /* @__PURE__ */ react.createElement(react.Fragment, null, (loading || !noData || searching) && /* @__PURE__ */ react.createElement(PaginatingTableToolbar, {
    count: rowLength,
    first: first2,
    max: max2,
    onNextClick: setFirst,
    onPreviousClick: setFirst,
    onPerPageSelect: (first22, max22) => {
      setFirst(first22);
      setMax(max22);
    },
    inputGroupName: searchPlaceholderKey ? `${ariaLabelKey}input` : void 0,
    inputGroupOnEnter: setSearch,
    inputGroupPlaceholder: t5(searchPlaceholderKey || ""),
    searchTypeComponent,
    toolbarItem,
    subToolbar
  }, !loading && !noData && /* @__PURE__ */ react.createElement(DataTable, {
    ...props,
    canSelectAll,
    onSelect: onSelect ? _onSelect : void 0,
    onCollapse: detailColumns ? onCollapse : void 0,
    actions: convertAction(),
    actionResolver,
    rows: data2.slice(0, maxRows),
    columns,
    isNotCompact,
    isRadio: isRadio3,
    ariaLabelKey
  }), !loading && noData && searching && /* @__PURE__ */ react.createElement(ListEmptyState, {
    hasIcon: true,
    icon,
    isSearchVariant: true,
    message: t5("noSearchResults"),
    instructions: t5("noSearchResultsInstructions")
  }), loading && /* @__PURE__ */ react.createElement(Loading, null)), !loading && noData && !searching && emptyState2);
}

// build/components/confirm-dialog/ConfirmDialog.js
var useConfirmDialog = (props) => {
  const [show2, setShow] = useState(false);
  function toggleDialog() {
    setShow((show22) => !show22);
  }
  const Dialog = () => /* @__PURE__ */ react.createElement(ConfirmDialogModal, {
    key: "confirmDialog",
    ...props,
    open: show2,
    toggleDialog
  });
  return [toggleDialog, Dialog];
};
var ConfirmDialogModal = ({
  titleKey,
  messageKey,
  noCancelButton,
  cancelButtonLabel,
  continueButtonLabel,
  continueButtonVariant,
  onConfirm,
  onCancel,
  children: children2,
  open: open2 = true,
  variant = ModalVariant.small,
  toggleDialog,
  confirmButtonDisabled
}) => {
  const {t: t5} = useTranslation();
  return /* @__PURE__ */ react.createElement(Modal, {
    title: t5(titleKey),
    isOpen: open2,
    onClose: toggleDialog,
    variant,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-confirm",
        "data-testid": "modalConfirm",
        key: "confirm",
        isDisabled: confirmButtonDisabled,
        variant: continueButtonVariant || ButtonVariant.primary,
        onClick: () => {
          onConfirm();
          toggleDialog();
        }
      }, t5(continueButtonLabel || "common:continue")),
      !noCancelButton && /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          if (onCancel)
            onCancel();
          toggleDialog();
        }
      }, t5(cancelButtonLabel || "common:cancel"))
    ]
  }, !messageKey && children2, messageKey && t5(messageKey));
};

// build/components/keycloak-tabs/KeycloakTabs.js
var createUrl = (path, params) => {
  let url = path;
  for (const key in params) {
    const value = params[key];
    if (url.includes(key)) {
      url = url.replace(new RegExp(`:${key}\\??`), value || "");
    }
  }
  return url;
};
var KeycloakTabs = ({
  paramName = "tab",
  children: children2,
  ...rest
}) => {
  const match2 = useRouteMatch();
  const params = match2.params;
  const history = useHistory();
  const form2 = useFormContext();
  const [key, setKey] = useState("");
  const firstTab = Children.toArray(children2)[0];
  const tab = params[paramName] || isValidElement(firstTab) && firstTab.props.eventKey || "";
  const pathIndex = match2.path.indexOf(paramName) + paramName.length;
  const path = match2.path.substr(0, pathIndex);
  const [toggleChangeTabDialog, ChangeTabConfirm] = useConfirmDialog({
    titleKey: "common:leaveDirtyTitle",
    messageKey: "common:leaveDirtyConfirm",
    continueButtonLabel: "common:leave",
    onConfirm: () => {
      form2.reset();
      history.push(createUrl(path, {...params, [paramName]: key}));
    }
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ChangeTabConfirm, null), /* @__PURE__ */ react.createElement(Tabs, {
    inset: {
      default: "insetNone",
      md: "insetSm",
      xl: "inset2xl",
      "2xl": "insetLg"
    },
    activeKey: tab,
    onSelect: (_23, key2) => {
      if (form2?.formState.isDirty) {
        setKey(key2);
        toggleChangeTabDialog();
      } else {
        history.push(createUrl(path, {...params, [paramName]: key2}));
      }
    },
    ...rest
  }, children2));
};

// build/utils/useToggle.js
function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);
  const toggleValue = useCallback(() => setValue((val) => !val), []);
  return [value, toggleValue, setValue];
}

// build/authentication/form/NameDescription.js
var NameDescription = () => {
  const {t: t5} = useTranslation("authentication");
  const {register: register2, errors} = useFormContext();
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:name"),
    fieldId: "kc-name",
    helperTextInvalid: t5("common:required"),
    validated: errors.alias ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:name",
      fieldLabelId: "name"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-name",
    name: "alias",
    "data-testid": "alias",
    ref: register2({required: true}),
    validated: errors.alias ? ValidatedOptions.error : ValidatedOptions.default
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:description"),
    fieldId: "kc-description",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:description",
      fieldLabelId: "description"
    }),
    validated: errors.description ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: errors.description?.message
  }, /* @__PURE__ */ react.createElement(TextArea, {
    ref: register2({
      maxLength: {
        value: 255,
        message: t5("common:maxLength", {length: 255})
      }
    }),
    type: "text",
    id: "kc-description",
    name: "description",
    "data-testid": "description",
    validated: errors.description ? ValidatedOptions.error : ValidatedOptions.default
  })));
};

// build/authentication/DuplicateFlowModal.js
var DuplicateFlowModal = ({
  name,
  description,
  toggleDialog,
  onComplete
}) => {
  const {t: t5} = useTranslation("authentication");
  const form2 = useForm({
    shouldUnregister: false
  });
  const {setValue, trigger, getValues} = form2;
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  useEffect(() => {
    setValue("description", description);
    setValue("alias", t5("copyOf", {name}));
  }, [name, description, setValue]);
  const save = async () => {
    await trigger();
    const form22 = getValues();
    try {
      await adminClient.authenticationManagement.copyFlow({
        flow: name,
        newName: form22.alias
      });
      if (form22.description !== description) {
        const newFlow = (await adminClient.authenticationManagement.getFlows()).find((flow) => flow.alias === form22.alias);
        newFlow.description = form22.description;
        await adminClient.authenticationManagement.updateFlow({flowId: newFlow.id}, newFlow);
      }
      addAlert(t5("copyFlowSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("authentication:copyFlowError", error2);
    }
    onComplete();
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    title: t5("duplicateFlow"),
    isOpen: true,
    onClose: toggleDialog,
    variant: ModalVariant.small,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-confirm",
        key: "confirm",
        onClick: save,
        "data-testid": "confirm"
      }, t5("duplicate")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "cancel",
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          toggleDialog();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(FormProvider, {
    ...form2
  }, /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(NameDescription, null))));
};

// build/authentication/form/FlowType.js
var TYPES = ["basic-flow", "client-flow"];
var FlowType = () => {
  const {t: t5} = useTranslation("authentication");
  const {control} = useFormContext();
  const [open2, setOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("flowType"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:topLevelFlowType",
      fieldLabelId: "authentication:flowType"
    }),
    fieldId: "flowType"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "providerId",
    defaultValue: TYPES[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "flowType",
      onToggle: setOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setOpen(false);
      },
      selections: t5(`top-level-flow-type.${value}`),
      variant: SelectVariant.single,
      "aria-label": t5("flowType"),
      isOpen: open2
    }, TYPES.map((type) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: type === value,
      key: type,
      value: type
    }, t5(`top-level-flow-type.${type}`))))
  }));
};

// build/authentication/components/modals/AddStepModal.js
var import_FlowDetails = require_FlowDetails();
var AuthenticationProviderList = ({
  list: list3,
  setValue
}) => {
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light",
    className: "pf-u-py-lg"
  }, /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true
  }, list3?.map((provider) => /* @__PURE__ */ react.createElement(Radio, {
    id: provider.id,
    key: provider.id,
    name: "provider",
    label: provider.displayName,
    "data-testid": provider.id,
    description: provider.description,
    onChange: (_val, event) => {
      const {id: id3} = event.currentTarget;
      const value = list3.find((p2) => p2.id === id3);
      setValue(value);
    }
  }))));
};
var AddStepModal = ({name, type, onSelect}) => {
  const {t: t5} = useTranslation("authentication");
  const adminClient = useAdminClient();
  const [value, setValue] = useState();
  const [providers, setProviders] = useState();
  const [max2, setMax] = useState(10);
  const [first2, setFirst] = useState(0);
  useFetch(async () => {
    switch (type) {
      case "client":
        return adminClient.authenticationManagement.getClientAuthenticatorProviders();
      case "form":
        return adminClient.authenticationManagement.getFormActionProviders();
      case "condition": {
        const providers2 = await adminClient.authenticationManagement.getAuthenticatorProviders();
        return providers2.filter(import_FlowDetails.providerConditionFilter);
      }
      case "basic":
      default: {
        const providers2 = await adminClient.authenticationManagement.getAuthenticatorProviders();
        return providers2.filter((p2) => !(0, import_FlowDetails.providerConditionFilter)(p2));
      }
    }
  }, (providers2) => setProviders(providers2), []);
  const page2 = providers?.slice(first2, first2 + max2 + 1);
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.medium,
    isOpen: true,
    title: t5("addStepTo", {name}),
    onClose: () => onSelect(),
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-add",
        "data-testid": "modal-add",
        key: "add",
        onClick: () => onSelect(value)
      }, t5("common:add")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "cancel",
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          onSelect();
        }
      }, t5("common:cancel"))
    ]
  }, providers && providers.length > max2 && /* @__PURE__ */ react.createElement(PaginatingTableToolbar, {
    count: page2?.length || 0,
    first: first2,
    max: max2,
    onNextClick: setFirst,
    onPreviousClick: setFirst,
    onPerPageSelect: (first22, max22) => {
      setFirst(first22);
      setMax(max22);
    }
  }, /* @__PURE__ */ react.createElement(AuthenticationProviderList, {
    list: page2,
    setValue
  })), providers && providers.length <= max2 && /* @__PURE__ */ react.createElement(AuthenticationProviderList, {
    list: providers,
    setValue
  }));
};

// build/authentication/components/modals/AddSubFlowModal.js
var types = ["basic-flow", "form-flow"];
var AddSubFlowModal = ({
  name,
  onConfirm,
  onCancel
}) => {
  const {t: t5} = useTranslation("authentication");
  const {register: register2, control, errors, handleSubmit} = useForm();
  const [open2, setOpen] = useState(false);
  const [openProvider, setOpenProvider] = useState(false);
  const [formProviders, setFormProviders] = useState();
  const adminClient = useAdminClient();
  useFetch(() => adminClient.authenticationManagement.getFormProviders(), (providers) => setFormProviders(providers), []);
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.medium,
    isOpen: true,
    title: t5("addStepTo", {name}),
    onClose: () => onCancel(),
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-add",
        "data-testid": "modal-add",
        key: "add",
        type: "submit",
        form: "sub-flow-form"
      }, t5("common:add")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "cancel",
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          onCancel();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(Form, {
    id: "sub-flow-form",
    isHorizontal: true,
    onSubmit: handleSubmit(onConfirm)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:name"),
    fieldId: "name",
    helperTextInvalid: t5("common:required"),
    validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:name",
      fieldLabelId: "name"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "name",
    name: "name",
    "data-testid": "name",
    ref: register2({required: true}),
    validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:description"),
    fieldId: "description",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:description",
      fieldLabelId: "description"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "description",
    name: "description",
    "data-testid": "description",
    ref: register2
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("flowType"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:flowType",
      fieldLabelId: "authentication:flowType"
    }),
    fieldId: "flowType"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "type",
    defaultValue: types[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      menuAppendTo: "parent",
      toggleId: "flowType",
      onToggle: setOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setOpen(false);
      },
      selections: t5(`flow-type.${value}`),
      variant: SelectVariant.single,
      "aria-label": t5("flowType"),
      isOpen: open2
    }, types.map((type) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: type === value,
      key: type,
      value: type
    }, t5(`flow-type.${type}`))))
  })), formProviders && formProviders.length > 1 && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("flowType"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:flowType",
      fieldLabelId: "authentication:flowType"
    }),
    fieldId: "flowType"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "provider",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      menuAppendTo: "parent",
      toggleId: "provider",
      onToggle: setOpenProvider,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setOpenProvider(false);
      },
      selections: value.displayName,
      variant: SelectVariant.single,
      "aria-label": t5("flowType"),
      isOpen: openProvider
    }, formProviders.map((provider) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: provider.displayName === value,
      key: provider.id,
      value: provider
    }, provider.displayName)))
  })), formProviders?.length === 1 && /* @__PURE__ */ react.createElement("input", {
    name: "provider",
    type: "hidden",
    ref: register2,
    value: formProviders[0].id
  })));
};

// build/authentication/EmptyExecutionState.js
var SECTIONS = ["addExecution", "addSubFlow"];
var EmptyExecutionState = ({
  flow,
  onAddExecution,
  onAddFlow
}) => {
  const {t: t5} = useTranslation("authentication");
  const [show2, setShow] = useState();
  return /* @__PURE__ */ react.createElement(react.Fragment, null, show2 === "addExecution" && /* @__PURE__ */ react.createElement(AddStepModal, {
    name: flow.alias,
    type: flow.providerId === "client-flow" ? "client" : "basic",
    onSelect: (type) => {
      if (type) {
        onAddExecution(type);
      }
      setShow(void 0);
    }
  }), show2 === "addSubFlow" && /* @__PURE__ */ react.createElement(AddSubFlowModal, {
    name: flow.alias,
    onCancel: () => setShow(void 0),
    onConfirm: (newFlow) => {
      onAddFlow(newFlow);
      setShow(void 0);
    }
  }), /* @__PURE__ */ react.createElement(ListEmptyState, {
    message: t5("emptyExecution"),
    instructions: t5("emptyExecutionInstructions")
  }), /* @__PURE__ */ react.createElement("div", {
    className: "keycloak__empty-execution-state__block"
  }, SECTIONS.map((section) => /* @__PURE__ */ react.createElement(Flex, {
    key: section,
    className: "keycloak__empty-execution-state__help"
  }, /* @__PURE__ */ react.createElement(FlexItem, {
    flex: {default: "flex_1"}
  }, /* @__PURE__ */ react.createElement(Title, {
    headingLevel: "h3",
    size: TitleSizes.md
  }, t5(`${section}Title`)), /* @__PURE__ */ react.createElement("p", null, t5(`authentication-help:${section}`))), /* @__PURE__ */ react.createElement(Flex, {
    alignSelf: {default: "alignSelfCenter"}
  }, /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Button, {
    "data-testid": section,
    variant: "tertiary",
    onClick: () => setShow(section)
  }, t5(section))))))));
};

// build/authentication/components/FlowHeader.js
var FlowHeader = () => {
  const {t: t5} = useTranslation("authentication");
  return /* @__PURE__ */ react.createElement(DataListItem, {
    "aria-labelledby": "headerName",
    id: "header"
  }, /* @__PURE__ */ react.createElement(DataListItemRow, null, /* @__PURE__ */ react.createElement(DataListDragButton, {
    className: "keycloak__authentication__header-drag-button"
  }), /* @__PURE__ */ react.createElement(DataListItemCells, {
    className: "keycloak__authentication__header",
    dataListCells: [
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: "step",
        id: "headerName"
      }, t5("steps")),
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: "requirement"
      }, t5("requirement")),
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: "config"
      })
    ]
  })));
};

// build/authentication/components/FlowTitle.js
var FlowTitle = ({title: title3}) => {
  return /* @__PURE__ */ react.createElement(Card, {
    "data-testid": title3,
    className: "keycloak__authentication__title",
    isFlat: true
  }, /* @__PURE__ */ react.createElement(CardBody, null, title3));
};

// build/authentication/components/FlowRequirementDropdown.js
var FlowRequirementDropdown = ({
  flow,
  onChange
}) => {
  const {t: t5} = useTranslation("authentication");
  const [open2, setOpen] = useState(false);
  const options = flow.requirementChoices.map((option, index3) => /* @__PURE__ */ react.createElement(SelectOption, {
    key: index3,
    value: option
  }, t5(`requirements.${option}`)));
  return /* @__PURE__ */ react.createElement(react.Fragment, null, flow.requirementChoices && flow.requirementChoices.length > 1 && /* @__PURE__ */ react.createElement(Select, {
    className: "keycloak__authentication__requirement-dropdown",
    variant: SelectVariant.single,
    onToggle: setOpen,
    onSelect: (_event, value) => {
      flow.requirement = value.toString();
      onChange(flow);
      setOpen(false);
    },
    selections: [flow.requirement],
    isOpen: open2
  }, options), (!flow.requirementChoices || flow.requirementChoices.length <= 1) && /* @__PURE__ */ react.createElement(react.Fragment, null, t5(`requirements.${flow.requirement}`)));
};

// build/authentication/components/ExecutionConfigModal.js
var ExecutionConfigModal = ({
  execution
}) => {
  const {t: t5} = useTranslation("authentication");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [show2, setShow] = useState(false);
  const [config2, setConfig] = useState();
  const [configDescription, setConfigDescription] = useState();
  const {register: register2, errors, setValue, handleSubmit} = useForm();
  const setupForm = (configDescription2, config22) => {
    configDescription2.properties.map((property2) => {
      setValue(property2.name, config22?.config?.[property2.name] || property2.defaultValue || "");
    });
    if (config22) {
      setValue("alias", config22.alias);
      setValue("id", config22.id);
    }
  };
  useFetch(async () => {
    const configDescription2 = await adminClient.authenticationManagement.getConfigDescription({
      providerId: execution.providerId
    });
    let config22;
    if (execution.authenticationConfig) {
      config22 = await adminClient.authenticationManagement.getConfig({
        id: execution.authenticationConfig
      });
    }
    return {configDescription: configDescription2, config: config22};
  }, ({configDescription: configDescription2, config: config22}) => {
    setConfigDescription(configDescription2);
    setConfig(config22);
  }, []);
  useEffect(() => {
    if (configDescription)
      setupForm(configDescription, config2);
  }, [show2]);
  const save = async (changedConfig) => {
    try {
      if (config2) {
        const newConfig = {
          ...config2,
          config: changedConfig
        };
        await adminClient.authenticationManagement.updateConfig(newConfig);
        setConfig(newConfig);
      } else {
        const newConfig = {
          id: execution.id,
          alias: changedConfig.alias,
          config: changedConfig
        };
        const {id: id3} = await adminClient.authenticationManagement.createConfig(newConfig);
        setConfig({...newConfig, id: id3});
      }
      addAlert(t5("configSaveSuccess"), AlertVariant.success);
      setShow(false);
    } catch (error2) {
      addError("authentication:configSaveError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "plain",
    "aria-label": t5("common:settings"),
    onClick: () => setShow(true)
  }, /* @__PURE__ */ react.createElement(CogIcon, null)), configDescription && /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    isOpen: show2,
    title: t5("executionConfig", {name: configDescription.name}),
    onClose: () => setShow(false)
  }, /* @__PURE__ */ react.createElement(Form, {
    id: "execution-config-form",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("alias"),
    fieldId: "alias",
    helperTextInvalid: t5("common:required"),
    validated: errors.alias ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:alias",
      fieldLabelId: "authentication:alias"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isReadOnly: !!config2,
    type: "text",
    id: "alias",
    name: "alias",
    "data-testid": "alias",
    ref: register2({required: true}),
    validated: errors.alias ? ValidatedOptions.error : ValidatedOptions.default
  })), configDescription.properties?.map((property2) => /* @__PURE__ */ react.createElement(FormGroup, {
    key: property2.name,
    label: property2.label,
    fieldId: property2.name,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: property2.helpText,
      fieldLabelId: property2.name
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: property2.name,
    name: property2.name,
    ref: register2
  }))), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "save",
    variant: "primary",
    type: "submit"
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "cancel",
    variant: ButtonVariant.link,
    onClick: () => {
      setShow(false);
    }
  }, t5("common:cancel")), config2 && /* @__PURE__ */ react.createElement(Button, {
    className: "pf-u-ml-4xl",
    "data-testid": "clear",
    variant: ButtonVariant.link,
    onClick: async () => {
      await adminClient.authenticationManagement.delConfig({
        id: config2.id
      });
      setConfig(void 0);
      setShow(false);
    }
  }, t5("common:clear"), " ", /* @__PURE__ */ react.createElement(TrashIcon, null))))));
};

// build/authentication/components/EditFlowDropdown.js
var EditFlowDropdown = ({
  execution,
  onAddExecution,
  onAddFlow
}) => {
  const {t: t5} = useTranslation("authentication");
  const adminClient = useAdminClient();
  const [open2, setOpen] = useState(false);
  const [type, setType] = useState();
  const [providerId, setProviderId] = useState();
  useFetch(() => adminClient.authenticationManagement.getFlow({
    flowId: execution.flowId
  }), ({providerId: providerId2}) => setProviderId(providerId2), []);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Dropdown, {
    isPlain: true,
    position: "right",
    "data-testid": `${execution.displayName}-edit-dropdown`,
    isOpen: open2,
    toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
      onToggle: setOpen
    }, /* @__PURE__ */ react.createElement(PlusIcon, null)),
    dropdownItems: [
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "addStep",
        onClick: () => setType(providerId === "form-flow" ? "form" : "basic")
      }, t5("addStep")),
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "addCondition",
        onClick: () => setType("condition")
      }, t5("addCondition")),
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "addSubFlow",
        onClick: () => setType("subFlow")
      }, t5("addSubFlow"))
    ],
    onSelect: () => setOpen(false)
  }), type && type !== "subFlow" && /* @__PURE__ */ react.createElement(AddStepModal, {
    name: execution.displayName,
    type,
    onSelect: (type2) => {
      if (type2) {
        onAddExecution(execution, type2);
      }
      setType(void 0);
    }
  }), type === "subFlow" && /* @__PURE__ */ react.createElement(AddSubFlowModal, {
    name: execution.displayName,
    onCancel: () => setType(void 0),
    onConfirm: (flow) => {
      onAddFlow(flow);
      setType(void 0);
    }
  }));
};

// build/authentication/components/FlowRow.js
var FlowRow = ({
  builtIn,
  execution,
  onRowClick,
  onRowChange,
  onAddExecution,
  onAddFlow,
  onDelete
}) => {
  const {t: t5} = useTranslation("authentication");
  const hasSubList = !!execution.executionList?.length;
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DataListItem, {
    className: "keycloak__authentication__flow-item",
    id: execution.id,
    isExpanded: !execution.isCollapsed
  }, /* @__PURE__ */ react.createElement(DataListItemRow, {
    className: "keycloak__authentication__flow-row",
    "aria-level": execution.level
  }, /* @__PURE__ */ react.createElement(DataListControl, null, /* @__PURE__ */ react.createElement(DataListDragButton, {
    "aria-labelledby": execution.displayName,
    "aria-describedby": t5("common-help:dragHelp")
  })), hasSubList && /* @__PURE__ */ react.createElement(DataListToggle, {
    onClick: () => onRowClick(execution),
    isExpanded: !execution.isCollapsed,
    id: `toggle1-${execution.id}`,
    "aria-controls": `expand-${execution.id}`
  }), /* @__PURE__ */ react.createElement(DataListItemCells, {
    dataListCells: [
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: `${execution.id}-name`
      }, !execution.authenticationFlow && /* @__PURE__ */ react.createElement(FlowTitle, {
        key: execution.id,
        title: execution.displayName
      }), execution.authenticationFlow && /* @__PURE__ */ react.createElement(react.Fragment, null, execution.displayName, " ", /* @__PURE__ */ react.createElement("br", null), " ", /* @__PURE__ */ react.createElement(Text, {
        component: TextVariants.small
      }, execution.description))),
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: `${execution.id}-requirement`
      }, /* @__PURE__ */ react.createElement(FlowRequirementDropdown, {
        flow: execution,
        onChange: onRowChange
      })),
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: `${execution.id}-config`
      }, execution.configurable && /* @__PURE__ */ react.createElement(ExecutionConfigModal, {
        execution
      }), execution.authenticationFlow && !builtIn && /* @__PURE__ */ react.createElement(EditFlowDropdown, {
        execution,
        onAddExecution,
        onAddFlow
      }), !builtIn && /* @__PURE__ */ react.createElement(Button, {
        variant: "plain",
        "aria-label": t5("common:delete"),
        onClick: onDelete
      }, /* @__PURE__ */ react.createElement(TrashIcon, null)))
    ]
  }))), !execution.isCollapsed && hasSubList && execution.executionList?.map((execution2) => /* @__PURE__ */ react.createElement(FlowRow, {
    builtIn,
    key: execution2.id,
    execution: execution2,
    onRowClick,
    onRowChange,
    onAddExecution,
    onAddFlow,
    onDelete
  })));
};

// build/authentication/execution-model.js
var IndexChange = class {
  constructor(oldIndex, newIndex) {
    this.oldIndex = oldIndex;
    this.newIndex = newIndex;
  }
};
var LevelChange = class extends IndexChange {
  constructor(oldIndex, newIndex, parent) {
    super(oldIndex, newIndex);
    this.parent = parent;
  }
};
var ExecutionList = class {
  constructor(list3) {
    this.list = list3;
    this.expandableList = this.transformToExpandableList(0, 0, {
      executionList: [],
      isCollapsed: false
    }).executionList || [];
  }
  transformToExpandableList(level2, currIndex, execution) {
    for (let index3 = currIndex; index3 < this.list.length; index3++) {
      const ex = this.list[index3];
      const nextRowLevel = this.list[index3 + 1]?.level || 0;
      if (ex.level === level2 && nextRowLevel <= level2) {
        execution.executionList?.push(ex);
      } else if (ex.level === level2 && nextRowLevel > level2) {
        const expandable2 = this.transformToExpandableList(nextRowLevel, index3 + 1, {
          ...ex,
          executionList: [],
          isCollapsed: false
        });
        execution.executionList?.push(expandable2);
      }
    }
    return execution;
  }
  order(list3) {
    let result = [];
    for (const row of list3 || this.expandableList) {
      result.push(row);
      if (row.executionList && !row.isCollapsed) {
        result = result.concat(this.order(row.executionList));
      }
    }
    return result;
  }
  findExecution(id3, list3) {
    let found = (list3 || this.expandableList).find((ex) => ex.id === id3);
    if (!found) {
      for (const ex of list3 || this.expandableList) {
        if (ex.executionList) {
          found = this.findExecution(id3, ex.executionList);
          if (found) {
            return found;
          }
        }
      }
    }
    return found;
  }
  getParentNodes(level2) {
    for (let index3 = 0; index3 < this.list.length; index3++) {
      const ex = this.list[index3];
      if (index3 + 1 < this.list.length && this.list[index3 + 1].level > ex.level && ex.level + 1 === level2) {
        return ex;
      }
    }
  }
  getChange(changed, order3) {
    const currentOrder = this.order();
    const newLocIndex = order3.findIndex((id3) => id3 === changed.id);
    const oldLocation = currentOrder[currentOrder.findIndex((ex) => ex.id === changed.id)];
    const newLocation = currentOrder[newLocIndex];
    if (newLocation.level !== oldLocation.level) {
      if (newLocation.level > 0) {
        const parent = this.getParentNodes(newLocation.level);
        return new LevelChange(parent?.executionList?.length || 0, newLocation.index, parent);
      }
      return new LevelChange(this.expandableList.length, newLocation.index);
    }
    return new IndexChange(oldLocation.index, newLocation.index);
  }
  clone() {
    const newList = new ExecutionList([]);
    newList.list = this.list;
    newList.expandableList = this.expandableList;
    return newList;
  }
};

// build/_snowpack/pkg/react-flow-renderer.js
function _defineProperty$2(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _objectWithoutPropertiesLoose2(source2, excluded) {
  if (source2 == null)
    return {};
  var target = {};
  var sourceKeys = Object.keys(source2);
  var key, i3;
  for (i3 = 0; i3 < sourceKeys.length; i3++) {
    key = sourceKeys[i3];
    if (excluded.indexOf(key) >= 0)
      continue;
    target[key] = source2[key];
  }
  return target;
}
function _objectWithoutProperties3(source2, excluded) {
  if (source2 == null)
    return {};
  var target = _objectWithoutPropertiesLoose2(source2, excluded);
  var key, i3;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source2);
    for (i3 = 0; i3 < sourceSymbolKeys.length; i3++) {
      key = sourceSymbolKeys[i3];
      if (excluded.indexOf(key) >= 0)
        continue;
      if (!Object.prototype.propertyIsEnumerable.call(source2, key))
        continue;
      target[key] = source2[key];
    }
  }
  return target;
}
function cc2(names) {
  if (typeof names === "string" || typeof names === "number")
    return "" + names;
  let out = "";
  if (Array.isArray(names)) {
    for (let i3 = 0, tmp; i3 < names.length; i3++) {
      if ((tmp = cc2(names[i3])) !== "") {
        out += (out && " ") + tmp;
      }
    }
  } else {
    for (let k2 in names) {
      if (names[k2])
        out += (out && " ") + k2;
    }
  }
  return out;
}
function formatProdErrorMessage(code2) {
  return "Minified Redux error #" + code2 + "; visit https://redux.js.org/Errors?code=" + code2 + " for the full message or use the non-minified dev environment for full errors. ";
}
var $$observable = function() {
  return typeof Symbol === "function" && Symbol.observable || "@@observable";
}();
var randomString = function randomString2() {
  return Math.random().toString(36).substring(7).split("").join(".");
};
var ActionTypes = {
  INIT: "@@redux/INIT" + randomString(),
  REPLACE: "@@redux/REPLACE" + randomString(),
  PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
    return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
  }
};
function isPlainObject3(obj) {
  if (typeof obj !== "object" || obj === null)
    return false;
  var proto = obj;
  while (Object.getPrototypeOf(proto) !== null) {
    proto = Object.getPrototypeOf(proto);
  }
  return Object.getPrototypeOf(obj) === proto;
}
function createStore(reducer, preloadedState, enhancer) {
  var _ref2;
  if (typeof preloadedState === "function" && typeof enhancer === "function" || typeof enhancer === "function" && typeof arguments[3] === "function") {
    throw new Error(formatProdErrorMessage(0));
  }
  if (typeof preloadedState === "function" && typeof enhancer === "undefined") {
    enhancer = preloadedState;
    preloadedState = void 0;
  }
  if (typeof enhancer !== "undefined") {
    if (typeof enhancer !== "function") {
      throw new Error(formatProdErrorMessage(1));
    }
    return enhancer(createStore)(reducer, preloadedState);
  }
  if (typeof reducer !== "function") {
    throw new Error(formatProdErrorMessage(2));
  }
  var currentReducer = reducer;
  var currentState = preloadedState;
  var currentListeners = [];
  var nextListeners = currentListeners;
  var isDispatching = false;
  function ensureCanMutateNextListeners() {
    if (nextListeners === currentListeners) {
      nextListeners = currentListeners.slice();
    }
  }
  function getState() {
    if (isDispatching) {
      throw new Error(formatProdErrorMessage(3));
    }
    return currentState;
  }
  function subscribe2(listener) {
    if (typeof listener !== "function") {
      throw new Error(formatProdErrorMessage(4));
    }
    if (isDispatching) {
      throw new Error(formatProdErrorMessage(5));
    }
    var isSubscribed = true;
    ensureCanMutateNextListeners();
    nextListeners.push(listener);
    return function unsubscribe2() {
      if (!isSubscribed) {
        return;
      }
      if (isDispatching) {
        throw new Error(formatProdErrorMessage(6));
      }
      isSubscribed = false;
      ensureCanMutateNextListeners();
      var index3 = nextListeners.indexOf(listener);
      nextListeners.splice(index3, 1);
      currentListeners = null;
    };
  }
  function dispatch2(action) {
    if (!isPlainObject3(action)) {
      throw new Error(formatProdErrorMessage(7));
    }
    if (typeof action.type === "undefined") {
      throw new Error(formatProdErrorMessage(8));
    }
    if (isDispatching) {
      throw new Error(formatProdErrorMessage(9));
    }
    try {
      isDispatching = true;
      currentState = currentReducer(currentState, action);
    } finally {
      isDispatching = false;
    }
    var listeners = currentListeners = nextListeners;
    for (var i3 = 0; i3 < listeners.length; i3++) {
      var listener = listeners[i3];
      listener();
    }
    return action;
  }
  function replaceReducer(nextReducer) {
    if (typeof nextReducer !== "function") {
      throw new Error(formatProdErrorMessage(10));
    }
    currentReducer = nextReducer;
    dispatch2({
      type: ActionTypes.REPLACE
    });
  }
  function observable() {
    var _ref;
    var outerSubscribe = subscribe2;
    return _ref = {
      subscribe: function subscribe3(observer) {
        if (typeof observer !== "object" || observer === null) {
          throw new Error(formatProdErrorMessage(11));
        }
        function observeState() {
          if (observer.next) {
            observer.next(getState());
          }
        }
        observeState();
        var unsubscribe2 = outerSubscribe(observeState);
        return {
          unsubscribe: unsubscribe2
        };
      }
    }, _ref[$$observable] = function() {
      return this;
    }, _ref;
  }
  dispatch2({
    type: ActionTypes.INIT
  });
  return _ref2 = {
    dispatch: dispatch2,
    subscribe: subscribe2,
    getState,
    replaceReducer
  }, _ref2[$$observable] = observable, _ref2;
}
function bindActionCreator(actionCreator, dispatch2) {
  return function() {
    return dispatch2(actionCreator.apply(this, arguments));
  };
}
function bindActionCreators(actionCreators, dispatch2) {
  if (typeof actionCreators === "function") {
    return bindActionCreator(actionCreators, dispatch2);
  }
  if (typeof actionCreators !== "object" || actionCreators === null) {
    throw new Error(formatProdErrorMessage(16));
  }
  var boundActionCreators = {};
  for (var key in actionCreators) {
    var actionCreator = actionCreators[key];
    if (typeof actionCreator === "function") {
      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch2);
    }
  }
  return boundActionCreators;
}
function getAugmentedNamespace(n3) {
  if (n3.__esModule)
    return n3;
  var a2 = Object.defineProperty({}, "__esModule", {value: true});
  Object.keys(n3).forEach(function(k2) {
    var d2 = Object.getOwnPropertyDescriptor(n3, k2);
    Object.defineProperty(a2, k2, d2.get ? d2 : {
      enumerable: true,
      get: function() {
        return n3[k2];
      }
    });
  });
  return a2;
}
var propTypes2 = {exports: {}};
var reactIs$12 = {exports: {}};
var reactIs_production_min$12 = {};
/** @license React v16.13.1
 * react-is.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var b$12 = typeof Symbol === "function" && Symbol.for;
var c$12 = b$12 ? Symbol.for("react.element") : 60103;
var d$12 = b$12 ? Symbol.for("react.portal") : 60106;
var e$12 = b$12 ? Symbol.for("react.fragment") : 60107;
var f$12 = b$12 ? Symbol.for("react.strict_mode") : 60108;
var g$12 = b$12 ? Symbol.for("react.profiler") : 60114;
var h$12 = b$12 ? Symbol.for("react.provider") : 60109;
var k$12 = b$12 ? Symbol.for("react.context") : 60110;
var l$12 = b$12 ? Symbol.for("react.async_mode") : 60111;
var m$12 = b$12 ? Symbol.for("react.concurrent_mode") : 60111;
var n$12 = b$12 ? Symbol.for("react.forward_ref") : 60112;
var p$12 = b$12 ? Symbol.for("react.suspense") : 60113;
var q$12 = b$12 ? Symbol.for("react.suspense_list") : 60120;
var r$12 = b$12 ? Symbol.for("react.memo") : 60115;
var t4 = b$12 ? Symbol.for("react.lazy") : 60116;
var v$12 = b$12 ? Symbol.for("react.block") : 60121;
var w$12 = b$12 ? Symbol.for("react.fundamental") : 60117;
var x$12 = b$12 ? Symbol.for("react.responder") : 60118;
var y$12 = b$12 ? Symbol.for("react.scope") : 60119;
function z$12(a2) {
  if (typeof a2 === "object" && a2 !== null) {
    var u = a2.$$typeof;
    switch (u) {
      case c$12:
        switch (a2 = a2.type, a2) {
          case l$12:
          case m$12:
          case e$12:
          case g$12:
          case f$12:
          case p$12:
            return a2;
          default:
            switch (a2 = a2 && a2.$$typeof, a2) {
              case k$12:
              case n$12:
              case t4:
              case r$12:
              case h$12:
                return a2;
              default:
                return u;
            }
        }
      case d$12:
        return u;
    }
  }
}
function A$12(a2) {
  return z$12(a2) === m$12;
}
reactIs_production_min$12.AsyncMode = l$12;
reactIs_production_min$12.ConcurrentMode = m$12;
reactIs_production_min$12.ContextConsumer = k$12;
reactIs_production_min$12.ContextProvider = h$12;
reactIs_production_min$12.Element = c$12;
reactIs_production_min$12.ForwardRef = n$12;
reactIs_production_min$12.Fragment = e$12;
reactIs_production_min$12.Lazy = t4;
reactIs_production_min$12.Memo = r$12;
reactIs_production_min$12.Portal = d$12;
reactIs_production_min$12.Profiler = g$12;
reactIs_production_min$12.StrictMode = f$12;
reactIs_production_min$12.Suspense = p$12;
reactIs_production_min$12.isAsyncMode = function(a2) {
  return A$12(a2) || z$12(a2) === l$12;
};
reactIs_production_min$12.isConcurrentMode = A$12;
reactIs_production_min$12.isContextConsumer = function(a2) {
  return z$12(a2) === k$12;
};
reactIs_production_min$12.isContextProvider = function(a2) {
  return z$12(a2) === h$12;
};
reactIs_production_min$12.isElement = function(a2) {
  return typeof a2 === "object" && a2 !== null && a2.$$typeof === c$12;
};
reactIs_production_min$12.isForwardRef = function(a2) {
  return z$12(a2) === n$12;
};
reactIs_production_min$12.isFragment = function(a2) {
  return z$12(a2) === e$12;
};
reactIs_production_min$12.isLazy = function(a2) {
  return z$12(a2) === t4;
};
reactIs_production_min$12.isMemo = function(a2) {
  return z$12(a2) === r$12;
};
reactIs_production_min$12.isPortal = function(a2) {
  return z$12(a2) === d$12;
};
reactIs_production_min$12.isProfiler = function(a2) {
  return z$12(a2) === g$12;
};
reactIs_production_min$12.isStrictMode = function(a2) {
  return z$12(a2) === f$12;
};
reactIs_production_min$12.isSuspense = function(a2) {
  return z$12(a2) === p$12;
};
reactIs_production_min$12.isValidElementType = function(a2) {
  return typeof a2 === "string" || typeof a2 === "function" || a2 === e$12 || a2 === m$12 || a2 === g$12 || a2 === f$12 || a2 === p$12 || a2 === q$12 || typeof a2 === "object" && a2 !== null && (a2.$$typeof === t4 || a2.$$typeof === r$12 || a2.$$typeof === h$12 || a2.$$typeof === k$12 || a2.$$typeof === n$12 || a2.$$typeof === w$12 || a2.$$typeof === x$12 || a2.$$typeof === y$12 || a2.$$typeof === v$12);
};
reactIs_production_min$12.typeOf = z$12;
{
  reactIs$12.exports = reactIs_production_min$12;
}
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var getOwnPropertySymbols2 = Object.getOwnPropertySymbols;
var hasOwnProperty4 = Object.prototype.hasOwnProperty;
var propIsEnumerable2 = Object.prototype.propertyIsEnumerable;
function toObject2(val) {
  if (val === null || val === void 0) {
    throw new TypeError("Object.assign cannot be called with null or undefined");
  }
  return Object(val);
}
function shouldUseNative2() {
  try {
    if (!Object.assign) {
      return false;
    }
    var test1 = new String("abc");
    test1[5] = "de";
    if (Object.getOwnPropertyNames(test1)[0] === "5") {
      return false;
    }
    var test2 = {};
    for (var i3 = 0; i3 < 10; i3++) {
      test2["_" + String.fromCharCode(i3)] = i3;
    }
    var order22 = Object.getOwnPropertyNames(test2).map(function(n3) {
      return test2[n3];
    });
    if (order22.join("") !== "0123456789") {
      return false;
    }
    var test3 = {};
    "abcdefghijklmnopqrst".split("").forEach(function(letter) {
      test3[letter] = letter;
    });
    if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
      return false;
    }
    return true;
  } catch (err) {
    return false;
  }
}
var objectAssign2 = shouldUseNative2() ? Object.assign : function(target, source2) {
  var from;
  var to = toObject2(target);
  var symbols;
  for (var s2 = 1; s2 < arguments.length; s2++) {
    from = Object(arguments[s2]);
    for (var key in from) {
      if (hasOwnProperty4.call(from, key)) {
        to[key] = from[key];
      }
    }
    if (getOwnPropertySymbols2) {
      symbols = getOwnPropertySymbols2(from);
      for (var i3 = 0; i3 < symbols.length; i3++) {
        if (propIsEnumerable2.call(from, symbols[i3])) {
          to[symbols[i3]] = from[symbols[i3]];
        }
      }
    }
  }
  return to;
};
var ReactPropTypesSecret$3 = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
var ReactPropTypesSecret_12 = ReactPropTypesSecret$3;
var has = Function.call.bind(Object.prototype.hasOwnProperty);
var ReactPropTypesSecret2 = ReactPropTypesSecret_12;
function emptyFunction2() {
}
function emptyFunctionWithReset2() {
}
emptyFunctionWithReset2.resetWarningCache = emptyFunction2;
var factoryWithThrowingShims2 = function() {
  function shim(props, propName, componentName, location2, propFullName, secret) {
    if (secret === ReactPropTypesSecret2) {
      return;
    }
    var err = new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");
    err.name = "Invariant Violation";
    throw err;
  }
  shim.isRequired = shim;
  function getShim() {
    return shim;
  }
  var ReactPropTypes = {
    array: shim,
    bool: shim,
    func: shim,
    number: shim,
    object: shim,
    string: shim,
    symbol: shim,
    any: shim,
    arrayOf: getShim,
    element: shim,
    elementType: shim,
    instanceOf: getShim,
    node: shim,
    objectOf: getShim,
    oneOf: getShim,
    oneOfType: getShim,
    shape: getShim,
    exact: getShim,
    checkPropTypes: emptyFunctionWithReset2,
    resetWarningCache: emptyFunction2
  };
  ReactPropTypes.PropTypes = ReactPropTypes;
  return ReactPropTypes;
};
{
  propTypes2.exports = factoryWithThrowingShims2();
}
var ReactReduxContext = /* @__PURE__ */ react.createContext(null);
function defaultNoopBatch(callback) {
  callback();
}
var batch = defaultNoopBatch;
var setBatch = function setBatch2(newBatch) {
  return batch = newBatch;
};
var getBatch = function getBatch2() {
  return batch;
};
function createListenerCollection() {
  var batch2 = getBatch();
  var first2 = null;
  var last2 = null;
  return {
    clear: function clear() {
      first2 = null;
      last2 = null;
    },
    notify: function notify2() {
      batch2(function() {
        var listener = first2;
        while (listener) {
          listener.callback();
          listener = listener.next;
        }
      });
    },
    get: function get7() {
      var listeners = [];
      var listener = first2;
      while (listener) {
        listeners.push(listener);
        listener = listener.next;
      }
      return listeners;
    },
    subscribe: function subscribe2(callback) {
      var isSubscribed = true;
      var listener = last2 = {
        callback,
        next: null,
        prev: last2
      };
      if (listener.prev) {
        listener.prev.next = listener;
      } else {
        first2 = listener;
      }
      return function unsubscribe2() {
        if (!isSubscribed || first2 === null)
          return;
        isSubscribed = false;
        if (listener.next) {
          listener.next.prev = listener.prev;
        } else {
          last2 = listener.prev;
        }
        if (listener.prev) {
          listener.prev.next = listener.next;
        } else {
          first2 = listener.next;
        }
      };
    }
  };
}
var nullListeners = {
  notify: function notify() {
  },
  get: function get4() {
    return [];
  }
};
function createSubscription(store2, parentSub) {
  var unsubscribe2;
  var listeners = nullListeners;
  function addNestedSub(listener) {
    trySubscribe();
    return listeners.subscribe(listener);
  }
  function notifyNestedSubs() {
    listeners.notify();
  }
  function handleChangeWrapper() {
    if (subscription.onStateChange) {
      subscription.onStateChange();
    }
  }
  function isSubscribed() {
    return Boolean(unsubscribe2);
  }
  function trySubscribe() {
    if (!unsubscribe2) {
      unsubscribe2 = parentSub ? parentSub.addNestedSub(handleChangeWrapper) : store2.subscribe(handleChangeWrapper);
      listeners = createListenerCollection();
    }
  }
  function tryUnsubscribe() {
    if (unsubscribe2) {
      unsubscribe2();
      unsubscribe2 = void 0;
      listeners.clear();
      listeners = nullListeners;
    }
  }
  var subscription = {
    addNestedSub,
    notifyNestedSubs,
    handleChangeWrapper,
    isSubscribed,
    trySubscribe,
    tryUnsubscribe,
    getListeners: function getListeners() {
      return listeners;
    }
  };
  return subscription;
}
var useIsomorphicLayoutEffect2 = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined" ? react.useLayoutEffect : react.useEffect;
function Provider$1(_ref) {
  var store2 = _ref.store, context2 = _ref.context, children2 = _ref.children;
  var contextValue = react.useMemo(function() {
    var subscription = createSubscription(store2);
    subscription.onStateChange = subscription.notifyNestedSubs;
    return {
      store: store2,
      subscription
    };
  }, [store2]);
  var previousState = react.useMemo(function() {
    return store2.getState();
  }, [store2]);
  useIsomorphicLayoutEffect2(function() {
    var subscription = contextValue.subscription;
    subscription.trySubscribe();
    if (previousState !== store2.getState()) {
      subscription.notifyNestedSubs();
    }
    return function() {
      subscription.tryUnsubscribe();
      subscription.onStateChange = null;
    };
  }, [contextValue, previousState]);
  var Context2 = context2 || ReactReduxContext;
  return /* @__PURE__ */ react.createElement(Context2.Provider, {
    value: contextValue
  }, children2);
}
var reactIs2 = reactIs$12.exports;
var FORWARD_REF_STATICS2 = {
  $$typeof: true,
  render: true,
  defaultProps: true,
  displayName: true,
  propTypes: true
};
var MEMO_STATICS2 = {
  $$typeof: true,
  compare: true,
  defaultProps: true,
  displayName: true,
  propTypes: true,
  type: true
};
var TYPE_STATICS2 = {};
TYPE_STATICS2[reactIs2.ForwardRef] = FORWARD_REF_STATICS2;
TYPE_STATICS2[reactIs2.Memo] = MEMO_STATICS2;
if (typeof Symbol === "function" && Symbol.for) {
  x2 = Symbol.for;
  x2("react.element");
  x2("react.portal");
  x2("react.fragment");
  x2("react.strict_mode");
  x2("react.profiler");
  x2("react.provider");
  x2("react.context");
  x2("react.forward_ref");
  x2("react.suspense");
  x2("react.suspense_list");
  x2("react.memo");
  x2("react.lazy");
  x2("react.block");
  x2("react.server.block");
  x2("react.fundamental");
  x2("react.debug_trace_mode");
  x2("react.legacy_hidden");
}
var x2;
function useReduxContext() {
  var contextValue = react.useContext(ReactReduxContext);
  return contextValue;
}
function createStoreHook(context2) {
  if (context2 === void 0) {
    context2 = ReactReduxContext;
  }
  var useReduxContext$1 = context2 === ReactReduxContext ? useReduxContext : function() {
    return react.useContext(context2);
  };
  return function useStore3() {
    var _useReduxContext = useReduxContext$1(), store2 = _useReduxContext.store;
    return store2;
  };
}
var useStore$1 = /* @__PURE__ */ createStoreHook();
function createDispatchHook(context2) {
  if (context2 === void 0) {
    context2 = ReactReduxContext;
  }
  var useStore3 = context2 === ReactReduxContext ? useStore$1 : createStoreHook(context2);
  return function useDispatch() {
    var store2 = useStore3();
    return store2.dispatch;
  };
}
var useDispatch$1 = /* @__PURE__ */ createDispatchHook();
var refEquality = function refEquality2(a2, b2) {
  return a2 === b2;
};
function useSelectorWithStoreAndSubscription(selector2, equalityFn, store2, contextSub) {
  var _useReducer = react.useReducer(function(s2) {
    return s2 + 1;
  }, 0), forceRender = _useReducer[1];
  var subscription = react.useMemo(function() {
    return createSubscription(store2, contextSub);
  }, [store2, contextSub]);
  var latestSubscriptionCallbackError = react.useRef();
  var latestSelector = react.useRef();
  var latestStoreState = react.useRef();
  var latestSelectedState = react.useRef();
  var storeState = store2.getState();
  var selectedState;
  try {
    if (selector2 !== latestSelector.current || storeState !== latestStoreState.current || latestSubscriptionCallbackError.current) {
      var newSelectedState = selector2(storeState);
      if (latestSelectedState.current === void 0 || !equalityFn(newSelectedState, latestSelectedState.current)) {
        selectedState = newSelectedState;
      } else {
        selectedState = latestSelectedState.current;
      }
    } else {
      selectedState = latestSelectedState.current;
    }
  } catch (err) {
    if (latestSubscriptionCallbackError.current) {
      err.message += "\nThe error may be correlated with this previous error:\n" + latestSubscriptionCallbackError.current.stack + "\n\n";
    }
    throw err;
  }
  useIsomorphicLayoutEffect2(function() {
    latestSelector.current = selector2;
    latestStoreState.current = storeState;
    latestSelectedState.current = selectedState;
    latestSubscriptionCallbackError.current = void 0;
  });
  useIsomorphicLayoutEffect2(function() {
    function checkForUpdates() {
      try {
        var newStoreState = store2.getState();
        if (newStoreState === latestStoreState.current) {
          return;
        }
        var _newSelectedState = latestSelector.current(newStoreState);
        if (equalityFn(_newSelectedState, latestSelectedState.current)) {
          return;
        }
        latestSelectedState.current = _newSelectedState;
        latestStoreState.current = newStoreState;
      } catch (err) {
        latestSubscriptionCallbackError.current = err;
      }
      forceRender();
    }
    subscription.onStateChange = checkForUpdates;
    subscription.trySubscribe();
    checkForUpdates();
    return function() {
      return subscription.tryUnsubscribe();
    };
  }, [store2, subscription]);
  return selectedState;
}
function createSelectorHook(context2) {
  if (context2 === void 0) {
    context2 = ReactReduxContext;
  }
  var useReduxContext$1 = context2 === ReactReduxContext ? useReduxContext : function() {
    return react.useContext(context2);
  };
  return function useSelector2(selector2, equalityFn) {
    if (equalityFn === void 0) {
      equalityFn = refEquality;
    }
    var _useReduxContext = useReduxContext$1(), store2 = _useReduxContext.store, contextSub = _useReduxContext.subscription;
    var selectedState = useSelectorWithStoreAndSubscription(selector2, equalityFn, store2, contextSub);
    react.useDebugValue(selectedState);
    return selectedState;
  };
}
var useSelector = /* @__PURE__ */ createSelectorHook();
setBatch(reactDom.unstable_batchedUpdates);
function createAction(type, payload) {
  return {
    type,
    payload
  };
}
var SET_ON_CONNECT = "SET_ON_CONNECT";
var SET_ON_CONNECT_START = "SET_ON_CONNECT_START";
var SET_ON_CONNECT_STOP = "SET_ON_CONNECT_STOP";
var SET_ON_CONNECT_END = "SET_ON_CONNECT_END";
var SET_ELEMENTS = "SET_ELEMENTS";
var UPDATE_NODE_DIMENSIONS = "UPDATE_NODE_DIMENSIONS";
var UPDATE_NODE_POS = "UPDATE_NODE_POS";
var UPDATE_NODE_POS_DIFF = "UPDATE_NODE_POS_DIFF";
var SET_USER_SELECTION = "SET_USER_SELECTION";
var UPDATE_USER_SELECTION = "UPDATE_USER_SELECTION";
var UNSET_USER_SELECTION = "UNSET_USER_SELECTION";
var SET_SELECTION = "SET_SELECTION";
var UNSET_NODES_SELECTION = "UNSET_NODES_SELECTION";
var SET_SELECTED_ELEMENTS = "SET_SELECTED_ELEMENTS";
var RESET_SELECTED_ELEMENTS = "RESET_SELECTED_ELEMENTS";
var ADD_SELECTED_ELEMENTS = "ADD_SELECTED_ELEMENTS";
var UPDATE_TRANSFORM = "UPDATE_TRANSFORM";
var UPDATE_SIZE = "UPDATE_SIZE";
var INIT_D3ZOOM = "INIT_D3ZOOM";
var SET_MINZOOM = "SET_MINZOOM";
var SET_MAXZOOM = "SET_MAXZOOM";
var SET_TRANSLATEEXTENT = "SET_TRANSLATEEXTENT";
var SET_CONNECTION_POSITION = "SET_CONNECTION_POSITION";
var SET_CONNECTION_NODEID = "SET_CONNECTION_NODEID";
var SET_SNAPTOGRID = "SET_SNAPTOGRID";
var SET_SNAPGRID = "SET_SNAPGRID";
var SET_INTERACTIVE = "SET_INTERACTIVE";
var SET_NODES_DRAGGABLE = "SET_NODES_DRAGGABLE";
var SET_NODES_CONNECTABLE = "SET_NODES_CONNECTABLE";
var SET_ELEMENTS_SELECTABLE = "SET_ELEMENTS_SELECTABLE";
var SET_MULTI_SELECTION_ACTIVE = "SET_MULTI_SELECTION_ACTIVE";
var SET_CONNECTION_MODE = "SET_CONNECTION_MODE";
var SET_NODE_EXTENT = "SET_NODE_EXTENT";
var setOnConnect = function setOnConnect2(onConnect) {
  return createAction(SET_ON_CONNECT, {
    onConnect
  });
};
var setOnConnectStart = function setOnConnectStart2(onConnectStart) {
  return createAction(SET_ON_CONNECT_START, {
    onConnectStart
  });
};
var setOnConnectStop = function setOnConnectStop2(onConnectStop) {
  return createAction(SET_ON_CONNECT_STOP, {
    onConnectStop
  });
};
var setOnConnectEnd = function setOnConnectEnd2(onConnectEnd) {
  return createAction(SET_ON_CONNECT_END, {
    onConnectEnd
  });
};
var setElements = function setElements2(elements) {
  return createAction(SET_ELEMENTS, elements);
};
var updateNodeDimensions = function updateNodeDimensions2(updates) {
  return createAction(UPDATE_NODE_DIMENSIONS, updates);
};
var updateNodePos = function updateNodePos2(payload) {
  return createAction(UPDATE_NODE_POS, payload);
};
var updateNodePosDiff = function updateNodePosDiff2(payload) {
  return createAction(UPDATE_NODE_POS_DIFF, payload);
};
var setUserSelection = function setUserSelection2(mousePos) {
  return createAction(SET_USER_SELECTION, mousePos);
};
var updateUserSelection = function updateUserSelection2(mousePos) {
  return createAction(UPDATE_USER_SELECTION, mousePos);
};
var unsetUserSelection = function unsetUserSelection2() {
  return createAction(UNSET_USER_SELECTION);
};
var setSelection = function setSelection2(selectionActive) {
  return createAction(SET_SELECTION, {
    selectionActive
  });
};
var unsetNodesSelection = function unsetNodesSelection2() {
  return createAction(UNSET_NODES_SELECTION, {
    nodesSelectionActive: false
  });
};
var resetSelectedElements = function resetSelectedElements2() {
  return createAction(RESET_SELECTED_ELEMENTS, {
    selectedElements: null
  });
};
var setSelectedElements = function setSelectedElements2(elements) {
  return createAction(SET_SELECTED_ELEMENTS, elements);
};
var addSelectedElements = function addSelectedElements2(elements) {
  return createAction(ADD_SELECTED_ELEMENTS, elements);
};
var updateTransform = function updateTransform2(transform3) {
  return createAction(UPDATE_TRANSFORM, {
    transform: transform3
  });
};
var updateSize = function updateSize2(size2) {
  return createAction(UPDATE_SIZE, {
    width: size2.width || 500,
    height: size2.height || 500
  });
};
var initD3Zoom = function initD3Zoom2(payload) {
  return createAction(INIT_D3ZOOM, payload);
};
var setMinZoom = function setMinZoom2(minZoom) {
  return createAction(SET_MINZOOM, minZoom);
};
var setMaxZoom = function setMaxZoom2(maxZoom) {
  return createAction(SET_MAXZOOM, maxZoom);
};
var setTranslateExtent = function setTranslateExtent2(translateExtent) {
  return createAction(SET_TRANSLATEEXTENT, translateExtent);
};
var setConnectionPosition = function setConnectionPosition2(connectionPosition) {
  return createAction(SET_CONNECTION_POSITION, {
    connectionPosition
  });
};
var setConnectionNodeId = function setConnectionNodeId2(payload) {
  return createAction(SET_CONNECTION_NODEID, payload);
};
var setSnapToGrid = function setSnapToGrid2(snapToGrid2) {
  return createAction(SET_SNAPTOGRID, {
    snapToGrid: snapToGrid2
  });
};
var setSnapGrid = function setSnapGrid2(snapGrid) {
  return createAction(SET_SNAPGRID, {
    snapGrid
  });
};
var setInteractive = function setInteractive2(isInteractive) {
  return createAction(SET_INTERACTIVE, {
    nodesDraggable: isInteractive,
    nodesConnectable: isInteractive,
    elementsSelectable: isInteractive
  });
};
var setNodesDraggable = function setNodesDraggable2(nodesDraggable) {
  return createAction(SET_NODES_DRAGGABLE, {
    nodesDraggable
  });
};
var setNodesConnectable = function setNodesConnectable2(nodesConnectable) {
  return createAction(SET_NODES_CONNECTABLE, {
    nodesConnectable
  });
};
var setElementsSelectable = function setElementsSelectable2(elementsSelectable) {
  return createAction(SET_ELEMENTS_SELECTABLE, {
    elementsSelectable
  });
};
var setMultiSelectionActive = function setMultiSelectionActive2(multiSelectionActive) {
  return createAction(SET_MULTI_SELECTION_ACTIVE, {
    multiSelectionActive
  });
};
var setConnectionMode = function setConnectionMode2(connectionMode) {
  return createAction(SET_CONNECTION_MODE, {
    connectionMode
  });
};
var setNodeExtent = function setNodeExtent2(nodeExtent) {
  return createAction(SET_NODE_EXTENT, nodeExtent);
};
var actions = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  setOnConnect,
  setOnConnectStart,
  setOnConnectStop,
  setOnConnectEnd,
  setElements,
  updateNodeDimensions,
  updateNodePos,
  updateNodePosDiff,
  setUserSelection,
  updateUserSelection,
  unsetUserSelection,
  setSelection,
  unsetNodesSelection,
  resetSelectedElements,
  setSelectedElements,
  addSelectedElements,
  updateTransform,
  updateSize,
  initD3Zoom,
  setMinZoom,
  setMaxZoom,
  setTranslateExtent,
  setConnectionPosition,
  setConnectionNodeId,
  setSnapToGrid,
  setSnapGrid,
  setInteractive,
  setNodesDraggable,
  setNodesConnectable,
  setElementsSelectable,
  setMultiSelectionActive,
  setConnectionMode,
  setNodeExtent
});
var useTypedSelector = useSelector;
function useStoreActions(actionSelector) {
  var dispatch2 = useDispatch$1();
  var currAction = actionSelector(actions);
  var action = react.useMemo(function() {
    return typeof currAction === "function" ? bindActionCreators(currAction, dispatch2) : bindActionCreators(currAction, dispatch2);
  }, [dispatch2, currAction]);
  return action;
}
var useStoreState = useTypedSelector;
var useStore = function useStore2() {
  var store2 = useStore$1();
  return store2;
};
function _arrayLikeToArray$1(arr, len2) {
  if (len2 == null || len2 > arr.length)
    len2 = arr.length;
  for (var i3 = 0, arr2 = new Array(len2); i3 < len2; i3++) {
    arr2[i3] = arr[i3];
  }
  return arr2;
}
function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr))
    return _arrayLikeToArray$1(arr);
}
function _iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null)
    return Array.from(iter);
}
function _unsupportedIterableToArray$1(o, minLen) {
  if (!o)
    return;
  if (typeof o === "string")
    return _arrayLikeToArray$1(o, minLen);
  var n3 = Object.prototype.toString.call(o).slice(8, -1);
  if (n3 === "Object" && o.constructor)
    n3 = o.constructor.name;
  if (n3 === "Map" || n3 === "Set")
    return Array.from(o);
  if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3))
    return _arrayLikeToArray$1(o, minLen);
}
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray2(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread();
}
function _arrayWithHoles$1(arr) {
  if (Array.isArray(arr))
    return arr;
}
function _iterableToArrayLimit$1(arr, i3) {
  var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
  if (_i == null)
    return;
  var _arr = [];
  var _n = true;
  var _d = false;
  var _s, _e;
  try {
    for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);
      if (i3 && _arr.length === i3)
        break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null)
        _i["return"]();
    } finally {
      if (_d)
        throw _e;
    }
  }
  return _arr;
}
function _nonIterableRest$1() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _slicedToArray$1(arr, i3) {
  return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i3) || _unsupportedIterableToArray$1(arr, i3) || _nonIterableRest$1();
}
var isInputDOMNode = function isInputDOMNode2(e2) {
  var target = e2 === null || e2 === void 0 ? void 0 : e2.target;
  return ["INPUT", "SELECT", "TEXTAREA", "BUTTON"].includes(target === null || target === void 0 ? void 0 : target.nodeName) || (target === null || target === void 0 ? void 0 : target.hasAttribute("contenteditable"));
};
var getDimensions = function getDimensions2(node) {
  return {
    width: node.offsetWidth,
    height: node.offsetHeight
  };
};
var clamp3 = function clamp4(val) {
  var min2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
  var max2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1;
  return Math.min(Math.max(val, min2), max2);
};
var clampPosition = function clampPosition2(position2, extent) {
  return {
    x: clamp3(position2.x, extent[0][0], extent[1][0]),
    y: clamp3(position2.y, extent[0][1], extent[1][1])
  };
};
var getHostForElement = function getHostForElement2(element) {
  var _element$getRootNode, _window;
  return ((_element$getRootNode = element.getRootNode) === null || _element$getRootNode === void 0 ? void 0 : _element$getRootNode.call(element)) || ((_window = window) === null || _window === void 0 ? void 0 : _window.document);
};
var useKeyPress = function(keyCode) {
  var _useState = react.useState(false), _useState2 = _slicedToArray$1(_useState, 2), keyPressed = _useState2[0], setKeyPressed = _useState2[1];
  react.useEffect(function() {
    if (typeof keyCode !== "undefined") {
      var downHandler = function downHandler2(event) {
        if (!isInputDOMNode(event) && (event.key === keyCode || event.keyCode === keyCode)) {
          event.preventDefault();
          setKeyPressed(true);
        }
      };
      var upHandler = function upHandler2(event) {
        if (!isInputDOMNode(event) && (event.key === keyCode || event.keyCode === keyCode)) {
          setKeyPressed(false);
        }
      };
      var resetHandler = function resetHandler2() {
        return setKeyPressed(false);
      };
      window.addEventListener("keydown", downHandler);
      window.addEventListener("keyup", upHandler);
      window.addEventListener("blur", resetHandler);
      return function() {
        window.removeEventListener("keydown", downHandler);
        window.removeEventListener("keyup", upHandler);
        window.removeEventListener("blur", resetHandler);
      };
    }
  }, [keyCode, setKeyPressed]);
  return keyPressed;
};
function ownKeys$d(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$d(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$d(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$d(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var isEdge3 = function isEdge4(element) {
  return "id" in element && "source" in element && "target" in element;
};
var isNode = function isNode2(element) {
  return "id" in element && !("source" in element) && !("target" in element);
};
var removeElements = function removeElements2(elementsToRemove, elements) {
  var nodeIdsToRemove = elementsToRemove.map(function(n3) {
    return n3.id;
  });
  return elements.filter(function(element) {
    var edgeElement = element;
    return !(nodeIdsToRemove.includes(element.id) || nodeIdsToRemove.includes(edgeElement.target) || nodeIdsToRemove.includes(edgeElement.source));
  });
};
var pointToRendererPoint = function pointToRendererPoint2(_ref2, _ref3, snapToGrid2, _ref4) {
  var x2 = _ref2.x, y3 = _ref2.y;
  var _ref5 = _slicedToArray$1(_ref3, 3), tx = _ref5[0], ty = _ref5[1], tScale = _ref5[2];
  var _ref6 = _slicedToArray$1(_ref4, 2), snapX = _ref6[0], snapY = _ref6[1];
  var position2 = {
    x: (x2 - tx) / tScale,
    y: (y3 - ty) / tScale
  };
  if (snapToGrid2) {
    return {
      x: snapX * Math.round(position2.x / snapX),
      y: snapY * Math.round(position2.y / snapY)
    };
  }
  return position2;
};
var onLoadProject = function onLoadProject2(currentStore) {
  return function(position2) {
    var _currentStore$getStat = currentStore.getState(), transform3 = _currentStore$getStat.transform, snapToGrid2 = _currentStore$getStat.snapToGrid, snapGrid = _currentStore$getStat.snapGrid;
    return pointToRendererPoint(position2, transform3, snapToGrid2, snapGrid);
  };
};
var parseNode = function parseNode2(node, nodeExtent) {
  var _node$style, _node$style2;
  return _objectSpread$d(_objectSpread$d({}, node), {}, {
    id: node.id.toString(),
    type: node.type || "default",
    __rf: {
      position: clampPosition(node.position, nodeExtent),
      width: ((_node$style = node.style) === null || _node$style === void 0 ? void 0 : _node$style.width) || null,
      height: ((_node$style2 = node.style) === null || _node$style2 === void 0 ? void 0 : _node$style2.height) || null,
      handleBounds: {},
      isDragging: false
    }
  });
};
var parseEdge = function parseEdge2(edge) {
  return _objectSpread$d(_objectSpread$d({}, edge), {}, {
    source: edge.source.toString(),
    target: edge.target.toString(),
    sourceHandle: edge.sourceHandle ? edge.sourceHandle.toString() : null,
    targetHandle: edge.targetHandle ? edge.targetHandle.toString() : null,
    id: edge.id.toString(),
    type: edge.type || "default"
  });
};
var getBoundsOfBoxes = function getBoundsOfBoxes2(box1, box2) {
  return {
    x: Math.min(box1.x, box2.x),
    y: Math.min(box1.y, box2.y),
    x2: Math.max(box1.x2, box2.x2),
    y2: Math.max(box1.y2, box2.y2)
  };
};
var rectToBox = function rectToBox2(_ref7) {
  var x2 = _ref7.x, y3 = _ref7.y, width2 = _ref7.width, height = _ref7.height;
  return {
    x: x2,
    y: y3,
    x2: x2 + width2,
    y2: y3 + height
  };
};
var boxToRect = function boxToRect2(_ref8) {
  var x2 = _ref8.x, y3 = _ref8.y, x22 = _ref8.x2, y22 = _ref8.y2;
  return {
    x: x2,
    y: y3,
    width: x22 - x2,
    height: y22 - y3
  };
};
var getBoundsofRects = function getBoundsofRects2(rect1, rect2) {
  return boxToRect(getBoundsOfBoxes(rectToBox(rect1), rectToBox(rect2)));
};
var getRectOfNodes = function getRectOfNodes2(nodes) {
  var box = nodes.reduce(function(currBox, _ref9) {
    var _ref9$__rf = _ref9.__rf;
    _ref9$__rf = _ref9$__rf === void 0 ? {} : _ref9$__rf;
    var position2 = _ref9$__rf.position, width2 = _ref9$__rf.width, height = _ref9$__rf.height;
    return getBoundsOfBoxes(currBox, rectToBox(_objectSpread$d(_objectSpread$d({}, position2), {}, {
      width: width2,
      height
    })));
  }, {
    x: Infinity,
    y: Infinity,
    x2: -Infinity,
    y2: -Infinity
  });
  return boxToRect(box);
};
var getNodesInside = function getNodesInside2(nodes, rect) {
  var _ref13 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [0, 0, 1], _ref14 = _slicedToArray$1(_ref13, 3), tx = _ref14[0], ty = _ref14[1], tScale = _ref14[2];
  var partially = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
  var excludeNonSelectableNodes = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : false;
  var rBox = rectToBox({
    x: (rect.x - tx) / tScale,
    y: (rect.y - ty) / tScale,
    width: rect.width / tScale,
    height: rect.height / tScale
  });
  return nodes.filter(function(_ref15) {
    var _ref15$selectable = _ref15.selectable, selectable2 = _ref15$selectable === void 0 ? true : _ref15$selectable, _ref15$__rf = _ref15.__rf, position2 = _ref15$__rf.position, width2 = _ref15$__rf.width, height = _ref15$__rf.height, isDragging = _ref15$__rf.isDragging;
    if (excludeNonSelectableNodes && !selectable2) {
      return false;
    }
    var nBox = rectToBox(_objectSpread$d(_objectSpread$d({}, position2), {}, {
      width: width2,
      height
    }));
    var xOverlap = Math.max(0, Math.min(rBox.x2, nBox.x2) - Math.max(rBox.x, nBox.x));
    var yOverlap = Math.max(0, Math.min(rBox.y2, nBox.y2) - Math.max(rBox.y, nBox.y));
    var overlappingArea = Math.ceil(xOverlap * yOverlap);
    if (width2 === null || height === null || isDragging) {
      return true;
    }
    if (partially) {
      return overlappingArea > 0;
    }
    var area = width2 * height;
    return overlappingArea >= area;
  });
};
var getConnectedEdges = function getConnectedEdges2(nodes, edges) {
  var nodeIds = nodes.map(function(node) {
    return node.id;
  });
  return edges.filter(function(edge) {
    return nodeIds.includes(edge.source) || nodeIds.includes(edge.target);
  });
};
var parseElements = function parseElements2(nodes, edges) {
  return [].concat(_toConsumableArray2(nodes.map(function(node) {
    var n3 = _objectSpread$d({}, node);
    n3.position = n3.__rf.position;
    delete n3.__rf;
    return n3;
  })), _toConsumableArray2(edges.map(function(e2) {
    return _objectSpread$d({}, e2);
  })));
};
var onLoadGetElements = function onLoadGetElements2(currentStore) {
  return function() {
    var _currentStore$getStat2 = currentStore.getState(), _currentStore$getStat3 = _currentStore$getStat2.nodes, nodes = _currentStore$getStat3 === void 0 ? [] : _currentStore$getStat3, _currentStore$getStat4 = _currentStore$getStat2.edges, edges = _currentStore$getStat4 === void 0 ? [] : _currentStore$getStat4;
    return parseElements(nodes, edges);
  };
};
var onLoadToObject = function onLoadToObject2(currentStore) {
  return function() {
    var _currentStore$getStat5 = currentStore.getState(), _currentStore$getStat6 = _currentStore$getStat5.nodes, nodes = _currentStore$getStat6 === void 0 ? [] : _currentStore$getStat6, _currentStore$getStat7 = _currentStore$getStat5.edges, edges = _currentStore$getStat7 === void 0 ? [] : _currentStore$getStat7, transform3 = _currentStore$getStat5.transform;
    return {
      elements: parseElements(nodes, edges),
      position: [transform3[0], transform3[1]],
      zoom: transform3[2]
    };
  };
};
var getTransformForBounds = function getTransformForBounds2(bounds, width2, height, minZoom, maxZoom) {
  var padding = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : 0.1;
  var xZoom = width2 / (bounds.width * (1 + padding));
  var yZoom = height / (bounds.height * (1 + padding));
  var zoom2 = Math.min(xZoom, yZoom);
  var clampedZoom = clamp3(zoom2, minZoom, maxZoom);
  var boundsCenterX = bounds.x + bounds.width / 2;
  var boundsCenterY = bounds.y + bounds.height / 2;
  var x2 = width2 / 2 - boundsCenterX * clampedZoom;
  var y3 = height / 2 - boundsCenterY * clampedZoom;
  return [x2, y3, clampedZoom];
};
var useGlobalKeyHandler = function(_ref) {
  var deleteKeyCode = _ref.deleteKeyCode, multiSelectionKeyCode = _ref.multiSelectionKeyCode, onElementsRemove = _ref.onElementsRemove;
  var store2 = useStore();
  var unsetNodesSelection3 = useStoreActions(function(actions2) {
    return actions2.unsetNodesSelection;
  });
  var setMultiSelectionActive3 = useStoreActions(function(actions2) {
    return actions2.setMultiSelectionActive;
  });
  var resetSelectedElements3 = useStoreActions(function(actions2) {
    return actions2.resetSelectedElements;
  });
  var deleteKeyPressed = useKeyPress(deleteKeyCode);
  var multiSelectionKeyPressed = useKeyPress(multiSelectionKeyCode);
  react.useEffect(function() {
    var _store$getState = store2.getState(), edges = _store$getState.edges, selectedElements = _store$getState.selectedElements;
    if (onElementsRemove && deleteKeyPressed && selectedElements) {
      var selectedNodes = selectedElements.filter(isNode);
      var connectedEdges = getConnectedEdges(selectedNodes, edges);
      var elementsToRemove = [].concat(_toConsumableArray2(selectedElements), _toConsumableArray2(connectedEdges)).reduce(function(res, item) {
        return res.set(item.id, item);
      }, new Map());
      onElementsRemove(Array.from(elementsToRemove.values()));
      unsetNodesSelection3();
      resetSelectedElements3();
    }
  }, [deleteKeyPressed]);
  react.useEffect(function() {
    setMultiSelectionActive3(multiSelectionKeyPressed);
  }, [multiSelectionKeyPressed]);
};
var noop5 = {value: () => {
}};
function dispatch() {
  for (var i3 = 0, n3 = arguments.length, _23 = {}, t5; i3 < n3; ++i3) {
    if (!(t5 = arguments[i3] + "") || t5 in _23 || /[\s.]/.test(t5))
      throw new Error("illegal type: " + t5);
    _23[t5] = [];
  }
  return new Dispatch(_23);
}
function Dispatch(_23) {
  this._ = _23;
}
function parseTypenames$1(typenames, types2) {
  return typenames.trim().split(/^|\s+/).map(function(t5) {
    var name = "", i3 = t5.indexOf(".");
    if (i3 >= 0)
      name = t5.slice(i3 + 1), t5 = t5.slice(0, i3);
    if (t5 && !types2.hasOwnProperty(t5))
      throw new Error("unknown type: " + t5);
    return {type: t5, name};
  });
}
Dispatch.prototype = dispatch.prototype = {
  constructor: Dispatch,
  on: function(typename, callback) {
    var _23 = this._, T6 = parseTypenames$1(typename + "", _23), t5, i3 = -1, n3 = T6.length;
    if (arguments.length < 2) {
      while (++i3 < n3)
        if ((t5 = (typename = T6[i3]).type) && (t5 = get$1(_23[t5], typename.name)))
          return t5;
      return;
    }
    if (callback != null && typeof callback !== "function")
      throw new Error("invalid callback: " + callback);
    while (++i3 < n3) {
      if (t5 = (typename = T6[i3]).type)
        _23[t5] = set$1(_23[t5], typename.name, callback);
      else if (callback == null)
        for (t5 in _23)
          _23[t5] = set$1(_23[t5], typename.name, null);
    }
    return this;
  },
  copy: function() {
    var copy2 = {}, _23 = this._;
    for (var t5 in _23)
      copy2[t5] = _23[t5].slice();
    return new Dispatch(copy2);
  },
  call: function(type, that) {
    if ((n3 = arguments.length - 2) > 0)
      for (var args = new Array(n3), i3 = 0, n3, t5; i3 < n3; ++i3)
        args[i3] = arguments[i3 + 2];
    if (!this._.hasOwnProperty(type))
      throw new Error("unknown type: " + type);
    for (t5 = this._[type], i3 = 0, n3 = t5.length; i3 < n3; ++i3)
      t5[i3].value.apply(that, args);
  },
  apply: function(type, that, args) {
    if (!this._.hasOwnProperty(type))
      throw new Error("unknown type: " + type);
    for (var t5 = this._[type], i3 = 0, n3 = t5.length; i3 < n3; ++i3)
      t5[i3].value.apply(that, args);
  }
};
function get$1(type, name) {
  for (var i3 = 0, n3 = type.length, c3; i3 < n3; ++i3) {
    if ((c3 = type[i3]).name === name) {
      return c3.value;
    }
  }
}
function set$1(type, name, callback) {
  for (var i3 = 0, n3 = type.length; i3 < n3; ++i3) {
    if (type[i3].name === name) {
      type[i3] = noop5, type = type.slice(0, i3).concat(type.slice(i3 + 1));
      break;
    }
  }
  if (callback != null)
    type.push({name, value: callback});
  return type;
}
var xhtml = "http://www.w3.org/1999/xhtml";
var namespaces = {
  svg: "http://www.w3.org/2000/svg",
  xhtml,
  xlink: "http://www.w3.org/1999/xlink",
  xml: "http://www.w3.org/XML/1998/namespace",
  xmlns: "http://www.w3.org/2000/xmlns/"
};
function namespace(name) {
  var prefix2 = name += "", i3 = prefix2.indexOf(":");
  if (i3 >= 0 && (prefix2 = name.slice(0, i3)) !== "xmlns")
    name = name.slice(i3 + 1);
  return namespaces.hasOwnProperty(prefix2) ? {space: namespaces[prefix2], local: name} : name;
}
function creatorInherit(name) {
  return function() {
    var document2 = this.ownerDocument, uri = this.namespaceURI;
    return uri === xhtml && document2.documentElement.namespaceURI === xhtml ? document2.createElement(name) : document2.createElementNS(uri, name);
  };
}
function creatorFixed(fullname) {
  return function() {
    return this.ownerDocument.createElementNS(fullname.space, fullname.local);
  };
}
function creator(name) {
  var fullname = namespace(name);
  return (fullname.local ? creatorFixed : creatorInherit)(fullname);
}
function none() {
}
function selector(selector2) {
  return selector2 == null ? none : function() {
    return this.querySelector(selector2);
  };
}
function selection_select(select3) {
  if (typeof select3 !== "function")
    select3 = selector(select3);
  for (var groups2 = this._groups, m2 = groups2.length, subgroups = new Array(m2), j = 0; j < m2; ++j) {
    for (var group = groups2[j], n3 = group.length, subgroup = subgroups[j] = new Array(n3), node, subnode, i3 = 0; i3 < n3; ++i3) {
      if ((node = group[i3]) && (subnode = select3.call(node, node.__data__, i3, group))) {
        if ("__data__" in node)
          subnode.__data__ = node.__data__;
        subgroup[i3] = subnode;
      }
    }
  }
  return new Selection$12(subgroups, this._parents);
}
function array(x2) {
  return x2 == null ? [] : Array.isArray(x2) ? x2 : Array.from(x2);
}
function empty2() {
  return [];
}
function selectorAll(selector2) {
  return selector2 == null ? empty2 : function() {
    return this.querySelectorAll(selector2);
  };
}
function arrayAll(select3) {
  return function() {
    return array(select3.apply(this, arguments));
  };
}
function selection_selectAll(select3) {
  if (typeof select3 === "function")
    select3 = arrayAll(select3);
  else
    select3 = selectorAll(select3);
  for (var groups2 = this._groups, m2 = groups2.length, subgroups = [], parents = [], j = 0; j < m2; ++j) {
    for (var group = groups2[j], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) {
      if (node = group[i3]) {
        subgroups.push(select3.call(node, node.__data__, i3, group));
        parents.push(node);
      }
    }
  }
  return new Selection$12(subgroups, parents);
}
function matcher(selector2) {
  return function() {
    return this.matches(selector2);
  };
}
function childMatcher(selector2) {
  return function(node) {
    return node.matches(selector2);
  };
}
var find = Array.prototype.find;
function childFind(match2) {
  return function() {
    return find.call(this.children, match2);
  };
}
function childFirst() {
  return this.firstElementChild;
}
function selection_selectChild(match2) {
  return this.select(match2 == null ? childFirst : childFind(typeof match2 === "function" ? match2 : childMatcher(match2)));
}
var filter = Array.prototype.filter;
function children() {
  return Array.from(this.children);
}
function childrenFilter(match2) {
  return function() {
    return filter.call(this.children, match2);
  };
}
function selection_selectChildren(match2) {
  return this.selectAll(match2 == null ? children : childrenFilter(typeof match2 === "function" ? match2 : childMatcher(match2)));
}
function selection_filter(match2) {
  if (typeof match2 !== "function")
    match2 = matcher(match2);
  for (var groups2 = this._groups, m2 = groups2.length, subgroups = new Array(m2), j = 0; j < m2; ++j) {
    for (var group = groups2[j], n3 = group.length, subgroup = subgroups[j] = [], node, i3 = 0; i3 < n3; ++i3) {
      if ((node = group[i3]) && match2.call(node, node.__data__, i3, group)) {
        subgroup.push(node);
      }
    }
  }
  return new Selection$12(subgroups, this._parents);
}
function sparse(update) {
  return new Array(update.length);
}
function selection_enter() {
  return new Selection$12(this._enter || this._groups.map(sparse), this._parents);
}
function EnterNode(parent, datum2) {
  this.ownerDocument = parent.ownerDocument;
  this.namespaceURI = parent.namespaceURI;
  this._next = null;
  this._parent = parent;
  this.__data__ = datum2;
}
EnterNode.prototype = {
  constructor: EnterNode,
  appendChild: function(child) {
    return this._parent.insertBefore(child, this._next);
  },
  insertBefore: function(child, next) {
    return this._parent.insertBefore(child, next);
  },
  querySelector: function(selector2) {
    return this._parent.querySelector(selector2);
  },
  querySelectorAll: function(selector2) {
    return this._parent.querySelectorAll(selector2);
  }
};
function constant$2(x2) {
  return function() {
    return x2;
  };
}
function bindIndex(parent, group, enter, update, exit, data2) {
  var i3 = 0, node, groupLength = group.length, dataLength = data2.length;
  for (; i3 < dataLength; ++i3) {
    if (node = group[i3]) {
      node.__data__ = data2[i3];
      update[i3] = node;
    } else {
      enter[i3] = new EnterNode(parent, data2[i3]);
    }
  }
  for (; i3 < groupLength; ++i3) {
    if (node = group[i3]) {
      exit[i3] = node;
    }
  }
}
function bindKey(parent, group, enter, update, exit, data2, key) {
  var i3, node, nodeByKeyValue = new Map(), groupLength = group.length, dataLength = data2.length, keyValues = new Array(groupLength), keyValue;
  for (i3 = 0; i3 < groupLength; ++i3) {
    if (node = group[i3]) {
      keyValues[i3] = keyValue = key.call(node, node.__data__, i3, group) + "";
      if (nodeByKeyValue.has(keyValue)) {
        exit[i3] = node;
      } else {
        nodeByKeyValue.set(keyValue, node);
      }
    }
  }
  for (i3 = 0; i3 < dataLength; ++i3) {
    keyValue = key.call(parent, data2[i3], i3, data2) + "";
    if (node = nodeByKeyValue.get(keyValue)) {
      update[i3] = node;
      node.__data__ = data2[i3];
      nodeByKeyValue.delete(keyValue);
    } else {
      enter[i3] = new EnterNode(parent, data2[i3]);
    }
  }
  for (i3 = 0; i3 < groupLength; ++i3) {
    if ((node = group[i3]) && nodeByKeyValue.get(keyValues[i3]) === node) {
      exit[i3] = node;
    }
  }
}
function datum(node) {
  return node.__data__;
}
function selection_data(value, key) {
  if (!arguments.length)
    return Array.from(this, datum);
  var bind3 = key ? bindKey : bindIndex, parents = this._parents, groups2 = this._groups;
  if (typeof value !== "function")
    value = constant$2(value);
  for (var m2 = groups2.length, update = new Array(m2), enter = new Array(m2), exit = new Array(m2), j = 0; j < m2; ++j) {
    var parent = parents[j], group = groups2[j], groupLength = group.length, data2 = arraylike(value.call(parent, parent && parent.__data__, j, parents)), dataLength = data2.length, enterGroup = enter[j] = new Array(dataLength), updateGroup = update[j] = new Array(dataLength), exitGroup = exit[j] = new Array(groupLength);
    bind3(parent, group, enterGroup, updateGroup, exitGroup, data2, key);
    for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
      if (previous = enterGroup[i0]) {
        if (i0 >= i1)
          i1 = i0 + 1;
        while (!(next = updateGroup[i1]) && ++i1 < dataLength)
          ;
        previous._next = next || null;
      }
    }
  }
  update = new Selection$12(update, parents);
  update._enter = enter;
  update._exit = exit;
  return update;
}
function arraylike(data2) {
  return typeof data2 === "object" && "length" in data2 ? data2 : Array.from(data2);
}
function selection_exit() {
  return new Selection$12(this._exit || this._groups.map(sparse), this._parents);
}
function selection_join(onenter, onupdate, onexit) {
  var enter = this.enter(), update = this, exit = this.exit();
  if (typeof onenter === "function") {
    enter = onenter(enter);
    if (enter)
      enter = enter.selection();
  } else {
    enter = enter.append(onenter + "");
  }
  if (onupdate != null) {
    update = onupdate(update);
    if (update)
      update = update.selection();
  }
  if (onexit == null)
    exit.remove();
  else
    onexit(exit);
  return enter && update ? enter.merge(update).order() : update;
}
function selection_merge(context2) {
  var selection2 = context2.selection ? context2.selection() : context2;
  for (var groups0 = this._groups, groups1 = selection2._groups, m0 = groups0.length, m1 = groups1.length, m2 = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m2; ++j) {
    for (var group0 = groups0[j], group1 = groups1[j], n3 = group0.length, merge3 = merges[j] = new Array(n3), node, i3 = 0; i3 < n3; ++i3) {
      if (node = group0[i3] || group1[i3]) {
        merge3[i3] = node;
      }
    }
  }
  for (; j < m0; ++j) {
    merges[j] = groups0[j];
  }
  return new Selection$12(merges, this._parents);
}
function selection_order() {
  for (var groups2 = this._groups, j = -1, m2 = groups2.length; ++j < m2; ) {
    for (var group = groups2[j], i3 = group.length - 1, next = group[i3], node; --i3 >= 0; ) {
      if (node = group[i3]) {
        if (next && node.compareDocumentPosition(next) ^ 4)
          next.parentNode.insertBefore(node, next);
        next = node;
      }
    }
  }
  return this;
}
function selection_sort(compare2) {
  if (!compare2)
    compare2 = ascending;
  function compareNode(a2, b2) {
    return a2 && b2 ? compare2(a2.__data__, b2.__data__) : !a2 - !b2;
  }
  for (var groups2 = this._groups, m2 = groups2.length, sortgroups = new Array(m2), j = 0; j < m2; ++j) {
    for (var group = groups2[j], n3 = group.length, sortgroup = sortgroups[j] = new Array(n3), node, i3 = 0; i3 < n3; ++i3) {
      if (node = group[i3]) {
        sortgroup[i3] = node;
      }
    }
    sortgroup.sort(compareNode);
  }
  return new Selection$12(sortgroups, this._parents).order();
}
function ascending(a2, b2) {
  return a2 < b2 ? -1 : a2 > b2 ? 1 : a2 >= b2 ? 0 : NaN;
}
function selection_call() {
  var callback = arguments[0];
  arguments[0] = this;
  callback.apply(null, arguments);
  return this;
}
function selection_nodes() {
  return Array.from(this);
}
function selection_node() {
  for (var groups2 = this._groups, j = 0, m2 = groups2.length; j < m2; ++j) {
    for (var group = groups2[j], i3 = 0, n3 = group.length; i3 < n3; ++i3) {
      var node = group[i3];
      if (node)
        return node;
    }
  }
  return null;
}
function selection_size() {
  let size2 = 0;
  for (const node of this)
    ++size2;
  return size2;
}
function selection_empty() {
  return !this.node();
}
function selection_each(callback) {
  for (var groups2 = this._groups, j = 0, m2 = groups2.length; j < m2; ++j) {
    for (var group = groups2[j], i3 = 0, n3 = group.length, node; i3 < n3; ++i3) {
      if (node = group[i3])
        callback.call(node, node.__data__, i3, group);
    }
  }
  return this;
}
function attrRemove$1(name) {
  return function() {
    this.removeAttribute(name);
  };
}
function attrRemoveNS$1(fullname) {
  return function() {
    this.removeAttributeNS(fullname.space, fullname.local);
  };
}
function attrConstant$1(name, value) {
  return function() {
    this.setAttribute(name, value);
  };
}
function attrConstantNS$1(fullname, value) {
  return function() {
    this.setAttributeNS(fullname.space, fullname.local, value);
  };
}
function attrFunction$1(name, value) {
  return function() {
    var v2 = value.apply(this, arguments);
    if (v2 == null)
      this.removeAttribute(name);
    else
      this.setAttribute(name, v2);
  };
}
function attrFunctionNS$1(fullname, value) {
  return function() {
    var v2 = value.apply(this, arguments);
    if (v2 == null)
      this.removeAttributeNS(fullname.space, fullname.local);
    else
      this.setAttributeNS(fullname.space, fullname.local, v2);
  };
}
function selection_attr(name, value) {
  var fullname = namespace(name);
  if (arguments.length < 2) {
    var node = this.node();
    return fullname.local ? node.getAttributeNS(fullname.space, fullname.local) : node.getAttribute(fullname);
  }
  return this.each((value == null ? fullname.local ? attrRemoveNS$1 : attrRemove$1 : typeof value === "function" ? fullname.local ? attrFunctionNS$1 : attrFunction$1 : fullname.local ? attrConstantNS$1 : attrConstant$1)(fullname, value));
}
function defaultView(node) {
  return node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView;
}
function styleRemove$1(name) {
  return function() {
    this.style.removeProperty(name);
  };
}
function styleConstant$1(name, value, priority) {
  return function() {
    this.style.setProperty(name, value, priority);
  };
}
function styleFunction$1(name, value, priority) {
  return function() {
    var v2 = value.apply(this, arguments);
    if (v2 == null)
      this.style.removeProperty(name);
    else
      this.style.setProperty(name, v2, priority);
  };
}
function selection_style(name, value, priority) {
  return arguments.length > 1 ? this.each((value == null ? styleRemove$1 : typeof value === "function" ? styleFunction$1 : styleConstant$1)(name, value, priority == null ? "" : priority)) : styleValue(this.node(), name);
}
function styleValue(node, name) {
  return node.style.getPropertyValue(name) || defaultView(node).getComputedStyle(node, null).getPropertyValue(name);
}
function propertyRemove(name) {
  return function() {
    delete this[name];
  };
}
function propertyConstant(name, value) {
  return function() {
    this[name] = value;
  };
}
function propertyFunction(name, value) {
  return function() {
    var v2 = value.apply(this, arguments);
    if (v2 == null)
      delete this[name];
    else
      this[name] = v2;
  };
}
function selection_property(name, value) {
  return arguments.length > 1 ? this.each((value == null ? propertyRemove : typeof value === "function" ? propertyFunction : propertyConstant)(name, value)) : this.node()[name];
}
function classArray(string2) {
  return string2.trim().split(/^|\s+/);
}
function classList(node) {
  return node.classList || new ClassList(node);
}
function ClassList(node) {
  this._node = node;
  this._names = classArray(node.getAttribute("class") || "");
}
ClassList.prototype = {
  add: function(name) {
    var i3 = this._names.indexOf(name);
    if (i3 < 0) {
      this._names.push(name);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  remove: function(name) {
    var i3 = this._names.indexOf(name);
    if (i3 >= 0) {
      this._names.splice(i3, 1);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  contains: function(name) {
    return this._names.indexOf(name) >= 0;
  }
};
function classedAdd(node, names) {
  var list3 = classList(node), i3 = -1, n3 = names.length;
  while (++i3 < n3)
    list3.add(names[i3]);
}
function classedRemove(node, names) {
  var list3 = classList(node), i3 = -1, n3 = names.length;
  while (++i3 < n3)
    list3.remove(names[i3]);
}
function classedTrue(names) {
  return function() {
    classedAdd(this, names);
  };
}
function classedFalse(names) {
  return function() {
    classedRemove(this, names);
  };
}
function classedFunction(names, value) {
  return function() {
    (value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
  };
}
function selection_classed(name, value) {
  var names = classArray(name + "");
  if (arguments.length < 2) {
    var list3 = classList(this.node()), i3 = -1, n3 = names.length;
    while (++i3 < n3)
      if (!list3.contains(names[i3]))
        return false;
    return true;
  }
  return this.each((typeof value === "function" ? classedFunction : value ? classedTrue : classedFalse)(names, value));
}
function textRemove() {
  this.textContent = "";
}
function textConstant$1(value) {
  return function() {
    this.textContent = value;
  };
}
function textFunction$1(value) {
  return function() {
    var v2 = value.apply(this, arguments);
    this.textContent = v2 == null ? "" : v2;
  };
}
function selection_text(value) {
  return arguments.length ? this.each(value == null ? textRemove : (typeof value === "function" ? textFunction$1 : textConstant$1)(value)) : this.node().textContent;
}
function htmlRemove() {
  this.innerHTML = "";
}
function htmlConstant(value) {
  return function() {
    this.innerHTML = value;
  };
}
function htmlFunction(value) {
  return function() {
    var v2 = value.apply(this, arguments);
    this.innerHTML = v2 == null ? "" : v2;
  };
}
function selection_html(value) {
  return arguments.length ? this.each(value == null ? htmlRemove : (typeof value === "function" ? htmlFunction : htmlConstant)(value)) : this.node().innerHTML;
}
function raise() {
  if (this.nextSibling)
    this.parentNode.appendChild(this);
}
function selection_raise() {
  return this.each(raise);
}
function lower() {
  if (this.previousSibling)
    this.parentNode.insertBefore(this, this.parentNode.firstChild);
}
function selection_lower() {
  return this.each(lower);
}
function selection_append(name) {
  var create3 = typeof name === "function" ? name : creator(name);
  return this.select(function() {
    return this.appendChild(create3.apply(this, arguments));
  });
}
function constantNull() {
  return null;
}
function selection_insert(name, before) {
  var create3 = typeof name === "function" ? name : creator(name), select3 = before == null ? constantNull : typeof before === "function" ? before : selector(before);
  return this.select(function() {
    return this.insertBefore(create3.apply(this, arguments), select3.apply(this, arguments) || null);
  });
}
function remove2() {
  var parent = this.parentNode;
  if (parent)
    parent.removeChild(this);
}
function selection_remove() {
  return this.each(remove2);
}
function selection_cloneShallow() {
  var clone2 = this.cloneNode(false), parent = this.parentNode;
  return parent ? parent.insertBefore(clone2, this.nextSibling) : clone2;
}
function selection_cloneDeep() {
  var clone2 = this.cloneNode(true), parent = this.parentNode;
  return parent ? parent.insertBefore(clone2, this.nextSibling) : clone2;
}
function selection_clone(deep) {
  return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
}
function selection_datum(value) {
  return arguments.length ? this.property("__data__", value) : this.node().__data__;
}
function contextListener(listener) {
  return function(event) {
    listener.call(this, event, this.__data__);
  };
}
function parseTypenames(typenames) {
  return typenames.trim().split(/^|\s+/).map(function(t5) {
    var name = "", i3 = t5.indexOf(".");
    if (i3 >= 0)
      name = t5.slice(i3 + 1), t5 = t5.slice(0, i3);
    return {type: t5, name};
  });
}
function onRemove(typename) {
  return function() {
    var on2 = this.__on;
    if (!on2)
      return;
    for (var j = 0, i3 = -1, m2 = on2.length, o; j < m2; ++j) {
      if (o = on2[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.options);
      } else {
        on2[++i3] = o;
      }
    }
    if (++i3)
      on2.length = i3;
    else
      delete this.__on;
  };
}
function onAdd(typename, value, options) {
  return function() {
    var on2 = this.__on, o, listener = contextListener(value);
    if (on2)
      for (var j = 0, m2 = on2.length; j < m2; ++j) {
        if ((o = on2[j]).type === typename.type && o.name === typename.name) {
          this.removeEventListener(o.type, o.listener, o.options);
          this.addEventListener(o.type, o.listener = listener, o.options = options);
          o.value = value;
          return;
        }
      }
    this.addEventListener(typename.type, listener, options);
    o = {type: typename.type, name: typename.name, value, listener, options};
    if (!on2)
      this.__on = [o];
    else
      on2.push(o);
  };
}
function selection_on(typename, value, options) {
  var typenames = parseTypenames(typename + ""), i3, n3 = typenames.length, t5;
  if (arguments.length < 2) {
    var on2 = this.node().__on;
    if (on2)
      for (var j = 0, m2 = on2.length, o; j < m2; ++j) {
        for (i3 = 0, o = on2[j]; i3 < n3; ++i3) {
          if ((t5 = typenames[i3]).type === o.type && t5.name === o.name) {
            return o.value;
          }
        }
      }
    return;
  }
  on2 = value ? onAdd : onRemove;
  for (i3 = 0; i3 < n3; ++i3)
    this.each(on2(typenames[i3], value, options));
  return this;
}
function dispatchEvent(node, type, params) {
  var window2 = defaultView(node), event = window2.CustomEvent;
  if (typeof event === "function") {
    event = new event(type, params);
  } else {
    event = window2.document.createEvent("Event");
    if (params)
      event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail;
    else
      event.initEvent(type, false, false);
  }
  node.dispatchEvent(event);
}
function dispatchConstant(type, params) {
  return function() {
    return dispatchEvent(this, type, params);
  };
}
function dispatchFunction(type, params) {
  return function() {
    return dispatchEvent(this, type, params.apply(this, arguments));
  };
}
function selection_dispatch(type, params) {
  return this.each((typeof params === "function" ? dispatchFunction : dispatchConstant)(type, params));
}
function* selection_iterator() {
  for (var groups2 = this._groups, j = 0, m2 = groups2.length; j < m2; ++j) {
    for (var group = groups2[j], i3 = 0, n3 = group.length, node; i3 < n3; ++i3) {
      if (node = group[i3])
        yield node;
    }
  }
}
var root3 = [null];
function Selection$12(groups2, parents) {
  this._groups = groups2;
  this._parents = parents;
}
function selection() {
  return new Selection$12([[document.documentElement]], root3);
}
function selection_selection() {
  return this;
}
Selection$12.prototype = selection.prototype = {
  constructor: Selection$12,
  select: selection_select,
  selectAll: selection_selectAll,
  selectChild: selection_selectChild,
  selectChildren: selection_selectChildren,
  filter: selection_filter,
  data: selection_data,
  enter: selection_enter,
  exit: selection_exit,
  join: selection_join,
  merge: selection_merge,
  selection: selection_selection,
  order: selection_order,
  sort: selection_sort,
  call: selection_call,
  nodes: selection_nodes,
  node: selection_node,
  size: selection_size,
  empty: selection_empty,
  each: selection_each,
  attr: selection_attr,
  style: selection_style,
  property: selection_property,
  classed: selection_classed,
  text: selection_text,
  html: selection_html,
  raise: selection_raise,
  lower: selection_lower,
  append: selection_append,
  insert: selection_insert,
  remove: selection_remove,
  clone: selection_clone,
  datum: selection_datum,
  on: selection_on,
  dispatch: selection_dispatch,
  [Symbol.iterator]: selection_iterator
};
function select2(selector2) {
  return typeof selector2 === "string" ? new Selection$12([[document.querySelector(selector2)]], [document.documentElement]) : new Selection$12([[selector2]], root3);
}
function sourceEvent(event) {
  let sourceEvent2;
  while (sourceEvent2 = event.sourceEvent)
    event = sourceEvent2;
  return event;
}
function pointer(event, node) {
  event = sourceEvent(event);
  if (node === void 0)
    node = event.currentTarget;
  if (node) {
    var svg = node.ownerSVGElement || node;
    if (svg.createSVGPoint) {
      var point = svg.createSVGPoint();
      point.x = event.clientX, point.y = event.clientY;
      point = point.matrixTransform(node.getScreenCTM().inverse());
      return [point.x, point.y];
    }
    if (node.getBoundingClientRect) {
      var rect = node.getBoundingClientRect();
      return [event.clientX - rect.left - node.clientLeft, event.clientY - rect.top - node.clientTop];
    }
  }
  return [event.pageX, event.pageY];
}
var nonpassivecapture = {capture: true, passive: false};
function noevent$1(event) {
  event.preventDefault();
  event.stopImmediatePropagation();
}
function dragDisable(view) {
  var root4 = view.document.documentElement, selection2 = select2(view).on("dragstart.drag", noevent$1, nonpassivecapture);
  if ("onselectstart" in root4) {
    selection2.on("selectstart.drag", noevent$1, nonpassivecapture);
  } else {
    root4.__noselect = root4.style.MozUserSelect;
    root4.style.MozUserSelect = "none";
  }
}
function yesdrag(view, noclick) {
  var root4 = view.document.documentElement, selection2 = select2(view).on("dragstart.drag", null);
  if (noclick) {
    selection2.on("click.drag", noevent$1, nonpassivecapture);
    setTimeout(function() {
      selection2.on("click.drag", null);
    }, 0);
  }
  if ("onselectstart" in root4) {
    selection2.on("selectstart.drag", null);
  } else {
    root4.style.MozUserSelect = root4.__noselect;
    delete root4.__noselect;
  }
}
function define(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}
function extend2(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key in definition)
    prototype[key] = definition[key];
  return prototype;
}
function Color2() {
}
var darker = 0.7;
var brighter = 1 / darker;
var reI = "\\s*([+-]?\\d+)\\s*";
var reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*";
var reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*";
var reHex = /^#([0-9a-f]{3,8})$/;
var reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$");
var reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$");
var reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$");
var reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$");
var reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$");
var reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");
var named = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
};
define(Color2, color, {
  copy: function(channels) {
    return Object.assign(new this.constructor(), this, channels);
  },
  displayable: function() {
    return this.rgb().displayable();
  },
  hex: color_formatHex,
  formatHex: color_formatHex,
  formatHsl: color_formatHsl,
  formatRgb: color_formatRgb,
  toString: color_formatRgb
});
function color_formatHex() {
  return this.rgb().formatHex();
}
function color_formatHsl() {
  return hslConvert(this).formatHsl();
}
function color_formatRgb() {
  return this.rgb().formatRgb();
}
function color(format2) {
  var m2, l2;
  format2 = (format2 + "").trim().toLowerCase();
  return (m2 = reHex.exec(format2)) ? (l2 = m2[1].length, m2 = parseInt(m2[1], 16), l2 === 6 ? rgbn(m2) : l2 === 3 ? new Rgb(m2 >> 8 & 15 | m2 >> 4 & 240, m2 >> 4 & 15 | m2 & 240, (m2 & 15) << 4 | m2 & 15, 1) : l2 === 8 ? rgba(m2 >> 24 & 255, m2 >> 16 & 255, m2 >> 8 & 255, (m2 & 255) / 255) : l2 === 4 ? rgba(m2 >> 12 & 15 | m2 >> 8 & 240, m2 >> 8 & 15 | m2 >> 4 & 240, m2 >> 4 & 15 | m2 & 240, ((m2 & 15) << 4 | m2 & 15) / 255) : null) : (m2 = reRgbInteger.exec(format2)) ? new Rgb(m2[1], m2[2], m2[3], 1) : (m2 = reRgbPercent.exec(format2)) ? new Rgb(m2[1] * 255 / 100, m2[2] * 255 / 100, m2[3] * 255 / 100, 1) : (m2 = reRgbaInteger.exec(format2)) ? rgba(m2[1], m2[2], m2[3], m2[4]) : (m2 = reRgbaPercent.exec(format2)) ? rgba(m2[1] * 255 / 100, m2[2] * 255 / 100, m2[3] * 255 / 100, m2[4]) : (m2 = reHslPercent.exec(format2)) ? hsla(m2[1], m2[2] / 100, m2[3] / 100, 1) : (m2 = reHslaPercent.exec(format2)) ? hsla(m2[1], m2[2] / 100, m2[3] / 100, m2[4]) : named.hasOwnProperty(format2) ? rgbn(named[format2]) : format2 === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null;
}
function rgbn(n3) {
  return new Rgb(n3 >> 16 & 255, n3 >> 8 & 255, n3 & 255, 1);
}
function rgba(r3, g2, b2, a2) {
  if (a2 <= 0)
    r3 = g2 = b2 = NaN;
  return new Rgb(r3, g2, b2, a2);
}
function rgbConvert(o) {
  if (!(o instanceof Color2))
    o = color(o);
  if (!o)
    return new Rgb();
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}
function rgb(r3, g2, b2, opacity) {
  return arguments.length === 1 ? rgbConvert(r3) : new Rgb(r3, g2, b2, opacity == null ? 1 : opacity);
}
function Rgb(r3, g2, b2, opacity) {
  this.r = +r3;
  this.g = +g2;
  this.b = +b2;
  this.opacity = +opacity;
}
define(Rgb, rgb, extend2(Color2, {
  brighter: function(k2) {
    k2 = k2 == null ? brighter : Math.pow(brighter, k2);
    return new Rgb(this.r * k2, this.g * k2, this.b * k2, this.opacity);
  },
  darker: function(k2) {
    k2 = k2 == null ? darker : Math.pow(darker, k2);
    return new Rgb(this.r * k2, this.g * k2, this.b * k2, this.opacity);
  },
  rgb: function() {
    return this;
  },
  displayable: function() {
    return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: rgb_formatHex,
  formatHex: rgb_formatHex,
  formatRgb: rgb_formatRgb,
  toString: rgb_formatRgb
}));
function rgb_formatHex() {
  return "#" + hex(this.r) + hex(this.g) + hex(this.b);
}
function rgb_formatRgb() {
  var a2 = this.opacity;
  a2 = isNaN(a2) ? 1 : Math.max(0, Math.min(1, a2));
  return (a2 === 1 ? "rgb(" : "rgba(") + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.b) || 0)) + (a2 === 1 ? ")" : ", " + a2 + ")");
}
function hex(value) {
  value = Math.max(0, Math.min(255, Math.round(value) || 0));
  return (value < 16 ? "0" : "") + value.toString(16);
}
function hsla(h2, s2, l2, a2) {
  if (a2 <= 0)
    h2 = s2 = l2 = NaN;
  else if (l2 <= 0 || l2 >= 1)
    h2 = s2 = NaN;
  else if (s2 <= 0)
    h2 = NaN;
  return new Hsl(h2, s2, l2, a2);
}
function hslConvert(o) {
  if (o instanceof Hsl)
    return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color2))
    o = color(o);
  if (!o)
    return new Hsl();
  if (o instanceof Hsl)
    return o;
  o = o.rgb();
  var r3 = o.r / 255, g2 = o.g / 255, b2 = o.b / 255, min2 = Math.min(r3, g2, b2), max2 = Math.max(r3, g2, b2), h2 = NaN, s2 = max2 - min2, l2 = (max2 + min2) / 2;
  if (s2) {
    if (r3 === max2)
      h2 = (g2 - b2) / s2 + (g2 < b2) * 6;
    else if (g2 === max2)
      h2 = (b2 - r3) / s2 + 2;
    else
      h2 = (r3 - g2) / s2 + 4;
    s2 /= l2 < 0.5 ? max2 + min2 : 2 - max2 - min2;
    h2 *= 60;
  } else {
    s2 = l2 > 0 && l2 < 1 ? 0 : h2;
  }
  return new Hsl(h2, s2, l2, o.opacity);
}
function hsl(h2, s2, l2, opacity) {
  return arguments.length === 1 ? hslConvert(h2) : new Hsl(h2, s2, l2, opacity == null ? 1 : opacity);
}
function Hsl(h2, s2, l2, opacity) {
  this.h = +h2;
  this.s = +s2;
  this.l = +l2;
  this.opacity = +opacity;
}
define(Hsl, hsl, extend2(Color2, {
  brighter: function(k2) {
    k2 = k2 == null ? brighter : Math.pow(brighter, k2);
    return new Hsl(this.h, this.s, this.l * k2, this.opacity);
  },
  darker: function(k2) {
    k2 = k2 == null ? darker : Math.pow(darker, k2);
    return new Hsl(this.h, this.s, this.l * k2, this.opacity);
  },
  rgb: function() {
    var h2 = this.h % 360 + (this.h < 0) * 360, s2 = isNaN(h2) || isNaN(this.s) ? 0 : this.s, l2 = this.l, m2 = l2 + (l2 < 0.5 ? l2 : 1 - l2) * s2, m1 = 2 * l2 - m2;
    return new Rgb(hsl2rgb(h2 >= 240 ? h2 - 240 : h2 + 120, m1, m2), hsl2rgb(h2, m1, m2), hsl2rgb(h2 < 120 ? h2 + 240 : h2 - 120, m1, m2), this.opacity);
  },
  displayable: function() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1);
  },
  formatHsl: function() {
    var a2 = this.opacity;
    a2 = isNaN(a2) ? 1 : Math.max(0, Math.min(1, a2));
    return (a2 === 1 ? "hsl(" : "hsla(") + (this.h || 0) + ", " + (this.s || 0) * 100 + "%, " + (this.l || 0) * 100 + "%" + (a2 === 1 ? ")" : ", " + a2 + ")");
  }
}));
function hsl2rgb(h2, m1, m2) {
  return (h2 < 60 ? m1 + (m2 - m1) * h2 / 60 : h2 < 180 ? m2 : h2 < 240 ? m1 + (m2 - m1) * (240 - h2) / 60 : m1) * 255;
}
var constant$1 = (x2) => () => x2;
function linear(a2, d2) {
  return function(t5) {
    return a2 + t5 * d2;
  };
}
function exponential(a2, b2, y3) {
  return a2 = Math.pow(a2, y3), b2 = Math.pow(b2, y3) - a2, y3 = 1 / y3, function(t5) {
    return Math.pow(a2 + t5 * b2, y3);
  };
}
function gamma(y3) {
  return (y3 = +y3) === 1 ? nogamma : function(a2, b2) {
    return b2 - a2 ? exponential(a2, b2, y3) : constant$1(isNaN(a2) ? b2 : a2);
  };
}
function nogamma(a2, b2) {
  var d2 = b2 - a2;
  return d2 ? linear(a2, d2) : constant$1(isNaN(a2) ? b2 : a2);
}
var interpolateRgb = function rgbGamma(y3) {
  var color2 = gamma(y3);
  function rgb$1(start3, end2) {
    var r3 = color2((start3 = rgb(start3)).r, (end2 = rgb(end2)).r), g2 = color2(start3.g, end2.g), b2 = color2(start3.b, end2.b), opacity = nogamma(start3.opacity, end2.opacity);
    return function(t5) {
      start3.r = r3(t5);
      start3.g = g2(t5);
      start3.b = b2(t5);
      start3.opacity = opacity(t5);
      return start3 + "";
    };
  }
  rgb$1.gamma = rgbGamma;
  return rgb$1;
}(1);
function interpolateNumber(a2, b2) {
  return a2 = +a2, b2 = +b2, function(t5) {
    return a2 * (1 - t5) + b2 * t5;
  };
}
var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
var reB = new RegExp(reA.source, "g");
function zero(b2) {
  return function() {
    return b2;
  };
}
function one(b2) {
  return function(t5) {
    return b2(t5) + "";
  };
}
function interpolateString(a2, b2) {
  var bi2 = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i3 = -1, s2 = [], q2 = [];
  a2 = a2 + "", b2 = b2 + "";
  while ((am = reA.exec(a2)) && (bm = reB.exec(b2))) {
    if ((bs = bm.index) > bi2) {
      bs = b2.slice(bi2, bs);
      if (s2[i3])
        s2[i3] += bs;
      else
        s2[++i3] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) {
      if (s2[i3])
        s2[i3] += bm;
      else
        s2[++i3] = bm;
    } else {
      s2[++i3] = null;
      q2.push({i: i3, x: interpolateNumber(am, bm)});
    }
    bi2 = reB.lastIndex;
  }
  if (bi2 < b2.length) {
    bs = b2.slice(bi2);
    if (s2[i3])
      s2[i3] += bs;
    else
      s2[++i3] = bs;
  }
  return s2.length < 2 ? q2[0] ? one(q2[0].x) : zero(b2) : (b2 = q2.length, function(t5) {
    for (var i4 = 0, o; i4 < b2; ++i4)
      s2[(o = q2[i4]).i] = o.x(t5);
    return s2.join("");
  });
}
var degrees = 180 / Math.PI;
var identity$1 = {
  translateX: 0,
  translateY: 0,
  rotate: 0,
  skewX: 0,
  scaleX: 1,
  scaleY: 1
};
function decompose(a2, b2, c3, d2, e2, f2) {
  var scaleX, scaleY, skewX;
  if (scaleX = Math.sqrt(a2 * a2 + b2 * b2))
    a2 /= scaleX, b2 /= scaleX;
  if (skewX = a2 * c3 + b2 * d2)
    c3 -= a2 * skewX, d2 -= b2 * skewX;
  if (scaleY = Math.sqrt(c3 * c3 + d2 * d2))
    c3 /= scaleY, d2 /= scaleY, skewX /= scaleY;
  if (a2 * d2 < b2 * c3)
    a2 = -a2, b2 = -b2, skewX = -skewX, scaleX = -scaleX;
  return {
    translateX: e2,
    translateY: f2,
    rotate: Math.atan2(b2, a2) * degrees,
    skewX: Math.atan(skewX) * degrees,
    scaleX,
    scaleY
  };
}
var svgNode;
function parseCss(value) {
  const m2 = new (typeof DOMMatrix === "function" ? DOMMatrix : WebKitCSSMatrix)(value + "");
  return m2.isIdentity ? identity$1 : decompose(m2.a, m2.b, m2.c, m2.d, m2.e, m2.f);
}
function parseSvg(value) {
  if (value == null)
    return identity$1;
  if (!svgNode)
    svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g");
  svgNode.setAttribute("transform", value);
  if (!(value = svgNode.transform.baseVal.consolidate()))
    return identity$1;
  value = value.matrix;
  return decompose(value.a, value.b, value.c, value.d, value.e, value.f);
}
function interpolateTransform(parse3, pxComma, pxParen, degParen) {
  function pop(s2) {
    return s2.length ? s2.pop() + " " : "";
  }
  function translate(xa2, ya2, xb2, yb2, s2, q2) {
    if (xa2 !== xb2 || ya2 !== yb2) {
      var i3 = s2.push("translate(", null, pxComma, null, pxParen);
      q2.push({i: i3 - 4, x: interpolateNumber(xa2, xb2)}, {i: i3 - 2, x: interpolateNumber(ya2, yb2)});
    } else if (xb2 || yb2) {
      s2.push("translate(" + xb2 + pxComma + yb2 + pxParen);
    }
  }
  function rotate(a2, b2, s2, q2) {
    if (a2 !== b2) {
      if (a2 - b2 > 180)
        b2 += 360;
      else if (b2 - a2 > 180)
        a2 += 360;
      q2.push({i: s2.push(pop(s2) + "rotate(", null, degParen) - 2, x: interpolateNumber(a2, b2)});
    } else if (b2) {
      s2.push(pop(s2) + "rotate(" + b2 + degParen);
    }
  }
  function skewX(a2, b2, s2, q2) {
    if (a2 !== b2) {
      q2.push({i: s2.push(pop(s2) + "skewX(", null, degParen) - 2, x: interpolateNumber(a2, b2)});
    } else if (b2) {
      s2.push(pop(s2) + "skewX(" + b2 + degParen);
    }
  }
  function scale(xa2, ya2, xb2, yb2, s2, q2) {
    if (xa2 !== xb2 || ya2 !== yb2) {
      var i3 = s2.push(pop(s2) + "scale(", null, ",", null, ")");
      q2.push({i: i3 - 4, x: interpolateNumber(xa2, xb2)}, {i: i3 - 2, x: interpolateNumber(ya2, yb2)});
    } else if (xb2 !== 1 || yb2 !== 1) {
      s2.push(pop(s2) + "scale(" + xb2 + "," + yb2 + ")");
    }
  }
  return function(a2, b2) {
    var s2 = [], q2 = [];
    a2 = parse3(a2), b2 = parse3(b2);
    translate(a2.translateX, a2.translateY, b2.translateX, b2.translateY, s2, q2);
    rotate(a2.rotate, b2.rotate, s2, q2);
    skewX(a2.skewX, b2.skewX, s2, q2);
    scale(a2.scaleX, a2.scaleY, b2.scaleX, b2.scaleY, s2, q2);
    a2 = b2 = null;
    return function(t5) {
      var i3 = -1, n3 = q2.length, o;
      while (++i3 < n3)
        s2[(o = q2[i3]).i] = o.x(t5);
      return s2.join("");
    };
  };
}
var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)");
var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")");
var epsilon2 = 1e-12;
function cosh(x2) {
  return ((x2 = Math.exp(x2)) + 1 / x2) / 2;
}
function sinh(x2) {
  return ((x2 = Math.exp(x2)) - 1 / x2) / 2;
}
function tanh(x2) {
  return ((x2 = Math.exp(2 * x2)) - 1) / (x2 + 1);
}
var interpolateZoom = function zoomRho(rho, rho2, rho4) {
  function zoom2(p0, p1) {
    var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i3, S2;
    if (d2 < epsilon2) {
      S2 = Math.log(w1 / w0) / rho;
      i3 = function(t5) {
        return [
          ux0 + t5 * dx,
          uy0 + t5 * dy,
          w0 * Math.exp(rho * t5 * S2)
        ];
      };
    } else {
      var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1), b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
      S2 = (r1 - r0) / rho;
      i3 = function(t5) {
        var s2 = t5 * S2, coshr0 = cosh(r0), u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s2 + r0) - sinh(r0));
        return [
          ux0 + u * dx,
          uy0 + u * dy,
          w0 * coshr0 / cosh(rho * s2 + r0)
        ];
      };
    }
    i3.duration = S2 * 1e3 * rho / Math.SQRT2;
    return i3;
  }
  zoom2.rho = function(_23) {
    var _1 = Math.max(1e-3, +_23), _24 = _1 * _1, _42 = _24 * _24;
    return zoomRho(_1, _24, _42);
  };
  return zoom2;
}(Math.SQRT2, 2, 4);
var frame = 0;
var timeout$1 = 0;
var interval = 0;
var pokeDelay = 1e3;
var taskHead;
var taskTail;
var clockLast = 0;
var clockNow = 0;
var clockSkew = 0;
var clock = typeof performance === "object" && performance.now ? performance : Date;
var setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f2) {
  setTimeout(f2, 17);
};
function now() {
  return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
}
function clearNow() {
  clockNow = 0;
}
function Timer() {
  this._call = this._time = this._next = null;
}
Timer.prototype = timer.prototype = {
  constructor: Timer,
  restart: function(callback, delay3, time2) {
    if (typeof callback !== "function")
      throw new TypeError("callback is not a function");
    time2 = (time2 == null ? now() : +time2) + (delay3 == null ? 0 : +delay3);
    if (!this._next && taskTail !== this) {
      if (taskTail)
        taskTail._next = this;
      else
        taskHead = this;
      taskTail = this;
    }
    this._call = callback;
    this._time = time2;
    sleep();
  },
  stop: function() {
    if (this._call) {
      this._call = null;
      this._time = Infinity;
      sleep();
    }
  }
};
function timer(callback, delay3, time2) {
  var t5 = new Timer();
  t5.restart(callback, delay3, time2);
  return t5;
}
function timerFlush() {
  now();
  ++frame;
  var t5 = taskHead, e2;
  while (t5) {
    if ((e2 = clockNow - t5._time) >= 0)
      t5._call.call(void 0, e2);
    t5 = t5._next;
  }
  --frame;
}
function wake() {
  clockNow = (clockLast = clock.now()) + clockSkew;
  frame = timeout$1 = 0;
  try {
    timerFlush();
  } finally {
    frame = 0;
    nap();
    clockNow = 0;
  }
}
function poke() {
  var now3 = clock.now(), delay3 = now3 - clockLast;
  if (delay3 > pokeDelay)
    clockSkew -= delay3, clockLast = now3;
}
function nap() {
  var t0, t1 = taskHead, t22, time2 = Infinity;
  while (t1) {
    if (t1._call) {
      if (time2 > t1._time)
        time2 = t1._time;
      t0 = t1, t1 = t1._next;
    } else {
      t22 = t1._next, t1._next = null;
      t1 = t0 ? t0._next = t22 : taskHead = t22;
    }
  }
  taskTail = t0;
  sleep(time2);
}
function sleep(time2) {
  if (frame)
    return;
  if (timeout$1)
    timeout$1 = clearTimeout(timeout$1);
  var delay3 = time2 - clockNow;
  if (delay3 > 24) {
    if (time2 < Infinity)
      timeout$1 = setTimeout(wake, time2 - clock.now() - clockSkew);
    if (interval)
      interval = clearInterval(interval);
  } else {
    if (!interval)
      clockLast = clock.now(), interval = setInterval(poke, pokeDelay);
    frame = 1, setFrame(wake);
  }
}
function timeout2(callback, delay3, time2) {
  var t5 = new Timer();
  delay3 = delay3 == null ? 0 : +delay3;
  t5.restart((elapsed) => {
    t5.stop();
    callback(elapsed + delay3);
  }, delay3, time2);
  return t5;
}
var emptyOn = dispatch("start", "end", "cancel", "interrupt");
var emptyTween = [];
var CREATED = 0;
var SCHEDULED = 1;
var STARTING = 2;
var STARTED = 3;
var RUNNING = 4;
var ENDING = 5;
var ENDED = 6;
function schedule(node, name, id3, index3, group, timing) {
  var schedules = node.__transition;
  if (!schedules)
    node.__transition = {};
  else if (id3 in schedules)
    return;
  create2(node, id3, {
    name,
    index: index3,
    group,
    on: emptyOn,
    tween: emptyTween,
    time: timing.time,
    delay: timing.delay,
    duration: timing.duration,
    ease: timing.ease,
    timer: null,
    state: CREATED
  });
}
function init3(node, id3) {
  var schedule2 = get5(node, id3);
  if (schedule2.state > CREATED)
    throw new Error("too late; already scheduled");
  return schedule2;
}
function set2(node, id3) {
  var schedule2 = get5(node, id3);
  if (schedule2.state > STARTED)
    throw new Error("too late; already running");
  return schedule2;
}
function get5(node, id3) {
  var schedule2 = node.__transition;
  if (!schedule2 || !(schedule2 = schedule2[id3]))
    throw new Error("transition not found");
  return schedule2;
}
function create2(node, id3, self2) {
  var schedules = node.__transition, tween;
  schedules[id3] = self2;
  self2.timer = timer(schedule2, 0, self2.time);
  function schedule2(elapsed) {
    self2.state = SCHEDULED;
    self2.timer.restart(start3, self2.delay, self2.time);
    if (self2.delay <= elapsed)
      start3(elapsed - self2.delay);
  }
  function start3(elapsed) {
    var i3, j, n3, o;
    if (self2.state !== SCHEDULED)
      return stop();
    for (i3 in schedules) {
      o = schedules[i3];
      if (o.name !== self2.name)
        continue;
      if (o.state === STARTED)
        return timeout2(start3);
      if (o.state === RUNNING) {
        o.state = ENDED;
        o.timer.stop();
        o.on.call("interrupt", node, node.__data__, o.index, o.group);
        delete schedules[i3];
      } else if (+i3 < id3) {
        o.state = ENDED;
        o.timer.stop();
        o.on.call("cancel", node, node.__data__, o.index, o.group);
        delete schedules[i3];
      }
    }
    timeout2(function() {
      if (self2.state === STARTED) {
        self2.state = RUNNING;
        self2.timer.restart(tick, self2.delay, self2.time);
        tick(elapsed);
      }
    });
    self2.state = STARTING;
    self2.on.call("start", node, node.__data__, self2.index, self2.group);
    if (self2.state !== STARTING)
      return;
    self2.state = STARTED;
    tween = new Array(n3 = self2.tween.length);
    for (i3 = 0, j = -1; i3 < n3; ++i3) {
      if (o = self2.tween[i3].value.call(node, node.__data__, self2.index, self2.group)) {
        tween[++j] = o;
      }
    }
    tween.length = j + 1;
  }
  function tick(elapsed) {
    var t5 = elapsed < self2.duration ? self2.ease.call(null, elapsed / self2.duration) : (self2.timer.restart(stop), self2.state = ENDING, 1), i3 = -1, n3 = tween.length;
    while (++i3 < n3) {
      tween[i3].call(node, t5);
    }
    if (self2.state === ENDING) {
      self2.on.call("end", node, node.__data__, self2.index, self2.group);
      stop();
    }
  }
  function stop() {
    self2.state = ENDED;
    self2.timer.stop();
    delete schedules[id3];
    for (var i3 in schedules)
      return;
    delete node.__transition;
  }
}
function interrupt(node, name) {
  var schedules = node.__transition, schedule2, active, empty3 = true, i3;
  if (!schedules)
    return;
  name = name == null ? null : name + "";
  for (i3 in schedules) {
    if ((schedule2 = schedules[i3]).name !== name) {
      empty3 = false;
      continue;
    }
    active = schedule2.state > STARTING && schedule2.state < ENDING;
    schedule2.state = ENDED;
    schedule2.timer.stop();
    schedule2.on.call(active ? "interrupt" : "cancel", node, node.__data__, schedule2.index, schedule2.group);
    delete schedules[i3];
  }
  if (empty3)
    delete node.__transition;
}
function selection_interrupt(name) {
  return this.each(function() {
    interrupt(this, name);
  });
}
function tweenRemove(id3, name) {
  var tween0, tween1;
  return function() {
    var schedule2 = set2(this, id3), tween = schedule2.tween;
    if (tween !== tween0) {
      tween1 = tween0 = tween;
      for (var i3 = 0, n3 = tween1.length; i3 < n3; ++i3) {
        if (tween1[i3].name === name) {
          tween1 = tween1.slice();
          tween1.splice(i3, 1);
          break;
        }
      }
    }
    schedule2.tween = tween1;
  };
}
function tweenFunction(id3, name, value) {
  var tween0, tween1;
  if (typeof value !== "function")
    throw new Error();
  return function() {
    var schedule2 = set2(this, id3), tween = schedule2.tween;
    if (tween !== tween0) {
      tween1 = (tween0 = tween).slice();
      for (var t5 = {name, value}, i3 = 0, n3 = tween1.length; i3 < n3; ++i3) {
        if (tween1[i3].name === name) {
          tween1[i3] = t5;
          break;
        }
      }
      if (i3 === n3)
        tween1.push(t5);
    }
    schedule2.tween = tween1;
  };
}
function transition_tween(name, value) {
  var id3 = this._id;
  name += "";
  if (arguments.length < 2) {
    var tween = get5(this.node(), id3).tween;
    for (var i3 = 0, n3 = tween.length, t5; i3 < n3; ++i3) {
      if ((t5 = tween[i3]).name === name) {
        return t5.value;
      }
    }
    return null;
  }
  return this.each((value == null ? tweenRemove : tweenFunction)(id3, name, value));
}
function tweenValue(transition, name, value) {
  var id3 = transition._id;
  transition.each(function() {
    var schedule2 = set2(this, id3);
    (schedule2.value || (schedule2.value = {}))[name] = value.apply(this, arguments);
  });
  return function(node) {
    return get5(node, id3).value[name];
  };
}
function interpolate(a2, b2) {
  var c3;
  return (typeof b2 === "number" ? interpolateNumber : b2 instanceof color ? interpolateRgb : (c3 = color(b2)) ? (b2 = c3, interpolateRgb) : interpolateString)(a2, b2);
}
function attrRemove(name) {
  return function() {
    this.removeAttribute(name);
  };
}
function attrRemoveNS(fullname) {
  return function() {
    this.removeAttributeNS(fullname.space, fullname.local);
  };
}
function attrConstant(name, interpolate2, value1) {
  var string00, string1 = value1 + "", interpolate0;
  return function() {
    var string0 = this.getAttribute(name);
    return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, value1);
  };
}
function attrConstantNS(fullname, interpolate2, value1) {
  var string00, string1 = value1 + "", interpolate0;
  return function() {
    var string0 = this.getAttributeNS(fullname.space, fullname.local);
    return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, value1);
  };
}
function attrFunction(name, interpolate2, value) {
  var string00, string10, interpolate0;
  return function() {
    var string0, value1 = value(this), string1;
    if (value1 == null)
      return void this.removeAttribute(name);
    string0 = this.getAttribute(name);
    string1 = value1 + "";
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate2(string00 = string0, value1));
  };
}
function attrFunctionNS(fullname, interpolate2, value) {
  var string00, string10, interpolate0;
  return function() {
    var string0, value1 = value(this), string1;
    if (value1 == null)
      return void this.removeAttributeNS(fullname.space, fullname.local);
    string0 = this.getAttributeNS(fullname.space, fullname.local);
    string1 = value1 + "";
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate2(string00 = string0, value1));
  };
}
function transition_attr(name, value) {
  var fullname = namespace(name), i3 = fullname === "transform" ? interpolateTransformSvg : interpolate;
  return this.attrTween(name, typeof value === "function" ? (fullname.local ? attrFunctionNS : attrFunction)(fullname, i3, tweenValue(this, "attr." + name, value)) : value == null ? (fullname.local ? attrRemoveNS : attrRemove)(fullname) : (fullname.local ? attrConstantNS : attrConstant)(fullname, i3, value));
}
function attrInterpolate(name, i3) {
  return function(t5) {
    this.setAttribute(name, i3.call(this, t5));
  };
}
function attrInterpolateNS(fullname, i3) {
  return function(t5) {
    this.setAttributeNS(fullname.space, fullname.local, i3.call(this, t5));
  };
}
function attrTweenNS(fullname, value) {
  var t0, i0;
  function tween() {
    var i3 = value.apply(this, arguments);
    if (i3 !== i0)
      t0 = (i0 = i3) && attrInterpolateNS(fullname, i3);
    return t0;
  }
  tween._value = value;
  return tween;
}
function attrTween(name, value) {
  var t0, i0;
  function tween() {
    var i3 = value.apply(this, arguments);
    if (i3 !== i0)
      t0 = (i0 = i3) && attrInterpolate(name, i3);
    return t0;
  }
  tween._value = value;
  return tween;
}
function transition_attrTween(name, value) {
  var key = "attr." + name;
  if (arguments.length < 2)
    return (key = this.tween(key)) && key._value;
  if (value == null)
    return this.tween(key, null);
  if (typeof value !== "function")
    throw new Error();
  var fullname = namespace(name);
  return this.tween(key, (fullname.local ? attrTweenNS : attrTween)(fullname, value));
}
function delayFunction(id3, value) {
  return function() {
    init3(this, id3).delay = +value.apply(this, arguments);
  };
}
function delayConstant(id3, value) {
  return value = +value, function() {
    init3(this, id3).delay = value;
  };
}
function transition_delay(value) {
  var id3 = this._id;
  return arguments.length ? this.each((typeof value === "function" ? delayFunction : delayConstant)(id3, value)) : get5(this.node(), id3).delay;
}
function durationFunction(id3, value) {
  return function() {
    set2(this, id3).duration = +value.apply(this, arguments);
  };
}
function durationConstant(id3, value) {
  return value = +value, function() {
    set2(this, id3).duration = value;
  };
}
function transition_duration(value) {
  var id3 = this._id;
  return arguments.length ? this.each((typeof value === "function" ? durationFunction : durationConstant)(id3, value)) : get5(this.node(), id3).duration;
}
function easeConstant(id3, value) {
  if (typeof value !== "function")
    throw new Error();
  return function() {
    set2(this, id3).ease = value;
  };
}
function transition_ease(value) {
  var id3 = this._id;
  return arguments.length ? this.each(easeConstant(id3, value)) : get5(this.node(), id3).ease;
}
function easeVarying(id3, value) {
  return function() {
    var v2 = value.apply(this, arguments);
    if (typeof v2 !== "function")
      throw new Error();
    set2(this, id3).ease = v2;
  };
}
function transition_easeVarying(value) {
  if (typeof value !== "function")
    throw new Error();
  return this.each(easeVarying(this._id, value));
}
function transition_filter(match2) {
  if (typeof match2 !== "function")
    match2 = matcher(match2);
  for (var groups2 = this._groups, m2 = groups2.length, subgroups = new Array(m2), j = 0; j < m2; ++j) {
    for (var group = groups2[j], n3 = group.length, subgroup = subgroups[j] = [], node, i3 = 0; i3 < n3; ++i3) {
      if ((node = group[i3]) && match2.call(node, node.__data__, i3, group)) {
        subgroup.push(node);
      }
    }
  }
  return new Transition(subgroups, this._parents, this._name, this._id);
}
function transition_merge(transition) {
  if (transition._id !== this._id)
    throw new Error();
  for (var groups0 = this._groups, groups1 = transition._groups, m0 = groups0.length, m1 = groups1.length, m2 = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m2; ++j) {
    for (var group0 = groups0[j], group1 = groups1[j], n3 = group0.length, merge3 = merges[j] = new Array(n3), node, i3 = 0; i3 < n3; ++i3) {
      if (node = group0[i3] || group1[i3]) {
        merge3[i3] = node;
      }
    }
  }
  for (; j < m0; ++j) {
    merges[j] = groups0[j];
  }
  return new Transition(merges, this._parents, this._name, this._id);
}
function start2(name) {
  return (name + "").trim().split(/^|\s+/).every(function(t5) {
    var i3 = t5.indexOf(".");
    if (i3 >= 0)
      t5 = t5.slice(0, i3);
    return !t5 || t5 === "start";
  });
}
function onFunction(id3, name, listener) {
  var on0, on1, sit = start2(name) ? init3 : set2;
  return function() {
    var schedule2 = sit(this, id3), on2 = schedule2.on;
    if (on2 !== on0)
      (on1 = (on0 = on2).copy()).on(name, listener);
    schedule2.on = on1;
  };
}
function transition_on(name, listener) {
  var id3 = this._id;
  return arguments.length < 2 ? get5(this.node(), id3).on.on(name) : this.each(onFunction(id3, name, listener));
}
function removeFunction(id3) {
  return function() {
    var parent = this.parentNode;
    for (var i3 in this.__transition)
      if (+i3 !== id3)
        return;
    if (parent)
      parent.removeChild(this);
  };
}
function transition_remove() {
  return this.on("end.remove", removeFunction(this._id));
}
function transition_select(select3) {
  var name = this._name, id3 = this._id;
  if (typeof select3 !== "function")
    select3 = selector(select3);
  for (var groups2 = this._groups, m2 = groups2.length, subgroups = new Array(m2), j = 0; j < m2; ++j) {
    for (var group = groups2[j], n3 = group.length, subgroup = subgroups[j] = new Array(n3), node, subnode, i3 = 0; i3 < n3; ++i3) {
      if ((node = group[i3]) && (subnode = select3.call(node, node.__data__, i3, group))) {
        if ("__data__" in node)
          subnode.__data__ = node.__data__;
        subgroup[i3] = subnode;
        schedule(subgroup[i3], name, id3, i3, subgroup, get5(node, id3));
      }
    }
  }
  return new Transition(subgroups, this._parents, name, id3);
}
function transition_selectAll(select3) {
  var name = this._name, id3 = this._id;
  if (typeof select3 !== "function")
    select3 = selectorAll(select3);
  for (var groups2 = this._groups, m2 = groups2.length, subgroups = [], parents = [], j = 0; j < m2; ++j) {
    for (var group = groups2[j], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) {
      if (node = group[i3]) {
        for (var children2 = select3.call(node, node.__data__, i3, group), child, inherit2 = get5(node, id3), k2 = 0, l2 = children2.length; k2 < l2; ++k2) {
          if (child = children2[k2]) {
            schedule(child, name, id3, k2, children2, inherit2);
          }
        }
        subgroups.push(children2);
        parents.push(node);
      }
    }
  }
  return new Transition(subgroups, parents, name, id3);
}
var Selection2 = selection.prototype.constructor;
function transition_selection() {
  return new Selection2(this._groups, this._parents);
}
function styleNull(name, interpolate2) {
  var string00, string10, interpolate0;
  return function() {
    var string0 = styleValue(this, name), string1 = (this.style.removeProperty(name), styleValue(this, name));
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, string10 = string1);
  };
}
function styleRemove(name) {
  return function() {
    this.style.removeProperty(name);
  };
}
function styleConstant(name, interpolate2, value1) {
  var string00, string1 = value1 + "", interpolate0;
  return function() {
    var string0 = styleValue(this, name);
    return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, value1);
  };
}
function styleFunction(name, interpolate2, value) {
  var string00, string10, interpolate0;
  return function() {
    var string0 = styleValue(this, name), value1 = value(this), string1 = value1 + "";
    if (value1 == null)
      string1 = value1 = (this.style.removeProperty(name), styleValue(this, name));
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate2(string00 = string0, value1));
  };
}
function styleMaybeRemove(id3, name) {
  var on0, on1, listener0, key = "style." + name, event = "end." + key, remove3;
  return function() {
    var schedule2 = set2(this, id3), on2 = schedule2.on, listener = schedule2.value[key] == null ? remove3 || (remove3 = styleRemove(name)) : void 0;
    if (on2 !== on0 || listener0 !== listener)
      (on1 = (on0 = on2).copy()).on(event, listener0 = listener);
    schedule2.on = on1;
  };
}
function transition_style(name, value, priority) {
  var i3 = (name += "") === "transform" ? interpolateTransformCss : interpolate;
  return value == null ? this.styleTween(name, styleNull(name, i3)).on("end.style." + name, styleRemove(name)) : typeof value === "function" ? this.styleTween(name, styleFunction(name, i3, tweenValue(this, "style." + name, value))).each(styleMaybeRemove(this._id, name)) : this.styleTween(name, styleConstant(name, i3, value), priority).on("end.style." + name, null);
}
function styleInterpolate(name, i3, priority) {
  return function(t5) {
    this.style.setProperty(name, i3.call(this, t5), priority);
  };
}
function styleTween(name, value, priority) {
  var t5, i0;
  function tween() {
    var i3 = value.apply(this, arguments);
    if (i3 !== i0)
      t5 = (i0 = i3) && styleInterpolate(name, i3, priority);
    return t5;
  }
  tween._value = value;
  return tween;
}
function transition_styleTween(name, value, priority) {
  var key = "style." + (name += "");
  if (arguments.length < 2)
    return (key = this.tween(key)) && key._value;
  if (value == null)
    return this.tween(key, null);
  if (typeof value !== "function")
    throw new Error();
  return this.tween(key, styleTween(name, value, priority == null ? "" : priority));
}
function textConstant(value) {
  return function() {
    this.textContent = value;
  };
}
function textFunction(value) {
  return function() {
    var value1 = value(this);
    this.textContent = value1 == null ? "" : value1;
  };
}
function transition_text(value) {
  return this.tween("text", typeof value === "function" ? textFunction(tweenValue(this, "text", value)) : textConstant(value == null ? "" : value + ""));
}
function textInterpolate(i3) {
  return function(t5) {
    this.textContent = i3.call(this, t5);
  };
}
function textTween(value) {
  var t0, i0;
  function tween() {
    var i3 = value.apply(this, arguments);
    if (i3 !== i0)
      t0 = (i0 = i3) && textInterpolate(i3);
    return t0;
  }
  tween._value = value;
  return tween;
}
function transition_textTween(value) {
  var key = "text";
  if (arguments.length < 1)
    return (key = this.tween(key)) && key._value;
  if (value == null)
    return this.tween(key, null);
  if (typeof value !== "function")
    throw new Error();
  return this.tween(key, textTween(value));
}
function transition_transition() {
  var name = this._name, id0 = this._id, id1 = newId2();
  for (var groups2 = this._groups, m2 = groups2.length, j = 0; j < m2; ++j) {
    for (var group = groups2[j], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) {
      if (node = group[i3]) {
        var inherit2 = get5(node, id0);
        schedule(node, name, id1, i3, group, {
          time: inherit2.time + inherit2.delay + inherit2.duration,
          delay: 0,
          duration: inherit2.duration,
          ease: inherit2.ease
        });
      }
    }
  }
  return new Transition(groups2, this._parents, name, id1);
}
function transition_end() {
  var on0, on1, that = this, id3 = that._id, size2 = that.size();
  return new Promise(function(resolve2, reject) {
    var cancel = {value: reject}, end2 = {value: function() {
      if (--size2 === 0)
        resolve2();
    }};
    that.each(function() {
      var schedule2 = set2(this, id3), on2 = schedule2.on;
      if (on2 !== on0) {
        on1 = (on0 = on2).copy();
        on1._.cancel.push(cancel);
        on1._.interrupt.push(cancel);
        on1._.end.push(end2);
      }
      schedule2.on = on1;
    });
    if (size2 === 0)
      resolve2();
  });
}
var id2 = 0;
function Transition(groups2, parents, name, id3) {
  this._groups = groups2;
  this._parents = parents;
  this._name = name;
  this._id = id3;
}
function newId2() {
  return ++id2;
}
var selection_prototype = selection.prototype;
Transition.prototype = {
  constructor: Transition,
  select: transition_select,
  selectAll: transition_selectAll,
  selectChild: selection_prototype.selectChild,
  selectChildren: selection_prototype.selectChildren,
  filter: transition_filter,
  merge: transition_merge,
  selection: transition_selection,
  transition: transition_transition,
  call: selection_prototype.call,
  nodes: selection_prototype.nodes,
  node: selection_prototype.node,
  size: selection_prototype.size,
  empty: selection_prototype.empty,
  each: selection_prototype.each,
  on: transition_on,
  attr: transition_attr,
  attrTween: transition_attrTween,
  style: transition_style,
  styleTween: transition_styleTween,
  text: transition_text,
  textTween: transition_textTween,
  remove: transition_remove,
  tween: transition_tween,
  delay: transition_delay,
  duration: transition_duration,
  ease: transition_ease,
  easeVarying: transition_easeVarying,
  end: transition_end,
  [Symbol.iterator]: selection_prototype[Symbol.iterator]
};
function cubicInOut(t5) {
  return ((t5 *= 2) <= 1 ? t5 * t5 * t5 : (t5 -= 2) * t5 * t5 + 2) / 2;
}
var defaultTiming = {
  time: null,
  delay: 0,
  duration: 250,
  ease: cubicInOut
};
function inherit(node, id3) {
  var timing;
  while (!(timing = node.__transition) || !(timing = timing[id3])) {
    if (!(node = node.parentNode)) {
      throw new Error(`transition ${id3} not found`);
    }
  }
  return timing;
}
function selection_transition(name) {
  var id3, timing;
  if (name instanceof Transition) {
    id3 = name._id, name = name._name;
  } else {
    id3 = newId2(), (timing = defaultTiming).time = now(), name = name == null ? null : name + "";
  }
  for (var groups2 = this._groups, m2 = groups2.length, j = 0; j < m2; ++j) {
    for (var group = groups2[j], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) {
      if (node = group[i3]) {
        schedule(node, name, id3, i3, group, timing || inherit(node, id3));
      }
    }
  }
  return new Transition(groups2, this._parents, name, id3);
}
selection.prototype.interrupt = selection_interrupt;
selection.prototype.transition = selection_transition;
var constant2 = (x2) => () => x2;
function ZoomEvent(type, {
  sourceEvent: sourceEvent2,
  target,
  transform: transform3,
  dispatch: dispatch2
}) {
  Object.defineProperties(this, {
    type: {value: type, enumerable: true, configurable: true},
    sourceEvent: {value: sourceEvent2, enumerable: true, configurable: true},
    target: {value: target, enumerable: true, configurable: true},
    transform: {value: transform3, enumerable: true, configurable: true},
    _: {value: dispatch2}
  });
}
function Transform(k2, x2, y3) {
  this.k = k2;
  this.x = x2;
  this.y = y3;
}
Transform.prototype = {
  constructor: Transform,
  scale: function(k2) {
    return k2 === 1 ? this : new Transform(this.k * k2, this.x, this.y);
  },
  translate: function(x2, y3) {
    return x2 === 0 & y3 === 0 ? this : new Transform(this.k, this.x + this.k * x2, this.y + this.k * y3);
  },
  apply: function(point) {
    return [point[0] * this.k + this.x, point[1] * this.k + this.y];
  },
  applyX: function(x2) {
    return x2 * this.k + this.x;
  },
  applyY: function(y3) {
    return y3 * this.k + this.y;
  },
  invert: function(location2) {
    return [(location2[0] - this.x) / this.k, (location2[1] - this.y) / this.k];
  },
  invertX: function(x2) {
    return (x2 - this.x) / this.k;
  },
  invertY: function(y3) {
    return (y3 - this.y) / this.k;
  },
  rescaleX: function(x2) {
    return x2.copy().domain(x2.range().map(this.invertX, this).map(x2.invert, x2));
  },
  rescaleY: function(y3) {
    return y3.copy().domain(y3.range().map(this.invertY, this).map(y3.invert, y3));
  },
  toString: function() {
    return "translate(" + this.x + "," + this.y + ") scale(" + this.k + ")";
  }
};
var identity2 = new Transform(1, 0, 0);
function nopropagation(event) {
  event.stopImmediatePropagation();
}
function noevent(event) {
  event.preventDefault();
  event.stopImmediatePropagation();
}
function defaultFilter(event) {
  return (!event.ctrlKey || event.type === "wheel") && !event.button;
}
function defaultExtent() {
  var e2 = this;
  if (e2 instanceof SVGElement) {
    e2 = e2.ownerSVGElement || e2;
    if (e2.hasAttribute("viewBox")) {
      e2 = e2.viewBox.baseVal;
      return [[e2.x, e2.y], [e2.x + e2.width, e2.y + e2.height]];
    }
    return [[0, 0], [e2.width.baseVal.value, e2.height.baseVal.value]];
  }
  return [[0, 0], [e2.clientWidth, e2.clientHeight]];
}
function defaultTransform() {
  return this.__zoom || identity2;
}
function defaultWheelDelta(event) {
  return -event.deltaY * (event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 2e-3) * (event.ctrlKey ? 10 : 1);
}
function defaultTouchable() {
  return navigator.maxTouchPoints || "ontouchstart" in this;
}
function defaultConstrain(transform3, extent, translateExtent) {
  var dx0 = transform3.invertX(extent[0][0]) - translateExtent[0][0], dx1 = transform3.invertX(extent[1][0]) - translateExtent[1][0], dy0 = transform3.invertY(extent[0][1]) - translateExtent[0][1], dy1 = transform3.invertY(extent[1][1]) - translateExtent[1][1];
  return transform3.translate(dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1), dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1));
}
function zoom() {
  var filter3 = defaultFilter, extent = defaultExtent, constrain = defaultConstrain, wheelDelta = defaultWheelDelta, touchable = defaultTouchable, scaleExtent = [0, Infinity], translateExtent = [[-Infinity, -Infinity], [Infinity, Infinity]], duration = 250, interpolate2 = interpolateZoom, listeners = dispatch("start", "zoom", "end"), touchstarting, touchfirst, touchending, touchDelay = 500, wheelDelay = 150, clickDistance2 = 0, tapDistance = 10;
  function zoom2(selection2) {
    selection2.property("__zoom", defaultTransform).on("wheel.zoom", wheeled, {passive: false}).on("mousedown.zoom", mousedowned).on("dblclick.zoom", dblclicked).filter(touchable).on("touchstart.zoom", touchstarted).on("touchmove.zoom", touchmoved).on("touchend.zoom touchcancel.zoom", touchended).style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  }
  zoom2.transform = function(collection, transform3, point, event) {
    var selection2 = collection.selection ? collection.selection() : collection;
    selection2.property("__zoom", defaultTransform);
    if (collection !== selection2) {
      schedule2(collection, transform3, point, event);
    } else {
      selection2.interrupt().each(function() {
        gesture(this, arguments).event(event).start().zoom(null, typeof transform3 === "function" ? transform3.apply(this, arguments) : transform3).end();
      });
    }
  };
  zoom2.scaleBy = function(selection2, k2, p2, event) {
    zoom2.scaleTo(selection2, function() {
      var k0 = this.__zoom.k, k1 = typeof k2 === "function" ? k2.apply(this, arguments) : k2;
      return k0 * k1;
    }, p2, event);
  };
  zoom2.scaleTo = function(selection2, k2, p2, event) {
    zoom2.transform(selection2, function() {
      var e2 = extent.apply(this, arguments), t0 = this.__zoom, p0 = p2 == null ? centroid(e2) : typeof p2 === "function" ? p2.apply(this, arguments) : p2, p1 = t0.invert(p0), k1 = typeof k2 === "function" ? k2.apply(this, arguments) : k2;
      return constrain(translate(scale(t0, k1), p0, p1), e2, translateExtent);
    }, p2, event);
  };
  zoom2.translateBy = function(selection2, x2, y3, event) {
    zoom2.transform(selection2, function() {
      return constrain(this.__zoom.translate(typeof x2 === "function" ? x2.apply(this, arguments) : x2, typeof y3 === "function" ? y3.apply(this, arguments) : y3), extent.apply(this, arguments), translateExtent);
    }, null, event);
  };
  zoom2.translateTo = function(selection2, x2, y3, p2, event) {
    zoom2.transform(selection2, function() {
      var e2 = extent.apply(this, arguments), t5 = this.__zoom, p0 = p2 == null ? centroid(e2) : typeof p2 === "function" ? p2.apply(this, arguments) : p2;
      return constrain(identity2.translate(p0[0], p0[1]).scale(t5.k).translate(typeof x2 === "function" ? -x2.apply(this, arguments) : -x2, typeof y3 === "function" ? -y3.apply(this, arguments) : -y3), e2, translateExtent);
    }, p2, event);
  };
  function scale(transform3, k2) {
    k2 = Math.max(scaleExtent[0], Math.min(scaleExtent[1], k2));
    return k2 === transform3.k ? transform3 : new Transform(k2, transform3.x, transform3.y);
  }
  function translate(transform3, p0, p1) {
    var x2 = p0[0] - p1[0] * transform3.k, y3 = p0[1] - p1[1] * transform3.k;
    return x2 === transform3.x && y3 === transform3.y ? transform3 : new Transform(transform3.k, x2, y3);
  }
  function centroid(extent2) {
    return [(+extent2[0][0] + +extent2[1][0]) / 2, (+extent2[0][1] + +extent2[1][1]) / 2];
  }
  function schedule2(transition, transform3, point, event) {
    transition.on("start.zoom", function() {
      gesture(this, arguments).event(event).start();
    }).on("interrupt.zoom end.zoom", function() {
      gesture(this, arguments).event(event).end();
    }).tween("zoom", function() {
      var that = this, args = arguments, g2 = gesture(that, args).event(event), e2 = extent.apply(that, args), p2 = point == null ? centroid(e2) : typeof point === "function" ? point.apply(that, args) : point, w2 = Math.max(e2[1][0] - e2[0][0], e2[1][1] - e2[0][1]), a2 = that.__zoom, b2 = typeof transform3 === "function" ? transform3.apply(that, args) : transform3, i3 = interpolate2(a2.invert(p2).concat(w2 / a2.k), b2.invert(p2).concat(w2 / b2.k));
      return function(t5) {
        if (t5 === 1)
          t5 = b2;
        else {
          var l2 = i3(t5), k2 = w2 / l2[2];
          t5 = new Transform(k2, p2[0] - l2[0] * k2, p2[1] - l2[1] * k2);
        }
        g2.zoom(null, t5);
      };
    });
  }
  function gesture(that, args, clean) {
    return !clean && that.__zooming || new Gesture2(that, args);
  }
  function Gesture2(that, args) {
    this.that = that;
    this.args = args;
    this.active = 0;
    this.sourceEvent = null;
    this.extent = extent.apply(that, args);
    this.taps = 0;
  }
  Gesture2.prototype = {
    event: function(event) {
      if (event)
        this.sourceEvent = event;
      return this;
    },
    start: function() {
      if (++this.active === 1) {
        this.that.__zooming = this;
        this.emit("start");
      }
      return this;
    },
    zoom: function(key, transform3) {
      if (this.mouse && key !== "mouse")
        this.mouse[1] = transform3.invert(this.mouse[0]);
      if (this.touch0 && key !== "touch")
        this.touch0[1] = transform3.invert(this.touch0[0]);
      if (this.touch1 && key !== "touch")
        this.touch1[1] = transform3.invert(this.touch1[0]);
      this.that.__zoom = transform3;
      this.emit("zoom");
      return this;
    },
    end: function() {
      if (--this.active === 0) {
        delete this.that.__zooming;
        this.emit("end");
      }
      return this;
    },
    emit: function(type) {
      var d2 = select2(this.that).datum();
      listeners.call(type, this.that, new ZoomEvent(type, {
        sourceEvent: this.sourceEvent,
        target: zoom2,
        type,
        transform: this.that.__zoom,
        dispatch: listeners
      }), d2);
    }
  };
  function wheeled(event, ...args) {
    if (!filter3.apply(this, arguments))
      return;
    var g2 = gesture(this, args).event(event), t5 = this.__zoom, k2 = Math.max(scaleExtent[0], Math.min(scaleExtent[1], t5.k * Math.pow(2, wheelDelta.apply(this, arguments)))), p2 = pointer(event);
    if (g2.wheel) {
      if (g2.mouse[0][0] !== p2[0] || g2.mouse[0][1] !== p2[1]) {
        g2.mouse[1] = t5.invert(g2.mouse[0] = p2);
      }
      clearTimeout(g2.wheel);
    } else if (t5.k === k2)
      return;
    else {
      g2.mouse = [p2, t5.invert(p2)];
      interrupt(this);
      g2.start();
    }
    noevent(event);
    g2.wheel = setTimeout(wheelidled, wheelDelay);
    g2.zoom("mouse", constrain(translate(scale(t5, k2), g2.mouse[0], g2.mouse[1]), g2.extent, translateExtent));
    function wheelidled() {
      g2.wheel = null;
      g2.end();
    }
  }
  function mousedowned(event, ...args) {
    if (touchending || !filter3.apply(this, arguments))
      return;
    var currentTarget = event.currentTarget, g2 = gesture(this, args, true).event(event), v2 = select2(event.view).on("mousemove.zoom", mousemoved, true).on("mouseup.zoom", mouseupped, true), p2 = pointer(event, currentTarget), x0 = event.clientX, y0 = event.clientY;
    dragDisable(event.view);
    nopropagation(event);
    g2.mouse = [p2, this.__zoom.invert(p2)];
    interrupt(this);
    g2.start();
    function mousemoved(event2) {
      noevent(event2);
      if (!g2.moved) {
        var dx = event2.clientX - x0, dy = event2.clientY - y0;
        g2.moved = dx * dx + dy * dy > clickDistance2;
      }
      g2.event(event2).zoom("mouse", constrain(translate(g2.that.__zoom, g2.mouse[0] = pointer(event2, currentTarget), g2.mouse[1]), g2.extent, translateExtent));
    }
    function mouseupped(event2) {
      v2.on("mousemove.zoom mouseup.zoom", null);
      yesdrag(event2.view, g2.moved);
      noevent(event2);
      g2.event(event2).end();
    }
  }
  function dblclicked(event, ...args) {
    if (!filter3.apply(this, arguments))
      return;
    var t0 = this.__zoom, p0 = pointer(event.changedTouches ? event.changedTouches[0] : event, this), p1 = t0.invert(p0), k1 = t0.k * (event.shiftKey ? 0.5 : 2), t1 = constrain(translate(scale(t0, k1), p0, p1), extent.apply(this, args), translateExtent);
    noevent(event);
    if (duration > 0)
      select2(this).transition().duration(duration).call(schedule2, t1, p0, event);
    else
      select2(this).call(zoom2.transform, t1, p0, event);
  }
  function touchstarted(event, ...args) {
    if (!filter3.apply(this, arguments))
      return;
    var touches = event.touches, n3 = touches.length, g2 = gesture(this, args, event.changedTouches.length === n3).event(event), started, i3, t5, p2;
    nopropagation(event);
    for (i3 = 0; i3 < n3; ++i3) {
      t5 = touches[i3], p2 = pointer(t5, this);
      p2 = [p2, this.__zoom.invert(p2), t5.identifier];
      if (!g2.touch0)
        g2.touch0 = p2, started = true, g2.taps = 1 + !!touchstarting;
      else if (!g2.touch1 && g2.touch0[2] !== p2[2])
        g2.touch1 = p2, g2.taps = 0;
    }
    if (touchstarting)
      touchstarting = clearTimeout(touchstarting);
    if (started) {
      if (g2.taps < 2)
        touchfirst = p2[0], touchstarting = setTimeout(function() {
          touchstarting = null;
        }, touchDelay);
      interrupt(this);
      g2.start();
    }
  }
  function touchmoved(event, ...args) {
    if (!this.__zooming)
      return;
    var g2 = gesture(this, args).event(event), touches = event.changedTouches, n3 = touches.length, i3, t5, p2, l2;
    noevent(event);
    for (i3 = 0; i3 < n3; ++i3) {
      t5 = touches[i3], p2 = pointer(t5, this);
      if (g2.touch0 && g2.touch0[2] === t5.identifier)
        g2.touch0[0] = p2;
      else if (g2.touch1 && g2.touch1[2] === t5.identifier)
        g2.touch1[0] = p2;
    }
    t5 = g2.that.__zoom;
    if (g2.touch1) {
      var p0 = g2.touch0[0], l0 = g2.touch0[1], p1 = g2.touch1[0], l1 = g2.touch1[1], dp = (dp = p1[0] - p0[0]) * dp + (dp = p1[1] - p0[1]) * dp, dl = (dl = l1[0] - l0[0]) * dl + (dl = l1[1] - l0[1]) * dl;
      t5 = scale(t5, Math.sqrt(dp / dl));
      p2 = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2];
      l2 = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2];
    } else if (g2.touch0)
      p2 = g2.touch0[0], l2 = g2.touch0[1];
    else
      return;
    g2.zoom("touch", constrain(translate(t5, p2, l2), g2.extent, translateExtent));
  }
  function touchended(event, ...args) {
    if (!this.__zooming)
      return;
    var g2 = gesture(this, args).event(event), touches = event.changedTouches, n3 = touches.length, i3, t5;
    nopropagation(event);
    if (touchending)
      clearTimeout(touchending);
    touchending = setTimeout(function() {
      touchending = null;
    }, touchDelay);
    for (i3 = 0; i3 < n3; ++i3) {
      t5 = touches[i3];
      if (g2.touch0 && g2.touch0[2] === t5.identifier)
        delete g2.touch0;
      else if (g2.touch1 && g2.touch1[2] === t5.identifier)
        delete g2.touch1;
    }
    if (g2.touch1 && !g2.touch0)
      g2.touch0 = g2.touch1, delete g2.touch1;
    if (g2.touch0)
      g2.touch0[1] = this.__zoom.invert(g2.touch0[0]);
    else {
      g2.end();
      if (g2.taps === 2) {
        t5 = pointer(t5, this);
        if (Math.hypot(touchfirst[0] - t5[0], touchfirst[1] - t5[1]) < tapDistance) {
          var p2 = select2(this).on("dblclick.zoom");
          if (p2)
            p2.apply(this, arguments);
        }
      }
    }
  }
  zoom2.wheelDelta = function(_23) {
    return arguments.length ? (wheelDelta = typeof _23 === "function" ? _23 : constant2(+_23), zoom2) : wheelDelta;
  };
  zoom2.filter = function(_23) {
    return arguments.length ? (filter3 = typeof _23 === "function" ? _23 : constant2(!!_23), zoom2) : filter3;
  };
  zoom2.touchable = function(_23) {
    return arguments.length ? (touchable = typeof _23 === "function" ? _23 : constant2(!!_23), zoom2) : touchable;
  };
  zoom2.extent = function(_23) {
    return arguments.length ? (extent = typeof _23 === "function" ? _23 : constant2([[+_23[0][0], +_23[0][1]], [+_23[1][0], +_23[1][1]]]), zoom2) : extent;
  };
  zoom2.scaleExtent = function(_23) {
    return arguments.length ? (scaleExtent[0] = +_23[0], scaleExtent[1] = +_23[1], zoom2) : [scaleExtent[0], scaleExtent[1]];
  };
  zoom2.translateExtent = function(_23) {
    return arguments.length ? (translateExtent[0][0] = +_23[0][0], translateExtent[1][0] = +_23[1][0], translateExtent[0][1] = +_23[0][1], translateExtent[1][1] = +_23[1][1], zoom2) : [[translateExtent[0][0], translateExtent[0][1]], [translateExtent[1][0], translateExtent[1][1]]];
  };
  zoom2.constrain = function(_23) {
    return arguments.length ? (constrain = _23, zoom2) : constrain;
  };
  zoom2.duration = function(_23) {
    return arguments.length ? (duration = +_23, zoom2) : duration;
  };
  zoom2.interpolate = function(_23) {
    return arguments.length ? (interpolate2 = _23, zoom2) : interpolate2;
  };
  zoom2.on = function() {
    var value = listeners.on.apply(listeners, arguments);
    return value === listeners ? zoom2 : value;
  };
  zoom2.clickDistance = function(_23) {
    return arguments.length ? (clickDistance2 = (_23 = +_23) * _23, zoom2) : Math.sqrt(clickDistance2);
  };
  zoom2.tapDistance = function(_23) {
    return arguments.length ? (tapDistance = +_23, zoom2) : tapDistance;
  };
  return zoom2;
}
var useResizeHandler = function(rendererNode) {
  var updateSize3 = useStoreActions(function(actions2) {
    return actions2.updateSize;
  });
  react.useEffect(function() {
    var resizeObserver;
    var updateDimensions = function updateDimensions2() {
      if (!rendererNode.current) {
        return;
      }
      var size2 = getDimensions(rendererNode.current);
      if (size2.height === 0 || size2.width === 0) {
        console.warn("The React Flow parent container needs a width and a height to render the graph.");
      }
      updateSize3(size2);
    };
    updateDimensions();
    window.onresize = updateDimensions;
    if (rendererNode.current) {
      resizeObserver = new ResizeObserver(function() {
        return updateDimensions();
      });
      resizeObserver.observe(rendererNode.current);
    }
    return function() {
      window.onresize = null;
      if (resizeObserver && rendererNode.current) {
        resizeObserver.unobserve(rendererNode.current);
      }
    };
  }, []);
};
var Position2;
(function(Position3) {
  Position3["Left"] = "left";
  Position3["Top"] = "top";
  Position3["Right"] = "right";
  Position3["Bottom"] = "bottom";
})(Position2 || (Position2 = {}));
var ArrowHeadType;
(function(ArrowHeadType2) {
  ArrowHeadType2["Arrow"] = "arrow";
  ArrowHeadType2["ArrowClosed"] = "arrowclosed";
})(ArrowHeadType || (ArrowHeadType = {}));
var BackgroundVariant;
(function(BackgroundVariant2) {
  BackgroundVariant2["Lines"] = "lines";
  BackgroundVariant2["Dots"] = "dots";
})(BackgroundVariant || (BackgroundVariant = {}));
var ConnectionMode;
(function(ConnectionMode2) {
  ConnectionMode2["Strict"] = "strict";
  ConnectionMode2["Loose"] = "loose";
})(ConnectionMode || (ConnectionMode = {}));
var ConnectionLineType;
(function(ConnectionLineType2) {
  ConnectionLineType2["Bezier"] = "default";
  ConnectionLineType2["Straight"] = "straight";
  ConnectionLineType2["Step"] = "step";
  ConnectionLineType2["SmoothStep"] = "smoothstep";
})(ConnectionLineType || (ConnectionLineType = {}));
var PanOnScrollMode;
(function(PanOnScrollMode2) {
  PanOnScrollMode2["Free"] = "free";
  PanOnScrollMode2["Vertical"] = "vertical";
  PanOnScrollMode2["Horizontal"] = "horizontal";
})(PanOnScrollMode || (PanOnScrollMode = {}));
var viewChanged = function viewChanged2(prevTransform, eventTransform) {
  return prevTransform.x !== eventTransform.x || prevTransform.y !== eventTransform.y || prevTransform.zoom !== eventTransform.k;
};
var eventToFlowTransform = function eventToFlowTransform2(eventTransform) {
  return {
    x: eventTransform.x,
    y: eventTransform.y,
    zoom: eventTransform.k
  };
};
var hasNoWheelClass = function hasNoWheelClass2(event) {
  return event.target.closest(".nowheel");
};
var ZoomPane = function ZoomPane2(_ref) {
  var onMove = _ref.onMove, onMoveStart = _ref.onMoveStart, onMoveEnd = _ref.onMoveEnd, _ref$zoomOnScroll = _ref.zoomOnScroll, zoomOnScroll = _ref$zoomOnScroll === void 0 ? true : _ref$zoomOnScroll, _ref$zoomOnPinch = _ref.zoomOnPinch, zoomOnPinch = _ref$zoomOnPinch === void 0 ? true : _ref$zoomOnPinch, _ref$panOnScroll = _ref.panOnScroll, panOnScroll = _ref$panOnScroll === void 0 ? false : _ref$panOnScroll, _ref$panOnScrollSpeed = _ref.panOnScrollSpeed, panOnScrollSpeed = _ref$panOnScrollSpeed === void 0 ? 0.5 : _ref$panOnScrollSpeed, _ref$panOnScrollMode = _ref.panOnScrollMode, panOnScrollMode = _ref$panOnScrollMode === void 0 ? PanOnScrollMode.Free : _ref$panOnScrollMode, _ref$zoomOnDoubleClic = _ref.zoomOnDoubleClick, zoomOnDoubleClick = _ref$zoomOnDoubleClic === void 0 ? true : _ref$zoomOnDoubleClic, selectionKeyPressed = _ref.selectionKeyPressed, elementsSelectable = _ref.elementsSelectable, _ref$paneMoveable = _ref.paneMoveable, paneMoveable = _ref$paneMoveable === void 0 ? true : _ref$paneMoveable, _ref$defaultPosition = _ref.defaultPosition, defaultPosition = _ref$defaultPosition === void 0 ? [0, 0] : _ref$defaultPosition, _ref$defaultZoom = _ref.defaultZoom, defaultZoom = _ref$defaultZoom === void 0 ? 1 : _ref$defaultZoom, translateExtent = _ref.translateExtent, zoomActivationKeyCode = _ref.zoomActivationKeyCode, _ref$preventScrolling = _ref.preventScrolling, preventScrolling = _ref$preventScrolling === void 0 ? true : _ref$preventScrolling, children2 = _ref.children;
  var zoomPane = react.useRef(null);
  var prevTransform = react.useRef({
    x: 0,
    y: 0,
    zoom: 0
  });
  var store2 = useStore();
  var d3Zoom = useStoreState(function(s2) {
    return s2.d3Zoom;
  });
  var d3Selection = useStoreState(function(s2) {
    return s2.d3Selection;
  });
  var d3ZoomHandler = useStoreState(function(s2) {
    return s2.d3ZoomHandler;
  });
  var initD3Zoom3 = useStoreActions(function(actions2) {
    return actions2.initD3Zoom;
  });
  var updateTransform3 = useStoreActions(function(actions2) {
    return actions2.updateTransform;
  });
  var zoomActivationKeyPressed = useKeyPress(zoomActivationKeyCode);
  useResizeHandler(zoomPane);
  react.useEffect(function() {
    if (zoomPane.current) {
      var state = store2.getState();
      var currentTranslateExtent = typeof translateExtent !== "undefined" ? translateExtent : state.translateExtent;
      var d3ZoomInstance = zoom().scaleExtent([state.minZoom, state.maxZoom]).translateExtent(currentTranslateExtent);
      var selection2 = select2(zoomPane.current).call(d3ZoomInstance);
      var clampedX = clamp3(defaultPosition[0], currentTranslateExtent[0][0], currentTranslateExtent[1][0]);
      var clampedY = clamp3(defaultPosition[1], currentTranslateExtent[0][1], currentTranslateExtent[1][1]);
      var clampedZoom = clamp3(defaultZoom, state.minZoom, state.maxZoom);
      var updatedTransform = identity2.translate(clampedX, clampedY).scale(clampedZoom);
      d3ZoomInstance.transform(selection2, updatedTransform);
      initD3Zoom3({
        d3Zoom: d3ZoomInstance,
        d3Selection: selection2,
        d3ZoomHandler: selection2.on("wheel.zoom"),
        transform: [clampedX, clampedY, clampedZoom]
      });
    }
  }, []);
  react.useEffect(function() {
    if (d3Selection && d3Zoom) {
      if (panOnScroll && !zoomActivationKeyPressed) {
        d3Selection.on("wheel", function(event) {
          if (hasNoWheelClass(event)) {
            return false;
          }
          event.preventDefault();
          event.stopImmediatePropagation();
          var currentZoom = d3Selection.property("__zoom").k || 1;
          if (event.ctrlKey && zoomOnPinch) {
            var point = pointer(event);
            var pinchDelta = -event.deltaY * (event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 2e-3) * 10;
            var _zoom = currentZoom * Math.pow(2, pinchDelta);
            d3Zoom.scaleTo(d3Selection, _zoom, point);
            return;
          }
          var deltaNormalize = event.deltaMode === 1 ? 20 : 1;
          var deltaX = panOnScrollMode === PanOnScrollMode.Vertical ? 0 : event.deltaX * deltaNormalize;
          var deltaY = panOnScrollMode === PanOnScrollMode.Horizontal ? 0 : event.deltaY * deltaNormalize;
          d3Zoom.translateBy(d3Selection, -(deltaX / currentZoom) * panOnScrollSpeed, -(deltaY / currentZoom) * panOnScrollSpeed);
        }).on("wheel.zoom", null);
      } else if (typeof d3ZoomHandler !== "undefined") {
        d3Selection.on("wheel", function(event) {
          if (!preventScrolling || hasNoWheelClass(event)) {
            return null;
          }
          event.preventDefault();
        }).on("wheel.zoom", d3ZoomHandler);
      }
    }
  }, [panOnScroll, panOnScrollMode, d3Selection, d3Zoom, d3ZoomHandler, zoomActivationKeyPressed, zoomOnPinch, preventScrolling]);
  react.useEffect(function() {
    if (d3Zoom) {
      if (selectionKeyPressed) {
        d3Zoom.on("zoom", null);
      } else {
        d3Zoom.on("zoom", function(event) {
          updateTransform3([event.transform.x, event.transform.y, event.transform.k]);
          if (onMove) {
            var flowTransform = eventToFlowTransform(event.transform);
            onMove(flowTransform);
          }
        });
      }
    }
  }, [selectionKeyPressed, d3Zoom, updateTransform3, onMove]);
  react.useEffect(function() {
    if (d3Zoom) {
      if (onMoveStart) {
        d3Zoom.on("start", function(event) {
          var flowTransform = eventToFlowTransform(event.transform);
          prevTransform.current = flowTransform;
          onMoveStart(flowTransform);
        });
      } else {
        d3Zoom.on("start", null);
      }
    }
  }, [d3Zoom, onMoveStart]);
  react.useEffect(function() {
    if (d3Zoom) {
      if (onMoveEnd) {
        d3Zoom.on("end", function(event) {
          if (viewChanged(prevTransform.current, event.transform)) {
            var flowTransform = eventToFlowTransform(event.transform);
            prevTransform.current = flowTransform;
            onMoveEnd(flowTransform);
          }
        });
      } else {
        d3Zoom.on("end", null);
      }
    }
  }, [d3Zoom, onMoveEnd]);
  react.useEffect(function() {
    if (d3Zoom) {
      d3Zoom.filter(function(event) {
        var zoomScroll = zoomActivationKeyPressed || zoomOnScroll;
        var pinchZoom = zoomOnPinch && event.ctrlKey;
        if (!paneMoveable && !zoomScroll && !panOnScroll && !zoomOnDoubleClick && !zoomOnPinch) {
          return false;
        }
        if (selectionKeyPressed) {
          return false;
        }
        if (!zoomOnDoubleClick && event.type === "dblclick") {
          return false;
        }
        if (hasNoWheelClass(event) && event.type === "wheel") {
          return false;
        }
        if ((event.target.closest(".react-flow__node") || event.target.closest(".react-flow__edge")) && event.type !== "wheel") {
          return false;
        }
        if (event.target.closest(".react-flow__nodesselection") && event.type !== "wheel") {
          return false;
        }
        if (!zoomOnPinch && event.ctrlKey && event.type === "wheel") {
          return false;
        }
        if (!zoomScroll && !panOnScroll && !pinchZoom && event.type === "wheel") {
          return false;
        }
        if (!paneMoveable && (event.type === "mousedown" || event.type === "touchstart")) {
          return false;
        }
        return (!event.ctrlKey || event.type === "wheel") && !event.button;
      });
    }
  }, [d3Zoom, zoomOnScroll, zoomOnPinch, panOnScroll, zoomOnDoubleClick, paneMoveable, selectionKeyPressed, elementsSelectable, zoomActivationKeyPressed]);
  return /* @__PURE__ */ react.createElement("div", {
    className: "react-flow__renderer react-flow__zoompane",
    ref: zoomPane
  }, children2);
};
function getMousePosition(event) {
  var reactFlowNode = event.target.closest(".react-flow");
  if (!reactFlowNode) {
    return;
  }
  var containerBounds = reactFlowNode.getBoundingClientRect();
  return {
    x: event.clientX - containerBounds.left,
    y: event.clientY - containerBounds.top
  };
}
var SelectionRect = function SelectionRect2() {
  var userSelectionRect = useStoreState(function(state) {
    return state.userSelectionRect;
  });
  if (!userSelectionRect.draw) {
    return null;
  }
  return /* @__PURE__ */ react.createElement("div", {
    className: "react-flow__selection",
    style: {
      width: userSelectionRect.width,
      height: userSelectionRect.height,
      transform: "translate(".concat(userSelectionRect.x, "px, ").concat(userSelectionRect.y, "px)")
    }
  });
};
var UserSelection = /* @__PURE__ */ react.memo(function(_ref) {
  var selectionKeyPressed = _ref.selectionKeyPressed;
  var selectionActive = useStoreState(function(state) {
    return state.selectionActive;
  });
  var elementsSelectable = useStoreState(function(state) {
    return state.elementsSelectable;
  });
  var setUserSelection3 = useStoreActions(function(actions2) {
    return actions2.setUserSelection;
  });
  var updateUserSelection3 = useStoreActions(function(actions2) {
    return actions2.updateUserSelection;
  });
  var unsetUserSelection3 = useStoreActions(function(actions2) {
    return actions2.unsetUserSelection;
  });
  var unsetNodesSelection3 = useStoreActions(function(actions2) {
    return actions2.unsetNodesSelection;
  });
  var renderUserSelectionPane = selectionActive || selectionKeyPressed;
  if (!elementsSelectable || !renderUserSelectionPane) {
    return null;
  }
  var onMouseDown3 = function onMouseDown4(event) {
    var mousePos = getMousePosition(event);
    if (!mousePos) {
      return;
    }
    setUserSelection3(mousePos);
  };
  var onMouseMove = function onMouseMove2(event) {
    if (!selectionKeyPressed || !selectionActive) {
      return;
    }
    var mousePos = getMousePosition(event);
    if (!mousePos) {
      return;
    }
    updateUserSelection3(mousePos);
  };
  var onMouseUp = function onMouseUp2() {
    return unsetUserSelection3();
  };
  var onMouseLeave = function onMouseLeave2() {
    unsetUserSelection3();
    unsetNodesSelection3();
  };
  return /* @__PURE__ */ react.createElement("div", {
    className: "react-flow__selectionpane",
    onMouseDown: onMouseDown3,
    onMouseMove,
    onMouseUp,
    onMouseLeave
  }, /* @__PURE__ */ react.createElement(SelectionRect, null));
});
var cjs = {exports: {}};
var Draggable$1 = {};
function toVal(mix) {
  var k2, y3, str = "";
  if (typeof mix === "string" || typeof mix === "number") {
    str += mix;
  } else if (typeof mix === "object") {
    if (Array.isArray(mix)) {
      for (k2 = 0; k2 < mix.length; k2++) {
        if (mix[k2]) {
          if (y3 = toVal(mix[k2])) {
            str && (str += " ");
            str += y3;
          }
        }
      }
    } else {
      for (k2 in mix) {
        if (mix[k2]) {
          str && (str += " ");
          str += k2;
        }
      }
    }
  }
  return str;
}
function clsx_m() {
  var i3 = 0, tmp, x2, str = "";
  while (i3 < arguments.length) {
    if (tmp = arguments[i3++]) {
      if (x2 = toVal(tmp)) {
        str && (str += " ");
        str += x2;
      }
    }
  }
  return str;
}
var clsx_m$1 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  default: clsx_m
});
var require$$3 = /* @__PURE__ */ getAugmentedNamespace(clsx_m$1);
var domFns = {};
var shims = {};
Object.defineProperty(shims, "__esModule", {
  value: true
});
shims.findInArray = findInArray;
shims.isFunction = isFunction5;
shims.isNum = isNum;
shims.int = int;
shims.dontSetMe = dontSetMe;
function findInArray(array2, callback) {
  for (var i3 = 0, length = array2.length; i3 < length; i3++) {
    if (callback.apply(callback, [array2[i3], i3, array2]))
      return array2[i3];
  }
}
function isFunction5(func) {
  return typeof func === "function" || Object.prototype.toString.call(func) === "[object Function]";
}
function isNum(num) {
  return typeof num === "number" && !isNaN(num);
}
function int(a2) {
  return parseInt(a2, 10);
}
function dontSetMe(props, propName, componentName) {
  if (props[propName]) {
    return new Error("Invalid prop ".concat(propName, " passed to ").concat(componentName, " - do not set this, set it on the child."));
  }
}
var getPrefix$1 = {};
Object.defineProperty(getPrefix$1, "__esModule", {
  value: true
});
getPrefix$1.getPrefix = getPrefix;
getPrefix$1.browserPrefixToKey = browserPrefixToKey;
getPrefix$1.browserPrefixToStyle = browserPrefixToStyle;
getPrefix$1.default = void 0;
var prefixes = ["Moz", "Webkit", "O", "ms"];
function getPrefix() {
  var _window$document, _window$document$docu;
  var prop = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "transform";
  if (typeof window === "undefined")
    return "";
  var style = (_window$document = window.document) === null || _window$document === void 0 ? void 0 : (_window$document$docu = _window$document.documentElement) === null || _window$document$docu === void 0 ? void 0 : _window$document$docu.style;
  if (!style)
    return "";
  if (prop in style)
    return "";
  for (var i3 = 0; i3 < prefixes.length; i3++) {
    if (browserPrefixToKey(prop, prefixes[i3]) in style)
      return prefixes[i3];
  }
  return "";
}
function browserPrefixToKey(prop, prefix2) {
  return prefix2 ? "".concat(prefix2).concat(kebabToTitleCase(prop)) : prop;
}
function browserPrefixToStyle(prop, prefix2) {
  return prefix2 ? "-".concat(prefix2.toLowerCase(), "-").concat(prop) : prop;
}
function kebabToTitleCase(str) {
  var out = "";
  var shouldCapitalize = true;
  for (var i3 = 0; i3 < str.length; i3++) {
    if (shouldCapitalize) {
      out += str[i3].toUpperCase();
      shouldCapitalize = false;
    } else if (str[i3] === "-") {
      shouldCapitalize = true;
    } else {
      out += str[i3];
    }
  }
  return out;
}
var _default2 = getPrefix();
getPrefix$1.default = _default2;
function _typeof$1(obj) {
  "@babel/helpers - typeof";
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof$1 = function _typeof4(obj2) {
      return typeof obj2;
    };
  } else {
    _typeof$1 = function _typeof4(obj2) {
      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
    };
  }
  return _typeof$1(obj);
}
Object.defineProperty(domFns, "__esModule", {
  value: true
});
domFns.matchesSelector = matchesSelector;
domFns.matchesSelectorAndParentsTo = matchesSelectorAndParentsTo;
domFns.addEvent = addEvent;
domFns.removeEvent = removeEvent;
domFns.outerHeight = outerHeight;
domFns.outerWidth = outerWidth;
domFns.innerHeight = innerHeight;
domFns.innerWidth = innerWidth;
domFns.offsetXYFromParent = offsetXYFromParent;
domFns.createCSSTransform = createCSSTransform;
domFns.createSVGTransform = createSVGTransform;
domFns.getTranslation = getTranslation;
domFns.getTouch = getTouch;
domFns.getTouchIdentifier = getTouchIdentifier;
domFns.addUserSelectStyles = addUserSelectStyles;
domFns.removeUserSelectStyles = removeUserSelectStyles;
domFns.addClassName = addClassName;
domFns.removeClassName = removeClassName;
var _shims$2 = shims;
var _getPrefix = _interopRequireWildcard$1(getPrefix$1);
function _getRequireWildcardCache$1(nodeInterop) {
  if (typeof WeakMap !== "function")
    return null;
  var cacheBabelInterop = new WeakMap();
  var cacheNodeInterop = new WeakMap();
  return (_getRequireWildcardCache$1 = function _getRequireWildcardCache2(nodeInterop2) {
    return nodeInterop2 ? cacheNodeInterop : cacheBabelInterop;
  })(nodeInterop);
}
function _interopRequireWildcard$1(obj, nodeInterop) {
  if (!nodeInterop && obj && obj.__esModule) {
    return obj;
  }
  if (obj === null || _typeof$1(obj) !== "object" && typeof obj !== "function") {
    return {default: obj};
  }
  var cache3 = _getRequireWildcardCache$1(nodeInterop);
  if (cache3 && cache3.has(obj)) {
    return cache3.get(obj);
  }
  var newObj = {};
  var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
  for (var key in obj) {
    if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
      var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
      if (desc && (desc.get || desc.set)) {
        Object.defineProperty(newObj, key, desc);
      } else {
        newObj[key] = obj[key];
      }
    }
  }
  newObj.default = obj;
  if (cache3) {
    cache3.set(obj, newObj);
  }
  return newObj;
}
function ownKeys$c(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$c(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$c(Object(source2), true).forEach(function(key) {
        _defineProperty$1(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$c(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
function _defineProperty$1(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {value, enumerable: true, configurable: true, writable: true});
  } else {
    obj[key] = value;
  }
  return obj;
}
var matchesSelectorFunc = "";
function matchesSelector(el, selector2) {
  if (!matchesSelectorFunc) {
    matchesSelectorFunc = (0, _shims$2.findInArray)(["matches", "webkitMatchesSelector", "mozMatchesSelector", "msMatchesSelector", "oMatchesSelector"], function(method) {
      return (0, _shims$2.isFunction)(el[method]);
    });
  }
  if (!(0, _shims$2.isFunction)(el[matchesSelectorFunc]))
    return false;
  return el[matchesSelectorFunc](selector2);
}
function matchesSelectorAndParentsTo(el, selector2, baseNode) {
  var node = el;
  do {
    if (matchesSelector(node, selector2))
      return true;
    if (node === baseNode)
      return false;
    node = node.parentNode;
  } while (node);
  return false;
}
function addEvent(el, event, handler, inputOptions) {
  if (!el)
    return;
  var options = _objectSpread$c({
    capture: true
  }, inputOptions);
  if (el.addEventListener) {
    el.addEventListener(event, handler, options);
  } else if (el.attachEvent) {
    el.attachEvent("on" + event, handler);
  } else {
    el["on" + event] = handler;
  }
}
function removeEvent(el, event, handler, inputOptions) {
  if (!el)
    return;
  var options = _objectSpread$c({
    capture: true
  }, inputOptions);
  if (el.removeEventListener) {
    el.removeEventListener(event, handler, options);
  } else if (el.detachEvent) {
    el.detachEvent("on" + event, handler);
  } else {
    el["on" + event] = null;
  }
}
function outerHeight(node) {
  var height = node.clientHeight;
  var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
  height += (0, _shims$2.int)(computedStyle.borderTopWidth);
  height += (0, _shims$2.int)(computedStyle.borderBottomWidth);
  return height;
}
function outerWidth(node) {
  var width2 = node.clientWidth;
  var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
  width2 += (0, _shims$2.int)(computedStyle.borderLeftWidth);
  width2 += (0, _shims$2.int)(computedStyle.borderRightWidth);
  return width2;
}
function innerHeight(node) {
  var height = node.clientHeight;
  var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
  height -= (0, _shims$2.int)(computedStyle.paddingTop);
  height -= (0, _shims$2.int)(computedStyle.paddingBottom);
  return height;
}
function innerWidth(node) {
  var width2 = node.clientWidth;
  var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
  width2 -= (0, _shims$2.int)(computedStyle.paddingLeft);
  width2 -= (0, _shims$2.int)(computedStyle.paddingRight);
  return width2;
}
function offsetXYFromParent(evt, offsetParent2, scale) {
  var isBody = offsetParent2 === offsetParent2.ownerDocument.body;
  var offsetParentRect = isBody ? {
    left: 0,
    top: 0
  } : offsetParent2.getBoundingClientRect();
  var x2 = (evt.clientX + offsetParent2.scrollLeft - offsetParentRect.left) / scale;
  var y3 = (evt.clientY + offsetParent2.scrollTop - offsetParentRect.top) / scale;
  return {
    x: x2,
    y: y3
  };
}
function createCSSTransform(controlPos, positionOffset) {
  var translation = getTranslation(controlPos, positionOffset, "px");
  return _defineProperty$1({}, (0, _getPrefix.browserPrefixToKey)("transform", _getPrefix.default), translation);
}
function createSVGTransform(controlPos, positionOffset) {
  var translation = getTranslation(controlPos, positionOffset, "");
  return translation;
}
function getTranslation(_ref2, positionOffset, unitSuffix) {
  var x2 = _ref2.x, y3 = _ref2.y;
  var translation = "translate(".concat(x2).concat(unitSuffix, ",").concat(y3).concat(unitSuffix, ")");
  if (positionOffset) {
    var defaultX = "".concat(typeof positionOffset.x === "string" ? positionOffset.x : positionOffset.x + unitSuffix);
    var defaultY = "".concat(typeof positionOffset.y === "string" ? positionOffset.y : positionOffset.y + unitSuffix);
    translation = "translate(".concat(defaultX, ", ").concat(defaultY, ")") + translation;
  }
  return translation;
}
function getTouch(e2, identifier) {
  return e2.targetTouches && (0, _shims$2.findInArray)(e2.targetTouches, function(t5) {
    return identifier === t5.identifier;
  }) || e2.changedTouches && (0, _shims$2.findInArray)(e2.changedTouches, function(t5) {
    return identifier === t5.identifier;
  });
}
function getTouchIdentifier(e2) {
  if (e2.targetTouches && e2.targetTouches[0])
    return e2.targetTouches[0].identifier;
  if (e2.changedTouches && e2.changedTouches[0])
    return e2.changedTouches[0].identifier;
}
function addUserSelectStyles(doc) {
  if (!doc)
    return;
  var styleEl = doc.getElementById("react-draggable-style-el");
  if (!styleEl) {
    styleEl = doc.createElement("style");
    styleEl.type = "text/css";
    styleEl.id = "react-draggable-style-el";
    styleEl.innerHTML = ".react-draggable-transparent-selection *::-moz-selection {all: inherit;}\n";
    styleEl.innerHTML += ".react-draggable-transparent-selection *::selection {all: inherit;}\n";
    doc.getElementsByTagName("head")[0].appendChild(styleEl);
  }
  if (doc.body)
    addClassName(doc.body, "react-draggable-transparent-selection");
}
function removeUserSelectStyles(doc) {
  if (!doc)
    return;
  try {
    if (doc.body)
      removeClassName(doc.body, "react-draggable-transparent-selection");
    if (doc.selection) {
      doc.selection.empty();
    } else {
      var selection2 = (doc.defaultView || window).getSelection();
      if (selection2 && selection2.type !== "Caret") {
        selection2.removeAllRanges();
      }
    }
  } catch (e2) {
  }
}
function addClassName(el, className) {
  if (el.classList) {
    el.classList.add(className);
  } else {
    if (!el.className.match(new RegExp("(?:^|\\s)".concat(className, "(?!\\S)")))) {
      el.className += " ".concat(className);
    }
  }
}
function removeClassName(el, className) {
  if (el.classList) {
    el.classList.remove(className);
  } else {
    el.className = el.className.replace(new RegExp("(?:^|\\s)".concat(className, "(?!\\S)"), "g"), "");
  }
}
var positionFns = {};
Object.defineProperty(positionFns, "__esModule", {
  value: true
});
positionFns.getBoundPosition = getBoundPosition;
positionFns.snapToGrid = snapToGrid;
positionFns.canDragX = canDragX;
positionFns.canDragY = canDragY;
positionFns.getControlPosition = getControlPosition;
positionFns.createCoreData = createCoreData;
positionFns.createDraggableData = createDraggableData;
var _shims$1 = shims;
var _domFns$1 = domFns;
function getBoundPosition(draggable2, x2, y3) {
  if (!draggable2.props.bounds)
    return [x2, y3];
  var bounds = draggable2.props.bounds;
  bounds = typeof bounds === "string" ? bounds : cloneBounds(bounds);
  var node = findDOMNode2(draggable2);
  if (typeof bounds === "string") {
    var ownerDocument = node.ownerDocument;
    var ownerWindow = ownerDocument.defaultView;
    var boundNode;
    if (bounds === "parent") {
      boundNode = node.parentNode;
    } else {
      boundNode = ownerDocument.querySelector(bounds);
    }
    if (!(boundNode instanceof ownerWindow.HTMLElement)) {
      throw new Error('Bounds selector "' + bounds + '" could not find an element.');
    }
    var boundNodeEl = boundNode;
    var nodeStyle = ownerWindow.getComputedStyle(node);
    var boundNodeStyle = ownerWindow.getComputedStyle(boundNodeEl);
    bounds = {
      left: -node.offsetLeft + (0, _shims$1.int)(boundNodeStyle.paddingLeft) + (0, _shims$1.int)(nodeStyle.marginLeft),
      top: -node.offsetTop + (0, _shims$1.int)(boundNodeStyle.paddingTop) + (0, _shims$1.int)(nodeStyle.marginTop),
      right: (0, _domFns$1.innerWidth)(boundNodeEl) - (0, _domFns$1.outerWidth)(node) - node.offsetLeft + (0, _shims$1.int)(boundNodeStyle.paddingRight) - (0, _shims$1.int)(nodeStyle.marginRight),
      bottom: (0, _domFns$1.innerHeight)(boundNodeEl) - (0, _domFns$1.outerHeight)(node) - node.offsetTop + (0, _shims$1.int)(boundNodeStyle.paddingBottom) - (0, _shims$1.int)(nodeStyle.marginBottom)
    };
  }
  if ((0, _shims$1.isNum)(bounds.right))
    x2 = Math.min(x2, bounds.right);
  if ((0, _shims$1.isNum)(bounds.bottom))
    y3 = Math.min(y3, bounds.bottom);
  if ((0, _shims$1.isNum)(bounds.left))
    x2 = Math.max(x2, bounds.left);
  if ((0, _shims$1.isNum)(bounds.top))
    y3 = Math.max(y3, bounds.top);
  return [x2, y3];
}
function snapToGrid(grid2, pendingX, pendingY) {
  var x2 = Math.round(pendingX / grid2[0]) * grid2[0];
  var y3 = Math.round(pendingY / grid2[1]) * grid2[1];
  return [x2, y3];
}
function canDragX(draggable2) {
  return draggable2.props.axis === "both" || draggable2.props.axis === "x";
}
function canDragY(draggable2) {
  return draggable2.props.axis === "both" || draggable2.props.axis === "y";
}
function getControlPosition(e2, touchIdentifier, draggableCore) {
  var touchObj = typeof touchIdentifier === "number" ? (0, _domFns$1.getTouch)(e2, touchIdentifier) : null;
  if (typeof touchIdentifier === "number" && !touchObj)
    return null;
  var node = findDOMNode2(draggableCore);
  var offsetParent2 = draggableCore.props.offsetParent || node.offsetParent || node.ownerDocument.body;
  return (0, _domFns$1.offsetXYFromParent)(touchObj || e2, offsetParent2, draggableCore.props.scale);
}
function createCoreData(draggable2, x2, y3) {
  var state = draggable2.state;
  var isStart = !(0, _shims$1.isNum)(state.lastX);
  var node = findDOMNode2(draggable2);
  if (isStart) {
    return {
      node,
      deltaX: 0,
      deltaY: 0,
      lastX: x2,
      lastY: y3,
      x: x2,
      y: y3
    };
  } else {
    return {
      node,
      deltaX: x2 - state.lastX,
      deltaY: y3 - state.lastY,
      lastX: state.lastX,
      lastY: state.lastY,
      x: x2,
      y: y3
    };
  }
}
function createDraggableData(draggable2, coreData) {
  var scale = draggable2.props.scale;
  return {
    node: coreData.node,
    x: draggable2.state.x + coreData.deltaX / scale,
    y: draggable2.state.y + coreData.deltaY / scale,
    deltaX: coreData.deltaX / scale,
    deltaY: coreData.deltaY / scale,
    lastX: draggable2.state.x,
    lastY: draggable2.state.y
  };
}
function cloneBounds(bounds) {
  return {
    left: bounds.left,
    top: bounds.top,
    right: bounds.right,
    bottom: bounds.bottom
  };
}
function findDOMNode2(draggable2) {
  var node = draggable2.findDOMNode();
  if (!node) {
    throw new Error("<DraggableCore>: Unmounted during event!");
  }
  return node;
}
var DraggableCore$2 = {};
var log$1 = {};
Object.defineProperty(log$1, "__esModule", {
  value: true
});
log$1.default = log3;
function log3() {
}
function _typeof3(obj) {
  "@babel/helpers - typeof";
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof3 = function _typeof4(obj2) {
      return typeof obj2;
    };
  } else {
    _typeof3 = function _typeof4(obj2) {
      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
    };
  }
  return _typeof3(obj);
}
Object.defineProperty(DraggableCore$2, "__esModule", {
  value: true
});
DraggableCore$2.default = void 0;
var React = _interopRequireWildcard(react);
var _propTypes = _interopRequireDefault(propTypes2.exports);
var _reactDom = _interopRequireDefault(reactDom);
var _domFns = domFns;
var _positionFns = positionFns;
var _shims = shims;
var _log = _interopRequireDefault(log$1);
function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
  if (typeof WeakMap !== "function")
    return null;
  var cacheBabelInterop = new WeakMap();
  var cacheNodeInterop = new WeakMap();
  return (_getRequireWildcardCache = function _getRequireWildcardCache2(nodeInterop2) {
    return nodeInterop2 ? cacheNodeInterop : cacheBabelInterop;
  })(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
  if (!nodeInterop && obj && obj.__esModule) {
    return obj;
  }
  if (obj === null || _typeof3(obj) !== "object" && typeof obj !== "function") {
    return {default: obj};
  }
  var cache3 = _getRequireWildcardCache(nodeInterop);
  if (cache3 && cache3.has(obj)) {
    return cache3.get(obj);
  }
  var newObj = {};
  var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
  for (var key in obj) {
    if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
      var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
      if (desc && (desc.get || desc.set)) {
        Object.defineProperty(newObj, key, desc);
      } else {
        newObj[key] = obj[key];
      }
    }
  }
  newObj.default = obj;
  if (cache3) {
    cache3.set(obj, newObj);
  }
  return newObj;
}
function _slicedToArray3(arr, i3) {
  return _arrayWithHoles2(arr) || _iterableToArrayLimit2(arr, i3) || _unsupportedIterableToArray2(arr, i3) || _nonIterableRest2();
}
function _nonIterableRest2() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray2(o, minLen) {
  if (!o)
    return;
  if (typeof o === "string")
    return _arrayLikeToArray2(o, minLen);
  var n3 = Object.prototype.toString.call(o).slice(8, -1);
  if (n3 === "Object" && o.constructor)
    n3 = o.constructor.name;
  if (n3 === "Map" || n3 === "Set")
    return Array.from(o);
  if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3))
    return _arrayLikeToArray2(o, minLen);
}
function _arrayLikeToArray2(arr, len2) {
  if (len2 == null || len2 > arr.length)
    len2 = arr.length;
  for (var i3 = 0, arr2 = new Array(len2); i3 < len2; i3++) {
    arr2[i3] = arr[i3];
  }
  return arr2;
}
function _iterableToArrayLimit2(arr, i3) {
  var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
  if (_i == null)
    return;
  var _arr = [];
  var _n = true;
  var _d = false;
  var _s, _e;
  try {
    for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);
      if (i3 && _arr.length === i3)
        break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null)
        _i["return"]();
    } finally {
      if (_d)
        throw _e;
    }
  }
  return _arr;
}
function _arrayWithHoles2(arr) {
  if (Array.isArray(arr))
    return arr;
}
function _classCallCheck4(instance2, Constructor) {
  if (!(instance2 instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties2(target, props) {
  for (var i3 = 0; i3 < props.length; i3++) {
    var descriptor = props[i3];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor)
      descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}
function _createClass4(Constructor, protoProps, staticProps) {
  if (protoProps)
    _defineProperties2(Constructor.prototype, protoProps);
  if (staticProps)
    _defineProperties2(Constructor, staticProps);
  return Constructor;
}
function _inherits3(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, {constructor: {value: subClass, writable: true, configurable: true}});
  if (superClass)
    _setPrototypeOf2(subClass, superClass);
}
function _setPrototypeOf2(o, p2) {
  _setPrototypeOf2 = Object.setPrototypeOf || function _setPrototypeOf3(o2, p3) {
    o2.__proto__ = p3;
    return o2;
  };
  return _setPrototypeOf2(o, p2);
}
function _createSuper2(Derived) {
  var hasNativeReflectConstruct = _isNativeReflectConstruct2();
  return function _createSuperInternal() {
    var Super = _getPrototypeOf2(Derived), result;
    if (hasNativeReflectConstruct) {
      var NewTarget = _getPrototypeOf2(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return _possibleConstructorReturn3(this, result);
  };
}
function _possibleConstructorReturn3(self2, call) {
  if (call && (_typeof3(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized2(self2);
}
function _assertThisInitialized2(self2) {
  if (self2 === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self2;
}
function _isNativeReflectConstruct2() {
  if (typeof Reflect === "undefined" || !Reflect.construct)
    return false;
  if (Reflect.construct.sham)
    return false;
  if (typeof Proxy === "function")
    return true;
  try {
    Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
    return true;
  } catch (e2) {
    return false;
  }
}
function _getPrototypeOf2(o) {
  _getPrototypeOf2 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf3(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf2(o);
}
function _defineProperty6(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {value, enumerable: true, configurable: true, writable: true});
  } else {
    obj[key] = value;
  }
  return obj;
}
var eventsFor = {
  touch: {
    start: "touchstart",
    move: "touchmove",
    stop: "touchend"
  },
  mouse: {
    start: "mousedown",
    move: "mousemove",
    stop: "mouseup"
  }
};
var dragEventFor = eventsFor.mouse;
var DraggableCore$1 = /* @__PURE__ */ function(_React$Component) {
  _inherits3(DraggableCore2, _React$Component);
  var _super = _createSuper2(DraggableCore2);
  function DraggableCore2() {
    var _this;
    _classCallCheck4(this, DraggableCore2);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    _defineProperty6(_assertThisInitialized2(_this), "state", {
      dragging: false,
      lastX: NaN,
      lastY: NaN,
      touchIdentifier: null
    });
    _defineProperty6(_assertThisInitialized2(_this), "mounted", false);
    _defineProperty6(_assertThisInitialized2(_this), "handleDragStart", function(e2) {
      _this.props.onMouseDown(e2);
      if (!_this.props.allowAnyClick && typeof e2.button === "number" && e2.button !== 0)
        return false;
      var thisNode = _this.findDOMNode();
      if (!thisNode || !thisNode.ownerDocument || !thisNode.ownerDocument.body) {
        throw new Error("<DraggableCore> not mounted on DragStart!");
      }
      var ownerDocument = thisNode.ownerDocument;
      if (_this.props.disabled || !(e2.target instanceof ownerDocument.defaultView.Node) || _this.props.handle && !(0, _domFns.matchesSelectorAndParentsTo)(e2.target, _this.props.handle, thisNode) || _this.props.cancel && (0, _domFns.matchesSelectorAndParentsTo)(e2.target, _this.props.cancel, thisNode)) {
        return;
      }
      if (e2.type === "touchstart")
        e2.preventDefault();
      var touchIdentifier = (0, _domFns.getTouchIdentifier)(e2);
      _this.setState({
        touchIdentifier
      });
      var position2 = (0, _positionFns.getControlPosition)(e2, touchIdentifier, _assertThisInitialized2(_this));
      if (position2 == null)
        return;
      var x2 = position2.x, y3 = position2.y;
      var coreEvent = (0, _positionFns.createCoreData)(_assertThisInitialized2(_this), x2, y3);
      (0, _log.default)("DraggableCore: handleDragStart: %j", coreEvent);
      (0, _log.default)("calling", _this.props.onStart);
      var shouldUpdate = _this.props.onStart(e2, coreEvent);
      if (shouldUpdate === false || _this.mounted === false)
        return;
      if (_this.props.enableUserSelectHack)
        (0, _domFns.addUserSelectStyles)(ownerDocument);
      _this.setState({
        dragging: true,
        lastX: x2,
        lastY: y3
      });
      (0, _domFns.addEvent)(ownerDocument, dragEventFor.move, _this.handleDrag);
      (0, _domFns.addEvent)(ownerDocument, dragEventFor.stop, _this.handleDragStop);
    });
    _defineProperty6(_assertThisInitialized2(_this), "handleDrag", function(e2) {
      var position2 = (0, _positionFns.getControlPosition)(e2, _this.state.touchIdentifier, _assertThisInitialized2(_this));
      if (position2 == null)
        return;
      var x2 = position2.x, y3 = position2.y;
      if (Array.isArray(_this.props.grid)) {
        var deltaX = x2 - _this.state.lastX, deltaY = y3 - _this.state.lastY;
        var _snapToGrid = (0, _positionFns.snapToGrid)(_this.props.grid, deltaX, deltaY);
        var _snapToGrid2 = _slicedToArray3(_snapToGrid, 2);
        deltaX = _snapToGrid2[0];
        deltaY = _snapToGrid2[1];
        if (!deltaX && !deltaY)
          return;
        x2 = _this.state.lastX + deltaX, y3 = _this.state.lastY + deltaY;
      }
      var coreEvent = (0, _positionFns.createCoreData)(_assertThisInitialized2(_this), x2, y3);
      (0, _log.default)("DraggableCore: handleDrag: %j", coreEvent);
      var shouldUpdate = _this.props.onDrag(e2, coreEvent);
      if (shouldUpdate === false || _this.mounted === false) {
        try {
          _this.handleDragStop(new MouseEvent("mouseup"));
        } catch (err) {
          var event = document.createEvent("MouseEvents");
          event.initMouseEvent("mouseup", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
          _this.handleDragStop(event);
        }
        return;
      }
      _this.setState({
        lastX: x2,
        lastY: y3
      });
    });
    _defineProperty6(_assertThisInitialized2(_this), "handleDragStop", function(e2) {
      if (!_this.state.dragging)
        return;
      var position2 = (0, _positionFns.getControlPosition)(e2, _this.state.touchIdentifier, _assertThisInitialized2(_this));
      if (position2 == null)
        return;
      var x2 = position2.x, y3 = position2.y;
      var coreEvent = (0, _positionFns.createCoreData)(_assertThisInitialized2(_this), x2, y3);
      var shouldContinue = _this.props.onStop(e2, coreEvent);
      if (shouldContinue === false || _this.mounted === false)
        return false;
      var thisNode = _this.findDOMNode();
      if (thisNode) {
        if (_this.props.enableUserSelectHack)
          (0, _domFns.removeUserSelectStyles)(thisNode.ownerDocument);
      }
      (0, _log.default)("DraggableCore: handleDragStop: %j", coreEvent);
      _this.setState({
        dragging: false,
        lastX: NaN,
        lastY: NaN
      });
      if (thisNode) {
        (0, _log.default)("DraggableCore: Removing handlers");
        (0, _domFns.removeEvent)(thisNode.ownerDocument, dragEventFor.move, _this.handleDrag);
        (0, _domFns.removeEvent)(thisNode.ownerDocument, dragEventFor.stop, _this.handleDragStop);
      }
    });
    _defineProperty6(_assertThisInitialized2(_this), "onMouseDown", function(e2) {
      dragEventFor = eventsFor.mouse;
      return _this.handleDragStart(e2);
    });
    _defineProperty6(_assertThisInitialized2(_this), "onMouseUp", function(e2) {
      dragEventFor = eventsFor.mouse;
      return _this.handleDragStop(e2);
    });
    _defineProperty6(_assertThisInitialized2(_this), "onTouchStart", function(e2) {
      dragEventFor = eventsFor.touch;
      return _this.handleDragStart(e2);
    });
    _defineProperty6(_assertThisInitialized2(_this), "onTouchEnd", function(e2) {
      dragEventFor = eventsFor.touch;
      return _this.handleDragStop(e2);
    });
    return _this;
  }
  _createClass4(DraggableCore2, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.mounted = true;
      var thisNode = this.findDOMNode();
      if (thisNode) {
        (0, _domFns.addEvent)(thisNode, eventsFor.touch.start, this.onTouchStart, {
          passive: false
        });
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.mounted = false;
      var thisNode = this.findDOMNode();
      if (thisNode) {
        var ownerDocument = thisNode.ownerDocument;
        (0, _domFns.removeEvent)(ownerDocument, eventsFor.mouse.move, this.handleDrag);
        (0, _domFns.removeEvent)(ownerDocument, eventsFor.touch.move, this.handleDrag);
        (0, _domFns.removeEvent)(ownerDocument, eventsFor.mouse.stop, this.handleDragStop);
        (0, _domFns.removeEvent)(ownerDocument, eventsFor.touch.stop, this.handleDragStop);
        (0, _domFns.removeEvent)(thisNode, eventsFor.touch.start, this.onTouchStart, {
          passive: false
        });
        if (this.props.enableUserSelectHack)
          (0, _domFns.removeUserSelectStyles)(ownerDocument);
      }
    }
  }, {
    key: "findDOMNode",
    value: function findDOMNode3() {
      var _this$props$nodeRef$c, _this$props, _this$props$nodeRef;
      return (_this$props$nodeRef$c = (_this$props = this.props) === null || _this$props === void 0 ? void 0 : (_this$props$nodeRef = _this$props.nodeRef) === null || _this$props$nodeRef === void 0 ? void 0 : _this$props$nodeRef.current) !== null && _this$props$nodeRef$c !== void 0 ? _this$props$nodeRef$c : _reactDom.default.findDOMNode(this);
    }
  }, {
    key: "render",
    value: function render4() {
      return /* @__PURE__ */ React.cloneElement(React.Children.only(this.props.children), {
        onMouseDown: this.onMouseDown,
        onMouseUp: this.onMouseUp,
        onTouchEnd: this.onTouchEnd
      });
    }
  }]);
  return DraggableCore2;
}(React.Component);
DraggableCore$2.default = DraggableCore$1;
_defineProperty6(DraggableCore$1, "displayName", "DraggableCore");
_defineProperty6(DraggableCore$1, "propTypes", {
  allowAnyClick: _propTypes.default.bool,
  disabled: _propTypes.default.bool,
  enableUserSelectHack: _propTypes.default.bool,
  offsetParent: function offsetParent(props, propName) {
    if (props[propName] && props[propName].nodeType !== 1) {
      throw new Error("Draggable's offsetParent must be a DOM Node.");
    }
  },
  grid: _propTypes.default.arrayOf(_propTypes.default.number),
  handle: _propTypes.default.string,
  cancel: _propTypes.default.string,
  nodeRef: _propTypes.default.object,
  onStart: _propTypes.default.func,
  onDrag: _propTypes.default.func,
  onStop: _propTypes.default.func,
  onMouseDown: _propTypes.default.func,
  scale: _propTypes.default.number,
  className: _shims.dontSetMe,
  style: _shims.dontSetMe,
  transform: _shims.dontSetMe
});
_defineProperty6(DraggableCore$1, "defaultProps", {
  allowAnyClick: false,
  disabled: false,
  enableUserSelectHack: true,
  onStart: function onStart() {
  },
  onDrag: function onDrag() {
  },
  onStop: function onStop() {
  },
  onMouseDown: function onMouseDown() {
  },
  scale: 1
});
(function(exports2) {
  function _typeof4(obj) {
    "@babel/helpers - typeof";
    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
      _typeof4 = function _typeof5(obj2) {
        return typeof obj2;
      };
    } else {
      _typeof4 = function _typeof5(obj2) {
        return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
      };
    }
    return _typeof4(obj);
  }
  Object.defineProperty(exports2, "__esModule", {
    value: true
  });
  Object.defineProperty(exports2, "DraggableCore", {
    enumerable: true,
    get: function get7() {
      return _DraggableCore.default;
    }
  });
  exports2.default = void 0;
  var React2 = _interopRequireWildcard2(react);
  var _propTypes2 = _interopRequireDefault2(propTypes2.exports);
  var _reactDom2 = _interopRequireDefault2(reactDom);
  var _clsx2 = _interopRequireDefault2(require$$3);
  var _domFns2 = domFns;
  var _positionFns2 = positionFns;
  var _shims2 = shims;
  var _DraggableCore = _interopRequireDefault2(DraggableCore$2);
  var _log2 = _interopRequireDefault2(log$1);
  var _excluded4 = ["axis", "bounds", "children", "defaultPosition", "defaultClassName", "defaultClassNameDragging", "defaultClassNameDragged", "position", "positionOffset", "scale"];
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : {default: obj};
  }
  function _getRequireWildcardCache2(nodeInterop) {
    if (typeof WeakMap !== "function")
      return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache2 = function _getRequireWildcardCache3(nodeInterop2) {
      return nodeInterop2 ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
  }
  function _interopRequireWildcard2(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
      return obj;
    }
    if (obj === null || _typeof4(obj) !== "object" && typeof obj !== "function") {
      return {default: obj};
    }
    var cache3 = _getRequireWildcardCache2(nodeInterop);
    if (cache3 && cache3.has(obj)) {
      return cache3.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
      if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
        var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
        if (desc && (desc.get || desc.set)) {
          Object.defineProperty(newObj, key, desc);
        } else {
          newObj[key] = obj[key];
        }
      }
    }
    newObj.default = obj;
    if (cache3) {
      cache3.set(obj, newObj);
    }
    return newObj;
  }
  function _extends4() {
    _extends4 = Object.assign || function(target) {
      for (var i3 = 1; i3 < arguments.length; i3++) {
        var source2 = arguments[i3];
        for (var key in source2) {
          if (Object.prototype.hasOwnProperty.call(source2, key)) {
            target[key] = source2[key];
          }
        }
      }
      return target;
    };
    return _extends4.apply(this, arguments);
  }
  function _objectWithoutProperties4(source2, excluded) {
    if (source2 == null)
      return {};
    var target = _objectWithoutPropertiesLoose3(source2, excluded);
    var key, i3;
    if (Object.getOwnPropertySymbols) {
      var sourceSymbolKeys = Object.getOwnPropertySymbols(source2);
      for (i3 = 0; i3 < sourceSymbolKeys.length; i3++) {
        key = sourceSymbolKeys[i3];
        if (excluded.indexOf(key) >= 0)
          continue;
        if (!Object.prototype.propertyIsEnumerable.call(source2, key))
          continue;
        target[key] = source2[key];
      }
    }
    return target;
  }
  function _objectWithoutPropertiesLoose3(source2, excluded) {
    if (source2 == null)
      return {};
    var target = {};
    var sourceKeys = Object.keys(source2);
    var key, i3;
    for (i3 = 0; i3 < sourceKeys.length; i3++) {
      key = sourceKeys[i3];
      if (excluded.indexOf(key) >= 0)
        continue;
      target[key] = source2[key];
    }
    return target;
  }
  function ownKeys5(object, enumerableOnly) {
    var keys2 = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
      var symbols = Object.getOwnPropertySymbols(object);
      if (enumerableOnly) {
        symbols = symbols.filter(function(sym) {
          return Object.getOwnPropertyDescriptor(object, sym).enumerable;
        });
      }
      keys2.push.apply(keys2, symbols);
    }
    return keys2;
  }
  function _objectSpread5(target) {
    for (var i3 = 1; i3 < arguments.length; i3++) {
      var source2 = arguments[i3] != null ? arguments[i3] : {};
      if (i3 % 2) {
        ownKeys5(Object(source2), true).forEach(function(key) {
          _defineProperty7(target, key, source2[key]);
        });
      } else if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
      } else {
        ownKeys5(Object(source2)).forEach(function(key) {
          Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
        });
      }
    }
    return target;
  }
  function _slicedToArray4(arr, i3) {
    return _arrayWithHoles3(arr) || _iterableToArrayLimit3(arr, i3) || _unsupportedIterableToArray3(arr, i3) || _nonIterableRest3();
  }
  function _nonIterableRest3() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  function _unsupportedIterableToArray3(o, minLen) {
    if (!o)
      return;
    if (typeof o === "string")
      return _arrayLikeToArray3(o, minLen);
    var n3 = Object.prototype.toString.call(o).slice(8, -1);
    if (n3 === "Object" && o.constructor)
      n3 = o.constructor.name;
    if (n3 === "Map" || n3 === "Set")
      return Array.from(o);
    if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3))
      return _arrayLikeToArray3(o, minLen);
  }
  function _arrayLikeToArray3(arr, len2) {
    if (len2 == null || len2 > arr.length)
      len2 = arr.length;
    for (var i3 = 0, arr2 = new Array(len2); i3 < len2; i3++) {
      arr2[i3] = arr[i3];
    }
    return arr2;
  }
  function _iterableToArrayLimit3(arr, i3) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null)
      return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
      for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);
        if (i3 && _arr.length === i3)
          break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"] != null)
          _i["return"]();
      } finally {
        if (_d)
          throw _e;
      }
    }
    return _arr;
  }
  function _arrayWithHoles3(arr) {
    if (Array.isArray(arr))
      return arr;
  }
  function _classCallCheck5(instance2, Constructor) {
    if (!(instance2 instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }
  function _defineProperties3(target, props) {
    for (var i3 = 0; i3 < props.length; i3++) {
      var descriptor = props[i3];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass5(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties3(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties3(Constructor, staticProps);
    return Constructor;
  }
  function _inherits4(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
      throw new TypeError("Super expression must either be null or a function");
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, {constructor: {value: subClass, writable: true, configurable: true}});
    if (superClass)
      _setPrototypeOf3(subClass, superClass);
  }
  function _setPrototypeOf3(o, p2) {
    _setPrototypeOf3 = Object.setPrototypeOf || function _setPrototypeOf4(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf3(o, p2);
  }
  function _createSuper3(Derived) {
    var hasNativeReflectConstruct = _isNativeReflectConstruct3();
    return function _createSuperInternal() {
      var Super = _getPrototypeOf3(Derived), result;
      if (hasNativeReflectConstruct) {
        var NewTarget = _getPrototypeOf3(this).constructor;
        result = Reflect.construct(Super, arguments, NewTarget);
      } else {
        result = Super.apply(this, arguments);
      }
      return _possibleConstructorReturn4(this, result);
    };
  }
  function _possibleConstructorReturn4(self2, call) {
    if (call && (_typeof4(call) === "object" || typeof call === "function")) {
      return call;
    } else if (call !== void 0) {
      throw new TypeError("Derived constructors may only return object or undefined");
    }
    return _assertThisInitialized3(self2);
  }
  function _assertThisInitialized3(self2) {
    if (self2 === void 0) {
      throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }
    return self2;
  }
  function _isNativeReflectConstruct3() {
    if (typeof Reflect === "undefined" || !Reflect.construct)
      return false;
    if (Reflect.construct.sham)
      return false;
    if (typeof Proxy === "function")
      return true;
    try {
      Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
      }));
      return true;
    } catch (e2) {
      return false;
    }
  }
  function _getPrototypeOf3(o) {
    _getPrototypeOf3 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf4(o2) {
      return o2.__proto__ || Object.getPrototypeOf(o2);
    };
    return _getPrototypeOf3(o);
  }
  function _defineProperty7(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, {value, enumerable: true, configurable: true, writable: true});
    } else {
      obj[key] = value;
    }
    return obj;
  }
  var Draggable2 = /* @__PURE__ */ function(_React$Component) {
    _inherits4(Draggable3, _React$Component);
    var _super = _createSuper3(Draggable3);
    function Draggable3(props) {
      var _this;
      _classCallCheck5(this, Draggable3);
      _this = _super.call(this, props);
      _defineProperty7(_assertThisInitialized3(_this), "onDragStart", function(e2, coreData) {
        (0, _log2.default)("Draggable: onDragStart: %j", coreData);
        var shouldStart = _this.props.onStart(e2, (0, _positionFns2.createDraggableData)(_assertThisInitialized3(_this), coreData));
        if (shouldStart === false)
          return false;
        _this.setState({
          dragging: true,
          dragged: true
        });
      });
      _defineProperty7(_assertThisInitialized3(_this), "onDrag", function(e2, coreData) {
        if (!_this.state.dragging)
          return false;
        (0, _log2.default)("Draggable: onDrag: %j", coreData);
        var uiData = (0, _positionFns2.createDraggableData)(_assertThisInitialized3(_this), coreData);
        var newState = {
          x: uiData.x,
          y: uiData.y
        };
        if (_this.props.bounds) {
          var x2 = newState.x, y3 = newState.y;
          newState.x += _this.state.slackX;
          newState.y += _this.state.slackY;
          var _getBoundPosition = (0, _positionFns2.getBoundPosition)(_assertThisInitialized3(_this), newState.x, newState.y), _getBoundPosition2 = _slicedToArray4(_getBoundPosition, 2), newStateX = _getBoundPosition2[0], newStateY = _getBoundPosition2[1];
          newState.x = newStateX;
          newState.y = newStateY;
          newState.slackX = _this.state.slackX + (x2 - newState.x);
          newState.slackY = _this.state.slackY + (y3 - newState.y);
          uiData.x = newState.x;
          uiData.y = newState.y;
          uiData.deltaX = newState.x - _this.state.x;
          uiData.deltaY = newState.y - _this.state.y;
        }
        var shouldUpdate = _this.props.onDrag(e2, uiData);
        if (shouldUpdate === false)
          return false;
        _this.setState(newState);
      });
      _defineProperty7(_assertThisInitialized3(_this), "onDragStop", function(e2, coreData) {
        if (!_this.state.dragging)
          return false;
        var shouldContinue = _this.props.onStop(e2, (0, _positionFns2.createDraggableData)(_assertThisInitialized3(_this), coreData));
        if (shouldContinue === false)
          return false;
        (0, _log2.default)("Draggable: onDragStop: %j", coreData);
        var newState = {
          dragging: false,
          slackX: 0,
          slackY: 0
        };
        var controlled = Boolean(_this.props.position);
        if (controlled) {
          var _this$props$position = _this.props.position, x2 = _this$props$position.x, y3 = _this$props$position.y;
          newState.x = x2;
          newState.y = y3;
        }
        _this.setState(newState);
      });
      _this.state = {
        dragging: false,
        dragged: false,
        x: props.position ? props.position.x : props.defaultPosition.x,
        y: props.position ? props.position.y : props.defaultPosition.y,
        prevPropsPosition: _objectSpread5({}, props.position),
        slackX: 0,
        slackY: 0,
        isElementSVG: false
      };
      if (props.position && !(props.onDrag || props.onStop)) {
        console.warn("A `position` was applied to this <Draggable>, without drag handlers. This will make this component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the `position` of this element.");
      }
      return _this;
    }
    _createClass5(Draggable3, [{
      key: "componentDidMount",
      value: function componentDidMount() {
        if (typeof window.SVGElement !== "undefined" && this.findDOMNode() instanceof window.SVGElement) {
          this.setState({
            isElementSVG: true
          });
        }
      }
    }, {
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        this.setState({
          dragging: false
        });
      }
    }, {
      key: "findDOMNode",
      value: function findDOMNode3() {
        var _this$props$nodeRef$c, _this$props, _this$props$nodeRef;
        return (_this$props$nodeRef$c = (_this$props = this.props) === null || _this$props === void 0 ? void 0 : (_this$props$nodeRef = _this$props.nodeRef) === null || _this$props$nodeRef === void 0 ? void 0 : _this$props$nodeRef.current) !== null && _this$props$nodeRef$c !== void 0 ? _this$props$nodeRef$c : _reactDom2.default.findDOMNode(this);
      }
    }, {
      key: "render",
      value: function render4() {
        var _clsx;
        var _this$props2 = this.props;
        _this$props2.axis;
        _this$props2.bounds;
        var children2 = _this$props2.children, defaultPosition = _this$props2.defaultPosition, defaultClassName = _this$props2.defaultClassName, defaultClassNameDragging = _this$props2.defaultClassNameDragging, defaultClassNameDragged = _this$props2.defaultClassNameDragged, position2 = _this$props2.position, positionOffset = _this$props2.positionOffset;
        _this$props2.scale;
        var draggableCoreProps = _objectWithoutProperties4(_this$props2, _excluded4);
        var style = {};
        var svgTransform = null;
        var controlled = Boolean(position2);
        var draggable2 = !controlled || this.state.dragging;
        var validPosition = position2 || defaultPosition;
        var transformOpts = {
          x: (0, _positionFns2.canDragX)(this) && draggable2 ? this.state.x : validPosition.x,
          y: (0, _positionFns2.canDragY)(this) && draggable2 ? this.state.y : validPosition.y
        };
        if (this.state.isElementSVG) {
          svgTransform = (0, _domFns2.createSVGTransform)(transformOpts, positionOffset);
        } else {
          style = (0, _domFns2.createCSSTransform)(transformOpts, positionOffset);
        }
        var className = (0, _clsx2.default)(children2.props.className || "", defaultClassName, (_clsx = {}, _defineProperty7(_clsx, defaultClassNameDragging, this.state.dragging), _defineProperty7(_clsx, defaultClassNameDragged, this.state.dragged), _clsx));
        return /* @__PURE__ */ React2.createElement(_DraggableCore.default, _extends4({}, draggableCoreProps, {
          onStart: this.onDragStart,
          onDrag: this.onDrag,
          onStop: this.onDragStop
        }), /* @__PURE__ */ React2.cloneElement(React2.Children.only(children2), {
          className,
          style: _objectSpread5(_objectSpread5({}, children2.props.style), style),
          transform: svgTransform
        }));
      }
    }], [{
      key: "getDerivedStateFromProps",
      value: function getDerivedStateFromProps(_ref, _ref2) {
        var position2 = _ref.position;
        var prevPropsPosition = _ref2.prevPropsPosition;
        if (position2 && (!prevPropsPosition || position2.x !== prevPropsPosition.x || position2.y !== prevPropsPosition.y)) {
          (0, _log2.default)("Draggable: getDerivedStateFromProps %j", {
            position: position2,
            prevPropsPosition
          });
          return {
            x: position2.x,
            y: position2.y,
            prevPropsPosition: _objectSpread5({}, position2)
          };
        }
        return null;
      }
    }]);
    return Draggable3;
  }(React2.Component);
  exports2.default = Draggable2;
  _defineProperty7(Draggable2, "displayName", "Draggable");
  _defineProperty7(Draggable2, "propTypes", _objectSpread5(_objectSpread5({}, _DraggableCore.default.propTypes), {}, {
    axis: _propTypes2.default.oneOf(["both", "x", "y", "none"]),
    bounds: _propTypes2.default.oneOfType([_propTypes2.default.shape({
      left: _propTypes2.default.number,
      right: _propTypes2.default.number,
      top: _propTypes2.default.number,
      bottom: _propTypes2.default.number
    }), _propTypes2.default.string, _propTypes2.default.oneOf([false])]),
    defaultClassName: _propTypes2.default.string,
    defaultClassNameDragging: _propTypes2.default.string,
    defaultClassNameDragged: _propTypes2.default.string,
    defaultPosition: _propTypes2.default.shape({
      x: _propTypes2.default.number,
      y: _propTypes2.default.number
    }),
    positionOffset: _propTypes2.default.shape({
      x: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]),
      y: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string])
    }),
    position: _propTypes2.default.shape({
      x: _propTypes2.default.number,
      y: _propTypes2.default.number
    }),
    className: _shims2.dontSetMe,
    style: _shims2.dontSetMe,
    transform: _shims2.dontSetMe
  }));
  _defineProperty7(Draggable2, "defaultProps", _objectSpread5(_objectSpread5({}, _DraggableCore.default.defaultProps), {}, {
    axis: "both",
    bounds: false,
    defaultClassName: "react-draggable",
    defaultClassNameDragging: "react-draggable-dragging",
    defaultClassNameDragged: "react-draggable-dragged",
    defaultPosition: {
      x: 0,
      y: 0
    },
    scale: 1
  }));
})(Draggable$1);
var _require = Draggable$1;
var Draggable = _require.default;
var DraggableCore = _require.DraggableCore;
cjs.exports = Draggable;
cjs.exports.default = Draggable;
var DraggableCore_1 = cjs.exports.DraggableCore = DraggableCore;
var ReactDraggable = cjs.exports;
function ownKeys$b(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$b(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$b(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$b(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var NodesSelection = function(_ref) {
  var onSelectionDragStart = _ref.onSelectionDragStart, onSelectionDrag = _ref.onSelectionDrag, onSelectionDragStop = _ref.onSelectionDragStop, onSelectionContextMenu = _ref.onSelectionContextMenu;
  var _useStoreState = useStoreState(function(state) {
    return state.transform;
  }), _useStoreState2 = _slicedToArray$1(_useStoreState, 3), tX = _useStoreState2[0], tY = _useStoreState2[1], tScale = _useStoreState2[2];
  var selectedNodesBbox = useStoreState(function(state) {
    return state.selectedNodesBbox;
  });
  var selectionActive = useStoreState(function(state) {
    return state.selectionActive;
  });
  var selectedElements = useStoreState(function(state) {
    return state.selectedElements;
  });
  var snapToGrid2 = useStoreState(function(state) {
    return state.snapToGrid;
  });
  var snapGrid = useStoreState(function(state) {
    return state.snapGrid;
  });
  var nodes = useStoreState(function(state) {
    return state.nodes;
  });
  var updateNodePosDiff3 = useStoreActions(function(actions2) {
    return actions2.updateNodePosDiff;
  });
  var nodeRef = react.useRef(null);
  var grid2 = react.useMemo(function() {
    return snapToGrid2 ? snapGrid : [1, 1];
  }, [snapToGrid2, snapGrid]);
  var selectedNodes = react.useMemo(function() {
    return selectedElements ? selectedElements.filter(isNode).map(function(selectedNode) {
      var matchingNode = nodes.find(function(node) {
        return node.id === selectedNode.id;
      });
      return _objectSpread$b(_objectSpread$b({}, matchingNode), {}, {
        position: matchingNode === null || matchingNode === void 0 ? void 0 : matchingNode.__rf.position
      });
    }) : [];
  }, [selectedElements, nodes]);
  var style = react.useMemo(function() {
    return {
      transform: "translate(".concat(tX, "px,").concat(tY, "px) scale(").concat(tScale, ")")
    };
  }, [tX, tY, tScale]);
  var innerStyle = react.useMemo(function() {
    return {
      width: selectedNodesBbox.width,
      height: selectedNodesBbox.height,
      top: selectedNodesBbox.y,
      left: selectedNodesBbox.x
    };
  }, [selectedNodesBbox]);
  var _onStart = react.useCallback(function(event) {
    onSelectionDragStart === null || onSelectionDragStart === void 0 ? void 0 : onSelectionDragStart(event, selectedNodes);
  }, [onSelectionDragStart, selectedNodes]);
  var _onDrag = react.useCallback(function(event, data2) {
    if (onSelectionDrag) {
      onSelectionDrag(event, selectedNodes);
    }
    updateNodePosDiff3({
      diff: {
        x: data2.deltaX,
        y: data2.deltaY
      },
      isDragging: true
    });
  }, [onSelectionDrag, selectedNodes, updateNodePosDiff3]);
  var _onStop = react.useCallback(function(event) {
    updateNodePosDiff3({
      isDragging: false
    });
    onSelectionDragStop === null || onSelectionDragStop === void 0 ? void 0 : onSelectionDragStop(event, selectedNodes);
  }, [selectedNodes, onSelectionDragStop]);
  var onContextMenu = react.useCallback(function(event) {
    var selectedNodes2 = selectedElements ? selectedElements.filter(isNode).map(function(selectedNode) {
      return nodes.find(function(node) {
        return node.id === selectedNode.id;
      });
    }) : [];
    onSelectionContextMenu === null || onSelectionContextMenu === void 0 ? void 0 : onSelectionContextMenu(event, selectedNodes2);
  }, [onSelectionContextMenu]);
  if (!selectedElements || selectionActive) {
    return null;
  }
  return /* @__PURE__ */ react.createElement("div", {
    className: "react-flow__nodesselection",
    style
  }, /* @__PURE__ */ react.createElement(ReactDraggable, {
    scale: tScale,
    grid: grid2,
    onStart: function onStart2(event) {
      return _onStart(event);
    },
    onDrag: function onDrag2(event, data2) {
      return _onDrag(event, data2);
    },
    onStop: function onStop2(event) {
      return _onStop(event);
    },
    nodeRef,
    enableUserSelectHack: false
  }, /* @__PURE__ */ react.createElement("div", {
    ref: nodeRef,
    className: "react-flow__nodesselection-rect",
    onContextMenu,
    style: innerStyle
  })));
};
var FlowRenderer = function FlowRenderer2(_ref) {
  var children2 = _ref.children, onPaneClick = _ref.onPaneClick, onPaneContextMenu = _ref.onPaneContextMenu, onPaneScroll = _ref.onPaneScroll, onElementsRemove = _ref.onElementsRemove, deleteKeyCode = _ref.deleteKeyCode, onMove = _ref.onMove, onMoveStart = _ref.onMoveStart, onMoveEnd = _ref.onMoveEnd, selectionKeyCode = _ref.selectionKeyCode, multiSelectionKeyCode = _ref.multiSelectionKeyCode, zoomActivationKeyCode = _ref.zoomActivationKeyCode, elementsSelectable = _ref.elementsSelectable, zoomOnScroll = _ref.zoomOnScroll, zoomOnPinch = _ref.zoomOnPinch, panOnScroll = _ref.panOnScroll, panOnScrollSpeed = _ref.panOnScrollSpeed, panOnScrollMode = _ref.panOnScrollMode, zoomOnDoubleClick = _ref.zoomOnDoubleClick, paneMoveable = _ref.paneMoveable, defaultPosition = _ref.defaultPosition, defaultZoom = _ref.defaultZoom, translateExtent = _ref.translateExtent, preventScrolling = _ref.preventScrolling, onSelectionDragStart = _ref.onSelectionDragStart, onSelectionDrag = _ref.onSelectionDrag, onSelectionDragStop = _ref.onSelectionDragStop, onSelectionContextMenu = _ref.onSelectionContextMenu;
  var unsetNodesSelection3 = useStoreActions(function(actions2) {
    return actions2.unsetNodesSelection;
  });
  var resetSelectedElements3 = useStoreActions(function(actions2) {
    return actions2.resetSelectedElements;
  });
  var nodesSelectionActive = useStoreState(function(state) {
    return state.nodesSelectionActive;
  });
  var selectionKeyPressed = useKeyPress(selectionKeyCode);
  useGlobalKeyHandler({
    onElementsRemove,
    deleteKeyCode,
    multiSelectionKeyCode
  });
  var onClick = react.useCallback(function(event) {
    onPaneClick === null || onPaneClick === void 0 ? void 0 : onPaneClick(event);
    unsetNodesSelection3();
    resetSelectedElements3();
  }, [onPaneClick]);
  var onContextMenu = react.useCallback(function(event) {
    onPaneContextMenu === null || onPaneContextMenu === void 0 ? void 0 : onPaneContextMenu(event);
  }, [onPaneContextMenu]);
  var onWheel = react.useCallback(function(event) {
    onPaneScroll === null || onPaneScroll === void 0 ? void 0 : onPaneScroll(event);
  }, [onPaneScroll]);
  return /* @__PURE__ */ react.createElement(ZoomPane, {
    onMove,
    onMoveStart,
    onMoveEnd,
    selectionKeyPressed,
    elementsSelectable,
    zoomOnScroll,
    zoomOnPinch,
    panOnScroll,
    panOnScrollSpeed,
    panOnScrollMode,
    zoomOnDoubleClick,
    paneMoveable,
    defaultPosition,
    defaultZoom,
    translateExtent,
    zoomActivationKeyCode,
    preventScrolling
  }, children2, /* @__PURE__ */ react.createElement(UserSelection, {
    selectionKeyPressed
  }), nodesSelectionActive && /* @__PURE__ */ react.createElement(NodesSelection, {
    onSelectionDragStart,
    onSelectionDrag,
    onSelectionDragStop,
    onSelectionContextMenu
  }), /* @__PURE__ */ react.createElement("div", {
    className: "react-flow__pane",
    onClick,
    onContextMenu,
    onWheel
  }));
};
FlowRenderer.displayName = "FlowRenderer";
var FlowRenderer$1 = /* @__PURE__ */ react.memo(FlowRenderer);
var NodeRenderer = function NodeRenderer2(props) {
  var transform3 = useStoreState(function(state) {
    return state.transform;
  });
  var selectedElements = useStoreState(function(state) {
    return state.selectedElements;
  });
  var nodesDraggable = useStoreState(function(state) {
    return state.nodesDraggable;
  });
  var nodesConnectable = useStoreState(function(state) {
    return state.nodesConnectable;
  });
  var elementsSelectable = useStoreState(function(state) {
    return state.elementsSelectable;
  });
  var width2 = useStoreState(function(state) {
    return state.width;
  });
  var height = useStoreState(function(state) {
    return state.height;
  });
  var nodes = useStoreState(function(state) {
    return state.nodes;
  });
  var updateNodeDimensions3 = useStoreActions(function(actions2) {
    return actions2.updateNodeDimensions;
  });
  var visibleNodes = props.onlyRenderVisibleElements ? getNodesInside(nodes, {
    x: 0,
    y: 0,
    width: width2,
    height
  }, transform3, true) : nodes;
  var transformStyle = react.useMemo(function() {
    return {
      transform: "translate(".concat(transform3[0], "px,").concat(transform3[1], "px) scale(").concat(transform3[2], ")")
    };
  }, [transform3[0], transform3[1], transform3[2]]);
  var resizeObserver = react.useMemo(function() {
    if (typeof ResizeObserver === "undefined") {
      return null;
    }
    return new ResizeObserver(function(entries) {
      var updates = entries.map(function(entry) {
        return {
          id: entry.target.getAttribute("data-id"),
          nodeElement: entry.target
        };
      });
      updateNodeDimensions3(updates);
    });
  }, []);
  return /* @__PURE__ */ react.createElement("div", {
    className: "react-flow__nodes",
    style: transformStyle
  }, visibleNodes.map(function(node) {
    var nodeType = node.type || "default";
    var NodeComponent = props.nodeTypes[nodeType] || props.nodeTypes["default"];
    if (!props.nodeTypes[nodeType]) {
      console.warn('Node type "'.concat(nodeType, '" not found. Using fallback type "default".'));
    }
    var isDraggable = !!(node.draggable || nodesDraggable && typeof node.draggable === "undefined");
    var isSelectable = !!(node.selectable || elementsSelectable && typeof node.selectable === "undefined");
    var isConnectable = !!(node.connectable || nodesConnectable && typeof node.connectable === "undefined");
    return /* @__PURE__ */ react.createElement(NodeComponent, {
      key: node.id,
      id: node.id,
      className: node.className,
      style: node.style,
      type: nodeType,
      data: node.data,
      sourcePosition: node.sourcePosition,
      targetPosition: node.targetPosition,
      isHidden: node.isHidden,
      xPos: node.__rf.position.x,
      yPos: node.__rf.position.y,
      isDragging: node.__rf.isDragging,
      isInitialized: node.__rf.width !== null && node.__rf.height !== null,
      snapGrid: props.snapGrid,
      snapToGrid: props.snapToGrid,
      selectNodesOnDrag: props.selectNodesOnDrag,
      onClick: props.onElementClick,
      onMouseEnter: props.onNodeMouseEnter,
      onMouseMove: props.onNodeMouseMove,
      onMouseLeave: props.onNodeMouseLeave,
      onContextMenu: props.onNodeContextMenu,
      onNodeDoubleClick: props.onNodeDoubleClick,
      onNodeDragStart: props.onNodeDragStart,
      onNodeDrag: props.onNodeDrag,
      onNodeDragStop: props.onNodeDragStop,
      scale: transform3[2],
      selected: (selectedElements === null || selectedElements === void 0 ? void 0 : selectedElements.some(function(_ref) {
        var id3 = _ref.id;
        return id3 === node.id;
      })) || false,
      isDraggable,
      isSelectable,
      isConnectable,
      resizeObserver,
      dragHandle: node.dragHandle
    });
  }));
};
NodeRenderer.displayName = "NodeRenderer";
var NodeRenderer$1 = /* @__PURE__ */ react.memo(NodeRenderer);
var _excluded$3 = ["x", "y", "label", "labelStyle", "labelShowBg", "labelBgStyle", "labelBgPadding", "labelBgBorderRadius", "children", "className"];
function ownKeys$a(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$a(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$a(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$a(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var EdgeText = function EdgeText2(_ref) {
  var x2 = _ref.x, y3 = _ref.y, label2 = _ref.label, _ref$labelStyle = _ref.labelStyle, labelStyle = _ref$labelStyle === void 0 ? {} : _ref$labelStyle, _ref$labelShowBg = _ref.labelShowBg, labelShowBg = _ref$labelShowBg === void 0 ? true : _ref$labelShowBg, _ref$labelBgStyle = _ref.labelBgStyle, labelBgStyle = _ref$labelBgStyle === void 0 ? {} : _ref$labelBgStyle, _ref$labelBgPadding = _ref.labelBgPadding, labelBgPadding = _ref$labelBgPadding === void 0 ? [2, 4] : _ref$labelBgPadding, _ref$labelBgBorderRad = _ref.labelBgBorderRadius, labelBgBorderRadius = _ref$labelBgBorderRad === void 0 ? 2 : _ref$labelBgBorderRad, children2 = _ref.children, className = _ref.className, rest = _objectWithoutProperties3(_ref, _excluded$3);
  var edgeRef = react.useRef(null);
  var _useState = react.useState({
    x: 0,
    y: 0,
    width: 0,
    height: 0
  }), _useState2 = _slicedToArray$1(_useState, 2), edgeTextBbox = _useState2[0], setEdgeTextBbox = _useState2[1];
  var edgeTextClasses = cc2(["react-flow__edge-textwrapper", className]);
  react.useEffect(function() {
    if (edgeRef.current) {
      var textBbox = edgeRef.current.getBBox();
      setEdgeTextBbox({
        x: textBbox.x,
        y: textBbox.y,
        width: textBbox.width,
        height: textBbox.height
      });
    }
  }, [label2]);
  if (typeof label2 === "undefined" || !label2) {
    return null;
  }
  return /* @__PURE__ */ react.createElement("g", _objectSpread$a({
    transform: "translate(".concat(x2 - edgeTextBbox.width / 2, " ").concat(y3 - edgeTextBbox.height / 2, ")"),
    className: edgeTextClasses
  }, rest), labelShowBg && /* @__PURE__ */ react.createElement("rect", {
    width: edgeTextBbox.width + 2 * labelBgPadding[0],
    x: -labelBgPadding[0],
    y: -labelBgPadding[1],
    height: edgeTextBbox.height + 2 * labelBgPadding[1],
    className: "react-flow__edge-textbg",
    style: labelBgStyle,
    rx: labelBgBorderRadius,
    ry: labelBgBorderRadius
  }), /* @__PURE__ */ react.createElement("text", {
    className: "react-flow__edge-text",
    y: edgeTextBbox.height / 2,
    dy: "0.3em",
    ref: edgeRef,
    style: labelStyle
  }, label2), children2);
};
var EdgeText$1 = /* @__PURE__ */ react.memo(EdgeText);
var getMarkerEnd = function getMarkerEnd2(arrowHeadType, markerEndId) {
  if (typeof markerEndId !== "undefined" && markerEndId) {
    return "url(#".concat(markerEndId, ")");
  }
  return typeof arrowHeadType !== "undefined" ? "url(#react-flow__".concat(arrowHeadType, ")") : "none";
};
var LeftOrRight = [Position2.Left, Position2.Right];
var getCenter = function getCenter2(_ref) {
  var sourceX = _ref.sourceX, sourceY = _ref.sourceY, targetX = _ref.targetX, targetY = _ref.targetY, _ref$sourcePosition = _ref.sourcePosition, sourcePosition = _ref$sourcePosition === void 0 ? Position2.Bottom : _ref$sourcePosition, _ref$targetPosition = _ref.targetPosition, targetPosition = _ref$targetPosition === void 0 ? Position2.Top : _ref$targetPosition;
  var sourceIsLeftOrRight = LeftOrRight.includes(sourcePosition);
  var targetIsLeftOrRight = LeftOrRight.includes(targetPosition);
  var mixedEdge = sourceIsLeftOrRight && !targetIsLeftOrRight || targetIsLeftOrRight && !sourceIsLeftOrRight;
  if (mixedEdge) {
    var _xOffset = sourceIsLeftOrRight ? Math.abs(targetX - sourceX) : 0;
    var _centerX = sourceX > targetX ? sourceX - _xOffset : sourceX + _xOffset;
    var _yOffset = sourceIsLeftOrRight ? 0 : Math.abs(targetY - sourceY);
    var _centerY = sourceY < targetY ? sourceY + _yOffset : sourceY - _yOffset;
    return [_centerX, _centerY, _xOffset, _yOffset];
  }
  var xOffset = Math.abs(targetX - sourceX) / 2;
  var centerX = targetX < sourceX ? targetX + xOffset : targetX - xOffset;
  var yOffset = Math.abs(targetY - sourceY) / 2;
  var centerY = targetY < sourceY ? targetY + yOffset : targetY - yOffset;
  return [centerX, centerY, xOffset, yOffset];
};
function getBezierPath(_ref) {
  var sourceX = _ref.sourceX, sourceY = _ref.sourceY, _ref$sourcePosition = _ref.sourcePosition, sourcePosition = _ref$sourcePosition === void 0 ? Position2.Bottom : _ref$sourcePosition, targetX = _ref.targetX, targetY = _ref.targetY, _ref$targetPosition = _ref.targetPosition, targetPosition = _ref$targetPosition === void 0 ? Position2.Top : _ref$targetPosition, centerX = _ref.centerX, centerY = _ref.centerY;
  var _getCenter = getCenter({
    sourceX,
    sourceY,
    targetX,
    targetY
  }), _getCenter2 = _slicedToArray$1(_getCenter, 2), _centerX = _getCenter2[0], _centerY = _getCenter2[1];
  var leftAndRight = [Position2.Left, Position2.Right];
  var cX = typeof centerX !== "undefined" ? centerX : _centerX;
  var cY = typeof centerY !== "undefined" ? centerY : _centerY;
  var path = "M".concat(sourceX, ",").concat(sourceY, " C").concat(sourceX, ",").concat(cY, " ").concat(targetX, ",").concat(cY, " ").concat(targetX, ",").concat(targetY);
  if (leftAndRight.includes(sourcePosition) && leftAndRight.includes(targetPosition)) {
    path = "M".concat(sourceX, ",").concat(sourceY, " C").concat(cX, ",").concat(sourceY, " ").concat(cX, ",").concat(targetY, " ").concat(targetX, ",").concat(targetY);
  } else if (leftAndRight.includes(targetPosition)) {
    path = "M".concat(sourceX, ",").concat(sourceY, " Q").concat(sourceX, ",").concat(targetY, " ").concat(targetX, ",").concat(targetY);
  } else if (leftAndRight.includes(sourcePosition)) {
    path = "M".concat(sourceX, ",").concat(sourceY, " Q").concat(targetX, ",").concat(sourceY, " ").concat(targetX, ",").concat(targetY);
  }
  return path;
}
var BezierEdge = /* @__PURE__ */ react.memo(function(_ref2) {
  var sourceX = _ref2.sourceX, sourceY = _ref2.sourceY, targetX = _ref2.targetX, targetY = _ref2.targetY, _ref2$sourcePosition = _ref2.sourcePosition, sourcePosition = _ref2$sourcePosition === void 0 ? Position2.Bottom : _ref2$sourcePosition, _ref2$targetPosition = _ref2.targetPosition, targetPosition = _ref2$targetPosition === void 0 ? Position2.Top : _ref2$targetPosition, label2 = _ref2.label, labelStyle = _ref2.labelStyle, labelShowBg = _ref2.labelShowBg, labelBgStyle = _ref2.labelBgStyle, labelBgPadding = _ref2.labelBgPadding, labelBgBorderRadius = _ref2.labelBgBorderRadius, style = _ref2.style, arrowHeadType = _ref2.arrowHeadType, markerEndId = _ref2.markerEndId;
  var _getCenter3 = getCenter({
    sourceX,
    sourceY,
    targetX,
    targetY,
    sourcePosition,
    targetPosition
  }), _getCenter4 = _slicedToArray$1(_getCenter3, 2), centerX = _getCenter4[0], centerY = _getCenter4[1];
  var path = getBezierPath({
    sourceX,
    sourceY,
    sourcePosition,
    targetX,
    targetY,
    targetPosition
  });
  var text = label2 ? /* @__PURE__ */ react.createElement(EdgeText$1, {
    x: centerX,
    y: centerY,
    label: label2,
    labelStyle,
    labelShowBg,
    labelBgStyle,
    labelBgPadding,
    labelBgBorderRadius
  }) : null;
  var markerEnd = getMarkerEnd(arrowHeadType, markerEndId);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement("path", {
    style,
    d: path,
    className: "react-flow__edge-path",
    markerEnd
  }), text);
});
var bottomLeftCorner = function bottomLeftCorner2(x2, y3, size2) {
  return "L ".concat(x2, ",").concat(y3 - size2, "Q ").concat(x2, ",").concat(y3, " ").concat(x2 + size2, ",").concat(y3);
};
var leftBottomCorner = function leftBottomCorner2(x2, y3, size2) {
  return "L ".concat(x2 + size2, ",").concat(y3, "Q ").concat(x2, ",").concat(y3, " ").concat(x2, ",").concat(y3 - size2);
};
var bottomRightCorner = function bottomRightCorner2(x2, y3, size2) {
  return "L ".concat(x2, ",").concat(y3 - size2, "Q ").concat(x2, ",").concat(y3, " ").concat(x2 - size2, ",").concat(y3);
};
var rightBottomCorner = function rightBottomCorner2(x2, y3, size2) {
  return "L ".concat(x2 - size2, ",").concat(y3, "Q ").concat(x2, ",").concat(y3, " ").concat(x2, ",").concat(y3 - size2);
};
var leftTopCorner = function leftTopCorner2(x2, y3, size2) {
  return "L ".concat(x2 + size2, ",").concat(y3, "Q ").concat(x2, ",").concat(y3, " ").concat(x2, ",").concat(y3 + size2);
};
var topLeftCorner = function topLeftCorner2(x2, y3, size2) {
  return "L ".concat(x2, ",").concat(y3 + size2, "Q ").concat(x2, ",").concat(y3, " ").concat(x2 + size2, ",").concat(y3);
};
var topRightCorner = function topRightCorner2(x2, y3, size2) {
  return "L ".concat(x2, ",").concat(y3 + size2, "Q ").concat(x2, ",").concat(y3, " ").concat(x2 - size2, ",").concat(y3);
};
var rightTopCorner = function rightTopCorner2(x2, y3, size2) {
  return "L ".concat(x2 - size2, ",").concat(y3, "Q ").concat(x2, ",").concat(y3, " ").concat(x2, ",").concat(y3 + size2);
};
function getSmoothStepPath(_ref) {
  var sourceX = _ref.sourceX, sourceY = _ref.sourceY, _ref$sourcePosition = _ref.sourcePosition, sourcePosition = _ref$sourcePosition === void 0 ? Position2.Bottom : _ref$sourcePosition, targetX = _ref.targetX, targetY = _ref.targetY, _ref$targetPosition = _ref.targetPosition, targetPosition = _ref$targetPosition === void 0 ? Position2.Top : _ref$targetPosition, _ref$borderRadius = _ref.borderRadius, borderRadius = _ref$borderRadius === void 0 ? 5 : _ref$borderRadius, centerX = _ref.centerX, centerY = _ref.centerY;
  var _getCenter = getCenter({
    sourceX,
    sourceY,
    targetX,
    targetY
  }), _getCenter2 = _slicedToArray$1(_getCenter, 4), _centerX = _getCenter2[0], _centerY = _getCenter2[1], offsetX = _getCenter2[2], offsetY = _getCenter2[3];
  var cornerWidth = Math.min(borderRadius, Math.abs(targetX - sourceX));
  var cornerHeight = Math.min(borderRadius, Math.abs(targetY - sourceY));
  var cornerSize = Math.min(cornerWidth, cornerHeight, offsetX, offsetY);
  var leftAndRight = [Position2.Left, Position2.Right];
  var cX = typeof centerX !== "undefined" ? centerX : _centerX;
  var cY = typeof centerY !== "undefined" ? centerY : _centerY;
  var firstCornerPath = null;
  var secondCornerPath = null;
  if (sourceX <= targetX) {
    firstCornerPath = sourceY <= targetY ? bottomLeftCorner(sourceX, cY, cornerSize) : topLeftCorner(sourceX, cY, cornerSize);
    secondCornerPath = sourceY <= targetY ? rightTopCorner(targetX, cY, cornerSize) : rightBottomCorner(targetX, cY, cornerSize);
  } else {
    firstCornerPath = sourceY < targetY ? bottomRightCorner(sourceX, cY, cornerSize) : topRightCorner(sourceX, cY, cornerSize);
    secondCornerPath = sourceY < targetY ? leftTopCorner(targetX, cY, cornerSize) : leftBottomCorner(targetX, cY, cornerSize);
  }
  if (leftAndRight.includes(sourcePosition) && leftAndRight.includes(targetPosition)) {
    if (sourceX <= targetX) {
      firstCornerPath = sourceY <= targetY ? rightTopCorner(cX, sourceY, cornerSize) : rightBottomCorner(cX, sourceY, cornerSize);
      secondCornerPath = sourceY <= targetY ? bottomLeftCorner(cX, targetY, cornerSize) : topLeftCorner(cX, targetY, cornerSize);
    } else if (sourcePosition === Position2.Right && targetPosition === Position2.Left || sourcePosition === Position2.Left && targetPosition === Position2.Right || sourcePosition === Position2.Left && targetPosition === Position2.Left) {
      firstCornerPath = sourceY <= targetY ? leftTopCorner(cX, sourceY, cornerSize) : leftBottomCorner(cX, sourceY, cornerSize);
      secondCornerPath = sourceY <= targetY ? bottomRightCorner(cX, targetY, cornerSize) : topRightCorner(cX, targetY, cornerSize);
    }
  } else if (leftAndRight.includes(sourcePosition) && !leftAndRight.includes(targetPosition)) {
    if (sourceX <= targetX) {
      firstCornerPath = sourceY <= targetY ? rightTopCorner(targetX, sourceY, cornerSize) : rightBottomCorner(targetX, sourceY, cornerSize);
    } else {
      firstCornerPath = sourceY <= targetY ? leftTopCorner(targetX, sourceY, cornerSize) : leftBottomCorner(targetX, sourceY, cornerSize);
    }
    secondCornerPath = "";
  } else if (!leftAndRight.includes(sourcePosition) && leftAndRight.includes(targetPosition)) {
    if (sourceX <= targetX) {
      firstCornerPath = sourceY <= targetY ? bottomLeftCorner(sourceX, targetY, cornerSize) : topLeftCorner(sourceX, targetY, cornerSize);
    } else {
      firstCornerPath = sourceY <= targetY ? bottomRightCorner(sourceX, targetY, cornerSize) : topRightCorner(sourceX, targetY, cornerSize);
    }
    secondCornerPath = "";
  }
  return "M ".concat(sourceX, ",").concat(sourceY).concat(firstCornerPath).concat(secondCornerPath, "L ").concat(targetX, ",").concat(targetY);
}
var SmoothStepEdge = /* @__PURE__ */ react.memo(function(_ref2) {
  var sourceX = _ref2.sourceX, sourceY = _ref2.sourceY, targetX = _ref2.targetX, targetY = _ref2.targetY, label2 = _ref2.label, labelStyle = _ref2.labelStyle, labelShowBg = _ref2.labelShowBg, labelBgStyle = _ref2.labelBgStyle, labelBgPadding = _ref2.labelBgPadding, labelBgBorderRadius = _ref2.labelBgBorderRadius, style = _ref2.style, _ref2$sourcePosition = _ref2.sourcePosition, sourcePosition = _ref2$sourcePosition === void 0 ? Position2.Bottom : _ref2$sourcePosition, _ref2$targetPosition = _ref2.targetPosition, targetPosition = _ref2$targetPosition === void 0 ? Position2.Top : _ref2$targetPosition, arrowHeadType = _ref2.arrowHeadType, markerEndId = _ref2.markerEndId, _ref2$borderRadius = _ref2.borderRadius, borderRadius = _ref2$borderRadius === void 0 ? 5 : _ref2$borderRadius;
  var _getCenter3 = getCenter({
    sourceX,
    sourceY,
    targetX,
    targetY,
    sourcePosition,
    targetPosition
  }), _getCenter4 = _slicedToArray$1(_getCenter3, 2), centerX = _getCenter4[0], centerY = _getCenter4[1];
  var path = getSmoothStepPath({
    sourceX,
    sourceY,
    sourcePosition,
    targetX,
    targetY,
    targetPosition,
    borderRadius
  });
  var markerEnd = getMarkerEnd(arrowHeadType, markerEndId);
  var text = label2 ? /* @__PURE__ */ react.createElement(EdgeText$1, {
    x: centerX,
    y: centerY,
    label: label2,
    labelStyle,
    labelShowBg,
    labelBgStyle,
    labelBgPadding,
    labelBgBorderRadius
  }) : null;
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement("path", {
    style,
    className: "react-flow__edge-path",
    d: path,
    markerEnd
  }), text);
});
var getSourceHandle = function getSourceHandle2(handleId, sourceNode, connectionHandleType) {
  var handleTypeInverted = connectionHandleType === "source" ? "target" : "source";
  var handleBound = sourceNode.__rf.handleBounds[connectionHandleType] || sourceNode.__rf.handleBounds[handleTypeInverted];
  return handleId ? handleBound.find(function(d2) {
    return d2.id === handleId;
  }) : handleBound[0];
};
var ConnectionLine = function(_ref) {
  var connectionNodeId = _ref.connectionNodeId, connectionHandleId = _ref.connectionHandleId, connectionHandleType = _ref.connectionHandleType, connectionLineStyle = _ref.connectionLineStyle, connectionPositionX = _ref.connectionPositionX, connectionPositionY = _ref.connectionPositionY, _ref$connectionLineTy = _ref.connectionLineType, connectionLineType = _ref$connectionLineTy === void 0 ? ConnectionLineType.Bezier : _ref$connectionLineTy, _ref$nodes = _ref.nodes, nodes = _ref$nodes === void 0 ? [] : _ref$nodes, transform3 = _ref.transform, isConnectable = _ref.isConnectable, CustomConnectionLineComponent = _ref.CustomConnectionLineComponent;
  var _useState = react.useState(null), _useState2 = _slicedToArray$1(_useState, 2), sourceNode = _useState2[0], setSourceNode = _useState2[1];
  var nodeId = connectionNodeId;
  var handleId = connectionHandleId;
  react.useEffect(function() {
    var nextSourceNode = nodes.find(function(n3) {
      return n3.id === nodeId;
    }) || null;
    setSourceNode(nextSourceNode);
  }, []);
  if (!sourceNode || !isConnectable) {
    return null;
  }
  var sourceHandle = getSourceHandle(handleId, sourceNode, connectionHandleType);
  var sourceHandleX = sourceHandle ? sourceHandle.x + sourceHandle.width / 2 : sourceNode.__rf.width / 2;
  var sourceHandleY = sourceHandle ? sourceHandle.y + sourceHandle.height / 2 : sourceNode.__rf.height;
  var sourceX = sourceNode.__rf.position.x + sourceHandleX;
  var sourceY = sourceNode.__rf.position.y + sourceHandleY;
  var targetX = (connectionPositionX - transform3[0]) / transform3[2];
  var targetY = (connectionPositionY - transform3[1]) / transform3[2];
  var isRightOrLeft = (sourceHandle === null || sourceHandle === void 0 ? void 0 : sourceHandle.position) === Position2.Left || (sourceHandle === null || sourceHandle === void 0 ? void 0 : sourceHandle.position) === Position2.Right;
  var targetPosition = isRightOrLeft ? Position2.Left : Position2.Top;
  if (CustomConnectionLineComponent) {
    return /* @__PURE__ */ react.createElement("g", {
      className: "react-flow__connection"
    }, /* @__PURE__ */ react.createElement(CustomConnectionLineComponent, {
      sourceX,
      sourceY,
      sourcePosition: sourceHandle === null || sourceHandle === void 0 ? void 0 : sourceHandle.position,
      targetX,
      targetY,
      targetPosition,
      connectionLineType,
      connectionLineStyle,
      sourceNode,
      sourceHandle
    }));
  }
  var dAttr = "";
  if (connectionLineType === ConnectionLineType.Bezier) {
    dAttr = getBezierPath({
      sourceX,
      sourceY,
      sourcePosition: sourceHandle === null || sourceHandle === void 0 ? void 0 : sourceHandle.position,
      targetX,
      targetY,
      targetPosition
    });
  } else if (connectionLineType === ConnectionLineType.Step) {
    dAttr = getSmoothStepPath({
      sourceX,
      sourceY,
      sourcePosition: sourceHandle === null || sourceHandle === void 0 ? void 0 : sourceHandle.position,
      targetX,
      targetY,
      targetPosition,
      borderRadius: 0
    });
  } else if (connectionLineType === ConnectionLineType.SmoothStep) {
    dAttr = getSmoothStepPath({
      sourceX,
      sourceY,
      sourcePosition: sourceHandle === null || sourceHandle === void 0 ? void 0 : sourceHandle.position,
      targetX,
      targetY,
      targetPosition
    });
  } else {
    dAttr = "M".concat(sourceX, ",").concat(sourceY, " ").concat(targetX, ",").concat(targetY);
  }
  return /* @__PURE__ */ react.createElement("g", {
    className: "react-flow__connection"
  }, /* @__PURE__ */ react.createElement("path", {
    d: dAttr,
    className: "react-flow__connection-path",
    style: connectionLineStyle
  }));
};
var Marker = function Marker2(_ref) {
  var id3 = _ref.id, children2 = _ref.children;
  return /* @__PURE__ */ react.createElement("marker", {
    className: "react-flow__arrowhead",
    id: id3,
    markerWidth: "12.5",
    markerHeight: "12.5",
    viewBox: "-10 -10 20 20",
    orient: "auto",
    refX: "0",
    refY: "0"
  }, children2);
};
var MarkerDefinitions = function MarkerDefinitions2(_ref2) {
  var color2 = _ref2.color;
  return /* @__PURE__ */ react.createElement("defs", null, /* @__PURE__ */ react.createElement(Marker, {
    id: "react-flow__arrowclosed"
  }, /* @__PURE__ */ react.createElement("polyline", {
    stroke: color2,
    strokeLinecap: "round",
    strokeLinejoin: "round",
    strokeWidth: "1",
    fill: color2,
    points: "-5,-4 0,0 -5,4 -5,-4"
  })), /* @__PURE__ */ react.createElement(Marker, {
    id: "react-flow__arrow"
  }, /* @__PURE__ */ react.createElement("polyline", {
    stroke: color2,
    strokeLinecap: "round",
    strokeLinejoin: "round",
    strokeWidth: "1.5",
    fill: "none",
    points: "-5,-4 0,0 -5,4"
  })));
};
MarkerDefinitions.displayName = "MarkerDefinitions";
function ownKeys$9(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$9(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$9(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$9(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var StepEdge = /* @__PURE__ */ react.memo(function(props) {
  return /* @__PURE__ */ react.createElement(SmoothStepEdge, _objectSpread$9(_objectSpread$9({}, props), {}, {
    borderRadius: 0
  }));
});
var StraightEdge = /* @__PURE__ */ react.memo(function(_ref) {
  var sourceX = _ref.sourceX, sourceY = _ref.sourceY, targetX = _ref.targetX, targetY = _ref.targetY, label2 = _ref.label, labelStyle = _ref.labelStyle, labelShowBg = _ref.labelShowBg, labelBgStyle = _ref.labelBgStyle, labelBgPadding = _ref.labelBgPadding, labelBgBorderRadius = _ref.labelBgBorderRadius, style = _ref.style, arrowHeadType = _ref.arrowHeadType, markerEndId = _ref.markerEndId;
  var yOffset = Math.abs(targetY - sourceY) / 2;
  var centerY = targetY < sourceY ? targetY + yOffset : targetY - yOffset;
  var xOffset = Math.abs(targetX - sourceX) / 2;
  var centerX = targetX < sourceX ? targetX + xOffset : targetX - xOffset;
  var markerEnd = getMarkerEnd(arrowHeadType, markerEndId);
  var text = label2 ? /* @__PURE__ */ react.createElement(EdgeText$1, {
    x: centerX,
    y: centerY,
    label: label2,
    labelStyle,
    labelShowBg,
    labelBgStyle,
    labelBgPadding,
    labelBgBorderRadius
  }) : null;
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement("path", {
    style,
    className: "react-flow__edge-path",
    d: "M ".concat(sourceX, ",").concat(sourceY, "L ").concat(targetX, ",").concat(targetY),
    markerEnd
  }), text);
});
function checkElementBelowIsValid(event, connectionMode, isTarget, nodeId, handleId, isValidConnection, doc) {
  var elementBelow = doc.elementFromPoint(event.clientX, event.clientY);
  var elementBelowIsTarget = (elementBelow === null || elementBelow === void 0 ? void 0 : elementBelow.classList.contains("target")) || false;
  var elementBelowIsSource = (elementBelow === null || elementBelow === void 0 ? void 0 : elementBelow.classList.contains("source")) || false;
  var result = {
    elementBelow,
    isValid: false,
    connection: {
      source: null,
      target: null,
      sourceHandle: null,
      targetHandle: null
    },
    isHoveringHandle: false
  };
  if (elementBelow && (elementBelowIsTarget || elementBelowIsSource)) {
    result.isHoveringHandle = true;
    var isValid = connectionMode === ConnectionMode.Strict ? isTarget && elementBelowIsSource || !isTarget && elementBelowIsTarget : true;
    if (isValid) {
      var elementBelowNodeId = elementBelow.getAttribute("data-nodeid");
      var elementBelowHandleId = elementBelow.getAttribute("data-handleid");
      var connection = isTarget ? {
        source: elementBelowNodeId,
        sourceHandle: elementBelowHandleId,
        target: nodeId,
        targetHandle: handleId
      } : {
        source: nodeId,
        sourceHandle: handleId,
        target: elementBelowNodeId,
        targetHandle: elementBelowHandleId
      };
      result.connection = connection;
      result.isValid = isValidConnection(connection);
    }
  }
  return result;
}
function resetRecentHandle(hoveredHandle) {
  hoveredHandle === null || hoveredHandle === void 0 ? void 0 : hoveredHandle.classList.remove("react-flow__handle-valid");
  hoveredHandle === null || hoveredHandle === void 0 ? void 0 : hoveredHandle.classList.remove("react-flow__handle-connecting");
}
function onMouseDown2(event, handleId, nodeId, setConnectionNodeId3, setPosition, onConnect, isTarget, isValidConnection, connectionMode, elementEdgeUpdaterType, onEdgeUpdateEnd, onConnectStart, onConnectStop, onConnectEnd) {
  var reactFlowNode = event.target.closest(".react-flow");
  var doc = getHostForElement(event.target);
  if (!doc) {
    return;
  }
  var elementBelow = doc.elementFromPoint(event.clientX, event.clientY);
  var elementBelowIsTarget = elementBelow === null || elementBelow === void 0 ? void 0 : elementBelow.classList.contains("target");
  var elementBelowIsSource = elementBelow === null || elementBelow === void 0 ? void 0 : elementBelow.classList.contains("source");
  if (!reactFlowNode || !elementBelowIsTarget && !elementBelowIsSource && !elementEdgeUpdaterType) {
    return;
  }
  var handleType = elementEdgeUpdaterType ? elementEdgeUpdaterType : elementBelowIsTarget ? "target" : "source";
  var containerBounds = reactFlowNode.getBoundingClientRect();
  var recentHoveredHandle;
  setPosition({
    x: event.clientX - containerBounds.left,
    y: event.clientY - containerBounds.top
  });
  setConnectionNodeId3({
    connectionNodeId: nodeId,
    connectionHandleId: handleId,
    connectionHandleType: handleType
  });
  onConnectStart === null || onConnectStart === void 0 ? void 0 : onConnectStart(event, {
    nodeId,
    handleId,
    handleType
  });
  function onMouseMove(event2) {
    setPosition({
      x: event2.clientX - containerBounds.left,
      y: event2.clientY - containerBounds.top
    });
    var _checkElementBelowIsV = checkElementBelowIsValid(event2, connectionMode, isTarget, nodeId, handleId, isValidConnection, doc), connection = _checkElementBelowIsV.connection, elementBelow2 = _checkElementBelowIsV.elementBelow, isValid = _checkElementBelowIsV.isValid, isHoveringHandle = _checkElementBelowIsV.isHoveringHandle;
    if (!isHoveringHandle) {
      return resetRecentHandle(recentHoveredHandle);
    }
    var isOwnHandle = connection.source === connection.target;
    if (!isOwnHandle && elementBelow2) {
      recentHoveredHandle = elementBelow2;
      elementBelow2.classList.add("react-flow__handle-connecting");
      elementBelow2.classList.toggle("react-flow__handle-valid", isValid);
    }
  }
  function onMouseUp(event2) {
    var _checkElementBelowIsV2 = checkElementBelowIsValid(event2, connectionMode, isTarget, nodeId, handleId, isValidConnection, doc), connection = _checkElementBelowIsV2.connection, isValid = _checkElementBelowIsV2.isValid;
    onConnectStop === null || onConnectStop === void 0 ? void 0 : onConnectStop(event2);
    if (isValid) {
      onConnect === null || onConnect === void 0 ? void 0 : onConnect(connection);
    }
    onConnectEnd === null || onConnectEnd === void 0 ? void 0 : onConnectEnd(event2);
    if (elementEdgeUpdaterType && onEdgeUpdateEnd) {
      onEdgeUpdateEnd(event2);
    }
    resetRecentHandle(recentHoveredHandle);
    setConnectionNodeId3({
      connectionNodeId: null,
      connectionHandleId: null,
      connectionHandleType: null
    });
    doc.removeEventListener("mousemove", onMouseMove);
    doc.removeEventListener("mouseup", onMouseUp);
  }
  doc.addEventListener("mousemove", onMouseMove);
  doc.addEventListener("mouseup", onMouseUp);
}
var shiftX = function shiftX2(x2, shift2, position2) {
  if (position2 === Position2.Left)
    return x2 - shift2;
  if (position2 === Position2.Right)
    return x2 + shift2;
  return x2;
};
var shiftY = function shiftY2(y3, shift2, position2) {
  if (position2 === Position2.Top)
    return y3 - shift2;
  if (position2 === Position2.Bottom)
    return y3 + shift2;
  return y3;
};
var EdgeAnchor = function EdgeAnchor2(_ref) {
  var className = _ref.className, position2 = _ref.position, centerX = _ref.centerX, centerY = _ref.centerY, _ref$radius = _ref.radius, radius = _ref$radius === void 0 ? 10 : _ref$radius;
  return /* @__PURE__ */ react.createElement("circle", {
    className: cc2(["react-flow__edgeupdater", className]),
    cx: shiftX(centerX, radius, position2),
    cy: shiftY(centerY, radius, position2),
    r: radius,
    stroke: "transparent",
    fill: "transparent"
  });
};
var wrapEdge = function(EdgeComponent) {
  var EdgeWrapper = function EdgeWrapper2(_ref) {
    var id3 = _ref.id, className = _ref.className, type = _ref.type, data2 = _ref.data, onClick = _ref.onClick, onEdgeDoubleClick = _ref.onEdgeDoubleClick, selected = _ref.selected, animated = _ref.animated, label2 = _ref.label, labelStyle = _ref.labelStyle, labelShowBg = _ref.labelShowBg, labelBgStyle = _ref.labelBgStyle, labelBgPadding = _ref.labelBgPadding, labelBgBorderRadius = _ref.labelBgBorderRadius, style = _ref.style, arrowHeadType = _ref.arrowHeadType, source2 = _ref.source, target = _ref.target, sourceX = _ref.sourceX, sourceY = _ref.sourceY, targetX = _ref.targetX, targetY = _ref.targetY, sourcePosition = _ref.sourcePosition, targetPosition = _ref.targetPosition, elementsSelectable = _ref.elementsSelectable, markerEndId = _ref.markerEndId, isHidden3 = _ref.isHidden, sourceHandleId = _ref.sourceHandleId, targetHandleId = _ref.targetHandleId, handleEdgeUpdate = _ref.handleEdgeUpdate, onConnectEdge = _ref.onConnectEdge, onContextMenu = _ref.onContextMenu, onMouseEnter = _ref.onMouseEnter, onMouseMove = _ref.onMouseMove, onMouseLeave = _ref.onMouseLeave, edgeUpdaterRadius = _ref.edgeUpdaterRadius, onEdgeUpdateStart = _ref.onEdgeUpdateStart, onEdgeUpdateEnd = _ref.onEdgeUpdateEnd;
    var addSelectedElements3 = useStoreActions(function(actions2) {
      return actions2.addSelectedElements;
    });
    var setConnectionNodeId3 = useStoreActions(function(actions2) {
      return actions2.setConnectionNodeId;
    });
    var unsetNodesSelection3 = useStoreActions(function(actions2) {
      return actions2.unsetNodesSelection;
    });
    var setPosition = useStoreActions(function(actions2) {
      return actions2.setConnectionPosition;
    });
    var connectionMode = useStoreState(function(state) {
      return state.connectionMode;
    });
    var _useState = react.useState(false), _useState2 = _slicedToArray$1(_useState, 2), updating = _useState2[0], setUpdating = _useState2[1];
    var inactive = !elementsSelectable && !onClick;
    var edgeClasses = cc2(["react-flow__edge", "react-flow__edge-".concat(type), className, {
      selected,
      animated,
      inactive,
      updating
    }]);
    var edgeElement = react.useMemo(function() {
      var el = {
        id: id3,
        source: source2,
        target,
        type
      };
      if (sourceHandleId) {
        el.sourceHandle = sourceHandleId;
      }
      if (targetHandleId) {
        el.targetHandle = targetHandleId;
      }
      if (typeof data2 !== "undefined") {
        el.data = data2;
      }
      return el;
    }, [id3, source2, target, type, sourceHandleId, targetHandleId, data2]);
    var onEdgeClick = react.useCallback(function(event) {
      if (elementsSelectable) {
        unsetNodesSelection3();
        addSelectedElements3(edgeElement);
      }
      onClick === null || onClick === void 0 ? void 0 : onClick(event, edgeElement);
    }, [elementsSelectable, edgeElement, onClick]);
    var onEdgeDoubleClickHandler = react.useCallback(function(event) {
      onEdgeDoubleClick === null || onEdgeDoubleClick === void 0 ? void 0 : onEdgeDoubleClick(event, edgeElement);
    }, [edgeElement, onEdgeDoubleClick]);
    var onEdgeContextMenu = react.useCallback(function(event) {
      onContextMenu === null || onContextMenu === void 0 ? void 0 : onContextMenu(event, edgeElement);
    }, [edgeElement, onContextMenu]);
    var onEdgeMouseEnter = react.useCallback(function(event) {
      onMouseEnter === null || onMouseEnter === void 0 ? void 0 : onMouseEnter(event, edgeElement);
    }, [edgeElement, onContextMenu]);
    var onEdgeMouseMove = react.useCallback(function(event) {
      onMouseMove === null || onMouseMove === void 0 ? void 0 : onMouseMove(event, edgeElement);
    }, [edgeElement, onContextMenu]);
    var onEdgeMouseLeave = react.useCallback(function(event) {
      onMouseLeave === null || onMouseLeave === void 0 ? void 0 : onMouseLeave(event, edgeElement);
    }, [edgeElement, onContextMenu]);
    var handleEdgeUpdater = react.useCallback(function(event, isSourceHandle) {
      var nodeId = isSourceHandle ? target : source2;
      var handleId = isSourceHandle ? targetHandleId : sourceHandleId;
      var isValidConnection = function isValidConnection2() {
        return true;
      };
      var isTarget = isSourceHandle;
      onEdgeUpdateStart === null || onEdgeUpdateStart === void 0 ? void 0 : onEdgeUpdateStart(event, edgeElement);
      var _onEdgeUpdate = onEdgeUpdateEnd ? function(evt) {
        return onEdgeUpdateEnd(evt, edgeElement);
      } : void 0;
      onMouseDown2(event, handleId, nodeId, setConnectionNodeId3, setPosition, onConnectEdge, isTarget, isValidConnection, connectionMode, isSourceHandle ? "target" : "source", _onEdgeUpdate);
    }, [id3, source2, target, type, sourceHandleId, targetHandleId, setConnectionNodeId3, setPosition, edgeElement, onConnectEdge]);
    var onEdgeUpdaterSourceMouseDown = react.useCallback(function(event) {
      handleEdgeUpdater(event, true);
    }, [id3, source2, sourceHandleId, handleEdgeUpdater]);
    var onEdgeUpdaterTargetMouseDown = react.useCallback(function(event) {
      handleEdgeUpdater(event, false);
    }, [id3, target, targetHandleId, handleEdgeUpdater]);
    var onEdgeUpdaterMouseEnter = react.useCallback(function() {
      return setUpdating(true);
    }, [setUpdating]);
    var onEdgeUpdaterMouseOut = react.useCallback(function() {
      return setUpdating(false);
    }, [setUpdating]);
    if (isHidden3) {
      return null;
    }
    return /* @__PURE__ */ react.createElement("g", {
      className: edgeClasses,
      onClick: onEdgeClick,
      onDoubleClick: onEdgeDoubleClickHandler,
      onContextMenu: onEdgeContextMenu,
      onMouseEnter: onEdgeMouseEnter,
      onMouseMove: onEdgeMouseMove,
      onMouseLeave: onEdgeMouseLeave
    }, /* @__PURE__ */ react.createElement(EdgeComponent, {
      id: id3,
      source: source2,
      target,
      selected,
      animated,
      label: label2,
      labelStyle,
      labelShowBg,
      labelBgStyle,
      labelBgPadding,
      labelBgBorderRadius,
      data: data2,
      style,
      arrowHeadType,
      sourceX,
      sourceY,
      targetX,
      targetY,
      sourcePosition,
      targetPosition,
      markerEndId,
      sourceHandleId,
      targetHandleId
    }), handleEdgeUpdate && /* @__PURE__ */ react.createElement("g", {
      onMouseDown: onEdgeUpdaterSourceMouseDown,
      onMouseEnter: onEdgeUpdaterMouseEnter,
      onMouseOut: onEdgeUpdaterMouseOut
    }, /* @__PURE__ */ react.createElement(EdgeAnchor, {
      position: sourcePosition,
      centerX: sourceX,
      centerY: sourceY,
      radius: edgeUpdaterRadius
    })), handleEdgeUpdate && /* @__PURE__ */ react.createElement("g", {
      onMouseDown: onEdgeUpdaterTargetMouseDown,
      onMouseEnter: onEdgeUpdaterMouseEnter,
      onMouseOut: onEdgeUpdaterMouseOut
    }, /* @__PURE__ */ react.createElement(EdgeAnchor, {
      position: targetPosition,
      centerX: targetX,
      centerY: targetY,
      radius: edgeUpdaterRadius
    })));
  };
  EdgeWrapper.displayName = "EdgeWrapper";
  return /* @__PURE__ */ react.memo(EdgeWrapper);
};
function ownKeys$8(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$8(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$8(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$8(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
function createEdgeTypes(edgeTypes) {
  var standardTypes = {
    default: wrapEdge(edgeTypes["default"] || BezierEdge),
    straight: wrapEdge(edgeTypes.bezier || StraightEdge),
    step: wrapEdge(edgeTypes.step || StepEdge),
    smoothstep: wrapEdge(edgeTypes.step || SmoothStepEdge)
  };
  var wrappedTypes = {};
  var specialTypes = Object.keys(edgeTypes).filter(function(k2) {
    return !["default", "bezier"].includes(k2);
  }).reduce(function(res, key) {
    res[key] = wrapEdge(edgeTypes[key] || BezierEdge);
    return res;
  }, wrappedTypes);
  return _objectSpread$8(_objectSpread$8({}, standardTypes), specialTypes);
}
function getHandlePosition(position2, node) {
  var handle2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null;
  var x2 = ((handle2 === null || handle2 === void 0 ? void 0 : handle2.x) || 0) + node.__rf.position.x;
  var y3 = ((handle2 === null || handle2 === void 0 ? void 0 : handle2.y) || 0) + node.__rf.position.y;
  var width2 = (handle2 === null || handle2 === void 0 ? void 0 : handle2.width) || node.__rf.width;
  var height = (handle2 === null || handle2 === void 0 ? void 0 : handle2.height) || node.__rf.height;
  switch (position2) {
    case Position2.Top:
      return {
        x: x2 + width2 / 2,
        y: y3
      };
    case Position2.Right:
      return {
        x: x2 + width2,
        y: y3 + height / 2
      };
    case Position2.Bottom:
      return {
        x: x2 + width2 / 2,
        y: y3 + height
      };
    case Position2.Left:
      return {
        x: x2,
        y: y3 + height / 2
      };
  }
}
function getHandle(bounds, handleId) {
  if (!bounds) {
    return null;
  }
  var handle2 = null;
  if (bounds.length === 1 || !handleId) {
    handle2 = bounds[0];
  } else if (handleId) {
    handle2 = bounds.find(function(d2) {
      return d2.id === handleId;
    });
  }
  return typeof handle2 === "undefined" ? null : handle2;
}
var getEdgePositions = function getEdgePositions2(sourceNode, sourceHandle, sourcePosition, targetNode, targetHandle, targetPosition) {
  var sourceHandlePos = getHandlePosition(sourcePosition, sourceNode, sourceHandle);
  var targetHandlePos = getHandlePosition(targetPosition, targetNode, targetHandle);
  return {
    sourceX: sourceHandlePos.x,
    sourceY: sourceHandlePos.y,
    targetX: targetHandlePos.x,
    targetY: targetHandlePos.y
  };
};
function isEdgeVisible(_ref) {
  var sourcePos = _ref.sourcePos, targetPos = _ref.targetPos, width2 = _ref.width, height = _ref.height, transform3 = _ref.transform;
  var edgeBox = {
    x: Math.min(sourcePos.x, targetPos.x),
    y: Math.min(sourcePos.y, targetPos.y),
    x2: Math.max(sourcePos.x, targetPos.x),
    y2: Math.max(sourcePos.y, targetPos.y)
  };
  if (edgeBox.x === edgeBox.x2) {
    edgeBox.x2 += 1;
  }
  if (edgeBox.y === edgeBox.y2) {
    edgeBox.y2 += 1;
  }
  var viewBox = rectToBox({
    x: (0 - transform3[0]) / transform3[2],
    y: (0 - transform3[1]) / transform3[2],
    width: width2 / transform3[2],
    height: height / transform3[2]
  });
  var xOverlap = Math.max(0, Math.min(viewBox.x2, edgeBox.x2) - Math.max(viewBox.x, edgeBox.x));
  var yOverlap = Math.max(0, Math.min(viewBox.y2, edgeBox.y2) - Math.max(viewBox.y, edgeBox.y));
  var overlappingArea = Math.ceil(xOverlap * yOverlap);
  return overlappingArea > 0;
}
var getSourceTargetNodes = function getSourceTargetNodes2(edge, nodes) {
  return nodes.reduce(function(res, node) {
    if (node.id === edge.source) {
      res.sourceNode = node;
    }
    if (node.id === edge.target) {
      res.targetNode = node;
    }
    return res;
  }, {
    sourceNode: null,
    targetNode: null
  });
};
var Edge = function Edge2(_ref) {
  var edge = _ref.edge, props = _ref.props, nodes = _ref.nodes, selectedElements = _ref.selectedElements, elementsSelectable = _ref.elementsSelectable, transform3 = _ref.transform, width2 = _ref.width, height = _ref.height, onlyRenderVisibleElements = _ref.onlyRenderVisibleElements, connectionMode = _ref.connectionMode;
  var sourceHandleId = edge.sourceHandle || null;
  var targetHandleId = edge.targetHandle || null;
  var _getSourceTargetNodes = getSourceTargetNodes(edge, nodes), sourceNode = _getSourceTargetNodes.sourceNode, targetNode = _getSourceTargetNodes.targetNode;
  var onConnectEdge = react.useCallback(function(connection) {
    var _props$onEdgeUpdate;
    (_props$onEdgeUpdate = props.onEdgeUpdate) === null || _props$onEdgeUpdate === void 0 ? void 0 : _props$onEdgeUpdate.call(props, edge, connection);
  }, [edge, props.onEdgeUpdate]);
  if (!sourceNode) {
    console.warn("couldn't create edge for source id: ".concat(edge.source, "; edge id: ").concat(edge.id));
    return null;
  }
  if (!targetNode) {
    console.warn("couldn't create edge for target id: ".concat(edge.target, "; edge id: ").concat(edge.id));
    return null;
  }
  if (!sourceNode.__rf.width || !targetNode.__rf.width) {
    return null;
  }
  var edgeType = edge.type || "default";
  var EdgeComponent = props.edgeTypes[edgeType] || props.edgeTypes["default"];
  var targetNodeBounds = targetNode.__rf.handleBounds;
  var targetNodeHandles = connectionMode === ConnectionMode.Strict ? targetNodeBounds.target : targetNodeBounds.target || targetNodeBounds.source;
  var sourceHandle = getHandle(sourceNode.__rf.handleBounds.source, sourceHandleId);
  var targetHandle = getHandle(targetNodeHandles, targetHandleId);
  var sourcePosition = sourceHandle ? sourceHandle.position : Position2.Bottom;
  var targetPosition = targetHandle ? targetHandle.position : Position2.Top;
  if (!sourceHandle) {
    console.warn("couldn't create edge for source handle id: ".concat(sourceHandleId, "; edge id: ").concat(edge.id));
    return null;
  }
  if (!targetHandle) {
    console.warn("couldn't create edge for target handle id: ".concat(targetHandleId, "; edge id: ").concat(edge.id));
    return null;
  }
  var _getEdgePositions = getEdgePositions(sourceNode, sourceHandle, sourcePosition, targetNode, targetHandle, targetPosition), sourceX = _getEdgePositions.sourceX, sourceY = _getEdgePositions.sourceY, targetX = _getEdgePositions.targetX, targetY = _getEdgePositions.targetY;
  var isVisible = onlyRenderVisibleElements ? isEdgeVisible({
    sourcePos: {
      x: sourceX,
      y: sourceY
    },
    targetPos: {
      x: targetX,
      y: targetY
    },
    width: width2,
    height,
    transform: transform3
  }) : true;
  if (!isVisible) {
    return null;
  }
  var isSelected = (selectedElements === null || selectedElements === void 0 ? void 0 : selectedElements.some(function(elm) {
    return isEdge3(elm) && elm.id === edge.id;
  })) || false;
  return /* @__PURE__ */ react.createElement(EdgeComponent, {
    key: edge.id,
    id: edge.id,
    className: edge.className,
    type: edge.type,
    data: edge.data,
    onClick: props.onElementClick,
    selected: isSelected,
    animated: edge.animated,
    label: edge.label,
    labelStyle: edge.labelStyle,
    labelShowBg: edge.labelShowBg,
    labelBgStyle: edge.labelBgStyle,
    labelBgPadding: edge.labelBgPadding,
    labelBgBorderRadius: edge.labelBgBorderRadius,
    style: edge.style,
    arrowHeadType: edge.arrowHeadType,
    source: edge.source,
    target: edge.target,
    sourceHandleId,
    targetHandleId,
    sourceX,
    sourceY,
    targetX,
    targetY,
    sourcePosition,
    targetPosition,
    elementsSelectable,
    markerEndId: props.markerEndId,
    isHidden: edge.isHidden,
    onConnectEdge,
    handleEdgeUpdate: typeof props.onEdgeUpdate !== "undefined",
    onContextMenu: props.onEdgeContextMenu,
    onMouseEnter: props.onEdgeMouseEnter,
    onMouseMove: props.onEdgeMouseMove,
    onMouseLeave: props.onEdgeMouseLeave,
    edgeUpdaterRadius: props.edgeUpdaterRadius,
    onEdgeDoubleClick: props.onEdgeDoubleClick,
    onEdgeUpdateStart: props.onEdgeUpdateStart,
    onEdgeUpdateEnd: props.onEdgeUpdateEnd
  });
};
var EdgeRenderer = function EdgeRenderer2(props) {
  var transform3 = useStoreState(function(state) {
    return state.transform;
  });
  var nodes = useStoreState(function(state) {
    return state.nodes;
  });
  var edges = useStoreState(function(state) {
    return state.edges;
  });
  var connectionNodeId = useStoreState(function(state) {
    return state.connectionNodeId;
  });
  var connectionHandleId = useStoreState(function(state) {
    return state.connectionHandleId;
  });
  var connectionHandleType = useStoreState(function(state) {
    return state.connectionHandleType;
  });
  var connectionPosition = useStoreState(function(state) {
    return state.connectionPosition;
  });
  var selectedElements = useStoreState(function(state) {
    return state.selectedElements;
  });
  var nodesConnectable = useStoreState(function(state) {
    return state.nodesConnectable;
  });
  var elementsSelectable = useStoreState(function(state) {
    return state.elementsSelectable;
  });
  var width2 = useStoreState(function(state) {
    return state.width;
  });
  var height = useStoreState(function(state) {
    return state.height;
  });
  if (!width2) {
    return null;
  }
  var connectionLineType = props.connectionLineType, arrowHeadColor = props.arrowHeadColor, connectionLineStyle = props.connectionLineStyle, connectionLineComponent = props.connectionLineComponent, onlyRenderVisibleElements = props.onlyRenderVisibleElements;
  var transformStyle = "translate(".concat(transform3[0], ",").concat(transform3[1], ") scale(").concat(transform3[2], ")");
  var renderConnectionLine = connectionNodeId && connectionHandleType;
  return /* @__PURE__ */ react.createElement("svg", {
    width: width2,
    height,
    className: "react-flow__edges"
  }, /* @__PURE__ */ react.createElement(MarkerDefinitions, {
    color: arrowHeadColor
  }), /* @__PURE__ */ react.createElement("g", {
    transform: transformStyle
  }, edges.map(function(edge) {
    return /* @__PURE__ */ react.createElement(Edge, {
      key: edge.id,
      edge,
      props,
      nodes,
      selectedElements,
      elementsSelectable,
      transform: transform3,
      width: width2,
      height,
      onlyRenderVisibleElements
    });
  }), renderConnectionLine && /* @__PURE__ */ react.createElement(ConnectionLine, {
    nodes,
    connectionNodeId,
    connectionHandleId,
    connectionHandleType,
    connectionPositionX: connectionPosition.x,
    connectionPositionY: connectionPosition.y,
    transform: transform3,
    connectionLineStyle,
    connectionLineType,
    isConnectable: nodesConnectable,
    CustomConnectionLineComponent: connectionLineComponent
  })));
};
EdgeRenderer.displayName = "EdgeRenderer";
var EdgeRenderer$1 = /* @__PURE__ */ react.memo(EdgeRenderer);
var DEFAULT_PADDING = 0.1;
var initialZoomPanHelper = {
  zoomIn: function zoomIn() {
  },
  zoomOut: function zoomOut() {
  },
  zoomTo: function zoomTo(_23) {
  },
  transform: function transform(_23) {
  },
  fitView: function fitView() {
  },
  setCenter: function setCenter(_23, __) {
  },
  fitBounds: function fitBounds(_23) {
  },
  project: function project(position2) {
    return position2;
  },
  initialized: false
};
var getTransition = function getTransition2(selection2) {
  var duration = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
  return selection2.transition().duration(duration);
};
var useZoomPanHelper = function useZoomPanHelper2() {
  var store2 = useStore();
  var d3Zoom = useStoreState(function(s2) {
    return s2.d3Zoom;
  });
  var d3Selection = useStoreState(function(s2) {
    return s2.d3Selection;
  });
  var zoomPanHelperFunctions = react.useMemo(function() {
    if (d3Selection && d3Zoom) {
      return {
        zoomIn: function zoomIn2(duration) {
          return d3Zoom.scaleBy(getTransition(d3Selection, duration), 1.2);
        },
        zoomOut: function zoomOut2(duration) {
          return d3Zoom.scaleBy(getTransition(d3Selection, duration), 1 / 1.2);
        },
        zoomTo: function zoomTo2(zoomLevel, duration) {
          return d3Zoom.scaleTo(getTransition(d3Selection, duration), zoomLevel);
        },
        transform: function transform3(_transform) {
          var nextTransform = identity2.translate(_transform.x, _transform.y).scale(_transform.zoom);
          d3Zoom.transform(getTransition(d3Selection), nextTransform);
        },
        fitView: function fitView2() {
          var _options$minZoom, _options$maxZoom, _options$padding;
          var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {
            padding: DEFAULT_PADDING,
            includeHiddenNodes: false,
            duration: 0
          };
          var _store$getState = store2.getState(), nodes = _store$getState.nodes, width2 = _store$getState.width, height = _store$getState.height, minZoom = _store$getState.minZoom, maxZoom = _store$getState.maxZoom;
          if (!nodes.length) {
            return;
          }
          var bounds = getRectOfNodes(options.includeHiddenNodes ? nodes : nodes.filter(function(node) {
            return !node.isHidden;
          }));
          var _getTransformForBound = getTransformForBounds(bounds, width2, height, (_options$minZoom = options.minZoom) !== null && _options$minZoom !== void 0 ? _options$minZoom : minZoom, (_options$maxZoom = options.maxZoom) !== null && _options$maxZoom !== void 0 ? _options$maxZoom : maxZoom, (_options$padding = options.padding) !== null && _options$padding !== void 0 ? _options$padding : DEFAULT_PADDING), _getTransformForBound2 = _slicedToArray$1(_getTransformForBound, 3), x2 = _getTransformForBound2[0], y3 = _getTransformForBound2[1], zoom2 = _getTransformForBound2[2];
          var transform3 = identity2.translate(x2, y3).scale(zoom2);
          d3Zoom.transform(getTransition(d3Selection, options.duration), transform3);
        },
        setCenter: function setCenter2(x2, y3, zoom2, duration) {
          var _store$getState2 = store2.getState(), width2 = _store$getState2.width, height = _store$getState2.height, maxZoom = _store$getState2.maxZoom;
          var nextZoom = typeof zoom2 !== "undefined" ? zoom2 : maxZoom;
          var centerX = width2 / 2 - x2 * nextZoom;
          var centerY = height / 2 - y3 * nextZoom;
          var transform3 = identity2.translate(centerX, centerY).scale(nextZoom);
          d3Zoom.transform(getTransition(d3Selection, duration), transform3);
        },
        fitBounds: function fitBounds2(bounds) {
          var padding = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_PADDING;
          var duration = arguments.length > 2 ? arguments[2] : void 0;
          var _store$getState3 = store2.getState(), width2 = _store$getState3.width, height = _store$getState3.height, minZoom = _store$getState3.minZoom, maxZoom = _store$getState3.maxZoom;
          var _getTransformForBound3 = getTransformForBounds(bounds, width2, height, minZoom, maxZoom, padding), _getTransformForBound4 = _slicedToArray$1(_getTransformForBound3, 3), x2 = _getTransformForBound4[0], y3 = _getTransformForBound4[1], zoom2 = _getTransformForBound4[2];
          var transform3 = identity2.translate(x2, y3).scale(zoom2);
          d3Zoom.transform(getTransition(d3Selection, duration), transform3);
        },
        project: function project2(position2) {
          var _store$getState4 = store2.getState(), transform3 = _store$getState4.transform, snapToGrid2 = _store$getState4.snapToGrid, snapGrid = _store$getState4.snapGrid;
          return pointToRendererPoint(position2, transform3, snapToGrid2, snapGrid);
        },
        initialized: true
      };
    }
    return initialZoomPanHelper;
  }, [d3Zoom, d3Selection]);
  return zoomPanHelperFunctions;
};
var GraphView = function GraphView2(_ref) {
  var nodeTypes = _ref.nodeTypes, edgeTypes = _ref.edgeTypes, onMove = _ref.onMove, onMoveStart = _ref.onMoveStart, onMoveEnd = _ref.onMoveEnd, onLoad = _ref.onLoad, onElementClick = _ref.onElementClick, onNodeDoubleClick = _ref.onNodeDoubleClick, onEdgeDoubleClick = _ref.onEdgeDoubleClick, onNodeMouseEnter = _ref.onNodeMouseEnter, onNodeMouseMove = _ref.onNodeMouseMove, onNodeMouseLeave = _ref.onNodeMouseLeave, onNodeContextMenu = _ref.onNodeContextMenu, onNodeDragStart = _ref.onNodeDragStart, onNodeDrag = _ref.onNodeDrag, onNodeDragStop = _ref.onNodeDragStop, onSelectionDragStart = _ref.onSelectionDragStart, onSelectionDrag = _ref.onSelectionDrag, onSelectionDragStop = _ref.onSelectionDragStop, onSelectionContextMenu = _ref.onSelectionContextMenu, connectionMode = _ref.connectionMode, connectionLineType = _ref.connectionLineType, connectionLineStyle = _ref.connectionLineStyle, connectionLineComponent = _ref.connectionLineComponent, selectionKeyCode = _ref.selectionKeyCode, multiSelectionKeyCode = _ref.multiSelectionKeyCode, zoomActivationKeyCode = _ref.zoomActivationKeyCode, onElementsRemove = _ref.onElementsRemove, deleteKeyCode = _ref.deleteKeyCode, onConnect = _ref.onConnect, onConnectStart = _ref.onConnectStart, onConnectStop = _ref.onConnectStop, onConnectEnd = _ref.onConnectEnd, snapToGrid2 = _ref.snapToGrid, snapGrid = _ref.snapGrid, onlyRenderVisibleElements = _ref.onlyRenderVisibleElements, nodesDraggable = _ref.nodesDraggable, nodesConnectable = _ref.nodesConnectable, elementsSelectable = _ref.elementsSelectable, selectNodesOnDrag = _ref.selectNodesOnDrag, minZoom = _ref.minZoom, maxZoom = _ref.maxZoom, defaultZoom = _ref.defaultZoom, defaultPosition = _ref.defaultPosition, translateExtent = _ref.translateExtent, preventScrolling = _ref.preventScrolling, nodeExtent = _ref.nodeExtent, arrowHeadColor = _ref.arrowHeadColor, markerEndId = _ref.markerEndId, zoomOnScroll = _ref.zoomOnScroll, zoomOnPinch = _ref.zoomOnPinch, panOnScroll = _ref.panOnScroll, panOnScrollSpeed = _ref.panOnScrollSpeed, panOnScrollMode = _ref.panOnScrollMode, zoomOnDoubleClick = _ref.zoomOnDoubleClick, paneMoveable = _ref.paneMoveable, onPaneClick = _ref.onPaneClick, onPaneScroll = _ref.onPaneScroll, onPaneContextMenu = _ref.onPaneContextMenu, onEdgeUpdate = _ref.onEdgeUpdate, onEdgeContextMenu = _ref.onEdgeContextMenu, onEdgeMouseEnter = _ref.onEdgeMouseEnter, onEdgeMouseMove = _ref.onEdgeMouseMove, onEdgeMouseLeave = _ref.onEdgeMouseLeave, edgeUpdaterRadius = _ref.edgeUpdaterRadius, onEdgeUpdateStart = _ref.onEdgeUpdateStart, onEdgeUpdateEnd = _ref.onEdgeUpdateEnd;
  var isInitialized = react.useRef(false);
  var setOnConnect3 = useStoreActions(function(actions2) {
    return actions2.setOnConnect;
  });
  var setOnConnectStart3 = useStoreActions(function(actions2) {
    return actions2.setOnConnectStart;
  });
  var setOnConnectStop3 = useStoreActions(function(actions2) {
    return actions2.setOnConnectStop;
  });
  var setOnConnectEnd3 = useStoreActions(function(actions2) {
    return actions2.setOnConnectEnd;
  });
  var setSnapGrid3 = useStoreActions(function(actions2) {
    return actions2.setSnapGrid;
  });
  var setSnapToGrid3 = useStoreActions(function(actions2) {
    return actions2.setSnapToGrid;
  });
  var setNodesDraggable3 = useStoreActions(function(actions2) {
    return actions2.setNodesDraggable;
  });
  var setNodesConnectable3 = useStoreActions(function(actions2) {
    return actions2.setNodesConnectable;
  });
  var setElementsSelectable3 = useStoreActions(function(actions2) {
    return actions2.setElementsSelectable;
  });
  var setMinZoom3 = useStoreActions(function(actions2) {
    return actions2.setMinZoom;
  });
  var setMaxZoom3 = useStoreActions(function(actions2) {
    return actions2.setMaxZoom;
  });
  var setTranslateExtent3 = useStoreActions(function(actions2) {
    return actions2.setTranslateExtent;
  });
  var setNodeExtent3 = useStoreActions(function(actions2) {
    return actions2.setNodeExtent;
  });
  var setConnectionMode3 = useStoreActions(function(actions2) {
    return actions2.setConnectionMode;
  });
  var currentStore = useStore();
  var _useZoomPanHelper = useZoomPanHelper(), zoomIn2 = _useZoomPanHelper.zoomIn, zoomOut2 = _useZoomPanHelper.zoomOut, zoomTo2 = _useZoomPanHelper.zoomTo, transform3 = _useZoomPanHelper.transform, _fitView = _useZoomPanHelper.fitView, initialized = _useZoomPanHelper.initialized;
  react.useEffect(function() {
    if (!isInitialized.current && initialized) {
      if (onLoad) {
        onLoad({
          fitView: function fitView2() {
            var params = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {
              padding: 0.1
            };
            return _fitView(params);
          },
          zoomIn: zoomIn2,
          zoomOut: zoomOut2,
          zoomTo: zoomTo2,
          setTransform: transform3,
          project: onLoadProject(currentStore),
          getElements: onLoadGetElements(currentStore),
          toObject: onLoadToObject(currentStore)
        });
      }
      isInitialized.current = true;
    }
  }, [onLoad, zoomIn2, zoomOut2, zoomTo2, transform3, _fitView, initialized]);
  react.useEffect(function() {
    if (onConnect) {
      setOnConnect3(onConnect);
    }
  }, [onConnect]);
  react.useEffect(function() {
    if (onConnectStart) {
      setOnConnectStart3(onConnectStart);
    }
  }, [onConnectStart]);
  react.useEffect(function() {
    if (onConnectStop) {
      setOnConnectStop3(onConnectStop);
    }
  }, [onConnectStop]);
  react.useEffect(function() {
    if (onConnectEnd) {
      setOnConnectEnd3(onConnectEnd);
    }
  }, [onConnectEnd]);
  react.useEffect(function() {
    if (typeof snapToGrid2 !== "undefined") {
      setSnapToGrid3(snapToGrid2);
    }
  }, [snapToGrid2]);
  react.useEffect(function() {
    if (typeof snapGrid !== "undefined") {
      setSnapGrid3(snapGrid);
    }
  }, [snapGrid]);
  react.useEffect(function() {
    if (typeof nodesDraggable !== "undefined") {
      setNodesDraggable3(nodesDraggable);
    }
  }, [nodesDraggable]);
  react.useEffect(function() {
    if (typeof nodesConnectable !== "undefined") {
      setNodesConnectable3(nodesConnectable);
    }
  }, [nodesConnectable]);
  react.useEffect(function() {
    if (typeof elementsSelectable !== "undefined") {
      setElementsSelectable3(elementsSelectable);
    }
  }, [elementsSelectable]);
  react.useEffect(function() {
    if (typeof minZoom !== "undefined") {
      setMinZoom3(minZoom);
    }
  }, [minZoom]);
  react.useEffect(function() {
    if (typeof maxZoom !== "undefined") {
      setMaxZoom3(maxZoom);
    }
  }, [maxZoom]);
  react.useEffect(function() {
    if (typeof translateExtent !== "undefined") {
      setTranslateExtent3(translateExtent);
    }
  }, [translateExtent]);
  react.useEffect(function() {
    if (typeof nodeExtent !== "undefined") {
      setNodeExtent3(nodeExtent);
    }
  }, [nodeExtent]);
  react.useEffect(function() {
    if (typeof connectionMode !== "undefined") {
      setConnectionMode3(connectionMode);
    }
  }, [connectionMode]);
  return /* @__PURE__ */ react.createElement(FlowRenderer$1, {
    onPaneClick,
    onPaneContextMenu,
    onPaneScroll,
    onElementsRemove,
    deleteKeyCode,
    selectionKeyCode,
    multiSelectionKeyCode,
    zoomActivationKeyCode,
    elementsSelectable,
    onMove,
    onMoveStart,
    onMoveEnd,
    zoomOnScroll,
    zoomOnPinch,
    zoomOnDoubleClick,
    panOnScroll,
    panOnScrollSpeed,
    panOnScrollMode,
    paneMoveable,
    defaultPosition,
    defaultZoom,
    translateExtent,
    onSelectionDragStart,
    onSelectionDrag,
    onSelectionDragStop,
    onSelectionContextMenu,
    preventScrolling
  }, /* @__PURE__ */ react.createElement(NodeRenderer$1, {
    nodeTypes,
    onElementClick,
    onNodeDoubleClick,
    onNodeMouseEnter,
    onNodeMouseMove,
    onNodeMouseLeave,
    onNodeContextMenu,
    onNodeDragStop,
    onNodeDrag,
    onNodeDragStart,
    selectNodesOnDrag,
    snapToGrid: snapToGrid2,
    snapGrid,
    onlyRenderVisibleElements
  }), /* @__PURE__ */ react.createElement(EdgeRenderer$1, {
    edgeTypes,
    onElementClick,
    onEdgeDoubleClick,
    connectionLineType,
    connectionLineStyle,
    connectionLineComponent,
    connectionMode,
    arrowHeadColor,
    markerEndId,
    onEdgeUpdate,
    onlyRenderVisibleElements,
    onEdgeContextMenu,
    onEdgeMouseEnter,
    onEdgeMouseMove,
    onEdgeMouseLeave,
    onEdgeUpdateStart,
    onEdgeUpdateEnd,
    edgeUpdaterRadius
  }));
};
GraphView.displayName = "GraphView";
var GraphView$1 = /* @__PURE__ */ react.memo(GraphView);
var ElementUpdater = function ElementUpdater2(_ref) {
  var elements = _ref.elements;
  var setElements3 = useStoreActions(function(actions2) {
    return actions2.setElements;
  });
  react.useEffect(function() {
    setElements3(elements);
  }, [elements]);
  return null;
};
var NodeIdContext = /* @__PURE__ */ react.createContext(null);
var Provider2 = NodeIdContext.Provider;
NodeIdContext.Consumer;
var _excluded$2 = ["type", "position", "isValidConnection", "isConnectable", "id", "onConnect", "children", "className"];
function ownKeys$7(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$7(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$7(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$7(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var alwaysValid = function alwaysValid2() {
  return true;
};
var Handle = /* @__PURE__ */ react.forwardRef(function(_ref, ref) {
  var _ref$type = _ref.type, type = _ref$type === void 0 ? "source" : _ref$type, _ref$position = _ref.position, position2 = _ref$position === void 0 ? Position2.Top : _ref$position, _ref$isValidConnectio = _ref.isValidConnection, isValidConnection = _ref$isValidConnectio === void 0 ? alwaysValid : _ref$isValidConnectio, _ref$isConnectable = _ref.isConnectable, isConnectable = _ref$isConnectable === void 0 ? true : _ref$isConnectable, id3 = _ref.id, onConnect = _ref.onConnect, children2 = _ref.children, className = _ref.className, rest = _objectWithoutProperties3(_ref, _excluded$2);
  var nodeId = react.useContext(NodeIdContext);
  var setPosition = useStoreActions(function(actions2) {
    return actions2.setConnectionPosition;
  });
  var setConnectionNodeId3 = useStoreActions(function(actions2) {
    return actions2.setConnectionNodeId;
  });
  var onConnectAction = useStoreState(function(state) {
    return state.onConnect;
  });
  var onConnectStart = useStoreState(function(state) {
    return state.onConnectStart;
  });
  var onConnectStop = useStoreState(function(state) {
    return state.onConnectStop;
  });
  var onConnectEnd = useStoreState(function(state) {
    return state.onConnectEnd;
  });
  var connectionMode = useStoreState(function(state) {
    return state.connectionMode;
  });
  var handleId = id3 || null;
  var isTarget = type === "target";
  var onConnectExtended = react.useCallback(function(params) {
    onConnectAction === null || onConnectAction === void 0 ? void 0 : onConnectAction(params);
    onConnect === null || onConnect === void 0 ? void 0 : onConnect(params);
  }, [onConnectAction, onConnect]);
  var onMouseDownHandler = react.useCallback(function(event) {
    onMouseDown2(event, handleId, nodeId, setConnectionNodeId3, setPosition, onConnectExtended, isTarget, isValidConnection, connectionMode, void 0, void 0, onConnectStart, onConnectStop, onConnectEnd);
  }, [handleId, nodeId, setConnectionNodeId3, setPosition, onConnectExtended, isTarget, isValidConnection, connectionMode, onConnectStart, onConnectStop, onConnectEnd]);
  var handleClasses = cc2(["react-flow__handle", "react-flow__handle-".concat(position2), "nodrag", className, {
    source: !isTarget,
    target: isTarget,
    connectable: isConnectable
  }]);
  return /* @__PURE__ */ react.createElement("div", _objectSpread$7({
    "data-handleid": handleId,
    "data-nodeid": nodeId,
    "data-handlepos": position2,
    className: handleClasses,
    onMouseDown: onMouseDownHandler,
    ref
  }, rest), children2);
});
Handle.displayName = "Handle";
var Handle$1 = /* @__PURE__ */ react.memo(Handle);
var DefaultNode = function DefaultNode2(_ref) {
  var data2 = _ref.data, isConnectable = _ref.isConnectable, _ref$targetPosition = _ref.targetPosition, targetPosition = _ref$targetPosition === void 0 ? Position2.Top : _ref$targetPosition, _ref$sourcePosition = _ref.sourcePosition, sourcePosition = _ref$sourcePosition === void 0 ? Position2.Bottom : _ref$sourcePosition;
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Handle$1, {
    type: "target",
    position: targetPosition,
    isConnectable
  }), data2.label, /* @__PURE__ */ react.createElement(Handle$1, {
    type: "source",
    position: sourcePosition,
    isConnectable
  }));
};
DefaultNode.displayName = "DefaultNode";
var DefaultNode$1 = /* @__PURE__ */ react.memo(DefaultNode);
var InputNode = function InputNode2(_ref) {
  var data2 = _ref.data, isConnectable = _ref.isConnectable, _ref$sourcePosition = _ref.sourcePosition, sourcePosition = _ref$sourcePosition === void 0 ? Position2.Bottom : _ref$sourcePosition;
  return /* @__PURE__ */ react.createElement(react.Fragment, null, data2.label, /* @__PURE__ */ react.createElement(Handle$1, {
    type: "source",
    position: sourcePosition,
    isConnectable
  }));
};
InputNode.displayName = "InputNode";
var InputNode$1 = /* @__PURE__ */ react.memo(InputNode);
var OutputNode = function OutputNode2(_ref) {
  var data2 = _ref.data, isConnectable = _ref.isConnectable, _ref$targetPosition = _ref.targetPosition, targetPosition = _ref$targetPosition === void 0 ? Position2.Top : _ref$targetPosition;
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Handle$1, {
    type: "target",
    position: targetPosition,
    isConnectable
  }), data2.label);
};
OutputNode.displayName = "OutputNode";
var OutputNode$1 = /* @__PURE__ */ react.memo(OutputNode);
function ownKeys$62(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$62(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$62(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$62(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var wrapNode = function(NodeComponent) {
  var NodeWrapper = function NodeWrapper2(_ref) {
    var id3 = _ref.id, type = _ref.type, data2 = _ref.data, scale = _ref.scale, xPos = _ref.xPos, yPos = _ref.yPos, selected = _ref.selected, onClick = _ref.onClick, onMouseEnter = _ref.onMouseEnter, onMouseMove = _ref.onMouseMove, onMouseLeave = _ref.onMouseLeave, onContextMenu = _ref.onContextMenu, onNodeDoubleClick = _ref.onNodeDoubleClick, onNodeDragStart = _ref.onNodeDragStart, onNodeDrag = _ref.onNodeDrag, onNodeDragStop = _ref.onNodeDragStop, style = _ref.style, className = _ref.className, isDraggable = _ref.isDraggable, isSelectable = _ref.isSelectable, isConnectable = _ref.isConnectable, selectNodesOnDrag = _ref.selectNodesOnDrag, sourcePosition = _ref.sourcePosition, targetPosition = _ref.targetPosition, isHidden3 = _ref.isHidden, isInitialized = _ref.isInitialized, snapToGrid2 = _ref.snapToGrid, snapGrid = _ref.snapGrid, isDragging = _ref.isDragging, resizeObserver = _ref.resizeObserver, dragHandle = _ref.dragHandle;
    var updateNodeDimensions3 = useStoreActions(function(actions2) {
      return actions2.updateNodeDimensions;
    });
    var addSelectedElements3 = useStoreActions(function(actions2) {
      return actions2.addSelectedElements;
    });
    var updateNodePosDiff3 = useStoreActions(function(actions2) {
      return actions2.updateNodePosDiff;
    });
    var unsetNodesSelection3 = useStoreActions(function(actions2) {
      return actions2.unsetNodesSelection;
    });
    var nodeElement = react.useRef(null);
    var node = react.useMemo(function() {
      return {
        id: id3,
        type,
        position: {
          x: xPos,
          y: yPos
        },
        data: data2
      };
    }, [id3, type, xPos, yPos, data2]);
    var grid2 = react.useMemo(function() {
      return snapToGrid2 ? snapGrid : [1, 1];
    }, [snapToGrid2, snapGrid]);
    var nodeStyle = react.useMemo(function() {
      return _objectSpread$62({
        zIndex: selected ? 10 : 3,
        transform: "translate(".concat(xPos, "px,").concat(yPos, "px)"),
        pointerEvents: isSelectable || isDraggable || onClick || onMouseEnter || onMouseMove || onMouseLeave ? "all" : "none",
        opacity: isInitialized ? 1 : 0
      }, style);
    }, [selected, xPos, yPos, isSelectable, isDraggable, onClick, isInitialized, style, onMouseEnter, onMouseMove, onMouseLeave]);
    var onMouseEnterHandler = react.useMemo(function() {
      if (!onMouseEnter || isDragging) {
        return;
      }
      return function(event) {
        return onMouseEnter(event, node);
      };
    }, [onMouseEnter, isDragging, node]);
    var onMouseMoveHandler = react.useMemo(function() {
      if (!onMouseMove || isDragging) {
        return;
      }
      return function(event) {
        return onMouseMove(event, node);
      };
    }, [onMouseMove, isDragging, node]);
    var onMouseLeaveHandler = react.useMemo(function() {
      if (!onMouseLeave || isDragging) {
        return;
      }
      return function(event) {
        return onMouseLeave(event, node);
      };
    }, [onMouseLeave, isDragging, node]);
    var onContextMenuHandler = react.useMemo(function() {
      if (!onContextMenu) {
        return;
      }
      return function(event) {
        return onContextMenu(event, node);
      };
    }, [onContextMenu, node]);
    var onSelectNodeHandler = react.useCallback(function(event) {
      if (!isDraggable) {
        if (isSelectable) {
          unsetNodesSelection3();
          if (!selected) {
            addSelectedElements3(node);
          }
        }
        onClick === null || onClick === void 0 ? void 0 : onClick(event, node);
      }
    }, [isSelectable, selected, isDraggable, onClick, node]);
    var onDragStart = react.useCallback(function(event) {
      onNodeDragStart === null || onNodeDragStart === void 0 ? void 0 : onNodeDragStart(event, node);
      if (selectNodesOnDrag && isSelectable) {
        unsetNodesSelection3();
        if (!selected) {
          addSelectedElements3(node);
        }
      } else if (!selectNodesOnDrag && !selected && isSelectable) {
        unsetNodesSelection3();
        addSelectedElements3([]);
      }
    }, [node, selected, selectNodesOnDrag, isSelectable, onNodeDragStart]);
    var onDrag2 = react.useCallback(function(event, draggableData) {
      if (onNodeDrag) {
        node.position.x += draggableData.deltaX;
        node.position.y += draggableData.deltaY;
        onNodeDrag(event, node);
      }
      updateNodePosDiff3({
        id: id3,
        diff: {
          x: draggableData.deltaX,
          y: draggableData.deltaY
        },
        isDragging: true
      });
    }, [id3, node, onNodeDrag]);
    var onDragStop = react.useCallback(function(event) {
      if (!isDragging) {
        if (isSelectable && !selectNodesOnDrag && !selected) {
          addSelectedElements3(node);
        }
        onClick === null || onClick === void 0 ? void 0 : onClick(event, node);
        return;
      }
      updateNodePosDiff3({
        id: node.id,
        isDragging: false
      });
      onNodeDragStop === null || onNodeDragStop === void 0 ? void 0 : onNodeDragStop(event, node);
    }, [node, isSelectable, selectNodesOnDrag, onClick, onNodeDragStop, isDragging, selected]);
    var onNodeDoubleClickHandler = react.useCallback(function(event) {
      onNodeDoubleClick === null || onNodeDoubleClick === void 0 ? void 0 : onNodeDoubleClick(event, node);
    }, [node, onNodeDoubleClick]);
    react.useLayoutEffect(function() {
      if (nodeElement.current && !isHidden3) {
        updateNodeDimensions3([{
          id: id3,
          nodeElement: nodeElement.current,
          forceUpdate: true
        }]);
      }
    }, [id3, isHidden3, sourcePosition, targetPosition]);
    react.useEffect(function() {
      if (nodeElement.current) {
        var currNode = nodeElement.current;
        resizeObserver === null || resizeObserver === void 0 ? void 0 : resizeObserver.observe(currNode);
        return function() {
          return resizeObserver === null || resizeObserver === void 0 ? void 0 : resizeObserver.unobserve(currNode);
        };
      }
    }, []);
    if (isHidden3) {
      return null;
    }
    var nodeClasses = cc2(["react-flow__node", "react-flow__node-".concat(type), className, {
      selected,
      selectable: isSelectable
    }]);
    return /* @__PURE__ */ react.createElement(DraggableCore_1, {
      onStart: onDragStart,
      onDrag: onDrag2,
      onStop: onDragStop,
      scale,
      disabled: !isDraggable,
      cancel: ".nodrag",
      nodeRef: nodeElement,
      grid: grid2,
      enableUserSelectHack: false,
      handle: dragHandle
    }, /* @__PURE__ */ react.createElement("div", {
      className: nodeClasses,
      ref: nodeElement,
      style: nodeStyle,
      onMouseEnter: onMouseEnterHandler,
      onMouseMove: onMouseMoveHandler,
      onMouseLeave: onMouseLeaveHandler,
      onContextMenu: onContextMenuHandler,
      onClick: onSelectNodeHandler,
      onDoubleClick: onNodeDoubleClickHandler,
      "data-id": id3
    }, /* @__PURE__ */ react.createElement(Provider2, {
      value: id3
    }, /* @__PURE__ */ react.createElement(NodeComponent, {
      id: id3,
      data: data2,
      type,
      xPos,
      yPos,
      selected,
      isConnectable,
      sourcePosition,
      targetPosition,
      isDragging,
      dragHandle
    }))));
  };
  NodeWrapper.displayName = "NodeWrapper";
  return /* @__PURE__ */ react.memo(NodeWrapper);
};
function ownKeys$52(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$52(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$52(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$52(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
function createNodeTypes(nodeTypes) {
  var standardTypes = {
    input: wrapNode(nodeTypes.input || InputNode$1),
    default: wrapNode(nodeTypes["default"] || DefaultNode$1),
    output: wrapNode(nodeTypes.output || OutputNode$1)
  };
  var wrappedTypes = {};
  var specialTypes = Object.keys(nodeTypes).filter(function(k2) {
    return !["input", "default", "output"].includes(k2);
  }).reduce(function(res, key) {
    res[key] = wrapNode(nodeTypes[key] || DefaultNode$1);
    return res;
  }, wrappedTypes);
  return _objectSpread$52(_objectSpread$52({}, standardTypes), specialTypes);
}
var SelectionListener = function(_ref) {
  var onSelectionChange = _ref.onSelectionChange;
  var selectedElements = useStoreState(function(s2) {
    return s2.selectedElements;
  });
  react.useEffect(function() {
    onSelectionChange(selectedElements);
  }, [selectedElements]);
  return null;
};
var fastDeepEqual = function equal(a2, b2) {
  if (a2 === b2)
    return true;
  if (a2 && b2 && typeof a2 == "object" && typeof b2 == "object") {
    if (a2.constructor !== b2.constructor)
      return false;
    var length, i3, keys2;
    if (Array.isArray(a2)) {
      length = a2.length;
      if (length != b2.length)
        return false;
      for (i3 = length; i3-- !== 0; )
        if (!equal(a2[i3], b2[i3]))
          return false;
      return true;
    }
    if (a2.constructor === RegExp)
      return a2.source === b2.source && a2.flags === b2.flags;
    if (a2.valueOf !== Object.prototype.valueOf)
      return a2.valueOf() === b2.valueOf();
    if (a2.toString !== Object.prototype.toString)
      return a2.toString() === b2.toString();
    keys2 = Object.keys(a2);
    length = keys2.length;
    if (length !== Object.keys(b2).length)
      return false;
    for (i3 = length; i3-- !== 0; )
      if (!Object.prototype.hasOwnProperty.call(b2, keys2[i3]))
        return false;
    for (i3 = length; i3-- !== 0; ) {
      var key = keys2[i3];
      if (!equal(a2[key], b2[key]))
        return false;
    }
    return true;
  }
  return a2 !== a2 && b2 !== b2;
};
function ownKeys$42(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$42(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$42(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$42(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var getHandleBounds = function getHandleBounds2(nodeElement, scale) {
  var bounds = nodeElement.getBoundingClientRect();
  return {
    source: getHandleBoundsByHandleType(".source", nodeElement, bounds, scale),
    target: getHandleBoundsByHandleType(".target", nodeElement, bounds, scale)
  };
};
var getHandleBoundsByHandleType = function getHandleBoundsByHandleType2(selector2, nodeElement, parentBounds, k2) {
  var handles = nodeElement.querySelectorAll(selector2);
  if (!handles || !handles.length) {
    return null;
  }
  var handlesArray = Array.from(handles);
  return handlesArray.map(function(handle2) {
    var bounds = handle2.getBoundingClientRect();
    var dimensions = getDimensions(handle2);
    var handleId = handle2.getAttribute("data-handleid");
    var handlePosition = handle2.getAttribute("data-handlepos");
    return _objectSpread$42({
      id: handleId,
      position: handlePosition,
      x: (bounds.left - parentBounds.left) / k2,
      y: (bounds.top - parentBounds.top) / k2
    }, dimensions);
  });
};
function ownKeys$32(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$32(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$32(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$32(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
function reactFlowReducer() {
  var state = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : initialState2;
  var action = arguments.length > 1 ? arguments[1] : void 0;
  switch (action.type) {
    case SET_ELEMENTS: {
      var propElements = action.payload;
      var nextElements = {
        nextNodes: [],
        nextEdges: []
      };
      var _propElements$reduce = propElements.reduce(function(res, propElement) {
        if (isNode(propElement)) {
          var storeNode = state.nodes.find(function(node) {
            return node.id === propElement.id;
          });
          if (storeNode) {
            var updatedNode = _objectSpread$32(_objectSpread$32({}, storeNode), propElement);
            if (storeNode.position.x !== propElement.position.x || storeNode.position.y !== propElement.position.y) {
              updatedNode.__rf.position = propElement.position;
            }
            if (typeof propElement.type !== "undefined" && propElement.type !== storeNode.type) {
              updatedNode.__rf.width = null;
            }
            res.nextNodes.push(updatedNode);
          } else {
            res.nextNodes.push(parseNode(propElement, state.nodeExtent));
          }
        } else if (isEdge3(propElement)) {
          var storeEdge = state.edges.find(function(se2) {
            return se2.id === propElement.id;
          });
          if (storeEdge) {
            res.nextEdges.push(_objectSpread$32(_objectSpread$32({}, storeEdge), propElement));
          } else {
            res.nextEdges.push(parseEdge(propElement));
          }
        }
        return res;
      }, nextElements), nextNodes = _propElements$reduce.nextNodes, nextEdges = _propElements$reduce.nextEdges;
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        nodes: nextNodes,
        edges: nextEdges
      });
    }
    case UPDATE_NODE_DIMENSIONS: {
      var updatedNodes = state.nodes.map(function(node) {
        var update = action.payload.find(function(u) {
          return u.id === node.id;
        });
        if (update) {
          var dimensions = getDimensions(update.nodeElement);
          var doUpdate = dimensions.width && dimensions.height && (node.__rf.width !== dimensions.width || node.__rf.height !== dimensions.height || update.forceUpdate);
          if (doUpdate) {
            var handleBounds = getHandleBounds(update.nodeElement, state.transform[2]);
            return _objectSpread$32(_objectSpread$32({}, node), {}, {
              __rf: _objectSpread$32(_objectSpread$32(_objectSpread$32({}, node.__rf), dimensions), {}, {
                handleBounds
              })
            });
          }
        }
        return node;
      });
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        nodes: updatedNodes
      });
    }
    case UPDATE_NODE_POS: {
      var _action$payload = action.payload, id3 = _action$payload.id, pos = _action$payload.pos;
      var position2 = pos;
      if (state.snapToGrid) {
        var _state$snapGrid = _slicedToArray$1(state.snapGrid, 2), gridSizeX = _state$snapGrid[0], gridSizeY = _state$snapGrid[1];
        position2 = {
          x: gridSizeX * Math.round(pos.x / gridSizeX),
          y: gridSizeY * Math.round(pos.y / gridSizeY)
        };
      }
      var _nextNodes = state.nodes.map(function(node) {
        if (node.id === id3) {
          return _objectSpread$32(_objectSpread$32({}, node), {}, {
            __rf: _objectSpread$32(_objectSpread$32({}, node.__rf), {}, {
              position: position2
            })
          });
        }
        return node;
      });
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        nodes: _nextNodes
      });
    }
    case UPDATE_NODE_POS_DIFF: {
      var _action$payload2 = action.payload, _id = _action$payload2.id, diff = _action$payload2.diff, isDragging = _action$payload2.isDragging;
      var _nextNodes2 = state.nodes.map(function(node) {
        var _state$selectedElemen;
        if (_id === node.id || (_state$selectedElemen = state.selectedElements) !== null && _state$selectedElemen !== void 0 && _state$selectedElemen.find(function(sNode) {
          return sNode.id === node.id;
        })) {
          var updatedNode = _objectSpread$32(_objectSpread$32({}, node), {}, {
            __rf: _objectSpread$32(_objectSpread$32({}, node.__rf), {}, {
              isDragging
            })
          });
          if (diff) {
            updatedNode.__rf.position = {
              x: node.__rf.position.x + diff.x,
              y: node.__rf.position.y + diff.y
            };
          }
          return updatedNode;
        }
        return node;
      });
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        nodes: _nextNodes2
      });
    }
    case SET_USER_SELECTION: {
      var mousePos = action.payload;
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        selectionActive: true,
        userSelectionRect: {
          width: 0,
          height: 0,
          startX: mousePos.x,
          startY: mousePos.y,
          x: mousePos.x,
          y: mousePos.y,
          draw: true
        }
      });
    }
    case UPDATE_USER_SELECTION: {
      var _state$userSelectionR, _state$userSelectionR2;
      var _mousePos = action.payload;
      var startX = (_state$userSelectionR = state.userSelectionRect.startX) !== null && _state$userSelectionR !== void 0 ? _state$userSelectionR : 0;
      var startY = (_state$userSelectionR2 = state.userSelectionRect.startY) !== null && _state$userSelectionR2 !== void 0 ? _state$userSelectionR2 : 0;
      var nextUserSelectRect = _objectSpread$32(_objectSpread$32({}, state.userSelectionRect), {}, {
        x: _mousePos.x < startX ? _mousePos.x : state.userSelectionRect.x,
        y: _mousePos.y < startY ? _mousePos.y : state.userSelectionRect.y,
        width: Math.abs(_mousePos.x - startX),
        height: Math.abs(_mousePos.y - startY)
      });
      var selectedNodes = getNodesInside(state.nodes, nextUserSelectRect, state.transform, false, true);
      var selectedEdges = getConnectedEdges(selectedNodes, state.edges);
      var nextSelectedElements = [].concat(_toConsumableArray2(selectedNodes), _toConsumableArray2(selectedEdges));
      var selectedElementsChanged = !fastDeepEqual(nextSelectedElements, state.selectedElements);
      var selectedElementsUpdate = selectedElementsChanged ? {
        selectedElements: nextSelectedElements.length > 0 ? nextSelectedElements : null
      } : {};
      return _objectSpread$32(_objectSpread$32(_objectSpread$32({}, state), selectedElementsUpdate), {}, {
        userSelectionRect: nextUserSelectRect
      });
    }
    case UNSET_USER_SELECTION: {
      var _state$selectedElemen2;
      var _selectedNodes = (_state$selectedElemen2 = state.selectedElements) === null || _state$selectedElemen2 === void 0 ? void 0 : _state$selectedElemen2.filter(function(node) {
        return isNode(node) && node.__rf;
      });
      var stateUpdate = _objectSpread$32(_objectSpread$32({}, state), {}, {
        selectionActive: false,
        userSelectionRect: _objectSpread$32(_objectSpread$32({}, state.userSelectionRect), {}, {
          draw: false
        })
      });
      if (!_selectedNodes || _selectedNodes.length === 0) {
        stateUpdate.selectedElements = null;
        stateUpdate.nodesSelectionActive = false;
      } else {
        var selectedNodesBbox = getRectOfNodes(_selectedNodes);
        stateUpdate.selectedNodesBbox = selectedNodesBbox;
        stateUpdate.nodesSelectionActive = true;
      }
      return stateUpdate;
    }
    case SET_SELECTED_ELEMENTS: {
      var elements = action.payload;
      var selectedElementsArr = Array.isArray(elements) ? elements : [elements];
      var selectedElementsUpdated = !fastDeepEqual(selectedElementsArr, state.selectedElements);
      var selectedElements = selectedElementsUpdated ? selectedElementsArr : state.selectedElements;
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        selectedElements
      });
    }
    case ADD_SELECTED_ELEMENTS: {
      var multiSelectionActive = state.multiSelectionActive, _selectedElements = state.selectedElements;
      var _elements = action.payload;
      var _selectedElementsArr = Array.isArray(_elements) ? _elements : [_elements];
      var _nextElements = _selectedElementsArr;
      if (multiSelectionActive) {
        _nextElements = _selectedElements ? [].concat(_toConsumableArray2(_selectedElements), _toConsumableArray2(_selectedElementsArr)) : _selectedElementsArr;
      }
      var _selectedElementsUpdated = !fastDeepEqual(_nextElements, state.selectedElements);
      var _nextSelectedElements = _selectedElementsUpdated ? _nextElements : state.selectedElements;
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        selectedElements: _nextSelectedElements
      });
    }
    case INIT_D3ZOOM: {
      var _action$payload3 = action.payload, d3Zoom = _action$payload3.d3Zoom, d3Selection = _action$payload3.d3Selection, d3ZoomHandler = _action$payload3.d3ZoomHandler, transform3 = _action$payload3.transform;
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        d3Zoom,
        d3Selection,
        d3ZoomHandler,
        transform: transform3
      });
    }
    case SET_MINZOOM: {
      var _state$d3Zoom;
      var minZoom = action.payload;
      (_state$d3Zoom = state.d3Zoom) === null || _state$d3Zoom === void 0 ? void 0 : _state$d3Zoom.scaleExtent([minZoom, state.maxZoom]);
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        minZoom
      });
    }
    case SET_MAXZOOM: {
      var _state$d3Zoom2;
      var maxZoom = action.payload;
      (_state$d3Zoom2 = state.d3Zoom) === null || _state$d3Zoom2 === void 0 ? void 0 : _state$d3Zoom2.scaleExtent([state.minZoom, maxZoom]);
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        maxZoom
      });
    }
    case SET_TRANSLATEEXTENT: {
      var _state$d3Zoom3;
      var translateExtent = action.payload;
      (_state$d3Zoom3 = state.d3Zoom) === null || _state$d3Zoom3 === void 0 ? void 0 : _state$d3Zoom3.translateExtent(translateExtent);
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        translateExtent
      });
    }
    case SET_NODE_EXTENT: {
      var nodeExtent = action.payload;
      return _objectSpread$32(_objectSpread$32({}, state), {}, {
        nodeExtent,
        nodes: state.nodes.map(function(node) {
          return _objectSpread$32(_objectSpread$32({}, node), {}, {
            __rf: _objectSpread$32(_objectSpread$32({}, node.__rf), {}, {
              position: clampPosition(node.__rf.position, nodeExtent)
            })
          });
        })
      });
    }
    case SET_ON_CONNECT:
    case SET_ON_CONNECT_START:
    case SET_ON_CONNECT_STOP:
    case SET_ON_CONNECT_END:
    case RESET_SELECTED_ELEMENTS:
    case UNSET_NODES_SELECTION:
    case UPDATE_TRANSFORM:
    case UPDATE_SIZE:
    case SET_CONNECTION_POSITION:
    case SET_CONNECTION_NODEID:
    case SET_SNAPTOGRID:
    case SET_SNAPGRID:
    case SET_INTERACTIVE:
    case SET_NODES_DRAGGABLE:
    case SET_NODES_CONNECTABLE:
    case SET_ELEMENTS_SELECTABLE:
    case SET_MULTI_SELECTION_ACTIVE:
    case SET_CONNECTION_MODE:
      return _objectSpread$32(_objectSpread$32({}, state), action.payload);
    default:
      return state;
  }
}
function configureStore(preloadedState) {
  var store2 = createStore(reactFlowReducer, preloadedState);
  return store2;
}
var initialState2 = {
  width: 0,
  height: 0,
  transform: [0, 0, 1],
  nodes: [],
  edges: [],
  selectedElements: null,
  selectedNodesBbox: {
    x: 0,
    y: 0,
    width: 0,
    height: 0
  },
  d3Zoom: null,
  d3Selection: null,
  d3ZoomHandler: void 0,
  minZoom: 0.5,
  maxZoom: 2,
  translateExtent: [[Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY], [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY]],
  nodeExtent: [[Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY], [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY]],
  nodesSelectionActive: false,
  selectionActive: false,
  userSelectionRect: {
    startX: 0,
    startY: 0,
    x: 0,
    y: 0,
    width: 0,
    height: 0,
    draw: false
  },
  connectionNodeId: null,
  connectionHandleId: null,
  connectionHandleType: "source",
  connectionPosition: {
    x: 0,
    y: 0
  },
  connectionMode: ConnectionMode.Strict,
  snapGrid: [15, 15],
  snapToGrid: false,
  nodesDraggable: true,
  nodesConnectable: true,
  elementsSelectable: true,
  multiSelectionActive: false,
  reactFlowVersion: "9.7.0"
};
var store = configureStore(initialState2);
var Wrapper = function Wrapper2(_ref) {
  var children2 = _ref.children;
  var contextValue = react.useContext(ReactReduxContext);
  var isWrappedWithReactFlowProvider = react.useMemo(function() {
    var _contextValue$store, _contextValue$store$g;
    return contextValue === null || contextValue === void 0 ? void 0 : (_contextValue$store = contextValue.store) === null || _contextValue$store === void 0 ? void 0 : (_contextValue$store$g = _contextValue$store.getState()) === null || _contextValue$store$g === void 0 ? void 0 : _contextValue$store$g.reactFlowVersion;
  }, [contextValue]);
  if (isWrappedWithReactFlowProvider) {
    return /* @__PURE__ */ react.createElement(react.Fragment, null, children2);
  }
  return /* @__PURE__ */ react.createElement(Provider$1, {
    store
  }, children2);
};
Wrapper.displayName = "ReactFlowWrapper";
function styleInject(css2, ref) {
  if (ref === void 0)
    ref = {};
  var insertAt = ref.insertAt;
  if (!css2 || typeof document === "undefined") {
    return;
  }
  var head = document.head || document.getElementsByTagName("head")[0];
  var style = document.createElement("style");
  style.type = "text/css";
  if (insertAt === "top") {
    if (head.firstChild) {
      head.insertBefore(style, head.firstChild);
    } else {
      head.appendChild(style);
    }
  } else {
    head.appendChild(style);
  }
  if (style.styleSheet) {
    style.styleSheet.cssText = css2;
  } else {
    style.appendChild(document.createTextNode(css2));
  }
}
var css_248z$1 = ".react-flow{height:100%;overflow:hidden;position:relative;width:100%}.react-flow__pane,.react-flow__renderer,.react-flow__selectionpane{height:100%;left:0;position:absolute;top:0;width:100%}.react-flow__pane{z-index:1}.react-flow__renderer{z-index:4}.react-flow__selectionpane{z-index:5}.react-flow__edges,.react-flow__selection{left:0;position:absolute;top:0}.react-flow__edges{pointer-events:none;z-index:2}.react-flow__edge{pointer-events:visibleStroke}.react-flow__edge.inactive{pointer-events:none}@-webkit-keyframes dashdraw{0%{stroke-dashoffset:10}}@keyframes dashdraw{0%{stroke-dashoffset:10}}.react-flow__edge-path{fill:none}.react-flow__edge-textwrapper{pointer-events:all}.react-flow__edge-text{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.react-flow__connection{pointer-events:none}.react-flow__connection .animated{stroke-dasharray:5;-webkit-animation:dashdraw .5s linear infinite;animation:dashdraw .5s linear infinite}.react-flow__connection-path{fill:none}.react-flow__nodes{height:100%;pointer-events:none;width:100%;z-index:3}.react-flow__node,.react-flow__nodes{position:absolute;transform-origin:0 0}.react-flow__node{pointer-events:all;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.react-flow__nodesselection{height:100%;left:0;pointer-events:none;position:absolute;top:0;transform-origin:left top;width:100%;z-index:3}.react-flow__nodesselection-rect{cursor:-webkit-grab;cursor:grab;pointer-events:all;position:absolute}.react-flow__handle{pointer-events:none}.react-flow__handle.connectable{pointer-events:all}.react-flow__handle-bottom{bottom:-4px;left:50%;top:auto;transform:translate(-50%)}.react-flow__handle-top{left:50%;top:-4px;transform:translate(-50%)}.react-flow__handle-left{left:-4px;top:50%;transform:translateY(-50%)}.react-flow__handle-right{right:-4px;top:50%;transform:translateY(-50%)}.react-flow__edgeupdater{cursor:move;pointer-events:all}.react-flow__background{height:100%;left:0;position:absolute;top:0;width:100%}.react-flow__controls{bottom:10px;left:10px;position:absolute;z-index:5}.react-flow__controls-button{border:none;height:24px;width:24px}.react-flow__controls-button svg{width:100%}.react-flow__minimap{bottom:10px;position:absolute;right:10px;z-index:5}";
styleInject(css_248z$1);
var css_248z = ".react-flow__selection{background:rgba(0,89,220,.08);border:1px dotted rgba(0,89,220,.8)}.react-flow__edge.selected .react-flow__edge-path{stroke:#555}.react-flow__edge.animated path{stroke-dasharray:5;-webkit-animation:dashdraw .5s linear infinite;animation:dashdraw .5s linear infinite}.react-flow__edge.updating .react-flow__edge-path{stroke:#777}.react-flow__edge-path{stroke:#b1b1b7;stroke-width:1}.react-flow__edge-text{font-size:10px}.react-flow__edge-textbg{fill:#fff}.react-flow__connection-path{stroke:#b1b1b7;stroke-width:1}.react-flow__node{cursor:-webkit-grab;cursor:grab}.react-flow__node-default,.react-flow__node-input,.react-flow__node-output{border-radius:3px;border-style:solid;border-width:1px;color:#222;font-size:12px;padding:10px;text-align:center;width:150px}.react-flow__node-default.selectable:hover,.react-flow__node-input.selectable:hover,.react-flow__node-output.selectable:hover{box-shadow:0 1px 4px 1px rgba(0,0,0,.08)}.react-flow__node-input{background:#fff;border-color:#0041d0}.react-flow__node-input.selected,.react-flow__node-input.selected:hover{box-shadow:0 0 0 .5px #0041d0}.react-flow__node-input .react-flow__handle{background:#0041d0}.react-flow__node-default{background:#fff;border-color:#1a192b}.react-flow__node-default.selected,.react-flow__node-default.selected:hover{box-shadow:0 0 0 .5px #1a192b}.react-flow__node-default .react-flow__handle{background:#1a192b}.react-flow__node-output{background:#fff;border-color:#ff0072}.react-flow__node-output.selected,.react-flow__node-output.selected:hover{box-shadow:0 0 0 .5px #ff0072}.react-flow__node-output .react-flow__handle{background:#ff0072}.react-flow__nodesselection-rect{background:rgba(0,89,220,.08);border:1px dotted rgba(0,89,220,.8)}.react-flow__handle{background:#555;border:1px solid #fff;border-radius:100%;height:6px;position:absolute;width:6px}.react-flow__handle.connectable{cursor:crosshair}.react-flow__minimap{background-color:#fff}.react-flow__controls{box-shadow:0 0 2px 1px rgba(0,0,0,.08)}.react-flow__controls-button{align-items:center;background:#fefefe;border-bottom:1px solid #eee;box-sizing:content-box;cursor:pointer;display:flex;height:16px;justify-content:center;padding:5px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;width:16px}.react-flow__controls-button svg{max-height:12px;max-width:12px}.react-flow__controls-button:hover{background:#f4f4f4}";
styleInject(css_248z);
var _excluded$1 = ["elements", "className", "nodeTypes", "edgeTypes", "onElementClick", "onLoad", "onMove", "onMoveStart", "onMoveEnd", "onElementsRemove", "onConnect", "onConnectStart", "onConnectStop", "onConnectEnd", "onNodeMouseEnter", "onNodeMouseMove", "onNodeMouseLeave", "onNodeContextMenu", "onNodeDoubleClick", "onNodeDragStart", "onNodeDrag", "onNodeDragStop", "onSelectionChange", "onSelectionDragStart", "onSelectionDrag", "onSelectionDragStop", "onSelectionContextMenu", "connectionMode", "connectionLineType", "connectionLineStyle", "connectionLineComponent", "deleteKeyCode", "selectionKeyCode", "multiSelectionKeyCode", "zoomActivationKeyCode", "snapToGrid", "snapGrid", "onlyRenderVisibleElements", "selectNodesOnDrag", "nodesDraggable", "nodesConnectable", "elementsSelectable", "minZoom", "maxZoom", "defaultZoom", "defaultPosition", "translateExtent", "preventScrolling", "nodeExtent", "arrowHeadColor", "markerEndId", "zoomOnScroll", "zoomOnPinch", "panOnScroll", "panOnScrollSpeed", "panOnScrollMode", "zoomOnDoubleClick", "paneMoveable", "onPaneClick", "onPaneScroll", "onPaneContextMenu", "children", "onEdgeUpdate", "onEdgeContextMenu", "onEdgeDoubleClick", "onEdgeMouseEnter", "onEdgeMouseMove", "onEdgeMouseLeave", "onEdgeUpdateStart", "onEdgeUpdateEnd", "edgeUpdaterRadius", "nodeTypesId", "edgeTypesId"];
function ownKeys$23(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$23(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$23(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$23(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var defaultNodeTypes = {
  input: InputNode$1,
  default: DefaultNode$1,
  output: OutputNode$1
};
var defaultEdgeTypes = {
  default: BezierEdge,
  straight: StraightEdge,
  step: StepEdge,
  smoothstep: SmoothStepEdge
};
var ReactFlow = /* @__PURE__ */ react.forwardRef(function(_ref, ref) {
  var _ref$elements = _ref.elements, elements = _ref$elements === void 0 ? [] : _ref$elements, className = _ref.className, _ref$nodeTypes = _ref.nodeTypes, nodeTypes = _ref$nodeTypes === void 0 ? defaultNodeTypes : _ref$nodeTypes, _ref$edgeTypes = _ref.edgeTypes, edgeTypes = _ref$edgeTypes === void 0 ? defaultEdgeTypes : _ref$edgeTypes, onElementClick = _ref.onElementClick, onLoad = _ref.onLoad, onMove = _ref.onMove, onMoveStart = _ref.onMoveStart, onMoveEnd = _ref.onMoveEnd, onElementsRemove = _ref.onElementsRemove, onConnect = _ref.onConnect, onConnectStart = _ref.onConnectStart, onConnectStop = _ref.onConnectStop, onConnectEnd = _ref.onConnectEnd, onNodeMouseEnter = _ref.onNodeMouseEnter, onNodeMouseMove = _ref.onNodeMouseMove, onNodeMouseLeave = _ref.onNodeMouseLeave, onNodeContextMenu = _ref.onNodeContextMenu, onNodeDoubleClick = _ref.onNodeDoubleClick, onNodeDragStart = _ref.onNodeDragStart, onNodeDrag = _ref.onNodeDrag, onNodeDragStop = _ref.onNodeDragStop, onSelectionChange = _ref.onSelectionChange, onSelectionDragStart = _ref.onSelectionDragStart, onSelectionDrag = _ref.onSelectionDrag, onSelectionDragStop = _ref.onSelectionDragStop, onSelectionContextMenu = _ref.onSelectionContextMenu, _ref$connectionMode = _ref.connectionMode, connectionMode = _ref$connectionMode === void 0 ? ConnectionMode.Strict : _ref$connectionMode, _ref$connectionLineTy = _ref.connectionLineType, connectionLineType = _ref$connectionLineTy === void 0 ? ConnectionLineType.Bezier : _ref$connectionLineTy, connectionLineStyle = _ref.connectionLineStyle, connectionLineComponent = _ref.connectionLineComponent, _ref$deleteKeyCode = _ref.deleteKeyCode, deleteKeyCode = _ref$deleteKeyCode === void 0 ? "Backspace" : _ref$deleteKeyCode, _ref$selectionKeyCode = _ref.selectionKeyCode, selectionKeyCode = _ref$selectionKeyCode === void 0 ? "Shift" : _ref$selectionKeyCode, _ref$multiSelectionKe = _ref.multiSelectionKeyCode, multiSelectionKeyCode = _ref$multiSelectionKe === void 0 ? "Meta" : _ref$multiSelectionKe, _ref$zoomActivationKe = _ref.zoomActivationKeyCode, zoomActivationKeyCode = _ref$zoomActivationKe === void 0 ? "Meta" : _ref$zoomActivationKe, _ref$snapToGrid = _ref.snapToGrid, snapToGrid2 = _ref$snapToGrid === void 0 ? false : _ref$snapToGrid, _ref$snapGrid = _ref.snapGrid, snapGrid = _ref$snapGrid === void 0 ? [15, 15] : _ref$snapGrid, _ref$onlyRenderVisibl = _ref.onlyRenderVisibleElements, onlyRenderVisibleElements = _ref$onlyRenderVisibl === void 0 ? false : _ref$onlyRenderVisibl, _ref$selectNodesOnDra = _ref.selectNodesOnDrag, selectNodesOnDrag = _ref$selectNodesOnDra === void 0 ? true : _ref$selectNodesOnDra, nodesDraggable = _ref.nodesDraggable, nodesConnectable = _ref.nodesConnectable, elementsSelectable = _ref.elementsSelectable, minZoom = _ref.minZoom, maxZoom = _ref.maxZoom, _ref$defaultZoom = _ref.defaultZoom, defaultZoom = _ref$defaultZoom === void 0 ? 1 : _ref$defaultZoom, _ref$defaultPosition = _ref.defaultPosition, defaultPosition = _ref$defaultPosition === void 0 ? [0, 0] : _ref$defaultPosition, translateExtent = _ref.translateExtent, _ref$preventScrolling = _ref.preventScrolling, preventScrolling = _ref$preventScrolling === void 0 ? true : _ref$preventScrolling, nodeExtent = _ref.nodeExtent, _ref$arrowHeadColor = _ref.arrowHeadColor, arrowHeadColor = _ref$arrowHeadColor === void 0 ? "#b1b1b7" : _ref$arrowHeadColor, markerEndId = _ref.markerEndId, _ref$zoomOnScroll = _ref.zoomOnScroll, zoomOnScroll = _ref$zoomOnScroll === void 0 ? true : _ref$zoomOnScroll, _ref$zoomOnPinch = _ref.zoomOnPinch, zoomOnPinch = _ref$zoomOnPinch === void 0 ? true : _ref$zoomOnPinch, _ref$panOnScroll = _ref.panOnScroll, panOnScroll = _ref$panOnScroll === void 0 ? false : _ref$panOnScroll, _ref$panOnScrollSpeed = _ref.panOnScrollSpeed, panOnScrollSpeed = _ref$panOnScrollSpeed === void 0 ? 0.5 : _ref$panOnScrollSpeed, _ref$panOnScrollMode = _ref.panOnScrollMode, panOnScrollMode = _ref$panOnScrollMode === void 0 ? PanOnScrollMode.Free : _ref$panOnScrollMode, _ref$zoomOnDoubleClic = _ref.zoomOnDoubleClick, zoomOnDoubleClick = _ref$zoomOnDoubleClic === void 0 ? true : _ref$zoomOnDoubleClic, _ref$paneMoveable = _ref.paneMoveable, paneMoveable = _ref$paneMoveable === void 0 ? true : _ref$paneMoveable, onPaneClick = _ref.onPaneClick, onPaneScroll = _ref.onPaneScroll, onPaneContextMenu = _ref.onPaneContextMenu, children2 = _ref.children, onEdgeUpdate = _ref.onEdgeUpdate, onEdgeContextMenu = _ref.onEdgeContextMenu, onEdgeDoubleClick = _ref.onEdgeDoubleClick, onEdgeMouseEnter = _ref.onEdgeMouseEnter, onEdgeMouseMove = _ref.onEdgeMouseMove, onEdgeMouseLeave = _ref.onEdgeMouseLeave, onEdgeUpdateStart = _ref.onEdgeUpdateStart, onEdgeUpdateEnd = _ref.onEdgeUpdateEnd, _ref$edgeUpdaterRadiu = _ref.edgeUpdaterRadius, edgeUpdaterRadius = _ref$edgeUpdaterRadiu === void 0 ? 10 : _ref$edgeUpdaterRadiu, _ref$nodeTypesId = _ref.nodeTypesId, nodeTypesId = _ref$nodeTypesId === void 0 ? "1" : _ref$nodeTypesId, _ref$edgeTypesId = _ref.edgeTypesId, edgeTypesId = _ref$edgeTypesId === void 0 ? "1" : _ref$edgeTypesId, rest = _objectWithoutProperties3(_ref, _excluded$1);
  var nodeTypesParsed = react.useMemo(function() {
    return createNodeTypes(nodeTypes);
  }, [nodeTypesId]);
  var edgeTypesParsed = react.useMemo(function() {
    return createEdgeTypes(edgeTypes);
  }, [edgeTypesId]);
  var reactFlowClasses = cc2(["react-flow", className]);
  return /* @__PURE__ */ react.createElement("div", _objectSpread$23(_objectSpread$23({}, rest), {}, {
    ref,
    className: reactFlowClasses
  }), /* @__PURE__ */ react.createElement(Wrapper, null, /* @__PURE__ */ react.createElement(GraphView$1, {
    onLoad,
    onMove,
    onMoveStart,
    onMoveEnd,
    onElementClick,
    onNodeMouseEnter,
    onNodeMouseMove,
    onNodeMouseLeave,
    onNodeContextMenu,
    onNodeDoubleClick,
    onNodeDragStart,
    onNodeDrag,
    onNodeDragStop,
    nodeTypes: nodeTypesParsed,
    edgeTypes: edgeTypesParsed,
    connectionMode,
    connectionLineType,
    connectionLineStyle,
    connectionLineComponent,
    selectionKeyCode,
    onElementsRemove,
    deleteKeyCode,
    multiSelectionKeyCode,
    zoomActivationKeyCode,
    onConnect,
    onConnectStart,
    onConnectStop,
    onConnectEnd,
    snapToGrid: snapToGrid2,
    snapGrid,
    onlyRenderVisibleElements,
    nodesDraggable,
    nodesConnectable,
    elementsSelectable,
    selectNodesOnDrag,
    minZoom,
    maxZoom,
    defaultZoom,
    defaultPosition,
    translateExtent,
    preventScrolling,
    nodeExtent,
    arrowHeadColor,
    markerEndId,
    zoomOnScroll,
    zoomOnPinch,
    zoomOnDoubleClick,
    panOnScroll,
    panOnScrollSpeed,
    panOnScrollMode,
    paneMoveable,
    onPaneClick,
    onPaneScroll,
    onPaneContextMenu,
    onSelectionDragStart,
    onSelectionDrag,
    onSelectionDragStop,
    onSelectionContextMenu,
    onEdgeUpdate,
    onEdgeContextMenu,
    onEdgeDoubleClick,
    onEdgeMouseEnter,
    onEdgeMouseMove,
    onEdgeMouseLeave,
    onEdgeUpdateStart,
    onEdgeUpdateEnd,
    edgeUpdaterRadius
  }), /* @__PURE__ */ react.createElement(ElementUpdater, {
    elements
  }), onSelectionChange && /* @__PURE__ */ react.createElement(SelectionListener, {
    onSelectionChange
  }), children2));
});
ReactFlow.displayName = "ReactFlow";
var MiniMapNode = function MiniMapNode2(_ref) {
  var x2 = _ref.x, y3 = _ref.y, width2 = _ref.width, height = _ref.height, style = _ref.style, color2 = _ref.color, strokeColor = _ref.strokeColor, strokeWidth = _ref.strokeWidth, className = _ref.className, borderRadius = _ref.borderRadius, shapeRendering = _ref.shapeRendering;
  var _ref2 = style || {}, background = _ref2.background, backgroundColor = _ref2.backgroundColor;
  var fill2 = color2 || background || backgroundColor;
  return /* @__PURE__ */ react.createElement("rect", {
    className: cc2(["react-flow__minimap-node", className]),
    x: x2,
    y: y3,
    rx: borderRadius,
    ry: borderRadius,
    width: width2,
    height,
    fill: fill2,
    stroke: strokeColor,
    strokeWidth,
    shapeRendering
  });
};
MiniMapNode.displayName = "MiniMapNode";
var MiniMapNode$1 = /* @__PURE__ */ react.memo(MiniMapNode);
var defaultWidth = 200;
var defaultHeight = 150;
var MiniMap = function MiniMap2(_ref) {
  var style = _ref.style, className = _ref.className, _ref$nodeStrokeColor = _ref.nodeStrokeColor, nodeStrokeColor = _ref$nodeStrokeColor === void 0 ? "#555" : _ref$nodeStrokeColor, _ref$nodeColor = _ref.nodeColor, nodeColor = _ref$nodeColor === void 0 ? "#fff" : _ref$nodeColor, _ref$nodeClassName = _ref.nodeClassName, nodeClassName = _ref$nodeClassName === void 0 ? "" : _ref$nodeClassName, _ref$nodeBorderRadius = _ref.nodeBorderRadius, nodeBorderRadius = _ref$nodeBorderRadius === void 0 ? 5 : _ref$nodeBorderRadius, _ref$nodeStrokeWidth = _ref.nodeStrokeWidth, nodeStrokeWidth = _ref$nodeStrokeWidth === void 0 ? 2 : _ref$nodeStrokeWidth, _ref$maskColor = _ref.maskColor, maskColor = _ref$maskColor === void 0 ? "rgb(240, 242, 243, 0.7)" : _ref$maskColor;
  var containerWidth = useStoreState(function(s2) {
    return s2.width;
  });
  var containerHeight = useStoreState(function(s2) {
    return s2.height;
  });
  var _useStoreState = useStoreState(function(s2) {
    return s2.transform;
  }), _useStoreState2 = _slicedToArray$1(_useStoreState, 3), tX = _useStoreState2[0], tY = _useStoreState2[1], tScale = _useStoreState2[2];
  var nodes = useStoreState(function(s2) {
    return s2.nodes;
  });
  var mapClasses = cc2(["react-flow__minimap", className]);
  var elementWidth = (style === null || style === void 0 ? void 0 : style.width) || defaultWidth;
  var elementHeight = (style === null || style === void 0 ? void 0 : style.height) || defaultHeight;
  var nodeColorFunc = nodeColor instanceof Function ? nodeColor : function() {
    return nodeColor;
  };
  var nodeStrokeColorFunc = nodeStrokeColor instanceof Function ? nodeStrokeColor : function() {
    return nodeStrokeColor;
  };
  var nodeClassNameFunc = nodeClassName instanceof Function ? nodeClassName : function() {
    return nodeClassName;
  };
  var hasNodes = nodes && nodes.length;
  var bb2 = getRectOfNodes(nodes);
  var viewBB = {
    x: -tX / tScale,
    y: -tY / tScale,
    width: containerWidth / tScale,
    height: containerHeight / tScale
  };
  var boundingRect = hasNodes ? getBoundsofRects(bb2, viewBB) : viewBB;
  var scaledWidth = boundingRect.width / elementWidth;
  var scaledHeight = boundingRect.height / elementHeight;
  var viewScale = Math.max(scaledWidth, scaledHeight);
  var viewWidth = viewScale * elementWidth;
  var viewHeight = viewScale * elementHeight;
  var offset2 = 5 * viewScale;
  var x2 = boundingRect.x - (viewWidth - boundingRect.width) / 2 - offset2;
  var y3 = boundingRect.y - (viewHeight - boundingRect.height) / 2 - offset2;
  var width2 = viewWidth + offset2 * 2;
  var height = viewHeight + offset2 * 2;
  var shapeRendering = typeof window === "undefined" || !!window.chrome ? "crispEdges" : "geometricPrecision";
  return /* @__PURE__ */ react.createElement("svg", {
    width: elementWidth,
    height: elementHeight,
    viewBox: "".concat(x2, " ").concat(y3, " ").concat(width2, " ").concat(height),
    style,
    className: mapClasses
  }, nodes.filter(function(node) {
    return !node.isHidden;
  }).map(function(node) {
    return /* @__PURE__ */ react.createElement(MiniMapNode$1, {
      key: node.id,
      x: node.__rf.position.x,
      y: node.__rf.position.y,
      width: node.__rf.width,
      height: node.__rf.height,
      style: node.style,
      className: nodeClassNameFunc(node),
      color: nodeColorFunc(node),
      borderRadius: nodeBorderRadius,
      strokeColor: nodeStrokeColorFunc(node),
      strokeWidth: nodeStrokeWidth,
      shapeRendering
    });
  }), /* @__PURE__ */ react.createElement("path", {
    className: "react-flow__minimap-mask",
    d: "M".concat(x2 - offset2, ",").concat(y3 - offset2, "h").concat(width2 + offset2 * 2, "v").concat(height + offset2 * 2, "h").concat(-width2 - offset2 * 2, "z\n        M").concat(viewBB.x, ",").concat(viewBB.y, "h").concat(viewBB.width, "v").concat(viewBB.height, "h").concat(-viewBB.width, "z"),
    fill: maskColor,
    fillRule: "evenodd"
  }));
};
MiniMap.displayName = "MiniMap";
var index$2 = /* @__PURE__ */ react.memo(MiniMap);
var _path$4;
function _extends$4() {
  _extends$4 = Object.assign || function(target) {
    for (var i3 = 1; i3 < arguments.length; i3++) {
      var source2 = arguments[i3];
      for (var key in source2) {
        if (Object.prototype.hasOwnProperty.call(source2, key)) {
          target[key] = source2[key];
        }
      }
    }
    return target;
  };
  return _extends$4.apply(this, arguments);
}
var SvgPlus = function SvgPlus2(props) {
  return /* @__PURE__ */ react.createElement("svg", _extends$4({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 32 32"
  }, props), _path$4 || (_path$4 = /* @__PURE__ */ react.createElement("path", {
    d: "M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"
  })));
};
var _path$3;
function _extends$3() {
  _extends$3 = Object.assign || function(target) {
    for (var i3 = 1; i3 < arguments.length; i3++) {
      var source2 = arguments[i3];
      for (var key in source2) {
        if (Object.prototype.hasOwnProperty.call(source2, key)) {
          target[key] = source2[key];
        }
      }
    }
    return target;
  };
  return _extends$3.apply(this, arguments);
}
var SvgMinus = function SvgMinus2(props) {
  return /* @__PURE__ */ react.createElement("svg", _extends$3({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 32 5"
  }, props), _path$3 || (_path$3 = /* @__PURE__ */ react.createElement("path", {
    d: "M0 0h32v4.2H0z"
  })));
};
var _path$2;
function _extends$2() {
  _extends$2 = Object.assign || function(target) {
    for (var i3 = 1; i3 < arguments.length; i3++) {
      var source2 = arguments[i3];
      for (var key in source2) {
        if (Object.prototype.hasOwnProperty.call(source2, key)) {
          target[key] = source2[key];
        }
      }
    }
    return target;
  };
  return _extends$2.apply(this, arguments);
}
var SvgFitview = function SvgFitview2(props) {
  return /* @__PURE__ */ react.createElement("svg", _extends$2({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 32 30"
  }, props), _path$2 || (_path$2 = /* @__PURE__ */ react.createElement("path", {
    d: "M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0 0 27.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94a.919.919 0 0 1-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"
  })));
};
var _path$1;
function _extends$1() {
  _extends$1 = Object.assign || function(target) {
    for (var i3 = 1; i3 < arguments.length; i3++) {
      var source2 = arguments[i3];
      for (var key in source2) {
        if (Object.prototype.hasOwnProperty.call(source2, key)) {
          target[key] = source2[key];
        }
      }
    }
    return target;
  };
  return _extends$1.apply(this, arguments);
}
var SvgLock = function SvgLock2(props) {
  return /* @__PURE__ */ react.createElement("svg", _extends$1({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 25 32"
  }, props), _path$1 || (_path$1 = /* @__PURE__ */ react.createElement("path", {
    d: "M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 0 0 0 13.714v15.238A3.056 3.056 0 0 0 3.048 32h18.285a3.056 3.056 0 0 0 3.048-3.048V13.714a3.056 3.056 0 0 0-3.048-3.047zM12.19 24.533a3.056 3.056 0 0 1-3.047-3.047 3.056 3.056 0 0 1 3.047-3.048 3.056 3.056 0 0 1 3.048 3.048 3.056 3.056 0 0 1-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"
  })));
};
var _path;
function _extends3() {
  _extends3 = Object.assign || function(target) {
    for (var i3 = 1; i3 < arguments.length; i3++) {
      var source2 = arguments[i3];
      for (var key in source2) {
        if (Object.prototype.hasOwnProperty.call(source2, key)) {
          target[key] = source2[key];
        }
      }
    }
    return target;
  };
  return _extends3.apply(this, arguments);
}
var SvgUnlock = function SvgUnlock2(props) {
  return /* @__PURE__ */ react.createElement("svg", _extends3({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 25 32"
  }, props), _path || (_path = /* @__PURE__ */ react.createElement("path", {
    d: "M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 0 0 0 13.714v15.238A3.056 3.056 0 0 0 3.048 32h18.285a3.056 3.056 0 0 0 3.048-3.048V13.714a3.056 3.056 0 0 0-3.048-3.047zM12.19 24.533a3.056 3.056 0 0 1-3.047-3.047 3.056 3.056 0 0 1 3.047-3.048 3.056 3.056 0 0 1 3.048 3.048 3.056 3.056 0 0 1-3.048 3.047z"
  })));
};
var _excluded3 = ["children", "className"];
function ownKeys$13(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread$13(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys$13(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys$13(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var ControlButton = function ControlButton2(_ref) {
  var children2 = _ref.children, className = _ref.className, rest = _objectWithoutProperties3(_ref, _excluded3);
  return /* @__PURE__ */ react.createElement("button", _objectSpread$13({
    type: "button",
    className: cc2(["react-flow__controls-button", className])
  }, rest), children2);
};
var Controls = function Controls2(_ref2) {
  var style = _ref2.style, _ref2$showZoom = _ref2.showZoom, showZoom = _ref2$showZoom === void 0 ? true : _ref2$showZoom, _ref2$showFitView = _ref2.showFitView, showFitView = _ref2$showFitView === void 0 ? true : _ref2$showFitView, _ref2$showInteractive = _ref2.showInteractive, showInteractive = _ref2$showInteractive === void 0 ? true : _ref2$showInteractive, fitViewParams = _ref2.fitViewParams, onZoomIn = _ref2.onZoomIn, onZoomOut = _ref2.onZoomOut, onFitView = _ref2.onFitView, onInteractiveChange = _ref2.onInteractiveChange, className = _ref2.className, children2 = _ref2.children;
  var _useState = react.useState(false), _useState2 = _slicedToArray$1(_useState, 2), isVisible = _useState2[0], setIsVisible = _useState2[1];
  var setInteractive3 = useStoreActions(function(actions2) {
    return actions2.setInteractive;
  });
  var _useZoomPanHelper = useZoomPanHelper(), zoomIn2 = _useZoomPanHelper.zoomIn, zoomOut2 = _useZoomPanHelper.zoomOut, fitView2 = _useZoomPanHelper.fitView;
  var isInteractive = useStoreState(function(s2) {
    return s2.nodesDraggable && s2.nodesConnectable && s2.elementsSelectable;
  });
  var mapClasses = cc2(["react-flow__controls", className]);
  var onZoomInHandler = react.useCallback(function() {
    zoomIn2 === null || zoomIn2 === void 0 ? void 0 : zoomIn2();
    onZoomIn === null || onZoomIn === void 0 ? void 0 : onZoomIn();
  }, [zoomIn2, onZoomIn]);
  var onZoomOutHandler = react.useCallback(function() {
    zoomOut2 === null || zoomOut2 === void 0 ? void 0 : zoomOut2();
    onZoomOut === null || onZoomOut === void 0 ? void 0 : onZoomOut();
  }, [zoomOut2, onZoomOut]);
  var onFitViewHandler = react.useCallback(function() {
    fitView2 === null || fitView2 === void 0 ? void 0 : fitView2(fitViewParams);
    onFitView === null || onFitView === void 0 ? void 0 : onFitView();
  }, [fitView2, fitViewParams, onFitView]);
  var onInteractiveChangeHandler = react.useCallback(function() {
    setInteractive3 === null || setInteractive3 === void 0 ? void 0 : setInteractive3(!isInteractive);
    onInteractiveChange === null || onInteractiveChange === void 0 ? void 0 : onInteractiveChange(!isInteractive);
  }, [isInteractive, setInteractive3, onInteractiveChange]);
  react.useEffect(function() {
    setIsVisible(true);
  }, []);
  if (!isVisible) {
    return null;
  }
  return /* @__PURE__ */ react.createElement("div", {
    className: mapClasses,
    style
  }, showZoom && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ControlButton, {
    onClick: onZoomInHandler,
    className: "react-flow__controls-zoomin"
  }, /* @__PURE__ */ react.createElement(SvgPlus, null)), /* @__PURE__ */ react.createElement(ControlButton, {
    onClick: onZoomOutHandler,
    className: "react-flow__controls-zoomout"
  }, /* @__PURE__ */ react.createElement(SvgMinus, null))), showFitView && /* @__PURE__ */ react.createElement(ControlButton, {
    className: "react-flow__controls-fitview",
    onClick: onFitViewHandler
  }, /* @__PURE__ */ react.createElement(SvgFitview, null)), showInteractive && /* @__PURE__ */ react.createElement(ControlButton, {
    className: "react-flow__controls-interactive",
    onClick: onInteractiveChangeHandler
  }, isInteractive ? /* @__PURE__ */ react.createElement(SvgUnlock, null) : /* @__PURE__ */ react.createElement(SvgLock, null)), children2);
};
Controls.displayName = "Controls";
var index$1 = /* @__PURE__ */ react.memo(Controls);
var createGridLinesPath = function createGridLinesPath2(size2, strokeWidth, stroke) {
  return /* @__PURE__ */ react.createElement("path", {
    stroke,
    strokeWidth,
    d: "M".concat(size2 / 2, " 0 V").concat(size2, " M0 ").concat(size2 / 2, " H").concat(size2)
  });
};
var createGridDotsPath = function createGridDotsPath2(size2, fill2) {
  return /* @__PURE__ */ react.createElement("circle", {
    cx: size2,
    cy: size2,
    r: size2,
    fill: fill2
  });
};
var _defaultColors;
function ownKeys4(object, enumerableOnly) {
  var keys2 = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) {
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    }
    keys2.push.apply(keys2, symbols);
  }
  return keys2;
}
function _objectSpread4(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source2 = arguments[i3] != null ? arguments[i3] : {};
    if (i3 % 2) {
      ownKeys4(Object(source2), true).forEach(function(key) {
        _defineProperty$2(target, key, source2[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
    } else {
      ownKeys4(Object(source2)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
      });
    }
  }
  return target;
}
var defaultColors = (_defaultColors = {}, _defineProperty$2(_defaultColors, BackgroundVariant.Dots, "#81818a"), _defineProperty$2(_defaultColors, BackgroundVariant.Lines, "#eee"), _defaultColors);
var Background = function Background2(_ref) {
  var _ref$variant = _ref.variant, variant = _ref$variant === void 0 ? BackgroundVariant.Dots : _ref$variant, _ref$gap = _ref.gap, gap = _ref$gap === void 0 ? 15 : _ref$gap, _ref$size = _ref.size, size2 = _ref$size === void 0 ? 0.4 : _ref$size, color2 = _ref.color, style = _ref.style, className = _ref.className;
  var _useStoreState = useStoreState(function(s2) {
    return s2.transform;
  }), _useStoreState2 = _slicedToArray$1(_useStoreState, 3), x2 = _useStoreState2[0], y3 = _useStoreState2[1], scale = _useStoreState2[2];
  var patternId = react.useMemo(function() {
    return "pattern-".concat(Math.floor(Math.random() * 1e5));
  }, []);
  var bgClasses = cc2(["react-flow__background", className]);
  var scaledGap = gap * scale;
  var xOffset = x2 % scaledGap;
  var yOffset = y3 % scaledGap;
  var isLines = variant === BackgroundVariant.Lines;
  var bgColor = color2 ? color2 : defaultColors[variant];
  var path = isLines ? createGridLinesPath(scaledGap, size2, bgColor) : createGridDotsPath(size2 * scale, bgColor);
  return /* @__PURE__ */ react.createElement("svg", {
    className: bgClasses,
    style: _objectSpread4(_objectSpread4({}, style), {}, {
      width: "100%",
      height: "100%"
    })
  }, /* @__PURE__ */ react.createElement("pattern", {
    id: patternId,
    x: xOffset,
    y: yOffset,
    width: scaledGap,
    height: scaledGap,
    patternUnits: "userSpaceOnUse"
  }, path), /* @__PURE__ */ react.createElement("rect", {
    x: "0",
    y: "0",
    width: "100%",
    height: "100%",
    fill: "url(#".concat(patternId, ")")
  }));
};
Background.displayName = "Background";
var index2 = /* @__PURE__ */ react.memo(Background);
var react_flow_renderer_default = ReactFlow;

// build/authentication/components/diagram/SubFlowNode.js
var SubFlowNodeInner = ({
  data: {label: label2},
  prefix: prefix2,
  selected
}) => {
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Handle$1, {
    position: Position2.Right,
    type: "source"
  }), /* @__PURE__ */ react.createElement("div", {
    className: `react-flow__node-default keycloak__authentication__subflow_node ${selected ? "selected" : ""}`
  }, /* @__PURE__ */ react.createElement("div", null, prefix2, " ", label2)), /* @__PURE__ */ react.createElement(Handle$1, {
    position: Position2.Left,
    type: "target"
  }));
};
var SubFlowNode = memo(SubFlowNodeInner);
var StartSubFlowNode = ({...props}) => /* @__PURE__ */ react.createElement(SubFlowNode, {
  ...props,
  prefix: "Start"
});
var EndSubFlowNode = ({...props}) => /* @__PURE__ */ react.createElement(SubFlowNode, {
  ...props,
  prefix: "End"
});

// build/authentication/components/diagram/ConditionalNode.js
var ConditionalNodeInner = ({data: data2, selected}) => {
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Handle$1, {
    position: Position2.Right,
    type: "source"
  }), /* @__PURE__ */ react.createElement("div", {
    className: `react-flow__node-default keycloak__authentication__conditional_node ${selected ? "selected" : ""}`
  }, /* @__PURE__ */ react.createElement("div", null, data2.label)), /* @__PURE__ */ react.createElement(Handle$1, {
    position: Position2.Left,
    type: "target"
  }));
};
var ConditionalNode = memo(ConditionalNodeInner);

// build/authentication/components/diagram/ButtonEdge.js
var foreignObjectSize = 33;
var ButtonEdge = ({
  id: id3,
  sourceX,
  sourceY,
  targetX,
  targetY,
  sourcePosition,
  targetPosition,
  style = {},
  arrowHeadType,
  markerEndId,
  selected,
  data: {onEdgeClick}
}) => {
  const edgePath = getBezierPath({
    sourceX,
    sourceY,
    sourcePosition,
    targetX,
    targetY,
    targetPosition
  });
  const markerEnd = getMarkerEnd(arrowHeadType, markerEndId);
  const [edgeCenterX, edgeCenterY] = getCenter({
    sourceX,
    sourceY,
    targetX,
    targetY
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement("path", {
    id: id3,
    style,
    className: "react-flow__edge-path",
    d: edgePath,
    markerEnd
  }), selected && /* @__PURE__ */ react.createElement("foreignObject", {
    width: foreignObjectSize,
    height: foreignObjectSize,
    x: edgeCenterX - foreignObjectSize / 2,
    y: edgeCenterY - foreignObjectSize / 2,
    className: "edgebutton-foreignobject",
    requiredExtensions: "http://www.w3.org/1999/xhtml"
  }, /* @__PURE__ */ react.createElement("button", {
    className: "edgebutton",
    onClick: (event) => onEdgeClick(event, id3)
  }, /* @__PURE__ */ react.createElement(PlusIcon, null))));
};

// build/_snowpack/pkg/dagre.js
function arrayEach(array2, iteratee) {
  var index3 = -1, length = array2 == null ? 0 : array2.length;
  while (++index3 < length) {
    if (iteratee(array2[index3], index3, array2) === false) {
      break;
    }
  }
  return array2;
}
var _arrayEach = arrayEach;
function baseAssign(object, source2) {
  return object && _copyObject(source2, keys_1(source2), object);
}
var _baseAssign = baseAssign;
function baseAssignIn(object, source2) {
  return object && _copyObject(source2, keysIn_1(source2), object);
}
var _baseAssignIn = baseAssignIn;
function copySymbols(source2, object) {
  return _copyObject(source2, _getSymbols(source2), object);
}
var _copySymbols = copySymbols;
var nativeGetSymbols2 = Object.getOwnPropertySymbols;
var getSymbolsIn = !nativeGetSymbols2 ? stubArray_1 : function(object) {
  var result = [];
  while (object) {
    _arrayPush(result, _getSymbols(object));
    object = _getPrototype(object);
  }
  return result;
};
var _getSymbolsIn = getSymbolsIn;
function copySymbolsIn(source2, object) {
  return _copyObject(source2, _getSymbolsIn(source2), object);
}
var _copySymbolsIn = copySymbolsIn;
function getAllKeysIn(object) {
  return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
}
var _getAllKeysIn = getAllKeysIn;
var objectProto3 = Object.prototype;
var hasOwnProperty5 = objectProto3.hasOwnProperty;
function initCloneArray(array2) {
  var length = array2.length, result = new array2.constructor(length);
  if (length && typeof array2[0] == "string" && hasOwnProperty5.call(array2, "index")) {
    result.index = array2.index;
    result.input = array2.input;
  }
  return result;
}
var _initCloneArray = initCloneArray;
function cloneDataView(dataView, isDeep) {
  var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
var _cloneDataView = cloneDataView;
var reFlags = /\w*$/;
function cloneRegExp(regexp) {
  var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  result.lastIndex = regexp.lastIndex;
  return result;
}
var _cloneRegExp = cloneRegExp;
var symbolProto3 = _Symbol ? _Symbol.prototype : void 0;
var symbolValueOf2 = symbolProto3 ? symbolProto3.valueOf : void 0;
function cloneSymbol(symbol) {
  return symbolValueOf2 ? Object(symbolValueOf2.call(symbol)) : {};
}
var _cloneSymbol = cloneSymbol;
var boolTag2 = "[object Boolean]";
var dateTag2 = "[object Date]";
var mapTag2 = "[object Map]";
var numberTag2 = "[object Number]";
var regexpTag2 = "[object RegExp]";
var setTag2 = "[object Set]";
var stringTag2 = "[object String]";
var symbolTag3 = "[object Symbol]";
var arrayBufferTag2 = "[object ArrayBuffer]";
var dataViewTag2 = "[object DataView]";
var float32Tag2 = "[object Float32Array]";
var float64Tag2 = "[object Float64Array]";
var int8Tag2 = "[object Int8Array]";
var int16Tag2 = "[object Int16Array]";
var int32Tag2 = "[object Int32Array]";
var uint8Tag2 = "[object Uint8Array]";
var uint8ClampedTag2 = "[object Uint8ClampedArray]";
var uint16Tag2 = "[object Uint16Array]";
var uint32Tag2 = "[object Uint32Array]";
function initCloneByTag(object, tag, isDeep) {
  var Ctor = object.constructor;
  switch (tag) {
    case arrayBufferTag2:
      return _cloneArrayBuffer(object);
    case boolTag2:
    case dateTag2:
      return new Ctor(+object);
    case dataViewTag2:
      return _cloneDataView(object, isDeep);
    case float32Tag2:
    case float64Tag2:
    case int8Tag2:
    case int16Tag2:
    case int32Tag2:
    case uint8Tag2:
    case uint8ClampedTag2:
    case uint16Tag2:
    case uint32Tag2:
      return _cloneTypedArray(object, isDeep);
    case mapTag2:
      return new Ctor();
    case numberTag2:
    case stringTag2:
      return new Ctor(object);
    case regexpTag2:
      return _cloneRegExp(object);
    case setTag2:
      return new Ctor();
    case symbolTag3:
      return _cloneSymbol(object);
  }
}
var _initCloneByTag = initCloneByTag;
var mapTag$12 = "[object Map]";
function baseIsMap(value) {
  return isObjectLike_1(value) && _getTag(value) == mapTag$12;
}
var _baseIsMap = baseIsMap;
var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
var isMap_1 = isMap;
var setTag$12 = "[object Set]";
function baseIsSet(value) {
  return isObjectLike_1(value) && _getTag(value) == setTag$12;
}
var _baseIsSet = baseIsSet;
var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
var isSet_1 = isSet;
var CLONE_DEEP_FLAG = 1;
var CLONE_FLAT_FLAG = 2;
var CLONE_SYMBOLS_FLAG = 4;
var argsTag2 = "[object Arguments]";
var arrayTag2 = "[object Array]";
var boolTag$12 = "[object Boolean]";
var dateTag$12 = "[object Date]";
var errorTag2 = "[object Error]";
var funcTag2 = "[object Function]";
var genTag2 = "[object GeneratorFunction]";
var mapTag$22 = "[object Map]";
var numberTag$12 = "[object Number]";
var objectTag2 = "[object Object]";
var regexpTag$12 = "[object RegExp]";
var setTag$22 = "[object Set]";
var stringTag$12 = "[object String]";
var symbolTag$1 = "[object Symbol]";
var weakMapTag2 = "[object WeakMap]";
var arrayBufferTag$12 = "[object ArrayBuffer]";
var dataViewTag$12 = "[object DataView]";
var float32Tag$1 = "[object Float32Array]";
var float64Tag$1 = "[object Float64Array]";
var int8Tag$1 = "[object Int8Array]";
var int16Tag$1 = "[object Int16Array]";
var int32Tag$1 = "[object Int32Array]";
var uint8Tag$1 = "[object Uint8Array]";
var uint8ClampedTag$1 = "[object Uint8ClampedArray]";
var uint16Tag$1 = "[object Uint16Array]";
var uint32Tag$1 = "[object Uint32Array]";
var cloneableTags = {};
cloneableTags[argsTag2] = cloneableTags[arrayTag2] = cloneableTags[arrayBufferTag$12] = cloneableTags[dataViewTag$12] = cloneableTags[boolTag$12] = cloneableTags[dateTag$12] = cloneableTags[float32Tag$1] = cloneableTags[float64Tag$1] = cloneableTags[int8Tag$1] = cloneableTags[int16Tag$1] = cloneableTags[int32Tag$1] = cloneableTags[mapTag$22] = cloneableTags[numberTag$12] = cloneableTags[objectTag2] = cloneableTags[regexpTag$12] = cloneableTags[setTag$22] = cloneableTags[stringTag$12] = cloneableTags[symbolTag$1] = cloneableTags[uint8Tag$1] = cloneableTags[uint8ClampedTag$1] = cloneableTags[uint16Tag$1] = cloneableTags[uint32Tag$1] = true;
cloneableTags[errorTag2] = cloneableTags[funcTag2] = cloneableTags[weakMapTag2] = false;
function baseClone(value, bitmask, customizer, key, object, stack2) {
  var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
  if (customizer) {
    result = object ? customizer(value, key, object, stack2) : customizer(value);
  }
  if (result !== void 0) {
    return result;
  }
  if (!isObject_1(value)) {
    return value;
  }
  var isArr = isArray_1(value);
  if (isArr) {
    result = _initCloneArray(value);
    if (!isDeep) {
      return _copyArray(value, result);
    }
  } else {
    var tag = _getTag(value), isFunc = tag == funcTag2 || tag == genTag2;
    if (isBuffer_1(value)) {
      return _cloneBuffer(value, isDeep);
    }
    if (tag == objectTag2 || tag == argsTag2 || isFunc && !object) {
      result = isFlat || isFunc ? {} : _initCloneObject(value);
      if (!isDeep) {
        return isFlat ? _copySymbolsIn(value, _baseAssignIn(result, value)) : _copySymbols(value, _baseAssign(result, value));
      }
    } else {
      if (!cloneableTags[tag]) {
        return object ? value : {};
      }
      result = _initCloneByTag(value, tag, isDeep);
    }
  }
  stack2 || (stack2 = new _Stack());
  var stacked = stack2.get(value);
  if (stacked) {
    return stacked;
  }
  stack2.set(value, result);
  if (isSet_1(value)) {
    value.forEach(function(subValue) {
      result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack2));
    });
  } else if (isMap_1(value)) {
    value.forEach(function(subValue, key2) {
      result.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack2));
    });
  }
  var keysFunc = isFull ? isFlat ? _getAllKeysIn : _getAllKeys : isFlat ? keysIn_1 : keys_1;
  var props = isArr ? void 0 : keysFunc(value);
  _arrayEach(props || value, function(subValue, key2) {
    if (props) {
      key2 = subValue;
      subValue = value[key2];
    }
    _assignValue(result, key2, baseClone(subValue, bitmask, customizer, key2, value, stack2));
  });
  return result;
}
var _baseClone = baseClone;
var CLONE_SYMBOLS_FLAG$1 = 4;
function clone(value) {
  return _baseClone(value, CLONE_SYMBOLS_FLAG$1);
}
var clone_1 = clone;
function baseForOwn(object, iteratee) {
  return object && _baseFor(object, iteratee, keys_1);
}
var _baseForOwn = baseForOwn;
function createBaseEach(eachFunc, fromRight) {
  return function(collection, iteratee) {
    if (collection == null) {
      return collection;
    }
    if (!isArrayLike_1(collection)) {
      return eachFunc(collection, iteratee);
    }
    var length = collection.length, index3 = fromRight ? length : -1, iterable = Object(collection);
    while (fromRight ? index3-- : ++index3 < length) {
      if (iteratee(iterable[index3], index3, iterable) === false) {
        break;
      }
    }
    return collection;
  };
}
var _createBaseEach = createBaseEach;
var baseEach = _createBaseEach(_baseForOwn);
var _baseEach = baseEach;
function castFunction(value) {
  return typeof value == "function" ? value : identity_1;
}
var _castFunction = castFunction;
function forEach4(collection, iteratee) {
  var func = isArray_1(collection) ? _arrayEach : _baseEach;
  return func(collection, _castFunction(iteratee));
}
var forEach_1 = forEach4;
var each = forEach_1;
function baseFilter(collection, predicate) {
  var result = [];
  _baseEach(collection, function(value, index3, collection2) {
    if (predicate(value, index3, collection2)) {
      result.push(value);
    }
  });
  return result;
}
var _baseFilter = baseFilter;
var COMPARE_PARTIAL_FLAG2 = 1;
var COMPARE_UNORDERED_FLAG2 = 2;
function baseIsMatch(object, source2, matchData, customizer) {
  var index3 = matchData.length, length = index3, noCustomizer = !customizer;
  if (object == null) {
    return !length;
  }
  object = Object(object);
  while (index3--) {
    var data2 = matchData[index3];
    if (noCustomizer && data2[2] ? data2[1] !== object[data2[0]] : !(data2[0] in object)) {
      return false;
    }
  }
  while (++index3 < length) {
    data2 = matchData[index3];
    var key = data2[0], objValue = object[key], srcValue = data2[1];
    if (noCustomizer && data2[2]) {
      if (objValue === void 0 && !(key in object)) {
        return false;
      }
    } else {
      var stack2 = new _Stack();
      if (customizer) {
        var result = customizer(objValue, srcValue, key, object, source2, stack2);
      }
      if (!(result === void 0 ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG2 | COMPARE_UNORDERED_FLAG2, customizer, stack2) : result)) {
        return false;
      }
    }
  }
  return true;
}
var _baseIsMatch = baseIsMatch;
function isStrictComparable(value) {
  return value === value && !isObject_1(value);
}
var _isStrictComparable = isStrictComparable;
function getMatchData(object) {
  var result = keys_1(object), length = result.length;
  while (length--) {
    var key = result[length], value = object[key];
    result[length] = [key, value, _isStrictComparable(value)];
  }
  return result;
}
var _getMatchData = getMatchData;
function matchesStrictComparable(key, srcValue) {
  return function(object) {
    if (object == null) {
      return false;
    }
    return object[key] === srcValue && (srcValue !== void 0 || key in Object(object));
  };
}
var _matchesStrictComparable = matchesStrictComparable;
function baseMatches(source2) {
  var matchData = _getMatchData(source2);
  if (matchData.length == 1 && matchData[0][2]) {
    return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  }
  return function(object) {
    return object === source2 || _baseIsMatch(object, source2, matchData);
  };
}
var _baseMatches = baseMatches;
var symbolTag$2 = "[object Symbol]";
function isSymbol2(value) {
  return typeof value == "symbol" || isObjectLike_1(value) && _baseGetTag(value) == symbolTag$2;
}
var isSymbol_1 = isSymbol2;
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
var reIsPlainProp = /^\w*$/;
function isKey2(value, object) {
  if (isArray_1(value)) {
    return false;
  }
  var type = typeof value;
  if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol_1(value)) {
    return true;
  }
  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
}
var _isKey = isKey2;
var FUNC_ERROR_TEXT = "Expected a function";
function memoize2(func, resolver) {
  if (typeof func != "function" || resolver != null && typeof resolver != "function") {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  var memoized = function() {
    var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache3 = memoized.cache;
    if (cache3.has(key)) {
      return cache3.get(key);
    }
    var result = func.apply(this, args);
    memoized.cache = cache3.set(key, result) || cache3;
    return result;
  };
  memoized.cache = new (memoize2.Cache || _MapCache)();
  return memoized;
}
memoize2.Cache = _MapCache;
var memoize_1 = memoize2;
var MAX_MEMOIZE_SIZE = 500;
function memoizeCapped(func) {
  var result = memoize_1(func, function(key) {
    if (cache3.size === MAX_MEMOIZE_SIZE) {
      cache3.clear();
    }
    return key;
  });
  var cache3 = result.cache;
  return result;
}
var _memoizeCapped = memoizeCapped;
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
var reEscapeChar = /\\(\\)?/g;
var stringToPath2 = _memoizeCapped(function(string2) {
  var result = [];
  if (string2.charCodeAt(0) === 46) {
    result.push("");
  }
  string2.replace(rePropName, function(match2, number, quote, subString) {
    result.push(quote ? subString.replace(reEscapeChar, "$1") : number || match2);
  });
  return result;
});
var _stringToPath = stringToPath2;
function arrayMap(array2, iteratee) {
  var index3 = -1, length = array2 == null ? 0 : array2.length, result = Array(length);
  while (++index3 < length) {
    result[index3] = iteratee(array2[index3], index3, array2);
  }
  return result;
}
var _arrayMap = arrayMap;
var INFINITY2 = 1 / 0;
var symbolProto$1 = _Symbol ? _Symbol.prototype : void 0;
var symbolToString2 = symbolProto$1 ? symbolProto$1.toString : void 0;
function baseToString2(value) {
  if (typeof value == "string") {
    return value;
  }
  if (isArray_1(value)) {
    return _arrayMap(value, baseToString2) + "";
  }
  if (isSymbol_1(value)) {
    return symbolToString2 ? symbolToString2.call(value) : "";
  }
  var result = value + "";
  return result == "0" && 1 / value == -INFINITY2 ? "-0" : result;
}
var _baseToString = baseToString2;
function toString4(value) {
  return value == null ? "" : _baseToString(value);
}
var toString_1 = toString4;
function castPath(value, object) {
  if (isArray_1(value)) {
    return value;
  }
  return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
}
var _castPath = castPath;
var INFINITY$1 = 1 / 0;
function toKey(value) {
  if (typeof value == "string" || isSymbol_1(value)) {
    return value;
  }
  var result = value + "";
  return result == "0" && 1 / value == -INFINITY$1 ? "-0" : result;
}
var _toKey = toKey;
function baseGet2(object, path) {
  path = _castPath(path, object);
  var index3 = 0, length = path.length;
  while (object != null && index3 < length) {
    object = object[_toKey(path[index3++])];
  }
  return index3 && index3 == length ? object : void 0;
}
var _baseGet = baseGet2;
function get6(object, path, defaultValue) {
  var result = object == null ? void 0 : _baseGet(object, path);
  return result === void 0 ? defaultValue : result;
}
var get_1 = get6;
function baseHasIn(object, key) {
  return object != null && key in Object(object);
}
var _baseHasIn = baseHasIn;
function hasPath(object, path, hasFunc) {
  path = _castPath(path, object);
  var index3 = -1, length = path.length, result = false;
  while (++index3 < length) {
    var key = _toKey(path[index3]);
    if (!(result = object != null && hasFunc(object, key))) {
      break;
    }
    object = object[key];
  }
  if (result || ++index3 != length) {
    return result;
  }
  length = object == null ? 0 : object.length;
  return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object));
}
var _hasPath = hasPath;
function hasIn(object, path) {
  return object != null && _hasPath(object, path, _baseHasIn);
}
var hasIn_1 = hasIn;
var COMPARE_PARTIAL_FLAG$12 = 1;
var COMPARE_UNORDERED_FLAG$12 = 2;
function baseMatchesProperty(path, srcValue) {
  if (_isKey(path) && _isStrictComparable(srcValue)) {
    return _matchesStrictComparable(_toKey(path), srcValue);
  }
  return function(object) {
    var objValue = get_1(object, path);
    return objValue === void 0 && objValue === srcValue ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$12 | COMPARE_UNORDERED_FLAG$12);
  };
}
var _baseMatchesProperty = baseMatchesProperty;
function baseProperty(key) {
  return function(object) {
    return object == null ? void 0 : object[key];
  };
}
var _baseProperty = baseProperty;
function basePropertyDeep(path) {
  return function(object) {
    return _baseGet(object, path);
  };
}
var _basePropertyDeep = basePropertyDeep;
function property(path) {
  return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
}
var property_1 = property;
function baseIteratee(value) {
  if (typeof value == "function") {
    return value;
  }
  if (value == null) {
    return identity_1;
  }
  if (typeof value == "object") {
    return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value);
  }
  return property_1(value);
}
var _baseIteratee = baseIteratee;
function filter2(collection, predicate) {
  var func = isArray_1(collection) ? _arrayFilter : _baseFilter;
  return func(collection, _baseIteratee(predicate));
}
var filter_1 = filter2;
var objectProto$12 = Object.prototype;
var hasOwnProperty$13 = objectProto$12.hasOwnProperty;
function baseHas(object, key) {
  return object != null && hasOwnProperty$13.call(object, key);
}
var _baseHas = baseHas;
function has2(object, path) {
  return object != null && _hasPath(object, path, _baseHas);
}
var has_1 = has2;
var mapTag$3 = "[object Map]";
var setTag$3 = "[object Set]";
var objectProto$22 = Object.prototype;
var hasOwnProperty$23 = objectProto$22.hasOwnProperty;
function isEmpty2(value) {
  if (value == null) {
    return true;
  }
  if (isArrayLike_1(value) && (isArray_1(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) {
    return !value.length;
  }
  var tag = _getTag(value);
  if (tag == mapTag$3 || tag == setTag$3) {
    return !value.size;
  }
  if (_isPrototype(value)) {
    return !_baseKeys(value).length;
  }
  for (var key in value) {
    if (hasOwnProperty$23.call(value, key)) {
      return false;
    }
  }
  return true;
}
var isEmpty_1 = isEmpty2;
function isUndefined4(value) {
  return value === void 0;
}
var isUndefined_1 = isUndefined4;
function baseMap(collection, iteratee) {
  var index3 = -1, result = isArrayLike_1(collection) ? Array(collection.length) : [];
  _baseEach(collection, function(value, key, collection2) {
    result[++index3] = iteratee(value, key, collection2);
  });
  return result;
}
var _baseMap = baseMap;
function map(collection, iteratee) {
  var func = isArray_1(collection) ? _arrayMap : _baseMap;
  return func(collection, _baseIteratee(iteratee));
}
var map_1 = map;
function arrayReduce2(array2, iteratee, accumulator, initAccum) {
  var index3 = -1, length = array2 == null ? 0 : array2.length;
  if (initAccum && length) {
    accumulator = array2[++index3];
  }
  while (++index3 < length) {
    accumulator = iteratee(accumulator, array2[index3], index3, array2);
  }
  return accumulator;
}
var _arrayReduce = arrayReduce2;
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
  eachFunc(collection, function(value, index3, collection2) {
    accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index3, collection2);
  });
  return accumulator;
}
var _baseReduce = baseReduce;
function reduce(collection, iteratee, accumulator) {
  var func = isArray_1(collection) ? _arrayReduce : _baseReduce, initAccum = arguments.length < 3;
  return func(collection, _baseIteratee(iteratee), accumulator, initAccum, _baseEach);
}
var reduce_1 = reduce;
var stringTag$2 = "[object String]";
function isString4(value) {
  return typeof value == "string" || !isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$2;
}
var isString_1 = isString4;
var asciiSize = _baseProperty("length");
var _asciiSize = asciiSize;
var rsAstralRange2 = "\\ud800-\\udfff";
var rsComboMarksRange2 = "\\u0300-\\u036f";
var reComboHalfMarksRange = "\\ufe20-\\ufe2f";
var rsComboSymbolsRange2 = "\\u20d0-\\u20ff";
var rsComboRange = rsComboMarksRange2 + reComboHalfMarksRange + rsComboSymbolsRange2;
var rsVarRange2 = "\\ufe0e\\ufe0f";
var rsZWJ2 = "\\u200d";
var reHasUnicode2 = RegExp("[" + rsZWJ2 + rsAstralRange2 + rsComboRange + rsVarRange2 + "]");
function hasUnicode2(string2) {
  return reHasUnicode2.test(string2);
}
var _hasUnicode = hasUnicode2;
var rsAstralRange$1 = "\\ud800-\\udfff";
var rsComboMarksRange$1 = "\\u0300-\\u036f";
var reComboHalfMarksRange$1 = "\\ufe20-\\ufe2f";
var rsComboSymbolsRange$1 = "\\u20d0-\\u20ff";
var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1;
var rsVarRange$1 = "\\ufe0e\\ufe0f";
var rsAstral2 = "[" + rsAstralRange$1 + "]";
var rsCombo2 = "[" + rsComboRange$1 + "]";
var rsFitz2 = "\\ud83c[\\udffb-\\udfff]";
var rsModifier2 = "(?:" + rsCombo2 + "|" + rsFitz2 + ")";
var rsNonAstral2 = "[^" + rsAstralRange$1 + "]";
var rsRegional2 = "(?:\\ud83c[\\udde6-\\uddff]){2}";
var rsSurrPair2 = "[\\ud800-\\udbff][\\udc00-\\udfff]";
var rsZWJ$1 = "\\u200d";
var reOptMod2 = rsModifier2 + "?";
var rsOptVar2 = "[" + rsVarRange$1 + "]?";
var rsOptJoin2 = "(?:" + rsZWJ$1 + "(?:" + [rsNonAstral2, rsRegional2, rsSurrPair2].join("|") + ")" + rsOptVar2 + reOptMod2 + ")*";
var rsSeq2 = rsOptVar2 + reOptMod2 + rsOptJoin2;
var rsSymbol2 = "(?:" + [rsNonAstral2 + rsCombo2 + "?", rsCombo2, rsRegional2, rsSurrPair2, rsAstral2].join("|") + ")";
var reUnicode2 = RegExp(rsFitz2 + "(?=" + rsFitz2 + ")|" + rsSymbol2 + rsSeq2, "g");
function unicodeSize(string2) {
  var result = reUnicode2.lastIndex = 0;
  while (reUnicode2.test(string2)) {
    ++result;
  }
  return result;
}
var _unicodeSize = unicodeSize;
function stringSize(string2) {
  return _hasUnicode(string2) ? _unicodeSize(string2) : _asciiSize(string2);
}
var _stringSize = stringSize;
var mapTag$4 = "[object Map]";
var setTag$4 = "[object Set]";
function size(collection) {
  if (collection == null) {
    return 0;
  }
  if (isArrayLike_1(collection)) {
    return isString_1(collection) ? _stringSize(collection) : collection.length;
  }
  var tag = _getTag(collection);
  if (tag == mapTag$4 || tag == setTag$4) {
    return collection.size;
  }
  return _baseKeys(collection).length;
}
var size_1 = size;
function transform2(object, iteratee, accumulator) {
  var isArr = isArray_1(object), isArrLike = isArr || isBuffer_1(object) || isTypedArray_1(object);
  iteratee = _baseIteratee(iteratee);
  if (accumulator == null) {
    var Ctor = object && object.constructor;
    if (isArrLike) {
      accumulator = isArr ? new Ctor() : [];
    } else if (isObject_1(object)) {
      accumulator = isFunction_1(Ctor) ? _baseCreate(_getPrototype(object)) : {};
    } else {
      accumulator = {};
    }
  }
  (isArrLike ? _arrayEach : _baseForOwn)(object, function(value, index3, object2) {
    return iteratee(accumulator, value, index3, object2);
  });
  return accumulator;
}
var transform_1 = transform2;
var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : void 0;
function isFlattenable(value) {
  return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
}
var _isFlattenable = isFlattenable;
function baseFlatten(array2, depth, predicate, isStrict, result) {
  var index3 = -1, length = array2.length;
  predicate || (predicate = _isFlattenable);
  result || (result = []);
  while (++index3 < length) {
    var value = array2[index3];
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        baseFlatten(value, depth - 1, predicate, isStrict, result);
      } else {
        _arrayPush(result, value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }
  return result;
}
var _baseFlatten = baseFlatten;
function baseFindIndex(array2, predicate, fromIndex, fromRight) {
  var length = array2.length, index3 = fromIndex + (fromRight ? 1 : -1);
  while (fromRight ? index3-- : ++index3 < length) {
    if (predicate(array2[index3], index3, array2)) {
      return index3;
    }
  }
  return -1;
}
var _baseFindIndex = baseFindIndex;
function baseIsNaN(value) {
  return value !== value;
}
var _baseIsNaN = baseIsNaN;
function strictIndexOf(array2, value, fromIndex) {
  var index3 = fromIndex - 1, length = array2.length;
  while (++index3 < length) {
    if (array2[index3] === value) {
      return index3;
    }
  }
  return -1;
}
var _strictIndexOf = strictIndexOf;
function baseIndexOf(array2, value, fromIndex) {
  return value === value ? _strictIndexOf(array2, value, fromIndex) : _baseFindIndex(array2, _baseIsNaN, fromIndex);
}
var _baseIndexOf = baseIndexOf;
function arrayIncludes(array2, value) {
  var length = array2 == null ? 0 : array2.length;
  return !!length && _baseIndexOf(array2, value, 0) > -1;
}
var _arrayIncludes = arrayIncludes;
function arrayIncludesWith(array2, value, comparator) {
  var index3 = -1, length = array2 == null ? 0 : array2.length;
  while (++index3 < length) {
    if (comparator(value, array2[index3])) {
      return true;
    }
  }
  return false;
}
var _arrayIncludesWith = arrayIncludesWith;
function noop6() {
}
var noop_1 = noop6;
var INFINITY$2 = 1 / 0;
var createSet = !(_Set && 1 / _setToArray(new _Set([, -0]))[1] == INFINITY$2) ? noop_1 : function(values2) {
  return new _Set(values2);
};
var _createSet = createSet;
var LARGE_ARRAY_SIZE2 = 200;
function baseUniq(array2, iteratee, comparator) {
  var index3 = -1, includes = _arrayIncludes, length = array2.length, isCommon = true, result = [], seen = result;
  if (comparator) {
    isCommon = false;
    includes = _arrayIncludesWith;
  } else if (length >= LARGE_ARRAY_SIZE2) {
    var set3 = iteratee ? null : _createSet(array2);
    if (set3) {
      return _setToArray(set3);
    }
    isCommon = false;
    includes = _cacheHas;
    seen = new _SetCache();
  } else {
    seen = iteratee ? [] : result;
  }
  outer:
    while (++index3 < length) {
      var value = array2[index3], computed = iteratee ? iteratee(value) : value;
      value = comparator || value !== 0 ? value : 0;
      if (isCommon && computed === computed) {
        var seenIndex = seen.length;
        while (seenIndex--) {
          if (seen[seenIndex] === computed) {
            continue outer;
          }
        }
        if (iteratee) {
          seen.push(computed);
        }
        result.push(value);
      } else if (!includes(seen, computed, comparator)) {
        if (seen !== result) {
          seen.push(computed);
        }
        result.push(value);
      }
    }
  return result;
}
var _baseUniq = baseUniq;
var union = _baseRest(function(arrays) {
  return _baseUniq(_baseFlatten(arrays, 1, isArrayLikeObject_1, true));
});
var union_1 = union;
function baseValues(object, props) {
  return _arrayMap(props, function(key) {
    return object[key];
  });
}
var _baseValues = baseValues;
function values(object) {
  return object == null ? [] : _baseValues(object, keys_1(object));
}
var values_1 = values;
var lodash2;
if (typeof commonjsRequire === "function") {
  try {
    lodash2 = {
      clone: clone_1,
      constant: constant_1,
      each,
      filter: filter_1,
      has: has_1,
      isArray: isArray_1,
      isEmpty: isEmpty_1,
      isFunction: isFunction_1,
      isUndefined: isUndefined_1,
      keys: keys_1,
      map: map_1,
      reduce: reduce_1,
      size: size_1,
      transform: transform_1,
      union: union_1,
      values: values_1
    };
  } catch (e2) {
  }
}
if (!lodash2) {
  lodash2 = window._;
}
var lodash_1 = lodash2;
var graph = Graph2;
var DEFAULT_EDGE_NAME = "\0";
var GRAPH_NODE = "\0";
var EDGE_KEY_DELIM = "";
function Graph2(opts) {
  this._isDirected = lodash_1.has(opts, "directed") ? opts.directed : true;
  this._isMultigraph = lodash_1.has(opts, "multigraph") ? opts.multigraph : false;
  this._isCompound = lodash_1.has(opts, "compound") ? opts.compound : false;
  this._label = void 0;
  this._defaultNodeLabelFn = lodash_1.constant(void 0);
  this._defaultEdgeLabelFn = lodash_1.constant(void 0);
  this._nodes = {};
  if (this._isCompound) {
    this._parent = {};
    this._children = {};
    this._children[GRAPH_NODE] = {};
  }
  this._in = {};
  this._preds = {};
  this._out = {};
  this._sucs = {};
  this._edgeObjs = {};
  this._edgeLabels = {};
}
Graph2.prototype._nodeCount = 0;
Graph2.prototype._edgeCount = 0;
Graph2.prototype.isDirected = function() {
  return this._isDirected;
};
Graph2.prototype.isMultigraph = function() {
  return this._isMultigraph;
};
Graph2.prototype.isCompound = function() {
  return this._isCompound;
};
Graph2.prototype.setGraph = function(label2) {
  this._label = label2;
  return this;
};
Graph2.prototype.graph = function() {
  return this._label;
};
Graph2.prototype.setDefaultNodeLabel = function(newDefault) {
  if (!lodash_1.isFunction(newDefault)) {
    newDefault = lodash_1.constant(newDefault);
  }
  this._defaultNodeLabelFn = newDefault;
  return this;
};
Graph2.prototype.nodeCount = function() {
  return this._nodeCount;
};
Graph2.prototype.nodes = function() {
  return lodash_1.keys(this._nodes);
};
Graph2.prototype.sources = function() {
  var self2 = this;
  return lodash_1.filter(this.nodes(), function(v2) {
    return lodash_1.isEmpty(self2._in[v2]);
  });
};
Graph2.prototype.sinks = function() {
  var self2 = this;
  return lodash_1.filter(this.nodes(), function(v2) {
    return lodash_1.isEmpty(self2._out[v2]);
  });
};
Graph2.prototype.setNodes = function(vs2, value) {
  var args = arguments;
  var self2 = this;
  lodash_1.each(vs2, function(v2) {
    if (args.length > 1) {
      self2.setNode(v2, value);
    } else {
      self2.setNode(v2);
    }
  });
  return this;
};
Graph2.prototype.setNode = function(v2, value) {
  if (lodash_1.has(this._nodes, v2)) {
    if (arguments.length > 1) {
      this._nodes[v2] = value;
    }
    return this;
  }
  this._nodes[v2] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v2);
  if (this._isCompound) {
    this._parent[v2] = GRAPH_NODE;
    this._children[v2] = {};
    this._children[GRAPH_NODE][v2] = true;
  }
  this._in[v2] = {};
  this._preds[v2] = {};
  this._out[v2] = {};
  this._sucs[v2] = {};
  ++this._nodeCount;
  return this;
};
Graph2.prototype.node = function(v2) {
  return this._nodes[v2];
};
Graph2.prototype.hasNode = function(v2) {
  return lodash_1.has(this._nodes, v2);
};
Graph2.prototype.removeNode = function(v2) {
  var self2 = this;
  if (lodash_1.has(this._nodes, v2)) {
    var removeEdge = function(e2) {
      self2.removeEdge(self2._edgeObjs[e2]);
    };
    delete this._nodes[v2];
    if (this._isCompound) {
      this._removeFromParentsChildList(v2);
      delete this._parent[v2];
      lodash_1.each(this.children(v2), function(child) {
        self2.setParent(child);
      });
      delete this._children[v2];
    }
    lodash_1.each(lodash_1.keys(this._in[v2]), removeEdge);
    delete this._in[v2];
    delete this._preds[v2];
    lodash_1.each(lodash_1.keys(this._out[v2]), removeEdge);
    delete this._out[v2];
    delete this._sucs[v2];
    --this._nodeCount;
  }
  return this;
};
Graph2.prototype.setParent = function(v2, parent) {
  if (!this._isCompound) {
    throw new Error("Cannot set parent in a non-compound graph");
  }
  if (lodash_1.isUndefined(parent)) {
    parent = GRAPH_NODE;
  } else {
    parent += "";
    for (var ancestor = parent; !lodash_1.isUndefined(ancestor); ancestor = this.parent(ancestor)) {
      if (ancestor === v2) {
        throw new Error("Setting " + parent + " as parent of " + v2 + " would create a cycle");
      }
    }
    this.setNode(parent);
  }
  this.setNode(v2);
  this._removeFromParentsChildList(v2);
  this._parent[v2] = parent;
  this._children[parent][v2] = true;
  return this;
};
Graph2.prototype._removeFromParentsChildList = function(v2) {
  delete this._children[this._parent[v2]][v2];
};
Graph2.prototype.parent = function(v2) {
  if (this._isCompound) {
    var parent = this._parent[v2];
    if (parent !== GRAPH_NODE) {
      return parent;
    }
  }
};
Graph2.prototype.children = function(v2) {
  if (lodash_1.isUndefined(v2)) {
    v2 = GRAPH_NODE;
  }
  if (this._isCompound) {
    var children2 = this._children[v2];
    if (children2) {
      return lodash_1.keys(children2);
    }
  } else if (v2 === GRAPH_NODE) {
    return this.nodes();
  } else if (this.hasNode(v2)) {
    return [];
  }
};
Graph2.prototype.predecessors = function(v2) {
  var predsV = this._preds[v2];
  if (predsV) {
    return lodash_1.keys(predsV);
  }
};
Graph2.prototype.successors = function(v2) {
  var sucsV = this._sucs[v2];
  if (sucsV) {
    return lodash_1.keys(sucsV);
  }
};
Graph2.prototype.neighbors = function(v2) {
  var preds = this.predecessors(v2);
  if (preds) {
    return lodash_1.union(preds, this.successors(v2));
  }
};
Graph2.prototype.isLeaf = function(v2) {
  var neighbors;
  if (this.isDirected()) {
    neighbors = this.successors(v2);
  } else {
    neighbors = this.neighbors(v2);
  }
  return neighbors.length === 0;
};
Graph2.prototype.filterNodes = function(filter3) {
  var copy2 = new this.constructor({
    directed: this._isDirected,
    multigraph: this._isMultigraph,
    compound: this._isCompound
  });
  copy2.setGraph(this.graph());
  var self2 = this;
  lodash_1.each(this._nodes, function(value, v2) {
    if (filter3(v2)) {
      copy2.setNode(v2, value);
    }
  });
  lodash_1.each(this._edgeObjs, function(e2) {
    if (copy2.hasNode(e2.v) && copy2.hasNode(e2.w)) {
      copy2.setEdge(e2, self2.edge(e2));
    }
  });
  var parents = {};
  function findParent(v2) {
    var parent = self2.parent(v2);
    if (parent === void 0 || copy2.hasNode(parent)) {
      parents[v2] = parent;
      return parent;
    } else if (parent in parents) {
      return parents[parent];
    } else {
      return findParent(parent);
    }
  }
  if (this._isCompound) {
    lodash_1.each(copy2.nodes(), function(v2) {
      copy2.setParent(v2, findParent(v2));
    });
  }
  return copy2;
};
Graph2.prototype.setDefaultEdgeLabel = function(newDefault) {
  if (!lodash_1.isFunction(newDefault)) {
    newDefault = lodash_1.constant(newDefault);
  }
  this._defaultEdgeLabelFn = newDefault;
  return this;
};
Graph2.prototype.edgeCount = function() {
  return this._edgeCount;
};
Graph2.prototype.edges = function() {
  return lodash_1.values(this._edgeObjs);
};
Graph2.prototype.setPath = function(vs2, value) {
  var self2 = this;
  var args = arguments;
  lodash_1.reduce(vs2, function(v2, w2) {
    if (args.length > 1) {
      self2.setEdge(v2, w2, value);
    } else {
      self2.setEdge(v2, w2);
    }
    return w2;
  });
  return this;
};
Graph2.prototype.setEdge = function() {
  var v2, w2, name, value;
  var valueSpecified = false;
  var arg0 = arguments[0];
  if (typeof arg0 === "object" && arg0 !== null && "v" in arg0) {
    v2 = arg0.v;
    w2 = arg0.w;
    name = arg0.name;
    if (arguments.length === 2) {
      value = arguments[1];
      valueSpecified = true;
    }
  } else {
    v2 = arg0;
    w2 = arguments[1];
    name = arguments[3];
    if (arguments.length > 2) {
      value = arguments[2];
      valueSpecified = true;
    }
  }
  v2 = "" + v2;
  w2 = "" + w2;
  if (!lodash_1.isUndefined(name)) {
    name = "" + name;
  }
  var e2 = edgeArgsToId(this._isDirected, v2, w2, name);
  if (lodash_1.has(this._edgeLabels, e2)) {
    if (valueSpecified) {
      this._edgeLabels[e2] = value;
    }
    return this;
  }
  if (!lodash_1.isUndefined(name) && !this._isMultigraph) {
    throw new Error("Cannot set a named edge when isMultigraph = false");
  }
  this.setNode(v2);
  this.setNode(w2);
  this._edgeLabels[e2] = valueSpecified ? value : this._defaultEdgeLabelFn(v2, w2, name);
  var edgeObj = edgeArgsToObj(this._isDirected, v2, w2, name);
  v2 = edgeObj.v;
  w2 = edgeObj.w;
  Object.freeze(edgeObj);
  this._edgeObjs[e2] = edgeObj;
  incrementOrInitEntry(this._preds[w2], v2);
  incrementOrInitEntry(this._sucs[v2], w2);
  this._in[w2][e2] = edgeObj;
  this._out[v2][e2] = edgeObj;
  this._edgeCount++;
  return this;
};
Graph2.prototype.edge = function(v2, w2, name) {
  var e2 = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v2, w2, name);
  return this._edgeLabels[e2];
};
Graph2.prototype.hasEdge = function(v2, w2, name) {
  var e2 = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v2, w2, name);
  return lodash_1.has(this._edgeLabels, e2);
};
Graph2.prototype.removeEdge = function(v2, w2, name) {
  var e2 = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v2, w2, name);
  var edge = this._edgeObjs[e2];
  if (edge) {
    v2 = edge.v;
    w2 = edge.w;
    delete this._edgeLabels[e2];
    delete this._edgeObjs[e2];
    decrementOrRemoveEntry(this._preds[w2], v2);
    decrementOrRemoveEntry(this._sucs[v2], w2);
    delete this._in[w2][e2];
    delete this._out[v2][e2];
    this._edgeCount--;
  }
  return this;
};
Graph2.prototype.inEdges = function(v2, u) {
  var inV = this._in[v2];
  if (inV) {
    var edges = lodash_1.values(inV);
    if (!u) {
      return edges;
    }
    return lodash_1.filter(edges, function(edge) {
      return edge.v === u;
    });
  }
};
Graph2.prototype.outEdges = function(v2, w2) {
  var outV = this._out[v2];
  if (outV) {
    var edges = lodash_1.values(outV);
    if (!w2) {
      return edges;
    }
    return lodash_1.filter(edges, function(edge) {
      return edge.w === w2;
    });
  }
};
Graph2.prototype.nodeEdges = function(v2, w2) {
  var inEdges = this.inEdges(v2, w2);
  if (inEdges) {
    return inEdges.concat(this.outEdges(v2, w2));
  }
};
function incrementOrInitEntry(map2, k2) {
  if (map2[k2]) {
    map2[k2]++;
  } else {
    map2[k2] = 1;
  }
}
function decrementOrRemoveEntry(map2, k2) {
  if (!--map2[k2]) {
    delete map2[k2];
  }
}
function edgeArgsToId(isDirected, v_, w_, name) {
  var v2 = "" + v_;
  var w2 = "" + w_;
  if (!isDirected && v2 > w2) {
    var tmp = v2;
    v2 = w2;
    w2 = tmp;
  }
  return v2 + EDGE_KEY_DELIM + w2 + EDGE_KEY_DELIM + (lodash_1.isUndefined(name) ? DEFAULT_EDGE_NAME : name);
}
function edgeArgsToObj(isDirected, v_, w_, name) {
  var v2 = "" + v_;
  var w2 = "" + w_;
  if (!isDirected && v2 > w2) {
    var tmp = v2;
    v2 = w2;
    w2 = tmp;
  }
  var edgeObj = {v: v2, w: w2};
  if (name) {
    edgeObj.name = name;
  }
  return edgeObj;
}
function edgeObjToId(isDirected, edgeObj) {
  return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name);
}
var version3 = "2.1.8";
var lib2 = {
  Graph: graph,
  version: version3
};
var json = {
  write: write2,
  read: read2
};
function write2(g2) {
  var json2 = {
    options: {
      directed: g2.isDirected(),
      multigraph: g2.isMultigraph(),
      compound: g2.isCompound()
    },
    nodes: writeNodes(g2),
    edges: writeEdges(g2)
  };
  if (!lodash_1.isUndefined(g2.graph())) {
    json2.value = lodash_1.clone(g2.graph());
  }
  return json2;
}
function writeNodes(g2) {
  return lodash_1.map(g2.nodes(), function(v2) {
    var nodeValue = g2.node(v2);
    var parent = g2.parent(v2);
    var node = {v: v2};
    if (!lodash_1.isUndefined(nodeValue)) {
      node.value = nodeValue;
    }
    if (!lodash_1.isUndefined(parent)) {
      node.parent = parent;
    }
    return node;
  });
}
function writeEdges(g2) {
  return lodash_1.map(g2.edges(), function(e2) {
    var edgeValue = g2.edge(e2);
    var edge = {v: e2.v, w: e2.w};
    if (!lodash_1.isUndefined(e2.name)) {
      edge.name = e2.name;
    }
    if (!lodash_1.isUndefined(edgeValue)) {
      edge.value = edgeValue;
    }
    return edge;
  });
}
function read2(json2) {
  var g2 = new graph(json2.options).setGraph(json2.value);
  lodash_1.each(json2.nodes, function(entry) {
    g2.setNode(entry.v, entry.value);
    if (entry.parent) {
      g2.setParent(entry.v, entry.parent);
    }
  });
  lodash_1.each(json2.edges, function(entry) {
    g2.setEdge({v: entry.v, w: entry.w, name: entry.name}, entry.value);
  });
  return g2;
}
var components_1 = components2;
function components2(g2) {
  var visited = {};
  var cmpts = [];
  var cmpt;
  function dfs3(v2) {
    if (lodash_1.has(visited, v2))
      return;
    visited[v2] = true;
    cmpt.push(v2);
    lodash_1.each(g2.successors(v2), dfs3);
    lodash_1.each(g2.predecessors(v2), dfs3);
  }
  lodash_1.each(g2.nodes(), function(v2) {
    cmpt = [];
    dfs3(v2);
    if (cmpt.length) {
      cmpts.push(cmpt);
    }
  });
  return cmpts;
}
var priorityQueue = PriorityQueue;
function PriorityQueue() {
  this._arr = [];
  this._keyIndices = {};
}
PriorityQueue.prototype.size = function() {
  return this._arr.length;
};
PriorityQueue.prototype.keys = function() {
  return this._arr.map(function(x2) {
    return x2.key;
  });
};
PriorityQueue.prototype.has = function(key) {
  return lodash_1.has(this._keyIndices, key);
};
PriorityQueue.prototype.priority = function(key) {
  var index3 = this._keyIndices[key];
  if (index3 !== void 0) {
    return this._arr[index3].priority;
  }
};
PriorityQueue.prototype.min = function() {
  if (this.size() === 0) {
    throw new Error("Queue underflow");
  }
  return this._arr[0].key;
};
PriorityQueue.prototype.add = function(key, priority) {
  var keyIndices = this._keyIndices;
  key = String(key);
  if (!lodash_1.has(keyIndices, key)) {
    var arr = this._arr;
    var index3 = arr.length;
    keyIndices[key] = index3;
    arr.push({key, priority});
    this._decrease(index3);
    return true;
  }
  return false;
};
PriorityQueue.prototype.removeMin = function() {
  this._swap(0, this._arr.length - 1);
  var min2 = this._arr.pop();
  delete this._keyIndices[min2.key];
  this._heapify(0);
  return min2.key;
};
PriorityQueue.prototype.decrease = function(key, priority) {
  var index3 = this._keyIndices[key];
  if (priority > this._arr[index3].priority) {
    throw new Error("New priority is greater than current priority. Key: " + key + " Old: " + this._arr[index3].priority + " New: " + priority);
  }
  this._arr[index3].priority = priority;
  this._decrease(index3);
};
PriorityQueue.prototype._heapify = function(i3) {
  var arr = this._arr;
  var l2 = 2 * i3;
  var r3 = l2 + 1;
  var largest = i3;
  if (l2 < arr.length) {
    largest = arr[l2].priority < arr[largest].priority ? l2 : largest;
    if (r3 < arr.length) {
      largest = arr[r3].priority < arr[largest].priority ? r3 : largest;
    }
    if (largest !== i3) {
      this._swap(i3, largest);
      this._heapify(largest);
    }
  }
};
PriorityQueue.prototype._decrease = function(index3) {
  var arr = this._arr;
  var priority = arr[index3].priority;
  var parent;
  while (index3 !== 0) {
    parent = index3 >> 1;
    if (arr[parent].priority < priority) {
      break;
    }
    this._swap(index3, parent);
    index3 = parent;
  }
};
PriorityQueue.prototype._swap = function(i3, j) {
  var arr = this._arr;
  var keyIndices = this._keyIndices;
  var origArrI = arr[i3];
  var origArrJ = arr[j];
  arr[i3] = origArrJ;
  arr[j] = origArrI;
  keyIndices[origArrJ.key] = i3;
  keyIndices[origArrI.key] = j;
};
var dijkstra_1 = dijkstra;
var DEFAULT_WEIGHT_FUNC = lodash_1.constant(1);
function dijkstra(g2, source2, weightFn, edgeFn) {
  return runDijkstra(g2, String(source2), weightFn || DEFAULT_WEIGHT_FUNC, edgeFn || function(v2) {
    return g2.outEdges(v2);
  });
}
function runDijkstra(g2, source2, weightFn, edgeFn) {
  var results = {};
  var pq = new priorityQueue();
  var v2, vEntry;
  var updateNeighbors = function(edge) {
    var w2 = edge.v !== v2 ? edge.v : edge.w;
    var wEntry = results[w2];
    var weight = weightFn(edge);
    var distance = vEntry.distance + weight;
    if (weight < 0) {
      throw new Error("dijkstra does not allow negative edge weights. Bad edge: " + edge + " Weight: " + weight);
    }
    if (distance < wEntry.distance) {
      wEntry.distance = distance;
      wEntry.predecessor = v2;
      pq.decrease(w2, distance);
    }
  };
  g2.nodes().forEach(function(v3) {
    var distance = v3 === source2 ? 0 : Number.POSITIVE_INFINITY;
    results[v3] = {distance};
    pq.add(v3, distance);
  });
  while (pq.size() > 0) {
    v2 = pq.removeMin();
    vEntry = results[v2];
    if (vEntry.distance === Number.POSITIVE_INFINITY) {
      break;
    }
    edgeFn(v2).forEach(updateNeighbors);
  }
  return results;
}
var dijkstraAll_1 = dijkstraAll;
function dijkstraAll(g2, weightFunc, edgeFunc) {
  return lodash_1.transform(g2.nodes(), function(acc, v2) {
    acc[v2] = dijkstra_1(g2, v2, weightFunc, edgeFunc);
  }, {});
}
var tarjan_1 = tarjan;
function tarjan(g2) {
  var index3 = 0;
  var stack2 = [];
  var visited = {};
  var results = [];
  function dfs3(v2) {
    var entry = visited[v2] = {
      onStack: true,
      lowlink: index3,
      index: index3++
    };
    stack2.push(v2);
    g2.successors(v2).forEach(function(w3) {
      if (!lodash_1.has(visited, w3)) {
        dfs3(w3);
        entry.lowlink = Math.min(entry.lowlink, visited[w3].lowlink);
      } else if (visited[w3].onStack) {
        entry.lowlink = Math.min(entry.lowlink, visited[w3].index);
      }
    });
    if (entry.lowlink === entry.index) {
      var cmpt = [];
      var w2;
      do {
        w2 = stack2.pop();
        visited[w2].onStack = false;
        cmpt.push(w2);
      } while (v2 !== w2);
      results.push(cmpt);
    }
  }
  g2.nodes().forEach(function(v2) {
    if (!lodash_1.has(visited, v2)) {
      dfs3(v2);
    }
  });
  return results;
}
var findCycles_1 = findCycles;
function findCycles(g2) {
  return lodash_1.filter(tarjan_1(g2), function(cmpt) {
    return cmpt.length > 1 || cmpt.length === 1 && g2.hasEdge(cmpt[0], cmpt[0]);
  });
}
var floydWarshall_1 = floydWarshall;
var DEFAULT_WEIGHT_FUNC$1 = lodash_1.constant(1);
function floydWarshall(g2, weightFn, edgeFn) {
  return runFloydWarshall(g2, weightFn || DEFAULT_WEIGHT_FUNC$1, edgeFn || function(v2) {
    return g2.outEdges(v2);
  });
}
function runFloydWarshall(g2, weightFn, edgeFn) {
  var results = {};
  var nodes = g2.nodes();
  nodes.forEach(function(v2) {
    results[v2] = {};
    results[v2][v2] = {distance: 0};
    nodes.forEach(function(w2) {
      if (v2 !== w2) {
        results[v2][w2] = {distance: Number.POSITIVE_INFINITY};
      }
    });
    edgeFn(v2).forEach(function(edge) {
      var w2 = edge.v === v2 ? edge.w : edge.v;
      var d2 = weightFn(edge);
      results[v2][w2] = {distance: d2, predecessor: v2};
    });
  });
  nodes.forEach(function(k2) {
    var rowK = results[k2];
    nodes.forEach(function(i3) {
      var rowI = results[i3];
      nodes.forEach(function(j) {
        var ik2 = rowI[k2];
        var kj2 = rowK[j];
        var ij2 = rowI[j];
        var altDistance = ik2.distance + kj2.distance;
        if (altDistance < ij2.distance) {
          ij2.distance = altDistance;
          ij2.predecessor = kj2.predecessor;
        }
      });
    });
  });
  return results;
}
var topsort_1 = topsort;
topsort.CycleException = CycleException;
function topsort(g2) {
  var visited = {};
  var stack2 = {};
  var results = [];
  function visit(node) {
    if (lodash_1.has(stack2, node)) {
      throw new CycleException();
    }
    if (!lodash_1.has(visited, node)) {
      stack2[node] = true;
      visited[node] = true;
      lodash_1.each(g2.predecessors(node), visit);
      delete stack2[node];
      results.push(node);
    }
  }
  lodash_1.each(g2.sinks(), visit);
  if (lodash_1.size(visited) !== g2.nodeCount()) {
    throw new CycleException();
  }
  return results;
}
function CycleException() {
}
CycleException.prototype = new Error();
var isAcyclic_1 = isAcyclic;
function isAcyclic(g2) {
  try {
    topsort_1(g2);
  } catch (e2) {
    if (e2 instanceof topsort_1.CycleException) {
      return false;
    }
    throw e2;
  }
  return true;
}
var dfs_1 = dfs2;
function dfs2(g2, vs2, order3) {
  if (!lodash_1.isArray(vs2)) {
    vs2 = [vs2];
  }
  var navigation = (g2.isDirected() ? g2.successors : g2.neighbors).bind(g2);
  var acc = [];
  var visited = {};
  lodash_1.each(vs2, function(v2) {
    if (!g2.hasNode(v2)) {
      throw new Error("Graph does not have node: " + v2);
    }
    doDfs(g2, v2, order3 === "post", visited, navigation, acc);
  });
  return acc;
}
function doDfs(g2, v2, postorder2, visited, navigation, acc) {
  if (!lodash_1.has(visited, v2)) {
    visited[v2] = true;
    if (!postorder2) {
      acc.push(v2);
    }
    lodash_1.each(navigation(v2), function(w2) {
      doDfs(g2, w2, postorder2, visited, navigation, acc);
    });
    if (postorder2) {
      acc.push(v2);
    }
  }
}
var postorder_1 = postorder;
function postorder(g2, vs2) {
  return dfs_1(g2, vs2, "post");
}
var preorder_1 = preorder;
function preorder(g2, vs2) {
  return dfs_1(g2, vs2, "pre");
}
var prim_1 = prim;
function prim(g2, weightFunc) {
  var result = new graph();
  var parents = {};
  var pq = new priorityQueue();
  var v2;
  function updateNeighbors(edge) {
    var w2 = edge.v === v2 ? edge.w : edge.v;
    var pri = pq.priority(w2);
    if (pri !== void 0) {
      var edgeWeight = weightFunc(edge);
      if (edgeWeight < pri) {
        parents[w2] = v2;
        pq.decrease(w2, edgeWeight);
      }
    }
  }
  if (g2.nodeCount() === 0) {
    return result;
  }
  lodash_1.each(g2.nodes(), function(v3) {
    pq.add(v3, Number.POSITIVE_INFINITY);
    result.setNode(v3);
  });
  pq.decrease(g2.nodes()[0], 0);
  var init4 = false;
  while (pq.size() > 0) {
    v2 = pq.removeMin();
    if (lodash_1.has(parents, v2)) {
      result.setEdge(v2, parents[v2]);
    } else if (init4) {
      throw new Error("Input graph is not connected: " + g2);
    } else {
      init4 = true;
    }
    g2.nodeEdges(v2).forEach(updateNeighbors);
  }
  return result;
}
var alg = {
  components: components_1,
  dijkstra: dijkstra_1,
  dijkstraAll: dijkstraAll_1,
  findCycles: findCycles_1,
  floydWarshall: floydWarshall_1,
  isAcyclic: isAcyclic_1,
  postorder: postorder_1,
  preorder: preorder_1,
  prim: prim_1,
  tarjan: tarjan_1,
  topsort: topsort_1
};
var graphlib = {
  Graph: lib2.Graph,
  json,
  alg,
  version: lib2.version
};
var graphlib$1;
if (typeof commonjsRequire === "function") {
  try {
    graphlib$1 = graphlib;
  } catch (e2) {
  }
}
if (!graphlib$1) {
  graphlib$1 = window.graphlib;
}
var graphlib_1 = graphlib$1;
var CLONE_DEEP_FLAG$1 = 1;
var CLONE_SYMBOLS_FLAG$2 = 4;
function cloneDeep2(value) {
  return _baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$2);
}
var cloneDeep_1 = cloneDeep2;
var objectProto$32 = Object.prototype;
var hasOwnProperty$33 = objectProto$32.hasOwnProperty;
var defaults2 = _baseRest(function(object, sources) {
  object = Object(object);
  var index3 = -1;
  var length = sources.length;
  var guard = length > 2 ? sources[2] : void 0;
  if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
    length = 1;
  }
  while (++index3 < length) {
    var source2 = sources[index3];
    var props = keysIn_1(source2);
    var propsIndex = -1;
    var propsLength = props.length;
    while (++propsIndex < propsLength) {
      var key = props[propsIndex];
      var value = object[key];
      if (value === void 0 || eq_1(value, objectProto$32[key]) && !hasOwnProperty$33.call(object, key)) {
        object[key] = source2[key];
      }
    }
  }
  return object;
});
var defaults_12 = defaults2;
function createFind(findIndexFunc) {
  return function(collection, predicate, fromIndex) {
    var iterable = Object(collection);
    if (!isArrayLike_1(collection)) {
      var iteratee = _baseIteratee(predicate);
      collection = keys_1(collection);
      predicate = function(key) {
        return iteratee(iterable[key], key, iterable);
      };
    }
    var index3 = findIndexFunc(collection, predicate, fromIndex);
    return index3 > -1 ? iterable[iteratee ? collection[index3] : index3] : void 0;
  };
}
var _createFind = createFind;
var reWhitespace = /\s/;
function trimmedEndIndex(string2) {
  var index3 = string2.length;
  while (index3-- && reWhitespace.test(string2.charAt(index3))) {
  }
  return index3;
}
var _trimmedEndIndex = trimmedEndIndex;
var reTrimStart = /^\s+/;
function baseTrim(string2) {
  return string2 ? string2.slice(0, _trimmedEndIndex(string2) + 1).replace(reTrimStart, "") : string2;
}
var _baseTrim = baseTrim;
var NAN = 0 / 0;
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
var reIsBinary = /^0b[01]+$/i;
var reIsOctal = /^0o[0-7]+$/i;
var freeParseInt = parseInt;
function toNumber(value) {
  if (typeof value == "number") {
    return value;
  }
  if (isSymbol_1(value)) {
    return NAN;
  }
  if (isObject_1(value)) {
    var other = typeof value.valueOf == "function" ? value.valueOf() : value;
    value = isObject_1(other) ? other + "" : other;
  }
  if (typeof value != "string") {
    return value === 0 ? value : +value;
  }
  value = _baseTrim(value);
  var isBinary = reIsBinary.test(value);
  return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
var toNumber_1 = toNumber;
var INFINITY$3 = 1 / 0;
var MAX_INTEGER = 17976931348623157e292;
function toFinite(value) {
  if (!value) {
    return value === 0 ? value : 0;
  }
  value = toNumber_1(value);
  if (value === INFINITY$3 || value === -INFINITY$3) {
    var sign = value < 0 ? -1 : 1;
    return sign * MAX_INTEGER;
  }
  return value === value ? value : 0;
}
var toFinite_1 = toFinite;
function toInteger(value) {
  var result = toFinite_1(value), remainder = result % 1;
  return result === result ? remainder ? result - remainder : result : 0;
}
var toInteger_1 = toInteger;
var nativeMax2 = Math.max;
function findIndex(array2, predicate, fromIndex) {
  var length = array2 == null ? 0 : array2.length;
  if (!length) {
    return -1;
  }
  var index3 = fromIndex == null ? 0 : toInteger_1(fromIndex);
  if (index3 < 0) {
    index3 = nativeMax2(length + index3, 0);
  }
  return _baseFindIndex(array2, _baseIteratee(predicate), index3);
}
var findIndex_1 = findIndex;
var find2 = _createFind(findIndex_1);
var find_1 = find2;
function flatten3(array2) {
  var length = array2 == null ? 0 : array2.length;
  return length ? _baseFlatten(array2, 1) : [];
}
var flatten_1 = flatten3;
function forIn(object, iteratee) {
  return object == null ? object : _baseFor(object, _castFunction(iteratee), keysIn_1);
}
var forIn_1 = forIn;
function last(array2) {
  var length = array2 == null ? 0 : array2.length;
  return length ? array2[length - 1] : void 0;
}
var last_1 = last;
function mapValues(object, iteratee) {
  var result = {};
  iteratee = _baseIteratee(iteratee);
  _baseForOwn(object, function(value, key, object2) {
    _baseAssignValue(result, key, iteratee(value, key, object2));
  });
  return result;
}
var mapValues_1 = mapValues;
function baseExtremum(array2, iteratee, comparator) {
  var index3 = -1, length = array2.length;
  while (++index3 < length) {
    var value = array2[index3], current = iteratee(value);
    if (current != null && (computed === void 0 ? current === current && !isSymbol_1(current) : comparator(current, computed))) {
      var computed = current, result = value;
    }
  }
  return result;
}
var _baseExtremum = baseExtremum;
function baseGt(value, other) {
  return value > other;
}
var _baseGt = baseGt;
function max(array2) {
  return array2 && array2.length ? _baseExtremum(array2, identity_1, _baseGt) : void 0;
}
var max_1 = max;
var merge2 = _createAssigner(function(object, source2, srcIndex) {
  _baseMerge(object, source2, srcIndex);
});
var merge_1 = merge2;
function baseLt(value, other) {
  return value < other;
}
var _baseLt = baseLt;
function min(array2) {
  return array2 && array2.length ? _baseExtremum(array2, identity_1, _baseLt) : void 0;
}
var min_1 = min;
function minBy(array2, iteratee) {
  return array2 && array2.length ? _baseExtremum(array2, _baseIteratee(iteratee), _baseLt) : void 0;
}
var minBy_1 = minBy;
var now2 = function() {
  return _root.Date.now();
};
var now_1 = now2;
function baseSet(object, path, value, customizer) {
  if (!isObject_1(object)) {
    return object;
  }
  path = _castPath(path, object);
  var index3 = -1, length = path.length, lastIndex = length - 1, nested = object;
  while (nested != null && ++index3 < length) {
    var key = _toKey(path[index3]), newValue = value;
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      return object;
    }
    if (index3 != lastIndex) {
      var objValue = nested[key];
      newValue = customizer ? customizer(objValue, key, nested) : void 0;
      if (newValue === void 0) {
        newValue = isObject_1(objValue) ? objValue : _isIndex(path[index3 + 1]) ? [] : {};
      }
    }
    _assignValue(nested, key, newValue);
    nested = nested[key];
  }
  return object;
}
var _baseSet = baseSet;
function basePickBy(object, paths, predicate) {
  var index3 = -1, length = paths.length, result = {};
  while (++index3 < length) {
    var path = paths[index3], value = _baseGet(object, path);
    if (predicate(value, path)) {
      _baseSet(result, _castPath(path, object), value);
    }
  }
  return result;
}
var _basePickBy = basePickBy;
function basePick(object, paths) {
  return _basePickBy(object, paths, function(value, path) {
    return hasIn_1(object, path);
  });
}
var _basePick = basePick;
function flatRest(func) {
  return _setToString(_overRest(func, void 0, flatten_1), func + "");
}
var _flatRest = flatRest;
var pick = _flatRest(function(object, paths) {
  return object == null ? {} : _basePick(object, paths);
});
var pick_1 = pick;
var nativeCeil = Math.ceil;
var nativeMax$1 = Math.max;
function baseRange(start3, end2, step, fromRight) {
  var index3 = -1, length = nativeMax$1(nativeCeil((end2 - start3) / (step || 1)), 0), result = Array(length);
  while (length--) {
    result[fromRight ? length : ++index3] = start3;
    start3 += step;
  }
  return result;
}
var _baseRange = baseRange;
function createRange(fromRight) {
  return function(start3, end2, step) {
    if (step && typeof step != "number" && _isIterateeCall(start3, end2, step)) {
      end2 = step = void 0;
    }
    start3 = toFinite_1(start3);
    if (end2 === void 0) {
      end2 = start3;
      start3 = 0;
    } else {
      end2 = toFinite_1(end2);
    }
    step = step === void 0 ? start3 < end2 ? 1 : -1 : toFinite_1(step);
    return _baseRange(start3, end2, step, fromRight);
  };
}
var _createRange = createRange;
var range2 = _createRange();
var range_1 = range2;
function baseSortBy(array2, comparer) {
  var length = array2.length;
  array2.sort(comparer);
  while (length--) {
    array2[length] = array2[length].value;
  }
  return array2;
}
var _baseSortBy = baseSortBy;
function compareAscending(value, other) {
  if (value !== other) {
    var valIsDefined = value !== void 0, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value);
    var othIsDefined = other !== void 0, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other);
    if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) {
      return 1;
    }
    if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) {
      return -1;
    }
  }
  return 0;
}
var _compareAscending = compareAscending;
function compareMultiple(object, other, orders) {
  var index3 = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length;
  while (++index3 < length) {
    var result = _compareAscending(objCriteria[index3], othCriteria[index3]);
    if (result) {
      if (index3 >= ordersLength) {
        return result;
      }
      var order3 = orders[index3];
      return result * (order3 == "desc" ? -1 : 1);
    }
  }
  return object.index - other.index;
}
var _compareMultiple = compareMultiple;
function baseOrderBy(collection, iteratees, orders) {
  if (iteratees.length) {
    iteratees = _arrayMap(iteratees, function(iteratee) {
      if (isArray_1(iteratee)) {
        return function(value) {
          return _baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
        };
      }
      return iteratee;
    });
  } else {
    iteratees = [identity_1];
  }
  var index3 = -1;
  iteratees = _arrayMap(iteratees, _baseUnary(_baseIteratee));
  var result = _baseMap(collection, function(value, key, collection2) {
    var criteria = _arrayMap(iteratees, function(iteratee) {
      return iteratee(value);
    });
    return {criteria, index: ++index3, value};
  });
  return _baseSortBy(result, function(object, other) {
    return _compareMultiple(object, other, orders);
  });
}
var _baseOrderBy = baseOrderBy;
var sortBy2 = _baseRest(function(collection, iteratees) {
  if (collection == null) {
    return [];
  }
  var length = iteratees.length;
  if (length > 1 && _isIterateeCall(collection, iteratees[0], iteratees[1])) {
    iteratees = [];
  } else if (length > 2 && _isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
    iteratees = [iteratees[0]];
  }
  return _baseOrderBy(collection, _baseFlatten(iteratees, 1), []);
});
var sortBy_1 = sortBy2;
var idCounter = 0;
function uniqueId(prefix2) {
  var id3 = ++idCounter;
  return toString_1(prefix2) + id3;
}
var uniqueId_1 = uniqueId;
function baseZipObject(props, values2, assignFunc) {
  var index3 = -1, length = props.length, valsLength = values2.length, result = {};
  while (++index3 < length) {
    var value = index3 < valsLength ? values2[index3] : void 0;
    assignFunc(result, props[index3], value);
  }
  return result;
}
var _baseZipObject = baseZipObject;
function zipObject(props, values2) {
  return _baseZipObject(props || [], values2 || [], _assignValue);
}
var zipObject_1 = zipObject;
var lodash$1;
if (typeof commonjsRequire === "function") {
  try {
    lodash$1 = {
      cloneDeep: cloneDeep_1,
      constant: constant_1,
      defaults: defaults_12,
      each,
      filter: filter_1,
      find: find_1,
      flatten: flatten_1,
      forEach: forEach_1,
      forIn: forIn_1,
      has: has_1,
      isUndefined: isUndefined_1,
      last: last_1,
      map: map_1,
      mapValues: mapValues_1,
      max: max_1,
      merge: merge_1,
      min: min_1,
      minBy: minBy_1,
      now: now_1,
      pick: pick_1,
      range: range_1,
      reduce: reduce_1,
      sortBy: sortBy_1,
      uniqueId: uniqueId_1,
      values: values_1,
      zipObject: zipObject_1
    };
  } catch (e2) {
  }
}
if (!lodash$1) {
  lodash$1 = window._;
}
var lodash_1$1 = lodash$1;
var list2 = List3;
function List3() {
  var sentinel = {};
  sentinel._next = sentinel._prev = sentinel;
  this._sentinel = sentinel;
}
List3.prototype.dequeue = function() {
  var sentinel = this._sentinel;
  var entry = sentinel._prev;
  if (entry !== sentinel) {
    unlink(entry);
    return entry;
  }
};
List3.prototype.enqueue = function(entry) {
  var sentinel = this._sentinel;
  if (entry._prev && entry._next) {
    unlink(entry);
  }
  entry._next = sentinel._next;
  sentinel._next._prev = entry;
  sentinel._next = entry;
  entry._prev = sentinel;
};
List3.prototype.toString = function() {
  var strs = [];
  var sentinel = this._sentinel;
  var curr = sentinel._prev;
  while (curr !== sentinel) {
    strs.push(JSON.stringify(curr, filterOutLinks));
    curr = curr._prev;
  }
  return "[" + strs.join(", ") + "]";
};
function unlink(entry) {
  entry._prev._next = entry._next;
  entry._next._prev = entry._prev;
  delete entry._next;
  delete entry._prev;
}
function filterOutLinks(k2, v2) {
  if (k2 !== "_next" && k2 !== "_prev") {
    return v2;
  }
}
var Graph$1 = graphlib_1.Graph;
var greedyFas = greedyFAS;
var DEFAULT_WEIGHT_FN = lodash_1$1.constant(1);
function greedyFAS(g2, weightFn) {
  if (g2.nodeCount() <= 1) {
    return [];
  }
  var state = buildState(g2, weightFn || DEFAULT_WEIGHT_FN);
  var results = doGreedyFAS(state.graph, state.buckets, state.zeroIdx);
  return lodash_1$1.flatten(lodash_1$1.map(results, function(e2) {
    return g2.outEdges(e2.v, e2.w);
  }), true);
}
function doGreedyFAS(g2, buckets, zeroIdx) {
  var results = [];
  var sources = buckets[buckets.length - 1];
  var sinks = buckets[0];
  var entry;
  while (g2.nodeCount()) {
    while (entry = sinks.dequeue()) {
      removeNode2(g2, buckets, zeroIdx, entry);
    }
    while (entry = sources.dequeue()) {
      removeNode2(g2, buckets, zeroIdx, entry);
    }
    if (g2.nodeCount()) {
      for (var i3 = buckets.length - 2; i3 > 0; --i3) {
        entry = buckets[i3].dequeue();
        if (entry) {
          results = results.concat(removeNode2(g2, buckets, zeroIdx, entry, true));
          break;
        }
      }
    }
  }
  return results;
}
function removeNode2(g2, buckets, zeroIdx, entry, collectPredecessors) {
  var results = collectPredecessors ? [] : void 0;
  lodash_1$1.forEach(g2.inEdges(entry.v), function(edge) {
    var weight = g2.edge(edge);
    var uEntry = g2.node(edge.v);
    if (collectPredecessors) {
      results.push({v: edge.v, w: edge.w});
    }
    uEntry.out -= weight;
    assignBucket(buckets, zeroIdx, uEntry);
  });
  lodash_1$1.forEach(g2.outEdges(entry.v), function(edge) {
    var weight = g2.edge(edge);
    var w2 = edge.w;
    var wEntry = g2.node(w2);
    wEntry["in"] -= weight;
    assignBucket(buckets, zeroIdx, wEntry);
  });
  g2.removeNode(entry.v);
  return results;
}
function buildState(g2, weightFn) {
  var fasGraph = new Graph$1();
  var maxIn = 0;
  var maxOut = 0;
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    fasGraph.setNode(v2, {v: v2, in: 0, out: 0});
  });
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var prevWeight = fasGraph.edge(e2.v, e2.w) || 0;
    var weight = weightFn(e2);
    var edgeWeight = prevWeight + weight;
    fasGraph.setEdge(e2.v, e2.w, edgeWeight);
    maxOut = Math.max(maxOut, fasGraph.node(e2.v).out += weight);
    maxIn = Math.max(maxIn, fasGraph.node(e2.w)["in"] += weight);
  });
  var buckets = lodash_1$1.range(maxOut + maxIn + 3).map(function() {
    return new list2();
  });
  var zeroIdx = maxIn + 1;
  lodash_1$1.forEach(fasGraph.nodes(), function(v2) {
    assignBucket(buckets, zeroIdx, fasGraph.node(v2));
  });
  return {graph: fasGraph, buckets, zeroIdx};
}
function assignBucket(buckets, zeroIdx, entry) {
  if (!entry.out) {
    buckets[0].enqueue(entry);
  } else if (!entry["in"]) {
    buckets[buckets.length - 1].enqueue(entry);
  } else {
    buckets[entry.out - entry["in"] + zeroIdx].enqueue(entry);
  }
}
var acyclic = {
  run,
  undo
};
function run(g2) {
  var fas = g2.graph().acyclicer === "greedy" ? greedyFas(g2, weightFn(g2)) : dfsFAS(g2);
  lodash_1$1.forEach(fas, function(e2) {
    var label2 = g2.edge(e2);
    g2.removeEdge(e2);
    label2.forwardName = e2.name;
    label2.reversed = true;
    g2.setEdge(e2.w, e2.v, label2, lodash_1$1.uniqueId("rev"));
  });
  function weightFn(g3) {
    return function(e2) {
      return g3.edge(e2).weight;
    };
  }
}
function dfsFAS(g2) {
  var fas = [];
  var stack2 = {};
  var visited = {};
  function dfs3(v2) {
    if (lodash_1$1.has(visited, v2)) {
      return;
    }
    visited[v2] = true;
    stack2[v2] = true;
    lodash_1$1.forEach(g2.outEdges(v2), function(e2) {
      if (lodash_1$1.has(stack2, e2.w)) {
        fas.push(e2);
      } else {
        dfs3(e2.w);
      }
    });
    delete stack2[v2];
  }
  lodash_1$1.forEach(g2.nodes(), dfs3);
  return fas;
}
function undo(g2) {
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var label2 = g2.edge(e2);
    if (label2.reversed) {
      g2.removeEdge(e2);
      var forwardName = label2.forwardName;
      delete label2.reversed;
      delete label2.forwardName;
      g2.setEdge(e2.w, e2.v, label2, forwardName);
    }
  });
}
var Graph$2 = graphlib_1.Graph;
var util = {
  addDummyNode,
  simplify,
  asNonCompoundGraph,
  successorWeights,
  predecessorWeights,
  intersectRect,
  buildLayerMatrix,
  normalizeRanks,
  removeEmptyRanks,
  addBorderNode,
  maxRank,
  partition,
  time,
  notime
};
function addDummyNode(g2, type, attrs, name) {
  var v2;
  do {
    v2 = lodash_1$1.uniqueId(name);
  } while (g2.hasNode(v2));
  attrs.dummy = type;
  g2.setNode(v2, attrs);
  return v2;
}
function simplify(g2) {
  var simplified = new Graph$2().setGraph(g2.graph());
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    simplified.setNode(v2, g2.node(v2));
  });
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var simpleLabel = simplified.edge(e2.v, e2.w) || {weight: 0, minlen: 1};
    var label2 = g2.edge(e2);
    simplified.setEdge(e2.v, e2.w, {
      weight: simpleLabel.weight + label2.weight,
      minlen: Math.max(simpleLabel.minlen, label2.minlen)
    });
  });
  return simplified;
}
function asNonCompoundGraph(g2) {
  var simplified = new Graph$2({multigraph: g2.isMultigraph()}).setGraph(g2.graph());
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    if (!g2.children(v2).length) {
      simplified.setNode(v2, g2.node(v2));
    }
  });
  lodash_1$1.forEach(g2.edges(), function(e2) {
    simplified.setEdge(e2, g2.edge(e2));
  });
  return simplified;
}
function successorWeights(g2) {
  var weightMap = lodash_1$1.map(g2.nodes(), function(v2) {
    var sucs = {};
    lodash_1$1.forEach(g2.outEdges(v2), function(e2) {
      sucs[e2.w] = (sucs[e2.w] || 0) + g2.edge(e2).weight;
    });
    return sucs;
  });
  return lodash_1$1.zipObject(g2.nodes(), weightMap);
}
function predecessorWeights(g2) {
  var weightMap = lodash_1$1.map(g2.nodes(), function(v2) {
    var preds = {};
    lodash_1$1.forEach(g2.inEdges(v2), function(e2) {
      preds[e2.v] = (preds[e2.v] || 0) + g2.edge(e2).weight;
    });
    return preds;
  });
  return lodash_1$1.zipObject(g2.nodes(), weightMap);
}
function intersectRect(rect, point) {
  var x2 = rect.x;
  var y3 = rect.y;
  var dx = point.x - x2;
  var dy = point.y - y3;
  var w2 = rect.width / 2;
  var h2 = rect.height / 2;
  if (!dx && !dy) {
    throw new Error("Not possible to find intersection inside of the rectangle");
  }
  var sx, sy;
  if (Math.abs(dy) * w2 > Math.abs(dx) * h2) {
    if (dy < 0) {
      h2 = -h2;
    }
    sx = h2 * dx / dy;
    sy = h2;
  } else {
    if (dx < 0) {
      w2 = -w2;
    }
    sx = w2;
    sy = w2 * dy / dx;
  }
  return {x: x2 + sx, y: y3 + sy};
}
function buildLayerMatrix(g2) {
  var layering = lodash_1$1.map(lodash_1$1.range(maxRank(g2) + 1), function() {
    return [];
  });
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    var node = g2.node(v2);
    var rank2 = node.rank;
    if (!lodash_1$1.isUndefined(rank2)) {
      layering[rank2][node.order] = v2;
    }
  });
  return layering;
}
function normalizeRanks(g2) {
  var min2 = lodash_1$1.min(lodash_1$1.map(g2.nodes(), function(v2) {
    return g2.node(v2).rank;
  }));
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    var node = g2.node(v2);
    if (lodash_1$1.has(node, "rank")) {
      node.rank -= min2;
    }
  });
}
function removeEmptyRanks(g2) {
  var offset2 = lodash_1$1.min(lodash_1$1.map(g2.nodes(), function(v2) {
    return g2.node(v2).rank;
  }));
  var layers = [];
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    var rank2 = g2.node(v2).rank - offset2;
    if (!layers[rank2]) {
      layers[rank2] = [];
    }
    layers[rank2].push(v2);
  });
  var delta = 0;
  var nodeRankFactor = g2.graph().nodeRankFactor;
  lodash_1$1.forEach(layers, function(vs2, i3) {
    if (lodash_1$1.isUndefined(vs2) && i3 % nodeRankFactor !== 0) {
      --delta;
    } else if (delta) {
      lodash_1$1.forEach(vs2, function(v2) {
        g2.node(v2).rank += delta;
      });
    }
  });
}
function addBorderNode(g2, prefix2, rank2, order3) {
  var node = {
    width: 0,
    height: 0
  };
  if (arguments.length >= 4) {
    node.rank = rank2;
    node.order = order3;
  }
  return addDummyNode(g2, "border", node, prefix2);
}
function maxRank(g2) {
  return lodash_1$1.max(lodash_1$1.map(g2.nodes(), function(v2) {
    var rank2 = g2.node(v2).rank;
    if (!lodash_1$1.isUndefined(rank2)) {
      return rank2;
    }
  }));
}
function partition(collection, fn) {
  var result = {lhs: [], rhs: []};
  lodash_1$1.forEach(collection, function(value) {
    if (fn(value)) {
      result.lhs.push(value);
    } else {
      result.rhs.push(value);
    }
  });
  return result;
}
function time(name, fn) {
  var start3 = lodash_1$1.now();
  try {
    return fn();
  } finally {
    console.log(name + " time: " + (lodash_1$1.now() - start3) + "ms");
  }
}
function notime(name, fn) {
  return fn();
}
var normalize2 = {
  run: run$1,
  undo: undo$1
};
function run$1(g2) {
  g2.graph().dummyChains = [];
  lodash_1$1.forEach(g2.edges(), function(edge) {
    normalizeEdge(g2, edge);
  });
}
function normalizeEdge(g2, e2) {
  var v2 = e2.v;
  var vRank = g2.node(v2).rank;
  var w2 = e2.w;
  var wRank = g2.node(w2).rank;
  var name = e2.name;
  var edgeLabel = g2.edge(e2);
  var labelRank = edgeLabel.labelRank;
  if (wRank === vRank + 1)
    return;
  g2.removeEdge(e2);
  var dummy, attrs, i3;
  for (i3 = 0, ++vRank; vRank < wRank; ++i3, ++vRank) {
    edgeLabel.points = [];
    attrs = {
      width: 0,
      height: 0,
      edgeLabel,
      edgeObj: e2,
      rank: vRank
    };
    dummy = util.addDummyNode(g2, "edge", attrs, "_d");
    if (vRank === labelRank) {
      attrs.width = edgeLabel.width;
      attrs.height = edgeLabel.height;
      attrs.dummy = "edge-label";
      attrs.labelpos = edgeLabel.labelpos;
    }
    g2.setEdge(v2, dummy, {weight: edgeLabel.weight}, name);
    if (i3 === 0) {
      g2.graph().dummyChains.push(dummy);
    }
    v2 = dummy;
  }
  g2.setEdge(v2, w2, {weight: edgeLabel.weight}, name);
}
function undo$1(g2) {
  lodash_1$1.forEach(g2.graph().dummyChains, function(v2) {
    var node = g2.node(v2);
    var origLabel = node.edgeLabel;
    var w2;
    g2.setEdge(node.edgeObj, origLabel);
    while (node.dummy) {
      w2 = g2.successors(v2)[0];
      g2.removeNode(v2);
      origLabel.points.push({x: node.x, y: node.y});
      if (node.dummy === "edge-label") {
        origLabel.x = node.x;
        origLabel.y = node.y;
        origLabel.width = node.width;
        origLabel.height = node.height;
      }
      v2 = w2;
      node = g2.node(v2);
    }
  });
}
var util$1 = {
  longestPath,
  slack
};
function longestPath(g2) {
  var visited = {};
  function dfs3(v2) {
    var label2 = g2.node(v2);
    if (lodash_1$1.has(visited, v2)) {
      return label2.rank;
    }
    visited[v2] = true;
    var rank2 = lodash_1$1.min(lodash_1$1.map(g2.outEdges(v2), function(e2) {
      return dfs3(e2.w) - g2.edge(e2).minlen;
    }));
    if (rank2 === Number.POSITIVE_INFINITY || rank2 === void 0 || rank2 === null) {
      rank2 = 0;
    }
    return label2.rank = rank2;
  }
  lodash_1$1.forEach(g2.sources(), dfs3);
}
function slack(g2, e2) {
  return g2.node(e2.w).rank - g2.node(e2.v).rank - g2.edge(e2).minlen;
}
var Graph$3 = graphlib_1.Graph;
var slack$1 = util$1.slack;
var feasibleTree_1 = feasibleTree;
function feasibleTree(g2) {
  var t5 = new Graph$3({directed: false});
  var start3 = g2.nodes()[0];
  var size2 = g2.nodeCount();
  t5.setNode(start3, {});
  var edge, delta;
  while (tightTree(t5, g2) < size2) {
    edge = findMinSlackEdge(t5, g2);
    delta = t5.hasNode(edge.v) ? slack$1(g2, edge) : -slack$1(g2, edge);
    shiftRanks(t5, g2, delta);
  }
  return t5;
}
function tightTree(t5, g2) {
  function dfs3(v2) {
    lodash_1$1.forEach(g2.nodeEdges(v2), function(e2) {
      var edgeV = e2.v, w2 = v2 === edgeV ? e2.w : edgeV;
      if (!t5.hasNode(w2) && !slack$1(g2, e2)) {
        t5.setNode(w2, {});
        t5.setEdge(v2, w2, {});
        dfs3(w2);
      }
    });
  }
  lodash_1$1.forEach(t5.nodes(), dfs3);
  return t5.nodeCount();
}
function findMinSlackEdge(t5, g2) {
  return lodash_1$1.minBy(g2.edges(), function(e2) {
    if (t5.hasNode(e2.v) !== t5.hasNode(e2.w)) {
      return slack$1(g2, e2);
    }
  });
}
function shiftRanks(t5, g2, delta) {
  lodash_1$1.forEach(t5.nodes(), function(v2) {
    g2.node(v2).rank += delta;
  });
}
var slack$2 = util$1.slack;
var initRank = util$1.longestPath;
var preorder$1 = graphlib_1.alg.preorder;
var postorder$1 = graphlib_1.alg.postorder;
var simplify$1 = util.simplify;
var networkSimplex_1 = networkSimplex;
networkSimplex.initLowLimValues = initLowLimValues;
networkSimplex.initCutValues = initCutValues;
networkSimplex.calcCutValue = calcCutValue;
networkSimplex.leaveEdge = leaveEdge;
networkSimplex.enterEdge = enterEdge;
networkSimplex.exchangeEdges = exchangeEdges;
function networkSimplex(g2) {
  g2 = simplify$1(g2);
  initRank(g2);
  var t5 = feasibleTree_1(g2);
  initLowLimValues(t5);
  initCutValues(t5, g2);
  var e2, f2;
  while (e2 = leaveEdge(t5)) {
    f2 = enterEdge(t5, g2, e2);
    exchangeEdges(t5, g2, e2, f2);
  }
}
function initCutValues(t5, g2) {
  var vs2 = postorder$1(t5, t5.nodes());
  vs2 = vs2.slice(0, vs2.length - 1);
  lodash_1$1.forEach(vs2, function(v2) {
    assignCutValue(t5, g2, v2);
  });
}
function assignCutValue(t5, g2, child) {
  var childLab = t5.node(child);
  var parent = childLab.parent;
  t5.edge(child, parent).cutvalue = calcCutValue(t5, g2, child);
}
function calcCutValue(t5, g2, child) {
  var childLab = t5.node(child);
  var parent = childLab.parent;
  var childIsTail = true;
  var graphEdge = g2.edge(child, parent);
  var cutValue = 0;
  if (!graphEdge) {
    childIsTail = false;
    graphEdge = g2.edge(parent, child);
  }
  cutValue = graphEdge.weight;
  lodash_1$1.forEach(g2.nodeEdges(child), function(e2) {
    var isOutEdge = e2.v === child, other = isOutEdge ? e2.w : e2.v;
    if (other !== parent) {
      var pointsToHead = isOutEdge === childIsTail, otherWeight = g2.edge(e2).weight;
      cutValue += pointsToHead ? otherWeight : -otherWeight;
      if (isTreeEdge(t5, child, other)) {
        var otherCutValue = t5.edge(child, other).cutvalue;
        cutValue += pointsToHead ? -otherCutValue : otherCutValue;
      }
    }
  });
  return cutValue;
}
function initLowLimValues(tree, root4) {
  if (arguments.length < 2) {
    root4 = tree.nodes()[0];
  }
  dfsAssignLowLim(tree, {}, 1, root4);
}
function dfsAssignLowLim(tree, visited, nextLim, v2, parent) {
  var low = nextLim;
  var label2 = tree.node(v2);
  visited[v2] = true;
  lodash_1$1.forEach(tree.neighbors(v2), function(w2) {
    if (!lodash_1$1.has(visited, w2)) {
      nextLim = dfsAssignLowLim(tree, visited, nextLim, w2, v2);
    }
  });
  label2.low = low;
  label2.lim = nextLim++;
  if (parent) {
    label2.parent = parent;
  } else {
    delete label2.parent;
  }
  return nextLim;
}
function leaveEdge(tree) {
  return lodash_1$1.find(tree.edges(), function(e2) {
    return tree.edge(e2).cutvalue < 0;
  });
}
function enterEdge(t5, g2, edge) {
  var v2 = edge.v;
  var w2 = edge.w;
  if (!g2.hasEdge(v2, w2)) {
    v2 = edge.w;
    w2 = edge.v;
  }
  var vLabel = t5.node(v2);
  var wLabel = t5.node(w2);
  var tailLabel = vLabel;
  var flip2 = false;
  if (vLabel.lim > wLabel.lim) {
    tailLabel = wLabel;
    flip2 = true;
  }
  var candidates = lodash_1$1.filter(g2.edges(), function(edge2) {
    return flip2 === isDescendant(t5, t5.node(edge2.v), tailLabel) && flip2 !== isDescendant(t5, t5.node(edge2.w), tailLabel);
  });
  return lodash_1$1.minBy(candidates, function(edge2) {
    return slack$2(g2, edge2);
  });
}
function exchangeEdges(t5, g2, e2, f2) {
  var v2 = e2.v;
  var w2 = e2.w;
  t5.removeEdge(v2, w2);
  t5.setEdge(f2.v, f2.w, {});
  initLowLimValues(t5);
  initCutValues(t5, g2);
  updateRanks(t5, g2);
}
function updateRanks(t5, g2) {
  var root4 = lodash_1$1.find(t5.nodes(), function(v2) {
    return !g2.node(v2).parent;
  });
  var vs2 = preorder$1(t5, root4);
  vs2 = vs2.slice(1);
  lodash_1$1.forEach(vs2, function(v2) {
    var parent = t5.node(v2).parent, edge = g2.edge(v2, parent), flipped = false;
    if (!edge) {
      edge = g2.edge(parent, v2);
      flipped = true;
    }
    g2.node(v2).rank = g2.node(parent).rank + (flipped ? edge.minlen : -edge.minlen);
  });
}
function isTreeEdge(tree, u, v2) {
  return tree.hasEdge(u, v2);
}
function isDescendant(tree, vLabel, rootLabel) {
  return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim;
}
var longestPath$1 = util$1.longestPath;
var rank_1 = rank;
function rank(g2) {
  switch (g2.graph().ranker) {
    case "network-simplex":
      networkSimplexRanker(g2);
      break;
    case "tight-tree":
      tightTreeRanker(g2);
      break;
    case "longest-path":
      longestPathRanker(g2);
      break;
    default:
      networkSimplexRanker(g2);
  }
}
var longestPathRanker = longestPath$1;
function tightTreeRanker(g2) {
  longestPath$1(g2);
  feasibleTree_1(g2);
}
function networkSimplexRanker(g2) {
  networkSimplex_1(g2);
}
var parentDummyChains_1 = parentDummyChains;
function parentDummyChains(g2) {
  var postorderNums = postorder$2(g2);
  lodash_1$1.forEach(g2.graph().dummyChains, function(v2) {
    var node = g2.node(v2);
    var edgeObj = node.edgeObj;
    var pathData = findPath(g2, postorderNums, edgeObj.v, edgeObj.w);
    var path = pathData.path;
    var lca = pathData.lca;
    var pathIdx = 0;
    var pathV = path[pathIdx];
    var ascending2 = true;
    while (v2 !== edgeObj.w) {
      node = g2.node(v2);
      if (ascending2) {
        while ((pathV = path[pathIdx]) !== lca && g2.node(pathV).maxRank < node.rank) {
          pathIdx++;
        }
        if (pathV === lca) {
          ascending2 = false;
        }
      }
      if (!ascending2) {
        while (pathIdx < path.length - 1 && g2.node(pathV = path[pathIdx + 1]).minRank <= node.rank) {
          pathIdx++;
        }
        pathV = path[pathIdx];
      }
      g2.setParent(v2, pathV);
      v2 = g2.successors(v2)[0];
    }
  });
}
function findPath(g2, postorderNums, v2, w2) {
  var vPath = [];
  var wPath = [];
  var low = Math.min(postorderNums[v2].low, postorderNums[w2].low);
  var lim = Math.max(postorderNums[v2].lim, postorderNums[w2].lim);
  var parent;
  var lca;
  parent = v2;
  do {
    parent = g2.parent(parent);
    vPath.push(parent);
  } while (parent && (postorderNums[parent].low > low || lim > postorderNums[parent].lim));
  lca = parent;
  parent = w2;
  while ((parent = g2.parent(parent)) !== lca) {
    wPath.push(parent);
  }
  return {path: vPath.concat(wPath.reverse()), lca};
}
function postorder$2(g2) {
  var result = {};
  var lim = 0;
  function dfs3(v2) {
    var low = lim;
    lodash_1$1.forEach(g2.children(v2), dfs3);
    result[v2] = {low, lim: lim++};
  }
  lodash_1$1.forEach(g2.children(), dfs3);
  return result;
}
var nestingGraph = {
  run: run$2,
  cleanup
};
function run$2(g2) {
  var root4 = util.addDummyNode(g2, "root", {}, "_root");
  var depths = treeDepths(g2);
  var height = lodash_1$1.max(lodash_1$1.values(depths)) - 1;
  var nodeSep = 2 * height + 1;
  g2.graph().nestingRoot = root4;
  lodash_1$1.forEach(g2.edges(), function(e2) {
    g2.edge(e2).minlen *= nodeSep;
  });
  var weight = sumWeights(g2) + 1;
  lodash_1$1.forEach(g2.children(), function(child) {
    dfs$12(g2, root4, nodeSep, weight, height, depths, child);
  });
  g2.graph().nodeRankFactor = nodeSep;
}
function dfs$12(g2, root4, nodeSep, weight, height, depths, v2) {
  var children2 = g2.children(v2);
  if (!children2.length) {
    if (v2 !== root4) {
      g2.setEdge(root4, v2, {weight: 0, minlen: nodeSep});
    }
    return;
  }
  var top2 = util.addBorderNode(g2, "_bt");
  var bottom2 = util.addBorderNode(g2, "_bb");
  var label2 = g2.node(v2);
  g2.setParent(top2, v2);
  label2.borderTop = top2;
  g2.setParent(bottom2, v2);
  label2.borderBottom = bottom2;
  lodash_1$1.forEach(children2, function(child) {
    dfs$12(g2, root4, nodeSep, weight, height, depths, child);
    var childNode = g2.node(child);
    var childTop = childNode.borderTop ? childNode.borderTop : child;
    var childBottom = childNode.borderBottom ? childNode.borderBottom : child;
    var thisWeight = childNode.borderTop ? weight : 2 * weight;
    var minlen = childTop !== childBottom ? 1 : height - depths[v2] + 1;
    g2.setEdge(top2, childTop, {
      weight: thisWeight,
      minlen,
      nestingEdge: true
    });
    g2.setEdge(childBottom, bottom2, {
      weight: thisWeight,
      minlen,
      nestingEdge: true
    });
  });
  if (!g2.parent(v2)) {
    g2.setEdge(root4, top2, {weight: 0, minlen: height + depths[v2]});
  }
}
function treeDepths(g2) {
  var depths = {};
  function dfs3(v2, depth) {
    var children2 = g2.children(v2);
    if (children2 && children2.length) {
      lodash_1$1.forEach(children2, function(child) {
        dfs3(child, depth + 1);
      });
    }
    depths[v2] = depth;
  }
  lodash_1$1.forEach(g2.children(), function(v2) {
    dfs3(v2, 1);
  });
  return depths;
}
function sumWeights(g2) {
  return lodash_1$1.reduce(g2.edges(), function(acc, e2) {
    return acc + g2.edge(e2).weight;
  }, 0);
}
function cleanup(g2) {
  var graphLabel = g2.graph();
  g2.removeNode(graphLabel.nestingRoot);
  delete graphLabel.nestingRoot;
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var edge = g2.edge(e2);
    if (edge.nestingEdge) {
      g2.removeEdge(e2);
    }
  });
}
var addBorderSegments_1 = addBorderSegments;
function addBorderSegments(g2) {
  function dfs3(v2) {
    var children2 = g2.children(v2);
    var node = g2.node(v2);
    if (children2.length) {
      lodash_1$1.forEach(children2, dfs3);
    }
    if (lodash_1$1.has(node, "minRank")) {
      node.borderLeft = [];
      node.borderRight = [];
      for (var rank2 = node.minRank, maxRank2 = node.maxRank + 1; rank2 < maxRank2; ++rank2) {
        addBorderNode$1(g2, "borderLeft", "_bl", v2, node, rank2);
        addBorderNode$1(g2, "borderRight", "_br", v2, node, rank2);
      }
    }
  }
  lodash_1$1.forEach(g2.children(), dfs3);
}
function addBorderNode$1(g2, prop, prefix2, sg2, sgNode, rank2) {
  var label2 = {width: 0, height: 0, rank: rank2, borderType: prop};
  var prev = sgNode[prop][rank2 - 1];
  var curr = util.addDummyNode(g2, "border", label2, prefix2);
  sgNode[prop][rank2] = curr;
  g2.setParent(curr, sg2);
  if (prev) {
    g2.setEdge(prev, curr, {weight: 1});
  }
}
var coordinateSystem = {
  adjust,
  undo: undo$2
};
function adjust(g2) {
  var rankDir = g2.graph().rankdir.toLowerCase();
  if (rankDir === "lr" || rankDir === "rl") {
    swapWidthHeight(g2);
  }
}
function undo$2(g2) {
  var rankDir = g2.graph().rankdir.toLowerCase();
  if (rankDir === "bt" || rankDir === "rl") {
    reverseY(g2);
  }
  if (rankDir === "lr" || rankDir === "rl") {
    swapXY(g2);
    swapWidthHeight(g2);
  }
}
function swapWidthHeight(g2) {
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    swapWidthHeightOne(g2.node(v2));
  });
  lodash_1$1.forEach(g2.edges(), function(e2) {
    swapWidthHeightOne(g2.edge(e2));
  });
}
function swapWidthHeightOne(attrs) {
  var w2 = attrs.width;
  attrs.width = attrs.height;
  attrs.height = w2;
}
function reverseY(g2) {
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    reverseYOne(g2.node(v2));
  });
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var edge = g2.edge(e2);
    lodash_1$1.forEach(edge.points, reverseYOne);
    if (lodash_1$1.has(edge, "y")) {
      reverseYOne(edge);
    }
  });
}
function reverseYOne(attrs) {
  attrs.y = -attrs.y;
}
function swapXY(g2) {
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    swapXYOne(g2.node(v2));
  });
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var edge = g2.edge(e2);
    lodash_1$1.forEach(edge.points, swapXYOne);
    if (lodash_1$1.has(edge, "x")) {
      swapXYOne(edge);
    }
  });
}
function swapXYOne(attrs) {
  var x2 = attrs.x;
  attrs.x = attrs.y;
  attrs.y = x2;
}
var initOrder_1 = initOrder;
function initOrder(g2) {
  var visited = {};
  var simpleNodes = lodash_1$1.filter(g2.nodes(), function(v2) {
    return !g2.children(v2).length;
  });
  var maxRank2 = lodash_1$1.max(lodash_1$1.map(simpleNodes, function(v2) {
    return g2.node(v2).rank;
  }));
  var layers = lodash_1$1.map(lodash_1$1.range(maxRank2 + 1), function() {
    return [];
  });
  function dfs3(v2) {
    if (lodash_1$1.has(visited, v2))
      return;
    visited[v2] = true;
    var node = g2.node(v2);
    layers[node.rank].push(v2);
    lodash_1$1.forEach(g2.successors(v2), dfs3);
  }
  var orderedVs = lodash_1$1.sortBy(simpleNodes, function(v2) {
    return g2.node(v2).rank;
  });
  lodash_1$1.forEach(orderedVs, dfs3);
  return layers;
}
var crossCount_1 = crossCount;
function crossCount(g2, layering) {
  var cc3 = 0;
  for (var i3 = 1; i3 < layering.length; ++i3) {
    cc3 += twoLayerCrossCount(g2, layering[i3 - 1], layering[i3]);
  }
  return cc3;
}
function twoLayerCrossCount(g2, northLayer, southLayer) {
  var southPos = lodash_1$1.zipObject(southLayer, lodash_1$1.map(southLayer, function(v2, i3) {
    return i3;
  }));
  var southEntries = lodash_1$1.flatten(lodash_1$1.map(northLayer, function(v2) {
    return lodash_1$1.sortBy(lodash_1$1.map(g2.outEdges(v2), function(e2) {
      return {pos: southPos[e2.w], weight: g2.edge(e2).weight};
    }), "pos");
  }), true);
  var firstIndex2 = 1;
  while (firstIndex2 < southLayer.length)
    firstIndex2 <<= 1;
  var treeSize = 2 * firstIndex2 - 1;
  firstIndex2 -= 1;
  var tree = lodash_1$1.map(new Array(treeSize), function() {
    return 0;
  });
  var cc3 = 0;
  lodash_1$1.forEach(southEntries.forEach(function(entry) {
    var index3 = entry.pos + firstIndex2;
    tree[index3] += entry.weight;
    var weightSum = 0;
    while (index3 > 0) {
      if (index3 % 2) {
        weightSum += tree[index3 + 1];
      }
      index3 = index3 - 1 >> 1;
      tree[index3] += entry.weight;
    }
    cc3 += entry.weight * weightSum;
  }));
  return cc3;
}
var barycenter_1 = barycenter;
function barycenter(g2, movable) {
  return lodash_1$1.map(movable, function(v2) {
    var inV = g2.inEdges(v2);
    if (!inV.length) {
      return {v: v2};
    } else {
      var result = lodash_1$1.reduce(inV, function(acc, e2) {
        var edge = g2.edge(e2), nodeU = g2.node(e2.v);
        return {
          sum: acc.sum + edge.weight * nodeU.order,
          weight: acc.weight + edge.weight
        };
      }, {sum: 0, weight: 0});
      return {
        v: v2,
        barycenter: result.sum / result.weight,
        weight: result.weight
      };
    }
  });
}
var resolveConflicts_1 = resolveConflicts;
function resolveConflicts(entries, cg2) {
  var mappedEntries = {};
  lodash_1$1.forEach(entries, function(entry, i3) {
    var tmp = mappedEntries[entry.v] = {
      indegree: 0,
      in: [],
      out: [],
      vs: [entry.v],
      i: i3
    };
    if (!lodash_1$1.isUndefined(entry.barycenter)) {
      tmp.barycenter = entry.barycenter;
      tmp.weight = entry.weight;
    }
  });
  lodash_1$1.forEach(cg2.edges(), function(e2) {
    var entryV = mappedEntries[e2.v];
    var entryW = mappedEntries[e2.w];
    if (!lodash_1$1.isUndefined(entryV) && !lodash_1$1.isUndefined(entryW)) {
      entryW.indegree++;
      entryV.out.push(mappedEntries[e2.w]);
    }
  });
  var sourceSet = lodash_1$1.filter(mappedEntries, function(entry) {
    return !entry.indegree;
  });
  return doResolveConflicts(sourceSet);
}
function doResolveConflicts(sourceSet) {
  var entries = [];
  function handleIn(vEntry) {
    return function(uEntry) {
      if (uEntry.merged) {
        return;
      }
      if (lodash_1$1.isUndefined(uEntry.barycenter) || lodash_1$1.isUndefined(vEntry.barycenter) || uEntry.barycenter >= vEntry.barycenter) {
        mergeEntries(vEntry, uEntry);
      }
    };
  }
  function handleOut(vEntry) {
    return function(wEntry) {
      wEntry["in"].push(vEntry);
      if (--wEntry.indegree === 0) {
        sourceSet.push(wEntry);
      }
    };
  }
  while (sourceSet.length) {
    var entry = sourceSet.pop();
    entries.push(entry);
    lodash_1$1.forEach(entry["in"].reverse(), handleIn(entry));
    lodash_1$1.forEach(entry.out, handleOut(entry));
  }
  return lodash_1$1.map(lodash_1$1.filter(entries, function(entry2) {
    return !entry2.merged;
  }), function(entry2) {
    return lodash_1$1.pick(entry2, ["vs", "i", "barycenter", "weight"]);
  });
}
function mergeEntries(target, source2) {
  var sum = 0;
  var weight = 0;
  if (target.weight) {
    sum += target.barycenter * target.weight;
    weight += target.weight;
  }
  if (source2.weight) {
    sum += source2.barycenter * source2.weight;
    weight += source2.weight;
  }
  target.vs = source2.vs.concat(target.vs);
  target.barycenter = sum / weight;
  target.weight = weight;
  target.i = Math.min(source2.i, target.i);
  source2.merged = true;
}
var sort_1 = sort;
function sort(entries, biasRight) {
  var parts = util.partition(entries, function(entry) {
    return lodash_1$1.has(entry, "barycenter");
  });
  var sortable2 = parts.lhs, unsortable = lodash_1$1.sortBy(parts.rhs, function(entry) {
    return -entry.i;
  }), vs2 = [], sum = 0, weight = 0, vsIndex = 0;
  sortable2.sort(compareWithBias(!!biasRight));
  vsIndex = consumeUnsortable(vs2, unsortable, vsIndex);
  lodash_1$1.forEach(sortable2, function(entry) {
    vsIndex += entry.vs.length;
    vs2.push(entry.vs);
    sum += entry.barycenter * entry.weight;
    weight += entry.weight;
    vsIndex = consumeUnsortable(vs2, unsortable, vsIndex);
  });
  var result = {vs: lodash_1$1.flatten(vs2, true)};
  if (weight) {
    result.barycenter = sum / weight;
    result.weight = weight;
  }
  return result;
}
function consumeUnsortable(vs2, unsortable, index3) {
  var last2;
  while (unsortable.length && (last2 = lodash_1$1.last(unsortable)).i <= index3) {
    unsortable.pop();
    vs2.push(last2.vs);
    index3++;
  }
  return index3;
}
function compareWithBias(bias) {
  return function(entryV, entryW) {
    if (entryV.barycenter < entryW.barycenter) {
      return -1;
    } else if (entryV.barycenter > entryW.barycenter) {
      return 1;
    }
    return !bias ? entryV.i - entryW.i : entryW.i - entryV.i;
  };
}
var sortSubgraph_1 = sortSubgraph;
function sortSubgraph(g2, v2, cg2, biasRight) {
  var movable = g2.children(v2);
  var node = g2.node(v2);
  var bl = node ? node.borderLeft : void 0;
  var br = node ? node.borderRight : void 0;
  var subgraphs = {};
  if (bl) {
    movable = lodash_1$1.filter(movable, function(w2) {
      return w2 !== bl && w2 !== br;
    });
  }
  var barycenters = barycenter_1(g2, movable);
  lodash_1$1.forEach(barycenters, function(entry) {
    if (g2.children(entry.v).length) {
      var subgraphResult = sortSubgraph(g2, entry.v, cg2, biasRight);
      subgraphs[entry.v] = subgraphResult;
      if (lodash_1$1.has(subgraphResult, "barycenter")) {
        mergeBarycenters(entry, subgraphResult);
      }
    }
  });
  var entries = resolveConflicts_1(barycenters, cg2);
  expandSubgraphs(entries, subgraphs);
  var result = sort_1(entries, biasRight);
  if (bl) {
    result.vs = lodash_1$1.flatten([bl, result.vs, br], true);
    if (g2.predecessors(bl).length) {
      var blPred = g2.node(g2.predecessors(bl)[0]), brPred = g2.node(g2.predecessors(br)[0]);
      if (!lodash_1$1.has(result, "barycenter")) {
        result.barycenter = 0;
        result.weight = 0;
      }
      result.barycenter = (result.barycenter * result.weight + blPred.order + brPred.order) / (result.weight + 2);
      result.weight += 2;
    }
  }
  return result;
}
function expandSubgraphs(entries, subgraphs) {
  lodash_1$1.forEach(entries, function(entry) {
    entry.vs = lodash_1$1.flatten(entry.vs.map(function(v2) {
      if (subgraphs[v2]) {
        return subgraphs[v2].vs;
      }
      return v2;
    }), true);
  });
}
function mergeBarycenters(target, other) {
  if (!lodash_1$1.isUndefined(target.barycenter)) {
    target.barycenter = (target.barycenter * target.weight + other.barycenter * other.weight) / (target.weight + other.weight);
    target.weight += other.weight;
  } else {
    target.barycenter = other.barycenter;
    target.weight = other.weight;
  }
}
var Graph$4 = graphlib_1.Graph;
var buildLayerGraph_1 = buildLayerGraph;
function buildLayerGraph(g2, rank2, relationship) {
  var root4 = createRootNode(g2), result = new Graph$4({compound: true}).setGraph({root: root4}).setDefaultNodeLabel(function(v2) {
    return g2.node(v2);
  });
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    var node = g2.node(v2), parent = g2.parent(v2);
    if (node.rank === rank2 || node.minRank <= rank2 && rank2 <= node.maxRank) {
      result.setNode(v2);
      result.setParent(v2, parent || root4);
      lodash_1$1.forEach(g2[relationship](v2), function(e2) {
        var u = e2.v === v2 ? e2.w : e2.v, edge = result.edge(u, v2), weight = !lodash_1$1.isUndefined(edge) ? edge.weight : 0;
        result.setEdge(u, v2, {weight: g2.edge(e2).weight + weight});
      });
      if (lodash_1$1.has(node, "minRank")) {
        result.setNode(v2, {
          borderLeft: node.borderLeft[rank2],
          borderRight: node.borderRight[rank2]
        });
      }
    }
  });
  return result;
}
function createRootNode(g2) {
  var v2;
  while (g2.hasNode(v2 = lodash_1$1.uniqueId("_root")))
    ;
  return v2;
}
var addSubgraphConstraints_1 = addSubgraphConstraints;
function addSubgraphConstraints(g2, cg2, vs2) {
  var prev = {}, rootPrev;
  lodash_1$1.forEach(vs2, function(v2) {
    var child = g2.parent(v2), parent, prevChild;
    while (child) {
      parent = g2.parent(child);
      if (parent) {
        prevChild = prev[parent];
        prev[parent] = child;
      } else {
        prevChild = rootPrev;
        rootPrev = child;
      }
      if (prevChild && prevChild !== child) {
        cg2.setEdge(prevChild, child);
        return;
      }
      child = parent;
    }
  });
}
var Graph$5 = graphlib_1.Graph;
var order_1 = order2;
function order2(g2) {
  var maxRank2 = util.maxRank(g2), downLayerGraphs = buildLayerGraphs(g2, lodash_1$1.range(1, maxRank2 + 1), "inEdges"), upLayerGraphs = buildLayerGraphs(g2, lodash_1$1.range(maxRank2 - 1, -1, -1), "outEdges");
  var layering = initOrder_1(g2);
  assignOrder(g2, layering);
  var bestCC = Number.POSITIVE_INFINITY, best;
  for (var i3 = 0, lastBest = 0; lastBest < 4; ++i3, ++lastBest) {
    sweepLayerGraphs(i3 % 2 ? downLayerGraphs : upLayerGraphs, i3 % 4 >= 2);
    layering = util.buildLayerMatrix(g2);
    var cc3 = crossCount_1(g2, layering);
    if (cc3 < bestCC) {
      lastBest = 0;
      best = lodash_1$1.cloneDeep(layering);
      bestCC = cc3;
    }
  }
  assignOrder(g2, best);
}
function buildLayerGraphs(g2, ranks, relationship) {
  return lodash_1$1.map(ranks, function(rank2) {
    return buildLayerGraph_1(g2, rank2, relationship);
  });
}
function sweepLayerGraphs(layerGraphs, biasRight) {
  var cg2 = new Graph$5();
  lodash_1$1.forEach(layerGraphs, function(lg2) {
    var root4 = lg2.graph().root;
    var sorted = sortSubgraph_1(lg2, root4, cg2, biasRight);
    lodash_1$1.forEach(sorted.vs, function(v2, i3) {
      lg2.node(v2).order = i3;
    });
    addSubgraphConstraints_1(lg2, cg2, sorted.vs);
  });
}
function assignOrder(g2, layering) {
  lodash_1$1.forEach(layering, function(layer) {
    lodash_1$1.forEach(layer, function(v2, i3) {
      g2.node(v2).order = i3;
    });
  });
}
var Graph$6 = graphlib_1.Graph;
var bk2 = {
  positionX,
  findType1Conflicts,
  findType2Conflicts,
  addConflict,
  hasConflict,
  verticalAlignment,
  horizontalCompaction,
  alignCoordinates,
  findSmallestWidthAlignment,
  balance
};
function findType1Conflicts(g2, layering) {
  var conflicts = {};
  function visitLayer(prevLayer, layer) {
    var k0 = 0, scanPos = 0, prevLayerLength = prevLayer.length, lastNode = lodash_1$1.last(layer);
    lodash_1$1.forEach(layer, function(v2, i3) {
      var w2 = findOtherInnerSegmentNode(g2, v2), k1 = w2 ? g2.node(w2).order : prevLayerLength;
      if (w2 || v2 === lastNode) {
        lodash_1$1.forEach(layer.slice(scanPos, i3 + 1), function(scanNode) {
          lodash_1$1.forEach(g2.predecessors(scanNode), function(u) {
            var uLabel = g2.node(u), uPos = uLabel.order;
            if ((uPos < k0 || k1 < uPos) && !(uLabel.dummy && g2.node(scanNode).dummy)) {
              addConflict(conflicts, u, scanNode);
            }
          });
        });
        scanPos = i3 + 1;
        k0 = k1;
      }
    });
    return layer;
  }
  lodash_1$1.reduce(layering, visitLayer);
  return conflicts;
}
function findType2Conflicts(g2, layering) {
  var conflicts = {};
  function scan(south, southPos, southEnd, prevNorthBorder, nextNorthBorder) {
    var v2;
    lodash_1$1.forEach(lodash_1$1.range(southPos, southEnd), function(i3) {
      v2 = south[i3];
      if (g2.node(v2).dummy) {
        lodash_1$1.forEach(g2.predecessors(v2), function(u) {
          var uNode = g2.node(u);
          if (uNode.dummy && (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) {
            addConflict(conflicts, u, v2);
          }
        });
      }
    });
  }
  function visitLayer(north, south) {
    var prevNorthPos = -1, nextNorthPos, southPos = 0;
    lodash_1$1.forEach(south, function(v2, southLookahead) {
      if (g2.node(v2).dummy === "border") {
        var predecessors = g2.predecessors(v2);
        if (predecessors.length) {
          nextNorthPos = g2.node(predecessors[0]).order;
          scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos);
          southPos = southLookahead;
          prevNorthPos = nextNorthPos;
        }
      }
      scan(south, southPos, south.length, nextNorthPos, north.length);
    });
    return south;
  }
  lodash_1$1.reduce(layering, visitLayer);
  return conflicts;
}
function findOtherInnerSegmentNode(g2, v2) {
  if (g2.node(v2).dummy) {
    return lodash_1$1.find(g2.predecessors(v2), function(u) {
      return g2.node(u).dummy;
    });
  }
}
function addConflict(conflicts, v2, w2) {
  if (v2 > w2) {
    var tmp = v2;
    v2 = w2;
    w2 = tmp;
  }
  var conflictsV = conflicts[v2];
  if (!conflictsV) {
    conflicts[v2] = conflictsV = {};
  }
  conflictsV[w2] = true;
}
function hasConflict(conflicts, v2, w2) {
  if (v2 > w2) {
    var tmp = v2;
    v2 = w2;
    w2 = tmp;
  }
  return lodash_1$1.has(conflicts[v2], w2);
}
function verticalAlignment(g2, layering, conflicts, neighborFn) {
  var root4 = {}, align = {}, pos = {};
  lodash_1$1.forEach(layering, function(layer) {
    lodash_1$1.forEach(layer, function(v2, order3) {
      root4[v2] = v2;
      align[v2] = v2;
      pos[v2] = order3;
    });
  });
  lodash_1$1.forEach(layering, function(layer) {
    var prevIdx = -1;
    lodash_1$1.forEach(layer, function(v2) {
      var ws = neighborFn(v2);
      if (ws.length) {
        ws = lodash_1$1.sortBy(ws, function(w3) {
          return pos[w3];
        });
        var mp = (ws.length - 1) / 2;
        for (var i3 = Math.floor(mp), il = Math.ceil(mp); i3 <= il; ++i3) {
          var w2 = ws[i3];
          if (align[v2] === v2 && prevIdx < pos[w2] && !hasConflict(conflicts, v2, w2)) {
            align[w2] = v2;
            align[v2] = root4[v2] = root4[w2];
            prevIdx = pos[w2];
          }
        }
      }
    });
  });
  return {root: root4, align};
}
function horizontalCompaction(g2, layering, root4, align, reverseSep) {
  var xs = {}, blockG = buildBlockGraph(g2, layering, root4, reverseSep), borderType = reverseSep ? "borderLeft" : "borderRight";
  function iterate(setXsFunc, nextNodesFunc) {
    var stack2 = blockG.nodes();
    var elem = stack2.pop();
    var visited = {};
    while (elem) {
      if (visited[elem]) {
        setXsFunc(elem);
      } else {
        visited[elem] = true;
        stack2.push(elem);
        stack2 = stack2.concat(nextNodesFunc(elem));
      }
      elem = stack2.pop();
    }
  }
  function pass1(elem) {
    xs[elem] = blockG.inEdges(elem).reduce(function(acc, e2) {
      return Math.max(acc, xs[e2.v] + blockG.edge(e2));
    }, 0);
  }
  function pass2(elem) {
    var min2 = blockG.outEdges(elem).reduce(function(acc, e2) {
      return Math.min(acc, xs[e2.w] - blockG.edge(e2));
    }, Number.POSITIVE_INFINITY);
    var node = g2.node(elem);
    if (min2 !== Number.POSITIVE_INFINITY && node.borderType !== borderType) {
      xs[elem] = Math.max(xs[elem], min2);
    }
  }
  iterate(pass1, blockG.predecessors.bind(blockG));
  iterate(pass2, blockG.successors.bind(blockG));
  lodash_1$1.forEach(align, function(v2) {
    xs[v2] = xs[root4[v2]];
  });
  return xs;
}
function buildBlockGraph(g2, layering, root4, reverseSep) {
  var blockGraph = new Graph$6(), graphLabel = g2.graph(), sepFn = sep2(graphLabel.nodesep, graphLabel.edgesep, reverseSep);
  lodash_1$1.forEach(layering, function(layer) {
    var u;
    lodash_1$1.forEach(layer, function(v2) {
      var vRoot = root4[v2];
      blockGraph.setNode(vRoot);
      if (u) {
        var uRoot = root4[u], prevMax = blockGraph.edge(uRoot, vRoot);
        blockGraph.setEdge(uRoot, vRoot, Math.max(sepFn(g2, v2, u), prevMax || 0));
      }
      u = v2;
    });
  });
  return blockGraph;
}
function findSmallestWidthAlignment(g2, xss) {
  return lodash_1$1.minBy(lodash_1$1.values(xss), function(xs) {
    var max2 = Number.NEGATIVE_INFINITY;
    var min2 = Number.POSITIVE_INFINITY;
    lodash_1$1.forIn(xs, function(x2, v2) {
      var halfWidth = width(g2, v2) / 2;
      max2 = Math.max(x2 + halfWidth, max2);
      min2 = Math.min(x2 - halfWidth, min2);
    });
    return max2 - min2;
  });
}
function alignCoordinates(xss, alignTo) {
  var alignToVals = lodash_1$1.values(alignTo), alignToMin = lodash_1$1.min(alignToVals), alignToMax = lodash_1$1.max(alignToVals);
  lodash_1$1.forEach(["u", "d"], function(vert) {
    lodash_1$1.forEach(["l", "r"], function(horiz) {
      var alignment = vert + horiz, xs = xss[alignment], delta;
      if (xs === alignTo)
        return;
      var xsVals = lodash_1$1.values(xs);
      delta = horiz === "l" ? alignToMin - lodash_1$1.min(xsVals) : alignToMax - lodash_1$1.max(xsVals);
      if (delta) {
        xss[alignment] = lodash_1$1.mapValues(xs, function(x2) {
          return x2 + delta;
        });
      }
    });
  });
}
function balance(xss, align) {
  return lodash_1$1.mapValues(xss.ul, function(ignore, v2) {
    if (align) {
      return xss[align.toLowerCase()][v2];
    } else {
      var xs = lodash_1$1.sortBy(lodash_1$1.map(xss, v2));
      return (xs[1] + xs[2]) / 2;
    }
  });
}
function positionX(g2) {
  var layering = util.buildLayerMatrix(g2);
  var conflicts = lodash_1$1.merge(findType1Conflicts(g2, layering), findType2Conflicts(g2, layering));
  var xss = {};
  var adjustedLayering;
  lodash_1$1.forEach(["u", "d"], function(vert) {
    adjustedLayering = vert === "u" ? layering : lodash_1$1.values(layering).reverse();
    lodash_1$1.forEach(["l", "r"], function(horiz) {
      if (horiz === "r") {
        adjustedLayering = lodash_1$1.map(adjustedLayering, function(inner) {
          return lodash_1$1.values(inner).reverse();
        });
      }
      var neighborFn = (vert === "u" ? g2.predecessors : g2.successors).bind(g2);
      var align = verticalAlignment(g2, adjustedLayering, conflicts, neighborFn);
      var xs = horizontalCompaction(g2, adjustedLayering, align.root, align.align, horiz === "r");
      if (horiz === "r") {
        xs = lodash_1$1.mapValues(xs, function(x2) {
          return -x2;
        });
      }
      xss[vert + horiz] = xs;
    });
  });
  var smallestWidth = findSmallestWidthAlignment(g2, xss);
  alignCoordinates(xss, smallestWidth);
  return balance(xss, g2.graph().align);
}
function sep2(nodeSep, edgeSep, reverseSep) {
  return function(g2, v2, w2) {
    var vLabel = g2.node(v2);
    var wLabel = g2.node(w2);
    var sum = 0;
    var delta;
    sum += vLabel.width / 2;
    if (lodash_1$1.has(vLabel, "labelpos")) {
      switch (vLabel.labelpos.toLowerCase()) {
        case "l":
          delta = -vLabel.width / 2;
          break;
        case "r":
          delta = vLabel.width / 2;
          break;
      }
    }
    if (delta) {
      sum += reverseSep ? delta : -delta;
    }
    delta = 0;
    sum += (vLabel.dummy ? edgeSep : nodeSep) / 2;
    sum += (wLabel.dummy ? edgeSep : nodeSep) / 2;
    sum += wLabel.width / 2;
    if (lodash_1$1.has(wLabel, "labelpos")) {
      switch (wLabel.labelpos.toLowerCase()) {
        case "l":
          delta = wLabel.width / 2;
          break;
        case "r":
          delta = -wLabel.width / 2;
          break;
      }
    }
    if (delta) {
      sum += reverseSep ? delta : -delta;
    }
    delta = 0;
    return sum;
  };
}
function width(g2, v2) {
  return g2.node(v2).width;
}
var positionX$1 = bk2.positionX;
var position_1 = position;
function position(g2) {
  g2 = util.asNonCompoundGraph(g2);
  positionY(g2);
  lodash_1$1.forEach(positionX$1(g2), function(x2, v2) {
    g2.node(v2).x = x2;
  });
}
function positionY(g2) {
  var layering = util.buildLayerMatrix(g2);
  var rankSep = g2.graph().ranksep;
  var prevY = 0;
  lodash_1$1.forEach(layering, function(layer) {
    var maxHeight = lodash_1$1.max(lodash_1$1.map(layer, function(v2) {
      return g2.node(v2).height;
    }));
    lodash_1$1.forEach(layer, function(v2) {
      g2.node(v2).y = prevY + maxHeight / 2;
    });
    prevY += maxHeight + rankSep;
  });
}
var normalizeRanks$1 = util.normalizeRanks;
var removeEmptyRanks$1 = util.removeEmptyRanks;
var util$2 = util;
var Graph$7 = graphlib_1.Graph;
var layout_1 = layout2;
function layout2(g2, opts) {
  var time2 = opts && opts.debugTiming ? util$2.time : util$2.notime;
  time2("layout", function() {
    var layoutGraph = time2("  buildLayoutGraph", function() {
      return buildLayoutGraph(g2);
    });
    time2("  runLayout", function() {
      runLayout(layoutGraph, time2);
    });
    time2("  updateInputGraph", function() {
      updateInputGraph(g2, layoutGraph);
    });
  });
}
function runLayout(g2, time2) {
  time2("    makeSpaceForEdgeLabels", function() {
    makeSpaceForEdgeLabels(g2);
  });
  time2("    removeSelfEdges", function() {
    removeSelfEdges(g2);
  });
  time2("    acyclic", function() {
    acyclic.run(g2);
  });
  time2("    nestingGraph.run", function() {
    nestingGraph.run(g2);
  });
  time2("    rank", function() {
    rank_1(util$2.asNonCompoundGraph(g2));
  });
  time2("    injectEdgeLabelProxies", function() {
    injectEdgeLabelProxies(g2);
  });
  time2("    removeEmptyRanks", function() {
    removeEmptyRanks$1(g2);
  });
  time2("    nestingGraph.cleanup", function() {
    nestingGraph.cleanup(g2);
  });
  time2("    normalizeRanks", function() {
    normalizeRanks$1(g2);
  });
  time2("    assignRankMinMax", function() {
    assignRankMinMax(g2);
  });
  time2("    removeEdgeLabelProxies", function() {
    removeEdgeLabelProxies(g2);
  });
  time2("    normalize.run", function() {
    normalize2.run(g2);
  });
  time2("    parentDummyChains", function() {
    parentDummyChains_1(g2);
  });
  time2("    addBorderSegments", function() {
    addBorderSegments_1(g2);
  });
  time2("    order", function() {
    order_1(g2);
  });
  time2("    insertSelfEdges", function() {
    insertSelfEdges(g2);
  });
  time2("    adjustCoordinateSystem", function() {
    coordinateSystem.adjust(g2);
  });
  time2("    position", function() {
    position_1(g2);
  });
  time2("    positionSelfEdges", function() {
    positionSelfEdges(g2);
  });
  time2("    removeBorderNodes", function() {
    removeBorderNodes(g2);
  });
  time2("    normalize.undo", function() {
    normalize2.undo(g2);
  });
  time2("    fixupEdgeLabelCoords", function() {
    fixupEdgeLabelCoords(g2);
  });
  time2("    undoCoordinateSystem", function() {
    coordinateSystem.undo(g2);
  });
  time2("    translateGraph", function() {
    translateGraph(g2);
  });
  time2("    assignNodeIntersects", function() {
    assignNodeIntersects(g2);
  });
  time2("    reversePoints", function() {
    reversePointsForReversedEdges(g2);
  });
  time2("    acyclic.undo", function() {
    acyclic.undo(g2);
  });
}
function updateInputGraph(inputGraph, layoutGraph) {
  lodash_1$1.forEach(inputGraph.nodes(), function(v2) {
    var inputLabel = inputGraph.node(v2);
    var layoutLabel = layoutGraph.node(v2);
    if (inputLabel) {
      inputLabel.x = layoutLabel.x;
      inputLabel.y = layoutLabel.y;
      if (layoutGraph.children(v2).length) {
        inputLabel.width = layoutLabel.width;
        inputLabel.height = layoutLabel.height;
      }
    }
  });
  lodash_1$1.forEach(inputGraph.edges(), function(e2) {
    var inputLabel = inputGraph.edge(e2);
    var layoutLabel = layoutGraph.edge(e2);
    inputLabel.points = layoutLabel.points;
    if (lodash_1$1.has(layoutLabel, "x")) {
      inputLabel.x = layoutLabel.x;
      inputLabel.y = layoutLabel.y;
    }
  });
  inputGraph.graph().width = layoutGraph.graph().width;
  inputGraph.graph().height = layoutGraph.graph().height;
}
var graphNumAttrs = ["nodesep", "edgesep", "ranksep", "marginx", "marginy"];
var graphDefaults = {ranksep: 50, edgesep: 20, nodesep: 50, rankdir: "tb"};
var graphAttrs = ["acyclicer", "ranker", "rankdir", "align"];
var nodeNumAttrs = ["width", "height"];
var nodeDefaults = {width: 0, height: 0};
var edgeNumAttrs = ["minlen", "weight", "width", "height", "labeloffset"];
var edgeDefaults = {
  minlen: 1,
  weight: 1,
  width: 0,
  height: 0,
  labeloffset: 10,
  labelpos: "r"
};
var edgeAttrs = ["labelpos"];
function buildLayoutGraph(inputGraph) {
  var g2 = new Graph$7({multigraph: true, compound: true});
  var graph2 = canonicalize(inputGraph.graph());
  g2.setGraph(lodash_1$1.merge({}, graphDefaults, selectNumberAttrs(graph2, graphNumAttrs), lodash_1$1.pick(graph2, graphAttrs)));
  lodash_1$1.forEach(inputGraph.nodes(), function(v2) {
    var node = canonicalize(inputGraph.node(v2));
    g2.setNode(v2, lodash_1$1.defaults(selectNumberAttrs(node, nodeNumAttrs), nodeDefaults));
    g2.setParent(v2, inputGraph.parent(v2));
  });
  lodash_1$1.forEach(inputGraph.edges(), function(e2) {
    var edge = canonicalize(inputGraph.edge(e2));
    g2.setEdge(e2, lodash_1$1.merge({}, edgeDefaults, selectNumberAttrs(edge, edgeNumAttrs), lodash_1$1.pick(edge, edgeAttrs)));
  });
  return g2;
}
function makeSpaceForEdgeLabels(g2) {
  var graph2 = g2.graph();
  graph2.ranksep /= 2;
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var edge = g2.edge(e2);
    edge.minlen *= 2;
    if (edge.labelpos.toLowerCase() !== "c") {
      if (graph2.rankdir === "TB" || graph2.rankdir === "BT") {
        edge.width += edge.labeloffset;
      } else {
        edge.height += edge.labeloffset;
      }
    }
  });
}
function injectEdgeLabelProxies(g2) {
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var edge = g2.edge(e2);
    if (edge.width && edge.height) {
      var v2 = g2.node(e2.v);
      var w2 = g2.node(e2.w);
      var label2 = {rank: (w2.rank - v2.rank) / 2 + v2.rank, e: e2};
      util$2.addDummyNode(g2, "edge-proxy", label2, "_ep");
    }
  });
}
function assignRankMinMax(g2) {
  var maxRank2 = 0;
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    var node = g2.node(v2);
    if (node.borderTop) {
      node.minRank = g2.node(node.borderTop).rank;
      node.maxRank = g2.node(node.borderBottom).rank;
      maxRank2 = lodash_1$1.max(maxRank2, node.maxRank);
    }
  });
  g2.graph().maxRank = maxRank2;
}
function removeEdgeLabelProxies(g2) {
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    var node = g2.node(v2);
    if (node.dummy === "edge-proxy") {
      g2.edge(node.e).labelRank = node.rank;
      g2.removeNode(v2);
    }
  });
}
function translateGraph(g2) {
  var minX = Number.POSITIVE_INFINITY;
  var maxX = 0;
  var minY = Number.POSITIVE_INFINITY;
  var maxY = 0;
  var graphLabel = g2.graph();
  var marginX = graphLabel.marginx || 0;
  var marginY = graphLabel.marginy || 0;
  function getExtremes(attrs) {
    var x2 = attrs.x;
    var y3 = attrs.y;
    var w2 = attrs.width;
    var h2 = attrs.height;
    minX = Math.min(minX, x2 - w2 / 2);
    maxX = Math.max(maxX, x2 + w2 / 2);
    minY = Math.min(minY, y3 - h2 / 2);
    maxY = Math.max(maxY, y3 + h2 / 2);
  }
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    getExtremes(g2.node(v2));
  });
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var edge = g2.edge(e2);
    if (lodash_1$1.has(edge, "x")) {
      getExtremes(edge);
    }
  });
  minX -= marginX;
  minY -= marginY;
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    var node = g2.node(v2);
    node.x -= minX;
    node.y -= minY;
  });
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var edge = g2.edge(e2);
    lodash_1$1.forEach(edge.points, function(p2) {
      p2.x -= minX;
      p2.y -= minY;
    });
    if (lodash_1$1.has(edge, "x")) {
      edge.x -= minX;
    }
    if (lodash_1$1.has(edge, "y")) {
      edge.y -= minY;
    }
  });
  graphLabel.width = maxX - minX + marginX;
  graphLabel.height = maxY - minY + marginY;
}
function assignNodeIntersects(g2) {
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var edge = g2.edge(e2);
    var nodeV = g2.node(e2.v);
    var nodeW = g2.node(e2.w);
    var p1, p2;
    if (!edge.points) {
      edge.points = [];
      p1 = nodeW;
      p2 = nodeV;
    } else {
      p1 = edge.points[0];
      p2 = edge.points[edge.points.length - 1];
    }
    edge.points.unshift(util$2.intersectRect(nodeV, p1));
    edge.points.push(util$2.intersectRect(nodeW, p2));
  });
}
function fixupEdgeLabelCoords(g2) {
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var edge = g2.edge(e2);
    if (lodash_1$1.has(edge, "x")) {
      if (edge.labelpos === "l" || edge.labelpos === "r") {
        edge.width -= edge.labeloffset;
      }
      switch (edge.labelpos) {
        case "l":
          edge.x -= edge.width / 2 + edge.labeloffset;
          break;
        case "r":
          edge.x += edge.width / 2 + edge.labeloffset;
          break;
      }
    }
  });
}
function reversePointsForReversedEdges(g2) {
  lodash_1$1.forEach(g2.edges(), function(e2) {
    var edge = g2.edge(e2);
    if (edge.reversed) {
      edge.points.reverse();
    }
  });
}
function removeBorderNodes(g2) {
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    if (g2.children(v2).length) {
      var node = g2.node(v2);
      var t5 = g2.node(node.borderTop);
      var b2 = g2.node(node.borderBottom);
      var l2 = g2.node(lodash_1$1.last(node.borderLeft));
      var r3 = g2.node(lodash_1$1.last(node.borderRight));
      node.width = Math.abs(r3.x - l2.x);
      node.height = Math.abs(b2.y - t5.y);
      node.x = l2.x + node.width / 2;
      node.y = t5.y + node.height / 2;
    }
  });
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    if (g2.node(v2).dummy === "border") {
      g2.removeNode(v2);
    }
  });
}
function removeSelfEdges(g2) {
  lodash_1$1.forEach(g2.edges(), function(e2) {
    if (e2.v === e2.w) {
      var node = g2.node(e2.v);
      if (!node.selfEdges) {
        node.selfEdges = [];
      }
      node.selfEdges.push({e: e2, label: g2.edge(e2)});
      g2.removeEdge(e2);
    }
  });
}
function insertSelfEdges(g2) {
  var layers = util$2.buildLayerMatrix(g2);
  lodash_1$1.forEach(layers, function(layer) {
    var orderShift = 0;
    lodash_1$1.forEach(layer, function(v2, i3) {
      var node = g2.node(v2);
      node.order = i3 + orderShift;
      lodash_1$1.forEach(node.selfEdges, function(selfEdge) {
        util$2.addDummyNode(g2, "selfedge", {
          width: selfEdge.label.width,
          height: selfEdge.label.height,
          rank: node.rank,
          order: i3 + ++orderShift,
          e: selfEdge.e,
          label: selfEdge.label
        }, "_se");
      });
      delete node.selfEdges;
    });
  });
}
function positionSelfEdges(g2) {
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    var node = g2.node(v2);
    if (node.dummy === "selfedge") {
      var selfNode = g2.node(node.e.v);
      var x2 = selfNode.x + selfNode.width / 2;
      var y3 = selfNode.y;
      var dx = node.x - x2;
      var dy = selfNode.height / 2;
      g2.setEdge(node.e, node.label);
      g2.removeNode(v2);
      node.label.points = [
        {x: x2 + 2 * dx / 3, y: y3 - dy},
        {x: x2 + 5 * dx / 6, y: y3 - dy},
        {x: x2 + dx, y: y3},
        {x: x2 + 5 * dx / 6, y: y3 + dy},
        {x: x2 + 2 * dx / 3, y: y3 + dy}
      ];
      node.label.x = node.x;
      node.label.y = node.y;
    }
  });
}
function selectNumberAttrs(obj, attrs) {
  return lodash_1$1.mapValues(lodash_1$1.pick(obj, attrs), Number);
}
function canonicalize(attrs) {
  var newAttrs = {};
  lodash_1$1.forEach(attrs, function(v2, k2) {
    newAttrs[k2.toLowerCase()] = v2;
  });
  return newAttrs;
}
var Graph$8 = graphlib_1.Graph;
var debug = {
  debugOrdering
};
function debugOrdering(g2) {
  var layerMatrix = util.buildLayerMatrix(g2);
  var h2 = new Graph$8({compound: true, multigraph: true}).setGraph({});
  lodash_1$1.forEach(g2.nodes(), function(v2) {
    h2.setNode(v2, {label: v2});
    h2.setParent(v2, "layer" + g2.node(v2).rank);
  });
  lodash_1$1.forEach(g2.edges(), function(e2) {
    h2.setEdge(e2.v, e2.w, {}, e2.name);
  });
  lodash_1$1.forEach(layerMatrix, function(layer, i3) {
    var layerV = "layer" + i3;
    h2.setNode(layerV, {rank: "same"});
    lodash_1$1.reduce(layer, function(u, v2) {
      h2.setEdge(u, v2, {style: "invis"});
      return v2;
    });
  });
  return h2;
}
var version$1 = "0.8.5";
var dagre = {
  graphlib: graphlib_1,
  layout: layout_1,
  debug,
  util: {
    time: util.time,
    notime: util.notime
  },
  version: version$1
};
var dagre_default = dagre;

// build/authentication/components/diagram/auto-layout.js
var dagreGraph = new dagre_default.graphlib.Graph();
dagreGraph.setDefaultEdgeLabel(() => ({}));
var nodeWidth = 130;
var nodeHeight = 28;
var getLayoutedElements = (elements, direction = "LR") => {
  const isHorizontal = direction === "LR";
  dagreGraph.setGraph({rankdir: direction});
  elements.forEach((element) => {
    if (isNode(element)) {
      dagreGraph.setNode(element.id, {
        width: nodeWidth,
        height: nodeHeight
      });
    } else {
      dagreGraph.setEdge(element.source, element.target);
    }
  });
  dagre_default.layout(dagreGraph);
  return elements.map((element) => {
    if (isNode(element)) {
      const nodeWithPosition = dagreGraph.node(element.id);
      element.targetPosition = isHorizontal ? Position2.Left : Position2.Top;
      element.sourcePosition = isHorizontal ? Position2.Right : Position2.Bottom;
      element.position = {
        x: nodeWithPosition.x - nodeWidth / 2 + Math.random() / 1e3,
        y: nodeWithPosition.y - nodeHeight / 2
      };
    }
    return element;
  });
};

// build/authentication/components/FlowDiagram.js
var import_FlowDetails2 = require_FlowDetails();
var createEdge = (fromNode, toNode) => ({
  id: `edge-${fromNode}-to-${toNode}`,
  type: "buttonEdge",
  source: fromNode,
  target: toNode,
  data: {
    onEdgeClick: (evt, id3) => {
      evt.stopPropagation();
      alert(`hello ${id3}`);
    }
  }
});
var createNode = (ex) => {
  let nodeType = void 0;
  if (ex.executionList) {
    nodeType = "startSubFlow";
  }
  if ((0, import_FlowDetails2.providerConditionFilter)(ex)) {
    nodeType = "conditional";
  }
  return {
    id: ex.id,
    type: nodeType,
    sourcePosition: Position2.Right,
    targetPosition: Position2.Left,
    data: {label: ex.displayName},
    position: {x: 0, y: 0}
  };
};
var renderParallelNodes = (start3, execution, end2) => {
  const elements = [];
  elements.push(createNode(execution));
  elements.push(createEdge(start3.id, execution.id));
  elements.push(createEdge(execution.id, end2.id));
  return elements;
};
var renderSequentialNodes = (start3, execution, end2, prefExecution, isFirst, isLast) => {
  const elements = [];
  elements.push(createNode(execution));
  if (isFirst) {
    elements.push(createEdge(start3.id, execution.id));
  } else {
    elements.push(createEdge(prefExecution.id, execution.id));
  }
  if (isLast) {
    elements.push(createEdge(execution.id, end2.id));
  }
  return elements;
};
var renderSubFlow = (execution, start3, end2, prefExecution) => {
  const elements = [];
  elements.push({
    id: execution.id,
    type: "startSubFlow",
    sourcePosition: Position2.Right,
    targetPosition: Position2.Left,
    data: {label: execution.displayName},
    position: {x: 0, y: 0}
  });
  const endSubFlowId = `flow-end-${execution.id}`;
  elements.push({
    id: endSubFlowId,
    type: "endSubFlow",
    sourcePosition: Position2.Right,
    targetPosition: Position2.Left,
    data: {label: execution.displayName},
    position: {x: 0, y: 0}
  });
  elements.push(createEdge(prefExecution && prefExecution.requirement !== "ALTERNATIVE" ? prefExecution.id : start3.id, execution.id));
  elements.push(createEdge(endSubFlowId, end2.id));
  return elements.concat(renderFlow(execution, execution.executionList || [], {
    ...execution,
    id: endSubFlowId
  }));
};
var renderFlow = (start3, executionList, end2) => {
  let elements = [];
  for (let index3 = 0; index3 < executionList.length; index3++) {
    const execution = executionList[index3];
    if (execution.executionList) {
      elements = elements.concat(renderSubFlow(execution, start3, end2, executionList[index3 - 1]));
    } else {
      if (execution.requirement === "ALTERNATIVE" || execution.requirement === "DISABLED") {
        elements = elements.concat(renderParallelNodes(start3, execution, end2));
      } else {
        elements = elements.concat(renderSequentialNodes(start3, execution, end2, executionList[index3 - 1], index3 === 0, index3 === executionList.length - 1));
      }
    }
  }
  return elements;
};
var FlowDiagram = ({
  executionList: {expandableList}
}) => {
  let elements = [
    {
      id: "start",
      sourcePosition: Position2.Right,
      type: "input",
      data: {label: "Start"},
      position: {x: 0, y: 0},
      className: "keycloak__authentication__input_node"
    },
    {
      id: "end",
      targetPosition: Position2.Left,
      type: "output",
      data: {label: "End"},
      position: {x: 0, y: 0},
      className: "keycloak__authentication__output_node"
    }
  ];
  elements = elements.concat(renderFlow({id: "start"}, expandableList, {id: "end"}));
  const onLoad = (reactFlowInstance) => reactFlowInstance.fitView();
  const [layoutedElements, setElements3] = useState(getLayoutedElements(elements));
  const [expandDrawer, setExpandDrawer] = useState(false);
  const onElementClick = (_event, element) => {
    if (isNode(element))
      setExpandDrawer(!expandDrawer);
  };
  const onElementsRemove = (elementsToRemove) => setElements3((els) => removeElements(elementsToRemove, els));
  return /* @__PURE__ */ react.createElement(Drawer, {
    isExpanded: expandDrawer,
    onExpand: () => setExpandDrawer(true)
  }, /* @__PURE__ */ react.createElement(DrawerContent, {
    panelContent: /* @__PURE__ */ react.createElement(DrawerPanelContent, null, /* @__PURE__ */ react.createElement(DrawerHead, null, /* @__PURE__ */ react.createElement("span", {
      tabIndex: expandDrawer ? 0 : -1
    }, "drawer-panel"), /* @__PURE__ */ react.createElement(DrawerActions, null, /* @__PURE__ */ react.createElement(DrawerCloseButton, {
      onClick: () => setExpandDrawer(false)
    }))))
  }, /* @__PURE__ */ react.createElement(DrawerContentBody, null, /* @__PURE__ */ react.createElement(react_flow_renderer_default, {
    nodeTypes: {
      conditional: ConditionalNode,
      startSubFlow: StartSubFlowNode,
      endSubFlow: EndSubFlowNode
    },
    edgeTypes: {
      buttonEdge: ButtonEdge
    },
    onElementClick,
    onElementsRemove,
    onLoad,
    elements: layoutedElements,
    nodesConnectable: false
  }, /* @__PURE__ */ react.createElement(index$2, null), /* @__PURE__ */ react.createElement(index$1, null), /* @__PURE__ */ react.createElement(index2, null)))));
};

// build/authentication/EditFlowModal.js
var EditFlowModal = ({flow, toggleDialog}) => {
  const {t: t5} = useTranslation("authentication");
  const form2 = useForm({
    shouldUnregister: false
  });
  const {reset: reset2, handleSubmit} = form2;
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  useEffect(() => {
    reset2(flow);
  }, [flow, reset2]);
  const save = async (values2) => {
    try {
      await adminClient.authenticationManagement.updateFlow({flowId: flow.id}, {...flow, ...values2});
      addAlert(t5("updateFlowSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("authentication:updateFlowError", error2);
    }
    toggleDialog();
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    title: t5("editFlow"),
    isOpen: true,
    onClose: toggleDialog,
    variant: ModalVariant.small,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-confirm",
        key: "confirm",
        onClick: handleSubmit(save),
        "data-testid": "confirm"
      }, t5("edit")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "cancel",
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          toggleDialog();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(FormProvider, {
    ...form2
  }, /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(NameDescription, null))));
};

// build/authentication/routes/Flow.js
var FlowRoute = {
  path: "/:realm/authentication/:id/:usedBy/:builtIn?",
  component: lazy(() => Promise.resolve().then(() => require_FlowDetails())),
  breadcrumb: (t5) => t5("authentication:flowDetails"),
  access: "manage-authorization"
};
var toFlow = (params) => ({
  pathname: generatePath(FlowRoute.path, params)
});

// build/authentication/routes/CreateFlow.js
var CreateFlowRoute = {
  path: "/:realm/authentication/flows/create",
  component: lazy(() => Promise.resolve().then(() => require_CreateFlow())),
  breadcrumb: (t5) => t5("authentication:createFlow"),
  access: "manage-authorization"
};
var toCreateFlow = (params) => ({
  pathname: generatePath(CreateFlowRoute.path, params)
});

// build/authentication/components/DraggableTable.js
function DraggableTable({
  keyField,
  columns,
  data: data2,
  onDragFinish
}) {
  const {t: t5} = useTranslation("authentication");
  const bodyRef = useRef(null);
  const [state, setState] = useState({
    draggedItemId: "",
    draggingToItemIndex: -1,
    dragging: false,
    tempItemOrder: [""]
  });
  const itemOrder = useMemo(() => data2.map((d2) => get(d2, keyField)), [data2]);
  const onDragStart = (evt) => {
    evt.dataTransfer.effectAllowed = "move";
    evt.dataTransfer.setData("text/plain", evt.currentTarget.id);
    const draggedItemId = evt.currentTarget.id;
    evt.currentTarget.classList.add(__pika_web_default_export_for_treeshaking__2.modifiers.ghostRow);
    evt.currentTarget.setAttribute("aria-pressed", "true");
    setState({...state, draggedItemId, dragging: true});
  };
  const moveItem2 = (arr, i1, toIndex) => {
    const fromIndex = arr.indexOf(i1);
    if (fromIndex === toIndex) {
      return arr;
    }
    const temp = arr.splice(fromIndex, 1);
    arr.splice(toIndex, 0, temp[0]);
    return arr;
  };
  const move = (itemOrder2) => {
    if (!bodyRef.current)
      return;
    const ulNode = bodyRef.current;
    const nodes = Array.from(ulNode.children);
    if (nodes.map((node) => node.id).every((id3, i3) => id3 === itemOrder2[i3])) {
      return;
    }
    while (ulNode.firstChild) {
      ulNode.removeChild(ulNode.lastChild);
    }
    itemOrder2.forEach((id3) => {
      ulNode.appendChild(nodes.find((n3) => n3.id === id3));
    });
  };
  const onDragCancel = () => {
    Array.from(bodyRef.current?.children || []).forEach((el) => {
      el.classList.remove(__pika_web_default_export_for_treeshaking__2.modifiers.ghostRow);
      el.setAttribute("aria-pressed", "false");
    });
    setState({
      ...state,
      draggedItemId: "",
      draggingToItemIndex: -1,
      dragging: false
    });
  };
  const onDragLeave = (evt) => {
    if (!isValidDrop(evt)) {
      move(itemOrder);
      setState({...state, draggingToItemIndex: -1});
    }
  };
  const isValidDrop = (evt) => {
    const ulRect = bodyRef.current.getBoundingClientRect();
    return evt.clientX > ulRect.x && evt.clientX < ulRect.x + ulRect.width && evt.clientY > ulRect.y && evt.clientY < ulRect.y + ulRect.height;
  };
  const onDrop = (evt) => {
    if (isValidDrop(evt)) {
      onDragFinish(state.draggedItemId, state.tempItemOrder);
    } else {
      onDragCancel();
    }
  };
  const onDragOver = (evt) => {
    evt.preventDefault();
    const td2 = evt.target;
    const curListItem = td2.closest("tr");
    if (!curListItem || bodyRef.current && !bodyRef.current.contains(curListItem) || curListItem.id === state.draggedItemId) {
      return null;
    } else {
      const dragId = curListItem.id;
      const draggingToItemIndex = Array.from(bodyRef.current?.children || []).findIndex((item) => item.id === dragId);
      if (draggingToItemIndex !== state.draggingToItemIndex) {
        const tempItemOrder = moveItem2(itemOrder, state.draggedItemId, draggingToItemIndex);
        move(tempItemOrder);
        setState({
          ...state,
          draggingToItemIndex,
          tempItemOrder
        });
      }
    }
  };
  const onDragEnd = (evt) => {
    const tr = evt.target;
    tr.classList.remove(__pika_web_default_export_for_treeshaking__2.modifiers.ghostRow);
    tr.setAttribute("aria-pressed", "false");
    setState({
      ...state,
      draggedItemId: "",
      draggingToItemIndex: -1,
      dragging: false
    });
  };
  return /* @__PURE__ */ react.createElement(TableComposable, {
    "aria-label": "Draggable table",
    className: state.dragging ? __pika_web_default_export_for_treeshaking__2.modifiers.dragOver : ""
  }, /* @__PURE__ */ react.createElement(Thead, null, /* @__PURE__ */ react.createElement(Tr, null, /* @__PURE__ */ react.createElement(Th2, null), columns.map((column) => /* @__PURE__ */ react.createElement(Th2, {
    key: column.name
  }, t5(column.displayKey || column.name))))), /* @__PURE__ */ react.createElement(Tbody, {
    ref: bodyRef,
    onDragOver,
    onDrop: onDragOver,
    onDragLeave
  }, data2.map((row) => /* @__PURE__ */ react.createElement(Tr, {
    key: get(row, keyField),
    id: get(row, keyField),
    draggable: true,
    onDrop,
    onDragEnd,
    onDragStart
  }, /* @__PURE__ */ react.createElement(Td2, {
    draggableRow: {
      id: `draggable-row-${get(row, "id")}`
    }
  }), columns.map((column) => /* @__PURE__ */ react.createElement(Td2, {
    key: `${get(row, "id")}_${column.name}`,
    dataLabel: column.name
  }, column.cellRenderer ? column.cellRenderer(row) : get(row, column.name)))))));
}

// build/authentication/RequiredActions.js
var RequiredActions = () => {
  const {t: t5} = useTranslation("authentication");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [actions2, setActions] = useState();
  const [key, setKey] = useState(0);
  const refresh = () => setKey(key + 1);
  useFetch(async () => {
    const [requiredActions, unregisteredRequiredActions] = await Promise.all([
      adminClient.authenticationManagement.getRequiredActions(),
      adminClient.authenticationManagement.getUnregisteredRequiredActions()
    ]);
    return [
      ...requiredActions.map((a2) => ({
        name: a2.name,
        enabled: a2.enabled,
        defaultAction: a2.defaultAction,
        data: a2
      })),
      ...unregisteredRequiredActions.map((a2) => ({
        name: a2.name,
        enabled: false,
        defaultAction: false,
        data: a2
      }))
    ];
  }, (actions22) => setActions(actions22), [key]);
  const isUnregisteredAction = (data2) => {
    return !("alias" in data2);
  };
  const updateAction = async (action, field) => {
    try {
      if (field in action) {
        action[field] = !action[field];
        await adminClient.authenticationManagement.updateRequiredAction({alias: action.alias}, action);
      } else if (isUnregisteredAction(action)) {
        await adminClient.authenticationManagement.registerRequiredAction({
          name: action.name,
          providerId: action.providerId
        });
      }
      refresh();
      addAlert(t5("updatedRequiredActionSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("authentication:updatedRequiredActionError", error2);
    }
  };
  const executeMove = async (action, times) => {
    try {
      const alias = action.alias;
      for (let index3 = 0; index3 < Math.abs(times); index3++) {
        if (times > 0) {
          await adminClient.authenticationManagement.lowerRequiredActionPriority({
            alias
          });
        } else {
          await adminClient.authenticationManagement.raiseRequiredActionPriority({
            alias
          });
        }
      }
      refresh();
      addAlert(t5("updatedRequiredActionSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("authentication:updatedRequiredActionError", error2);
    }
  };
  if (!actions2) {
    return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
  }
  return /* @__PURE__ */ react.createElement(DraggableTable, {
    keyField: "name",
    onDragFinish: async (nameDragged, items) => {
      const keys2 = actions2.map((e2) => e2.name);
      const newIndex = items.indexOf(nameDragged);
      const oldIndex = keys2.indexOf(nameDragged);
      const dragged = actions2[oldIndex].data;
      if (!dragged.alias)
        return;
      const times = newIndex - oldIndex;
      executeMove(dragged, times);
    },
    columns: [
      {
        name: "name",
        displayKey: "authentication:requiredActions"
      },
      {
        name: "enabled",
        displayKey: "common:enabled",
        cellRenderer: (row) => /* @__PURE__ */ react.createElement(Switch, {
          id: `enable-${row.name}`,
          label: t5("common:on"),
          labelOff: t5("common:off"),
          isChecked: row.enabled,
          onChange: () => {
            updateAction(row.data, "enabled");
          }
        })
      },
      {
        name: "default",
        displayKey: "authentication:setAsDefaultAction",
        cellRenderer: (row) => /* @__PURE__ */ react.createElement(Switch, {
          id: `default-${row.name}`,
          label: t5("common:on"),
          isDisabled: !!isUnregisteredAction(row.data),
          labelOff: isUnregisteredAction(row.data) ? t5("disabledOff") : t5("common:off"),
          isChecked: row.defaultAction,
          onChange: () => {
            updateAction(row.data, "defaultAction");
          }
        })
      }
    ],
    data: actions2
  });
};

// build/authentication/policies/util.js
var POLICY_SEPARATOR = " and ";
var serializePolicy = (policies, submitted) => policies.map((policy) => `${policy.id}(${submitted[policy.id]})`).join(POLICY_SEPARATOR);
var parsePolicy = (value, policies) => value.split(POLICY_SEPARATOR).map(parsePolicyToken).reduce((result, {id: id3, value: value2}) => {
  const matchingPolicy = policies.find((policy) => policy.id === id3);
  if (!matchingPolicy) {
    return result;
  }
  return result.concat({...matchingPolicy, value: value2});
}, []);
function parsePolicyToken(token2) {
  const valueStart = token2.indexOf("(");
  if (valueStart === -1) {
    return {id: token2.trim()};
  }
  const id3 = token2.substring(0, valueStart).trim();
  const valueEnd = token2.lastIndexOf(")");
  if (valueEnd === -1) {
    return {id: id3};
  }
  const value = token2.substring(valueStart + 1, valueEnd).trim();
  return {id: id3, value};
}

// build/authentication/policies/PolicyRow.js
var PolicyRow = ({
  policy: {id: id3, configType, defaultValue, displayName},
  onRemove: onRemove2
}) => {
  const {t: t5} = useTranslation("authentication");
  const {control, register: register2, errors} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: displayName,
    fieldId: id3,
    isRequired: true,
    helperTextInvalid: t5("common:required"),
    validated: errors[id3] ? ValidatedOptions.error : ValidatedOptions.default
  }, /* @__PURE__ */ react.createElement(Split, null, /* @__PURE__ */ react.createElement(SplitItem, {
    isFilled: true
  }, configType && configType !== "int" && /* @__PURE__ */ react.createElement(TextInput, {
    id: id3,
    "data-testid": id3,
    ref: register2({required: true}),
    name: id3,
    defaultValue,
    validated: errors[id3] ? ValidatedOptions.error : ValidatedOptions.default
  }), configType === "int" && /* @__PURE__ */ react.createElement(Controller, {
    name: id3,
    defaultValue: Number.parseInt(defaultValue || "0"),
    control,
    render: ({onChange, value}) => {
      const MIN_VALUE = 0;
      const setValue = (newValue) => onChange(Math.max(newValue, MIN_VALUE));
      return /* @__PURE__ */ react.createElement(NumberInput, {
        id: id3,
        value,
        min: MIN_VALUE,
        onPlus: () => setValue(value + 1),
        onMinus: () => setValue(value - 1),
        onChange: (event) => {
          const newValue = Number(event.currentTarget.value);
          setValue(!isNaN(newValue) ? newValue : 0);
        },
        className: "keycloak__policies_authentication__number-field"
      });
    }
  }), !configType && /* @__PURE__ */ react.createElement(Switch, {
    id: id3,
    label: t5("common:on"),
    labelOff: t5("common:off"),
    isChecked: true,
    isDisabled: true
  })), /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(Button, {
    "data-testid": `remove-${id3}`,
    variant: "link",
    className: "keycloak__policies_authentication__minus-icon",
    onClick: () => onRemove2(id3)
  }, /* @__PURE__ */ react.createElement(MinusCircleIcon, null)))));
};

// build/authentication/policies/PasswordPolicy.js
var PolicySelect = ({onSelect, selectedPolicies}) => {
  const {t: t5} = useTranslation("authentication");
  const {passwordPolicies} = useServerInfo();
  const [open2, setOpen] = useState(false);
  const policies = useMemo(() => passwordPolicies?.filter((p2) => selectedPolicies.find((o) => o.id === p2.id) === void 0), [selectedPolicies]);
  return /* @__PURE__ */ react.createElement(Select, {
    width: 300,
    onSelect: (_23, selection2) => {
      onSelect(selection2);
      setOpen(false);
    },
    onToggle: (value) => setOpen(value),
    isOpen: open2,
    selections: t5("addPolicy"),
    isDisabled: policies?.length === 0
  }, policies?.map((policy) => /* @__PURE__ */ react.createElement(SelectOption, {
    key: policy.id,
    value: policy
  }, policy.displayName)));
};
var PasswordPolicy = () => {
  const {t: t5} = useTranslation("authentication");
  const {passwordPolicies} = useServerInfo();
  const adminClient = useAdminClient();
  const {realm: realmName} = useRealm();
  const {addAlert, addError} = useAlerts();
  const [realm2, setRealm] = useState();
  const [rows, setRows] = useState([]);
  const onSelect = (row) => setRows([...rows, row]);
  const form2 = useForm({shouldUnregister: false});
  const {handleSubmit, setValue, getValues} = form2;
  const setupForm = (realm22) => {
    const values2 = parsePolicy(realm22.passwordPolicy || "", passwordPolicies);
    values2.forEach((v2) => {
      setValue(v2.id, v2.value);
    });
    setRows(values2);
  };
  useFetch(async () => {
    const realm22 = await adminClient.realms.findOne({realm: realmName});
    if (!realm22) {
      throw new Error(t5("common:notFound"));
    }
    return realm22;
  }, (realm22) => {
    setRealm(realm22);
    setupForm(realm22);
  }, []);
  const save = async (values2) => {
    const updatedRealm = {
      ...realm2,
      passwordPolicy: serializePolicy(rows, values2)
    };
    try {
      await adminClient.realms.update({realm: realmName}, updatedRealm);
      setRealm(updatedRealm);
      addAlert(t5("updatePasswordPolicySuccess"), AlertVariant.success);
    } catch (error2) {
      addError("authentication:updatePasswordPolicyError", error2);
    }
  };
  if (!realm2) {
    return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
  }
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light",
    className: "pf-u-p-0"
  }, (rows.length !== 0 || realm2.passwordPolicy) && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Toolbar, null, /* @__PURE__ */ react.createElement(ToolbarContent, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(PolicySelect, {
    onSelect,
    selectedPolicies: rows
  })))), /* @__PURE__ */ react.createElement(Divider, null), /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(FormProvider, {
    ...form2
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true,
    onSubmit: handleSubmit(save)
  }, rows.map((r3, index3) => /* @__PURE__ */ react.createElement(PolicyRow, {
    key: `${r3.id}-${index3}`,
    policy: r3,
    onRemove: (id3) => setRows(rows.filter((r22) => r22.id !== id3))
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "save",
    variant: "primary",
    type: "submit",
    isDisabled: serializePolicy(rows, getValues()) === realm2.passwordPolicy
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "reload",
    variant: ButtonVariant.link,
    onClick: () => setupForm(realm2)
  }, t5("common:reload"))))))), !rows.length && !realm2.passwordPolicy && /* @__PURE__ */ react.createElement(EmptyState, {
    "data-testid": "empty-state",
    variant: "large"
  }, /* @__PURE__ */ react.createElement(EmptyStateIcon, {
    icon: PlusCircleIcon
  }), /* @__PURE__ */ react.createElement(Title, {
    headingLevel: "h1",
    size: "lg"
  }, t5("noPasswordPolicies")), /* @__PURE__ */ react.createElement(EmptyStateBody, null, t5("noPasswordPoliciesInstructions")), /* @__PURE__ */ react.createElement(EmptyStatePrimary, null, /* @__PURE__ */ react.createElement(PolicySelect, {
    onSelect,
    selectedPolicies: []
  }))));
};

// build/components/time-selector/TimeSelector.js
var TimeSelector = ({
  value,
  units = ["seconds", "minutes", "hours", "days"],
  onChange,
  className,
  min: min2,
  ...rest
}) => {
  const {t: t5} = useTranslation("common");
  const allTimes = [
    {unit: "seconds", label: t5("times.seconds"), multiplier: 1},
    {unit: "minutes", label: t5("times.minutes"), multiplier: 60},
    {unit: "hours", label: t5("times.hours"), multiplier: 3600},
    {unit: "days", label: t5("times.days"), multiplier: 86400}
  ];
  const times = units.map((unit) => allTimes.find((time2) => time2.unit === unit));
  const defaultMultiplier = allTimes.find((time2) => time2.unit === units[0])?.multiplier;
  const [timeValue, setTimeValue] = useState("");
  const [multiplier, setMultiplier] = useState(defaultMultiplier);
  const [open2, setOpen] = useState(false);
  useEffect(() => {
    const x2 = times.reduce((v2, time2) => value % time2.multiplier === 0 && v2 < time2.multiplier ? time2.multiplier : v2, 1);
    if (value) {
      setMultiplier(x2);
      setTimeValue(value / x2);
    } else {
      setTimeValue("");
      setMultiplier(defaultMultiplier);
    }
  }, [value]);
  const updateTimeout = (timeout3, times2 = multiplier) => {
    if (timeout3 !== "") {
      onChange(timeout3 * (times2 || 1));
      setTimeValue(timeout3);
    } else {
      onChange("");
    }
  };
  return /* @__PURE__ */ react.createElement(Split, {
    hasGutter: true,
    className
  }, /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(TextInput, {
    ...rest,
    type: "number",
    "aria-label": "kc-time",
    min: min2 || 0,
    value: timeValue,
    className: `${className}-input`,
    onChange: (value2) => {
      updateTimeout(value2 === "" ? value2 : parseInt(value2));
    }
  })), /* @__PURE__ */ react.createElement(SplitItem, {
    id: `${className}-select-menu`
  }, /* @__PURE__ */ react.createElement(Select, {
    variant: SelectVariant.single,
    "aria-label": t5("unitLabel"),
    className: `${className}-select`,
    onSelect: (_23, value2) => {
      setMultiplier(value2);
      updateTimeout(timeValue, value2);
      setOpen(false);
    },
    selections: [multiplier],
    onToggle: () => {
      setOpen(!open2);
    },
    isOpen: open2
  }, times.map((time2) => /* @__PURE__ */ react.createElement(SelectOption, {
    id: time2.label,
    key: time2.label,
    value: time2.multiplier
  }, time2.label)))));
};

// build/authentication/policies/OtpPolicy.js
var POLICY_TYPES = ["totp", "hotp"];
var OTP_HASH_ALGORITHMS = ["SHA1", "SHA256", "SHA512"];
var NUMBER_OF_DIGITS = [6, 8];
var OtpPolicy = () => {
  const {t: t5} = useTranslation("authentication");
  const {
    control,
    errors,
    reset: reset2,
    handleSubmit,
    formState: {isDirty}
  } = useForm({mode: "onChange"});
  const adminClient = useAdminClient();
  const {realm: realmName} = useRealm();
  const {addAlert, addError} = useAlerts();
  const [open2, toggle] = useToggle();
  const [realm2, setRealm] = useState();
  const otpType = useWatch({
    name: "otpPolicyType",
    control,
    defaultValue: POLICY_TYPES[0]
  });
  useFetch(() => adminClient.realms.findOne({realm: realmName}), (realm22) => {
    setRealm(realm22);
    reset2({...realm22});
  }, []);
  const save = async (realm22) => {
    try {
      await adminClient.realms.update({realm: realmName}, realm22);
      const updatedRealm = await adminClient.realms.findOne({
        realm: realmName
      });
      setRealm(updatedRealm);
      reset2({...updatedRealm});
      addAlert(t5("updateOtpSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("authentication:updateOtpError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true,
    onSubmit: handleSubmit(save),
    className: "keycloak__otp_policies_authentication__form"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("otpType"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:otpType",
      fieldLabelId: "authentication:otpType"
    }),
    fieldId: "otpType",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "otpPolicyType",
    "data-testid": "otpPolicyType",
    defaultValue: POLICY_TYPES[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(react.Fragment, null, POLICY_TYPES.map((type) => /* @__PURE__ */ react.createElement(Radio, {
      id: type,
      key: type,
      "data-testid": type,
      isChecked: value === type,
      name: "otpPolicyType",
      onChange: () => onChange(type),
      label: t5(`policyType.${type}`),
      className: "keycloak__otp_policies_authentication__policy-type"
    })))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("otpHashAlgorithm"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:otpHashAlgorithm",
      fieldLabelId: "authentication:otpHashAlgorithm"
    }),
    fieldId: "otpHashAlgorithm"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "otpPolicyAlgorithm",
    defaultValue: `Hmac${OTP_HASH_ALGORITHMS[0]}`,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "otpHashAlgorithm",
      onToggle: toggle,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        toggle();
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("otpHashAlgorithm"),
      isOpen: open2
    }, OTP_HASH_ALGORITHMS.map((type) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: `Hmac${type}` === value,
      key: type,
      value: `Hmac${type}`
    }, type)))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("otpPolicyDigits"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:otpPolicyDigits",
      fieldLabelId: "authentication:otpPolicyDigits"
    }),
    fieldId: "otpPolicyDigits",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "otpPolicyDigits",
    "data-testid": "otpPolicyDigits",
    defaultValue: NUMBER_OF_DIGITS[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(react.Fragment, null, NUMBER_OF_DIGITS.map((type) => /* @__PURE__ */ react.createElement(Radio, {
      id: `digit-${type}`,
      key: type,
      "data-testid": `digit-${type}`,
      isChecked: value === type,
      name: "otpPolicyDigits",
      onChange: () => onChange(type),
      label: type,
      className: "keycloak__otp_policies_authentication__number-of-digits"
    })))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("lookAhead"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:lookAhead",
      fieldLabelId: "authentication:lookAhead"
    }),
    fieldId: "lookAhead"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "otpPolicyLookAheadWindow",
    defaultValue: 1,
    control,
    render: ({onChange, value}) => {
      const MIN_VALUE = 0;
      const setValue = (newValue) => onChange(Math.max(newValue, MIN_VALUE));
      return /* @__PURE__ */ react.createElement(NumberInput, {
        id: "lookAhead",
        value,
        min: MIN_VALUE,
        onPlus: () => setValue(value + 1),
        onMinus: () => setValue(value - 1),
        onChange: (event) => {
          const newValue = Number(event.currentTarget.value);
          setValue(!isNaN(newValue) ? newValue : 0);
        }
      });
    }
  })), otpType === POLICY_TYPES[0] && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("otpPolicyPeriod"),
    fieldId: "otpPolicyPeriod",
    helperTextInvalid: t5("otpPolicyPeriodErrorHint"),
    validated: errors.otpPolicyPeriod ? "error" : "default",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:otpPolicyPeriod",
      fieldLabelId: "authentication:otpPolicyPeriod"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "otpPolicyPeriod",
    defaultValue: 30,
    control,
    rules: {min: 1, max: 120},
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      "data-testid": "otpPolicyPeriod",
      "aria-label": t5("otpPolicyPeriod"),
      value,
      onChange,
      units: ["seconds", "minutes"],
      validated: errors.otpPolicyPeriod ? "error" : "default"
    })
  })), otpType === POLICY_TYPES[1] && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("initialCounter"),
    fieldId: "initialCounter",
    helperTextInvalid: t5("initialCounterErrorHint"),
    validated: errors.otpPolicyInitialCounter ? "error" : "default",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:initialCounter",
      fieldLabelId: "authentication:initialCounter"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "otpPolicyInitialCounter",
    defaultValue: 30,
    control,
    rules: {min: 1, max: 120},
    render: ({onChange, value}) => {
      const MIN_VALUE = 1;
      const setValue = (newValue) => onChange(Math.max(newValue, MIN_VALUE));
      return /* @__PURE__ */ react.createElement(NumberInput, {
        id: "initialCounter",
        value,
        min: MIN_VALUE,
        onPlus: () => setValue(value + 1),
        onMinus: () => setValue(value - 1),
        onChange: (event) => {
          const newValue = Number(event.currentTarget.value);
          setValue(!isNaN(newValue) ? newValue : 30);
        }
      });
    }
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("supportedActions"),
    fieldId: "supportedActions",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "authentication-help:supportedActions",
      fieldLabelId: "authentication:supportedActions"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    id: "supportedActions",
    "data-testid": "supportedActions",
    isReadOnly: true,
    value: realm2?.otpSupportedApplications?.join(", ")
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "save",
    variant: "primary",
    type: "submit",
    isDisabled: !isDirty
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "reload",
    variant: ButtonVariant.link,
    onClick: () => reset2({...realm2})
  }, t5("common:reload")))));
};

// build/authentication/policies/Policies.js
var Policies = () => {
  const {t: t5} = useTranslation("authentication");
  const [subTab, setSubTab] = useState(1);
  return /* @__PURE__ */ react.createElement(Tabs, {
    activeKey: subTab,
    onSelect: (_23, key) => setSubTab(key),
    mountOnEnter: true
  }, /* @__PURE__ */ react.createElement(Tab, {
    id: "passwordPolicy",
    eventKey: 1,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("passwordPolicy"))
  }, /* @__PURE__ */ react.createElement(PasswordPolicy, null)), /* @__PURE__ */ react.createElement(Tab, {
    id: "otpPolicy",
    eventKey: 2,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("otpPolicy"))
  }, /* @__PURE__ */ react.createElement(OtpPolicy, null)), /* @__PURE__ */ react.createElement(Tab, {
    id: "webauthnPolicy",
    eventKey: 3,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("webauthnPolicy"))
  }), /* @__PURE__ */ react.createElement(Tab, {
    id: "webauthnPasswordlessPolicy",
    eventKey: 4,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("webauthnPasswordlessPolicy"))
  }));
};

// build/authentication/routes/Authentication.js
var AuthenticationRoute = {
  path: "/:realm/authentication/:tab?",
  component: lazy(() => Promise.resolve().then(() => require_AuthenticationSection())),
  breadcrumb: (t5) => t5("authentication"),
  access: "view-realm"
};
var toAuthentication = (params) => ({
  pathname: generatePath(AuthenticationRoute.path, params)
});

// build/authentication/routes.js
var routes = [AuthenticationRoute, CreateFlowRoute, FlowRoute];
var routes_default = routes;

// build/client-scopes/add/MapperDialog.js
var AddMapperDialog = (props) => {
  const {t: t5} = useTranslation("client-scopes");
  const serverInfo2 = useServerInfo();
  const {whoAmI: whoAmI2} = useWhoAmI();
  const protocol = props.protocol;
  const protocolMappers = serverInfo2.protocolMapperTypes[protocol];
  const builtInMappers = serverInfo2.builtinProtocolMappers[protocol];
  const [filter3, setFilter] = useState([]);
  const allRows = useMemo(() => builtInMappers.sort((a2, b2) => a2.name.localeCompare(b2.name, whoAmI2.getLocale())).map((mapper) => {
    const mapperType = protocolMappers.filter((type) => type.id === mapper.protocolMapper)[0];
    return {
      item: mapper,
      selected: false,
      cells: [mapper.name, mapperType.helpText]
    };
  }), []);
  const [rows, setRows] = useState(allRows);
  if (props.filter && props.filter.length !== filter3.length) {
    setFilter(props.filter);
    const nameFilter2 = props.filter.map((f2) => f2.name);
    setRows([...allRows.filter((row) => !nameFilter2.includes(row.item.name))]);
  }
  const selectedRows = rows.filter((row) => row.selected).map((row) => row.item);
  const sortedProtocolMappers = useMemo(() => protocolMappers.sort((a2, b2) => a2.name.localeCompare(b2.name, whoAmI2.getLocale())), [protocolMappers]);
  const isBuiltIn = !!props.filter;
  const header = [t5("common:name"), t5("common:description")];
  return /* @__PURE__ */ react.createElement(Modal, {
    "aria-labelledby": t5("addPredefinedMappers"),
    variant: ModalVariant.medium,
    header: /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, {
      component: TextVariants.h1
    }, t5("addPredefinedMappers")), /* @__PURE__ */ react.createElement(Text, null, t5("predefinedMappingDescription"))),
    isOpen: props.open,
    onClose: props.toggleDialog,
    actions: isBuiltIn ? [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-confirm",
        "data-testid": "modalConfirm",
        key: "confirm",
        isDisabled: rows.length === 0 || selectedRows.length === 0,
        onClick: () => {
          props.onConfirm(selectedRows);
          props.toggleDialog();
        }
      }, t5("common:add")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          props.toggleDialog();
        }
      }, t5("common:cancel"))
    ] : []
  }, !isBuiltIn && /* @__PURE__ */ react.createElement(DataList, {
    onSelectDataListItem: (id3) => {
      const mapper = protocolMappers.find((mapper2) => mapper2.id === id3);
      props.onConfirm(mapper);
      props.toggleDialog();
    },
    "aria-label": t5("addPredefinedMappers"),
    isCompact: true
  }, /* @__PURE__ */ react.createElement(DataListItem, {
    "aria-labelledby": "headerName",
    id: "header"
  }, /* @__PURE__ */ react.createElement(DataListItemRow, null, /* @__PURE__ */ react.createElement(DataListItemCells, {
    dataListCells: header.map((name) => /* @__PURE__ */ react.createElement(DataListCell, {
      style: {fontWeight: 700},
      key: name
    }, name))
  }))), sortedProtocolMappers.map((mapper) => /* @__PURE__ */ react.createElement(DataListItem, {
    "aria-label": mapper.name,
    key: mapper.id,
    id: mapper.id
  }, /* @__PURE__ */ react.createElement(DataListItemRow, null, /* @__PURE__ */ react.createElement(DataListItemCells, {
    dataListCells: [
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: `name-${mapper.id}`
      }, mapper.name),
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: `helpText-${mapper.id}`
      }, mapper.helpText)
    ]
  }))))), isBuiltIn && rows.length > 0 && /* @__PURE__ */ react.createElement(Table, {
    variant: TableVariant.compact,
    cells: header,
    onSelect: (_23, isSelected, rowIndex) => {
      if (rowIndex === -1) {
        setRows(rows.map((row) => ({
          ...row,
          selected: isSelected
        })));
      } else {
        rows[rowIndex].selected = isSelected;
        setRows([...rows]);
      }
    },
    canSelectAll: true,
    rows,
    "aria-label": t5("addPredefinedMappers")
  }, /* @__PURE__ */ react.createElement(TableHeader, null), /* @__PURE__ */ react.createElement(TableBody, null)), isBuiltIn && rows.length === 0 && /* @__PURE__ */ react.createElement(ListEmptyState, {
    message: t5("common:emptyMappers"),
    instructions: t5("client-scopes:emptyBuiltInMappersInstructions")
  }));
};

// build/client-scopes/details/MapperList.js
var MapperList = ({
  model,
  onAdd: onAdd2,
  onDelete,
  detailLink
}) => {
  const {t: t5} = useTranslation("client-scopes");
  const [mapperAction, setMapperAction] = useState(false);
  const mapperList = model.protocolMappers;
  const mapperTypes = useServerInfo().protocolMapperTypes[model.protocol];
  const [key, setKey] = useState(0);
  useEffect(() => setKey(key + 1), [mapperList]);
  const [addMapperDialogOpen, setAddMapperDialogOpen] = useState(false);
  const [filter3, setFilter] = useState(model.protocolMappers);
  const toggleAddMapperDialog = (buildIn) => {
    if (buildIn) {
      setFilter(mapperList || []);
    } else {
      setFilter(void 0);
    }
    setAddMapperDialogOpen(!addMapperDialogOpen);
  };
  const loader = async () => {
    if (!mapperList) {
      return [];
    }
    const list3 = mapperList.reduce((rows, mapper) => {
      const mapperType = mapperTypes.find(({id: id3}) => id3 === mapper.protocolMapper);
      if (!mapperType) {
        return rows;
      }
      return rows.concat({
        ...mapper,
        category: mapperType.category,
        type: mapperType.name,
        priority: mapperType.priority
      });
    }, []);
    return list3.sort((a2, b2) => a2.priority - b2.priority);
  };
  const MapperLink = ({id: id3, name}) => /* @__PURE__ */ react.createElement(Link, {
    to: detailLink(id3)
  }, name);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(AddMapperDialog, {
    protocol: model.protocol,
    filter: filter3,
    onConfirm: onAdd2,
    open: addMapperDialogOpen,
    toggleDialog: () => setAddMapperDialogOpen(!addMapperDialogOpen)
  }), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key,
    loader,
    ariaLabelKey: "client-scopes:clientScopeList",
    searchPlaceholderKey: "common:searchForMapper",
    toolbarItem: /* @__PURE__ */ react.createElement(Dropdown, {
      onSelect: () => setMapperAction(false),
      toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
        isPrimary: true,
        id: "mapperAction",
        onToggle: () => setMapperAction(!mapperAction),
        toggleIndicator: CaretDownIcon
      }, t5("common:addMapper")),
      isOpen: mapperAction,
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "predefined",
          onClick: () => toggleAddMapperDialog(true)
        }, t5("fromPredefinedMapper")),
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "byConfiguration",
          onClick: () => toggleAddMapperDialog(false)
        }, t5("byConfiguration"))
      ]
    }),
    actions: [
      {
        title: t5("common:delete"),
        onRowClick: onDelete
      }
    ],
    columns: [
      {
        name: "name",
        cellRenderer: MapperLink
      },
      {name: "category"},
      {
        name: "type"
      },
      {
        name: "priority"
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      message: t5("common:emptyMappers"),
      instructions: t5("common:emptyMappersInstructions"),
      secondaryActions: [
        {
          text: t5("common:emptyPrimaryAction"),
          onClick: () => toggleAddMapperDialog(true)
        },
        {
          text: t5("emptySecondaryAction"),
          onClick: () => toggleAddMapperDialog(false)
        }
      ]
    })
  }));
};

// build/components/client-scope/ClientScopeTypes.js
var ClientScope;
(function(ClientScope2) {
  ClientScope2["default"] = "default";
  ClientScope2["optional"] = "optional";
})(ClientScope || (ClientScope = {}));
var AllClientScopes;
(function(AllClientScopes2) {
  AllClientScopes2["none"] = "none";
})(AllClientScopes || (AllClientScopes = {}));
var clientScopeTypes = Object.keys(ClientScope);
var allClientScopeTypes = Object.keys({
  ...AllClientScopes,
  ...ClientScope
});
var clientScopeTypesSelectOptions = (t5, scopeTypes = clientScopeTypes) => scopeTypes.map((type) => /* @__PURE__ */ react.createElement(SelectOption, {
  key: type,
  value: type
}, t5(`common:clientScope.${type}`)));
var clientScopeTypesDropdown = (t5, onClick) => clientScopeTypes.map((type) => /* @__PURE__ */ react.createElement(DropdownItem, {
  key: type,
  onClick: () => onClick(type)
}, t5(`common:clientScope.${type}`)));
var CellDropdown = ({
  clientScope,
  type,
  onSelect,
  all: all2 = false
}) => {
  const {t: t5} = useTranslation();
  const [open2, setOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(Select, {
    className: `keycloak__client-scope__${type}`,
    key: clientScope.id,
    onToggle: () => setOpen(!open2),
    isOpen: open2,
    selections: [type],
    onSelect: (_23, value) => {
      onSelect(all2 ? value : value);
      setOpen(false);
    }
  }, clientScopeTypesSelectOptions(t5, all2 ? allClientScopeTypes : clientScopeTypes));
};
var changeScope = async (adminClient, clientScope, changeTo) => {
  await removeScope(adminClient, clientScope);
  await addScope(adminClient, clientScope, changeTo);
};
var castAdminClient = (adminClient) => adminClient.clientScopes;
var removeScope = async (adminClient, clientScope) => {
  if (clientScope.type !== AllClientScopes.none)
    await castAdminClient(adminClient)[`delDefault${clientScope.type === ClientScope.optional ? "Optional" : ""}ClientScope`]({
      id: clientScope.id
    });
};
var addScope = async (adminClient, clientScope, type) => {
  if (type !== AllClientScopes.none)
    await castAdminClient(adminClient)[`addDefault${type === ClientScope.optional ? "Optional" : ""}ClientScope`]({
      id: clientScope.id
    });
};
var changeClientScope = async (adminClient, clientId, clientScope, type, changeTo) => {
  if (type !== "none") {
    await removeClientScope(adminClient, clientId, clientScope, type);
  }
  await addClientScope(adminClient, clientId, clientScope, changeTo);
};
var removeClientScope = async (adminClient, clientId, clientScope, type) => {
  const methodName = `del${toUpperCase(type)}ClientScope`;
  await adminClient.clients[methodName]({
    id: clientId,
    clientScopeId: clientScope.id
  });
};
var addClientScope = async (adminClient, clientId, clientScope, type) => {
  const methodName = `add${toUpperCase(type)}ClientScope`;
  await adminClient.clients[methodName]({
    id: clientId,
    clientScopeId: clientScope.id
  });
};

// build/clients/utils.js
var isRealmClient = (client2) => !client2.protocol;
var getProtocolName = (t5, protocol) => {
  switch (protocol) {
    case "openid-connect":
      return t5("clients:protocolTypes:openIdConnect");
    case "saml":
      return t5("clients:protocolTypes:saml");
  }
  return protocol;
};

// build/client-scopes/ChangeTypeDropdown.js
var ChangeTypeDropdown = ({
  clientId,
  selectedRows,
  refresh
}) => {
  const {t: t5} = useTranslation("client-scopes");
  const [open2, setOpen] = useState(false);
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  return /* @__PURE__ */ react.createElement(Select, {
    id: "change-type-dropdown",
    isOpen: open2,
    selections: [],
    isDisabled: selectedRows.length === 0,
    placeholderText: t5("changeTypeTo"),
    onToggle: setOpen,
    onSelect: async (_23, value) => {
      try {
        await Promise.all(selectedRows.map((row) => {
          return clientId ? changeClientScope(adminClient, clientId, row, row.type, value) : changeScope(adminClient, row, value);
        }));
        setOpen(false);
        refresh();
        addAlert(t5("clientScopeSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("clients:clientScopeError", error2);
      }
    }
  }, clientScopeTypesSelectOptions(t5, !clientId ? allClientScopeTypes : void 0));
};

// build/client-scopes/routes/NewClientScope.js
var NewClientScopeRoute = {
  path: "/:realm/client-scopes/new",
  component: lazy(() => Promise.resolve().then(() => require_ClientScopeForm())),
  breadcrumb: (t5) => t5("client-scopes:createClientScope"),
  access: "manage-clients"
};
var toNewClientScope = (params) => ({
  pathname: generatePath(NewClientScopeRoute.path, params)
});

// build/client-scopes/details/SearchFilter.js
var PROTOCOLS = ["all", "saml", "openid-connect"];
var nameFilter = (search2 = "") => (scope) => scope.name?.includes(search2);
var typeFilter = (type) => (scope) => type === AllClientScopes.none || scope.type === type;
var protocolFilter = (protocol) => (scope) => protocol === "all" || scope.protocol === protocol;
var SearchDropdown = ({
  searchType,
  withProtocol = false,
  onSelect
}) => {
  const {t: t5} = useTranslation("clients");
  const [searchToggle, setSearchToggle] = useState(false);
  const createDropdown = (searchType2) => /* @__PURE__ */ react.createElement(DropdownItem, {
    key: searchType2,
    onClick: () => {
      onSelect(searchType2);
      setSearchToggle(false);
    }
  }, t5(`clientScopeSearch.${searchType2}`));
  const options = [createDropdown("name"), createDropdown("type")];
  if (withProtocol) {
    options.push(createDropdown("protocol"));
  }
  return /* @__PURE__ */ react.createElement(Dropdown, {
    className: "keycloak__client-scopes__searchtype",
    toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
      id: "toggle-id",
      onToggle: setSearchToggle
    }, /* @__PURE__ */ react.createElement(FilterIcon, null), " ", t5(`clientScopeSearch.${searchType}`)),
    isOpen: searchToggle,
    dropdownItems: options
  });
};
var SearchToolbar = ({
  searchType,
  onSelect,
  type,
  onType,
  protocol,
  onProtocol
}) => {
  const {t: t5} = useTranslation("client-scopes");
  const [open2, setOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, searchType === "type" && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(SearchDropdown, {
    searchType,
    onSelect,
    withProtocol: !!protocol
  })), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Select, {
    className: "keycloak__client-scopes__searchtype",
    onToggle: setOpen,
    isOpen: open2,
    selections: [
      type === AllClientScopes.none ? t5("common:allTypes") : t5(`common:clientScope.${type}`)
    ],
    onSelect: (_23, value) => {
      onType(value);
      setOpen(false);
    }
  }, /* @__PURE__ */ react.createElement(SelectOption, {
    value: AllClientScopes.none
  }, t5("common:allTypes")), /* @__PURE__ */ react.createElement(react.Fragment, null, clientScopeTypesSelectOptions(t5))))), searchType === "protocol" && !!protocol && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(SearchDropdown, {
    searchType,
    onSelect,
    withProtocol: true
  })), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Select, {
    className: "keycloak__client-scopes__searchtype",
    onToggle: setOpen,
    isOpen: open2,
    selections: [t5(`protocolTypes.${protocol}`)],
    onSelect: (_23, value) => {
      onProtocol?.(value);
      setOpen(false);
    }
  }, PROTOCOLS.map((type2) => /* @__PURE__ */ react.createElement(SelectOption, {
    key: type2,
    value: type2
  }, t5(`protocolTypes.${type2}`)))))));
};

// build/client-scopes/routes/ClientScopes.js
var ClientScopesRoute = {
  path: "/:realm/client-scopes",
  component: lazy(() => Promise.resolve().then(() => require_ClientScopesSection())),
  breadcrumb: (t5) => t5("client-scopes:clientScopeList"),
  access: "view-clients"
};
var toClientScopes = (params) => ({
  pathname: generatePath(ClientScopesRoute.path, params)
});

// build/client-scopes/details/ScopeForm.js
var ScopeForm = ({clientScope, save}) => {
  const {t: t5} = useTranslation("client-scopes");
  const {t: tc2} = useTranslation("clients");
  const {register: register2, control, handleSubmit, errors, setValue} = useForm({
    defaultValues: {attributes: {"display.on.consent.screen": "true"}}
  });
  const {realm: realm2} = useRealm();
  const providers = useLoginProviders();
  const [open2, isOpen] = useState(false);
  const [openType, setOpenType] = useState(false);
  const {id: id3} = useParams();
  const displayOnConsentScreen = useWatch({
    control,
    name: "attributes.display.on.consent.screen"
  });
  useEffect(() => {
    convertToFormValues(clientScope, setValue);
  }, [clientScope]);
  return /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true,
    onSubmit: handleSubmit(save),
    className: "pf-u-mt-md"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:name"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "client-scopes-help:name",
      fieldLabelId: "name"
    }),
    fieldId: "kc-name",
    isRequired: true,
    validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2({required: true}),
    type: "text",
    id: "kc-name",
    name: "name",
    validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:description"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "client-scopes-help:description",
      fieldLabelId: "description"
    }),
    fieldId: "kc-description",
    validated: errors.description ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:maxLength", {length: 255})
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2({
      maxLength: 255
    }),
    validated: errors.description ? ValidatedOptions.error : ValidatedOptions.default,
    type: "text",
    id: "kc-description",
    name: "description"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("type"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "client-scopes-help:type",
      fieldLabelId: "client-scopes:type"
    }),
    fieldId: "type"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "type",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      id: "type",
      variant: SelectVariant.single,
      isOpen: openType,
      selections: value,
      onToggle: setOpenType,
      onSelect: (_23, value2) => {
        onChange(value2);
        setOpenType(false);
      }
    }, clientScopeTypesSelectOptions(t5, allClientScopeTypes))
  })), !id3 && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("protocol"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "client-scopes-help:protocol",
      fieldLabelId: "client-scopes:protocol"
    }),
    fieldId: "kc-protocol"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "protocol",
    defaultValue: providers[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-protocol",
      required: true,
      onToggle: isOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        isOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("selectEncryptionType"),
      isOpen: open2
    }, providers.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      key: option,
      value: option,
      "data-testid": `option-${option}`
    }, getProtocolName(tc2, option))))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("displayOnConsentScreen"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "client-scopes-help:displayOnConsentScreen",
      fieldLabelId: "client-scopes:displayOnConsentScreen"
    }),
    fieldId: "kc-display.on.consent.screen"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.display.on.consent.screen",
    control,
    defaultValue: "true",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-display.on.consent.screen-switch",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value === "true",
      onChange: (value2) => onChange("" + value2)
    })
  })), displayOnConsentScreen === "true" && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("consentScreenText"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "client-scopes-help:consentScreenText",
      fieldLabelId: "client-scopes:consentScreenText"
    }),
    fieldId: "kc-consent-screen-text"
  }, /* @__PURE__ */ react.createElement(TextArea, {
    ref: register2,
    type: "text",
    id: "kc-consent-screen-text",
    name: "attributes.consent.screen.text"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("includeInTokenScope"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "client-scopes-help:includeInTokenScope",
      fieldLabelId: "client-scopes:includeInTokenScope"
    }),
    fieldId: "includeInTokenScope"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.include.in.token.scope",
    control,
    defaultValue: "true",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "includeInTokenScope-switch",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value === "true",
      onChange: (value2) => onChange("" + value2)
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("guiOrder"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "client-scopes-help:guiOrder",
      fieldLabelId: "client-scopes:guiOrder"
    }),
    fieldId: "kc-gui-order"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.gui.order",
    defaultValue: 1,
    control,
    render: ({onChange, value}) => {
      const MIN_VALUE = 0;
      const setValue2 = (newValue) => onChange(Math.max(newValue, MIN_VALUE));
      return /* @__PURE__ */ react.createElement(NumberInput, {
        id: "kc-gui-order",
        value,
        min: MIN_VALUE,
        onPlus: () => setValue2(value + 1),
        onMinus: () => setValue2(value - 1),
        onChange: (event) => {
          const newValue = Number(event.currentTarget.value);
          setValue2(!isNaN(newValue) ? newValue : 0);
        }
      });
    }
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    type: "submit"
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    component: (props) => /* @__PURE__ */ react.createElement(Link, {
      ...props,
      to: toClientScopes({realm: realm2})
    })
  }, t5("common:cancel"))));
};

// build/components/role-mapping/AddRoleMappingModal.js
var realmRole = {
  name: "realmRoles"
};
var AddRoleMappingModal = ({
  id: id3,
  name,
  type,
  isRadio: isRadio3 = false,
  isLDAPmapper,
  onAssign,
  onClose
}) => {
  const {t: t5} = useTranslation("clients");
  const adminClient = useAdminClient();
  const [clients2, setClients] = useState([]);
  const [searchToggle, setSearchToggle] = useState(false);
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const [selectedClients, setSelectedClients] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  useFetch(async () => {
    const clients22 = await adminClient.clients.find();
    return (await Promise.all(clients22.map(async (client2) => {
      let roles2 = [];
      switch (type) {
        case "group":
          roles2 = await adminClient.groups.listAvailableClientRoleMappings({
            id: id3,
            clientUniqueId: client2.id
          });
          break;
        case "service-account":
          roles2 = await adminClient.users.listAvailableClientRoleMappings({
            id: id3,
            clientUniqueId: client2.id
          });
          break;
        case "client-scope":
          roles2 = await adminClient.clientScopes.listAvailableClientScopeMappings({
            id: id3,
            client: client2.id
          });
          break;
        case "role":
          roles2 = await adminClient.clients.listRoles({id: client2.id});
          break;
      }
      return {
        roles: roles2,
        client: client2
      };
    }))).flat().filter((row) => row.roles.length !== 0).map((row) => ({...row.client, numberOfRoles: row.roles.length}));
  }, (clients22) => {
    setClients(clients22);
  }, []);
  useEffect(refresh, [searchToggle]);
  const removeClient = (client2) => {
    setSelectedClients(selectedClients.filter((item) => item.id !== client2.id));
  };
  const loader = async () => {
    const realmRolesSelected = lodash.findIndex(selectedClients, (client2) => client2.name === "realmRoles");
    let selected = selectedClients;
    if (realmRolesSelected !== -1) {
      selected = selectedClients.filter((client2) => client2.name !== "realmRoles");
    }
    let availableRoles = [];
    switch (type) {
      case "group":
        availableRoles = await adminClient.groups.listAvailableRealmRoleMappings({
          id: id3
        });
        break;
      case "service-account":
        availableRoles = await adminClient.users.listAvailableRealmRoleMappings({
          id: id3
        });
        break;
      case "client-scope":
        availableRoles = await adminClient.clientScopes.listAvailableRealmScopeMappings({
          id: id3
        });
        break;
      case "role":
        availableRoles = await adminClient.roles.find();
        break;
    }
    const realmRoles = availableRoles.map((role) => {
      return {
        id: role.id,
        role,
        client: void 0
      };
    });
    const allClients = selectedClients.length !== 0 ? selected : await adminClient.clients.find();
    const roles2 = (await Promise.all(allClients.map(async (client2) => {
      let clientAvailableRoles = [];
      switch (type) {
        case "group":
          clientAvailableRoles = await adminClient.groups.listAvailableClientRoleMappings({
            id: id3,
            clientUniqueId: client2.id
          });
          break;
        case "service-account":
          clientAvailableRoles = await adminClient.users.listAvailableClientRoleMappings({
            id: id3,
            clientUniqueId: client2.id
          });
          break;
        case "client-scope":
          clientAvailableRoles = await adminClient.clientScopes.listAvailableClientScopeMappings({id: id3, client: client2.id});
          break;
        case "role":
          clientAvailableRoles = await adminClient.clients.listRoles({
            id: client2.id
          });
          break;
      }
      return clientAvailableRoles.map((role) => {
        return {
          id: role.id,
          role,
          client: client2
        };
      });
    }))).flat();
    return [
      ...realmRolesSelected !== -1 || selected.length === 0 ? realmRoles : [],
      ...roles2
    ];
  };
  const createSelectGroup = (clients22) => [
    /* @__PURE__ */ react.createElement(SelectGroup, {
      key: "role",
      label: t5("realmRoles")
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      key: "realmRoles",
      value: realmRole
    }, t5("realmRoles"))),
    /* @__PURE__ */ react.createElement(Divider, {
      key: "divider"
    }),
    /* @__PURE__ */ react.createElement(SelectGroup, {
      key: "group",
      label: t5("clients")
    }, clients22.map((client2) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: client2.id,
      value: client2
    }, client2.clientId)))
  ];
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.large,
    title: isLDAPmapper ? t5("assignRole") : t5("assignRolesTo", {client: name}),
    isOpen: true,
    onClose,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "assign",
        key: "confirm",
        isDisabled: selectedRows.length === 0,
        variant: "primary",
        onClick: () => {
          onAssign(selectedRows);
          onClose();
        }
      }, t5("assign")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "cancel",
        key: "cancel",
        variant: "link",
        onClick: onClose
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key,
    onSelect: (rows) => setSelectedRows([...rows]),
    searchPlaceholderKey: "clients:searchByRoleName",
    searchTypeComponent: /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Select, {
      toggleId: "role",
      onToggle: () => setSearchToggle(!searchToggle),
      isOpen: searchToggle,
      variant: isRadio3 ? SelectVariant.single : SelectVariant.checkbox,
      hasInlineFilter: true,
      placeholderText: /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FilterIcon, null), " ", t5("filterByOrigin")),
      isGrouped: true,
      onFilter: (evt) => {
        const value = evt?.target.value || "";
        return createSelectGroup(clients2.filter((client2) => client2.clientId?.includes(value)));
      },
      selections: selectedClients,
      onClear: () => setSelectedClients([]),
      onSelect: (_23, selection2) => {
        const client2 = selection2;
        if (selectedClients.includes(client2)) {
          removeClient(client2);
        } else {
          setSelectedClients([...selectedClients, client2]);
        }
      }
    }, createSelectGroup(clients2))),
    subToolbar: /* @__PURE__ */ react.createElement(ToolbarItem, {
      widths: {default: "100%"}
    }, /* @__PURE__ */ react.createElement(ChipGroup, null, selectedClients.map((client2) => /* @__PURE__ */ react.createElement(Chip, {
      key: `chip-${client2.id}`,
      onClick: () => {
        removeClient(client2);
        refresh();
      }
    }, client2.clientId || t5("realmRoles"), /* @__PURE__ */ react.createElement(Badge, {
      isRead: true
    }, client2.numberOfRoles))))),
    canSelectAll: true,
    isRadio: isRadio3,
    loader,
    ariaLabelKey: "clients:roles",
    columns: [
      {
        name: "name",
        cellRenderer: ServiceRole
      },
      {
        name: "role.description",
        displayKey: t5("description")
      }
    ]
  }));
};

// build/components/role-mapping/RoleMapping.js
var mapRoles = (assignedRoles, effectiveRoles, hide3) => {
  return [
    ...hide3 ? assignedRoles.map((row) => ({
      ...row,
      role: {
        ...row.role,
        isInherited: false
      }
    })) : effectiveRoles.map((row) => ({
      ...row,
      role: {
        ...row.role,
        isInherited: assignedRoles.find((r3) => r3.role.id === row.role.id) === void 0
      }
    }))
  ];
};
var ServiceRole = ({role, client: client2}) => /* @__PURE__ */ react.createElement(react.Fragment, null, client2 && /* @__PURE__ */ react.createElement(Badge, {
  key: `${client2.id}-${role.id}`,
  isRead: true,
  className: "keycloak-admin--role-mapping__client-name"
}, client2.clientId), role.name);
var RoleMapping = ({
  name,
  id: id3,
  type,
  loader,
  save,
  onHideRolesToggle
}) => {
  const {t: t5} = useTranslation("clients");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const [hide3, setHide] = useState(false);
  const [showAssign, setShowAssign] = useState(false);
  const [selected, setSelected] = useState([]);
  const assignRoles = async (rows) => {
    await save(rows);
    refresh();
  };
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: "clients:removeMappingTitle",
    messageKey: t5("removeMappingConfirm", {count: selected.length}),
    continueButtonLabel: "common:remove",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        switch (type) {
          case "group":
            await Promise.all(selected.map((row) => {
              const role = {id: row.role.id, name: row.role.name};
              if (row.client) {
                return adminClient.groups.delClientRoleMappings({
                  id: id3,
                  clientUniqueId: row.client.id,
                  roles: [role]
                });
              } else {
                return adminClient.groups.delRealmRoleMappings({
                  id: id3,
                  roles: [role]
                });
              }
            }));
            break;
          case "service-account":
            await Promise.all(selected.map((row) => {
              const role = {id: row.role.id, name: row.role.name};
              if (row.client) {
                return adminClient.users.delClientRoleMappings({
                  id: id3,
                  clientUniqueId: row.client.id,
                  roles: [role]
                });
              } else {
                return adminClient.users.delRealmRoleMappings({
                  id: id3,
                  roles: [role]
                });
              }
            }));
            break;
          case "client-scope":
            await Promise.all(selected.map((row) => {
              const role = {id: row.role.id, name: row.role.name};
              if (row.client) {
                return adminClient.clientScopes.delClientScopeMappings({
                  id: id3,
                  client: row.client.id
                }, [role]);
              } else {
                return adminClient.clientScopes.delRealmScopeMappings({
                  id: id3
                }, [role]);
              }
            }));
            break;
        }
        addAlert(t5("clientScopeRemoveSuccess"), AlertVariant.success);
        refresh();
      } catch (error2) {
        addError("clients:clientScopeRemoveError", error2);
      }
    }
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, showAssign && /* @__PURE__ */ react.createElement(AddRoleMappingModal, {
    id: id3,
    type,
    name,
    onAssign: assignRoles,
    onClose: () => setShowAssign(false)
  }), /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    "data-testid": "assigned-roles",
    key,
    loader,
    canSelectAll: true,
    onSelect: (rows) => setSelected(rows),
    searchPlaceholderKey: "clients:searchByName",
    ariaLabelKey: "clients:clientScopeList",
    isRowDisabled: (value) => value.role.isInherited || false,
    toolbarItem: /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Checkbox, {
      label: t5("hideInheritedRoles"),
      id: "hideInheritedRoles",
      isChecked: hide3,
      onChange: (check2) => {
        setHide(check2);
        onHideRolesToggle();
        refresh();
      }
    })), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "assignRole",
      onClick: () => setShowAssign(true)
    }, t5("assignRole"))), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      "data-testid": "unAssignRole",
      onClick: toggleDeleteDialog,
      isDisabled: selected.length === 0
    }, t5("unAssignRole")))),
    actions: [
      {
        title: t5("unAssignRole"),
        onRowClick: async (role) => {
          setSelected([role]);
          toggleDeleteDialog();
          return false;
        }
      }
    ],
    columns: [
      {
        name: "role.name",
        displayKey: t5("name"),
        cellRenderer: ServiceRole
      },
      {
        name: "role.parent.name",
        displayKey: t5("inherentFrom"),
        cellFormatters: [emptyFormatter()]
      },
      {
        name: "role.description",
        displayKey: t5("description"),
        cellFormatters: [emptyFormatter()]
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      message: t5("noRoles"),
      instructions: t5("noRolesInstructions"),
      primaryActionText: t5("assignRole"),
      onPrimaryAction: () => setShowAssign(true)
    })
  }));
};

// build/components/dynamic/StringComponent.js
var StringComponent = ({
  name,
  label: label2,
  helpText,
  defaultValue
}) => {
  const {t: t5} = useTranslation("dynamic");
  const {register: register2} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5(helpText),
      fieldLabelId: `dynamic:${label2}`
    }),
    fieldId: name
  }, /* @__PURE__ */ react.createElement(TextInput, {
    id: name,
    "data-testid": name,
    ref: register2(),
    type: "text",
    name: `config.${name}`,
    defaultValue: defaultValue?.toString()
  }));
};

// build/components/dynamic/BooleanComponent.js
var BooleanComponent = ({
  name,
  label: label2,
  helpText,
  defaultValue
}) => {
  const {t: t5} = useTranslation("dynamic");
  const {control} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5(label2),
    fieldId: name,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5(helpText),
      fieldLabelId: `dynamic:${label2}`
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: `config.${name}`,
    "data-testid": name,
    defaultValue: defaultValue || false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: name,
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value === "true" || value === true,
      onChange: (value2) => onChange("" + value2),
      "data-testid": name
    })
  }));
};

// build/components/dynamic/ListComponent.js
var ListComponent2 = ({
  name,
  label: label2,
  helpText,
  defaultValue,
  options
}) => {
  const {t: t5} = useTranslation("dynamic");
  const {control} = useFormContext();
  const [open2, setOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5(helpText),
      fieldLabelId: `dynamic:${label2}`
    }),
    fieldId: name
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: `config.${name}`,
    "data-testid": name,
    defaultValue: defaultValue || "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: name,
      onToggle: (toggle) => setOpen(toggle),
      onSelect: (_23, value2) => {
        onChange(value2);
        setOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5(label2),
      isOpen: open2
    }, options?.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      key: option,
      value: option
    })))
  }));
};

// build/components/dynamic/RoleComponent.js
var RealmClient = (realm2) => ({
  name: "realmRoles",
  clientId: realm2
});
var RoleComponent = ({name, label: label2, helpText}) => {
  const {t: t5} = useTranslation("dynamic");
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const {control, errors, getValues} = useFormContext();
  const [roleOpen, setRoleOpen] = useState(false);
  const [clientsOpen, setClientsOpen] = useState(false);
  const [clients2, setClients] = useState();
  const [selectedClient, setSelectedClient] = useState();
  const [clientRoles, setClientRoles] = useState([]);
  const [selectedRole, setSelectedRole] = useState();
  const fieldName = `config.${name}`;
  useFetch(async () => {
    const clients22 = await adminClient.clients.find();
    const asyncFilter = async (predicate) => {
      const results = await Promise.all(clients22.map(predicate));
      return clients22.filter((_23, index3) => results[index3]);
    };
    const filteredClients = await asyncFilter(async (client2) => (await adminClient.clients.listRoles({id: client2.id})).length > 0);
    return filteredClients;
  }, (filteredClients) => setClients(filteredClients), []);
  useEffect(() => {
    const value = getValues(fieldName);
    const [client2, role] = value?.includes(".") ? value.split(".") : ["", value || ""];
    if (client2) {
      setSelectedClient(clients2?.find((c3) => c3.clientId === client2));
    } else {
      setSelectedClient(RealmClient(realm2));
    }
    setSelectedRole({name: role});
  }, [clients2, getValues]);
  const createSelectGroup = (clients22) => {
    return [
      /* @__PURE__ */ react.createElement(SelectGroup, {
        key: "role",
        label: t5("roleGroup")
      }, /* @__PURE__ */ react.createElement(SelectOption, {
        key: "realmRoles",
        value: RealmClient(realm2)
      }, realm2)),
      /* @__PURE__ */ react.createElement(Divider, {
        key: "divider"
      }),
      /* @__PURE__ */ react.createElement(SelectGroup, {
        key: "group",
        label: t5("clientGroup")
      }, clients22.map((client2) => /* @__PURE__ */ react.createElement(SelectOption, {
        key: client2.id,
        value: client2
      }, client2.clientId)))
    ];
  };
  const roleSelectOptions = () => {
    const createItem = (role) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: role.id,
      value: role
    }, role.name);
    return clientRoles.map((role) => createItem(role));
  };
  useFetch(async () => {
    if (selectedClient && selectedClient.name !== "realmRoles") {
      const clientRoles2 = await adminClient.clients.listRoles({
        id: selectedClient.id
      });
      return clientRoles2;
    } else {
      return await adminClient.roles.find();
    }
  }, (clientRoles2) => setClientRoles(clientRoles2), [selectedClient]);
  const onClear = (onChange) => {
    setSelectedClient(void 0);
    setSelectedRole(void 0);
    onChange("");
  };
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5(helpText),
      fieldLabelId: `dynamic:${label2}`
    }),
    validated: errors[fieldName] ? "error" : "default",
    helperTextInvalid: t5("common:required"),
    fieldId: name
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: fieldName,
    defaultValue: "",
    control,
    render: ({onChange}) => /* @__PURE__ */ react.createElement(Split, {
      hasGutter: true
    }, /* @__PURE__ */ react.createElement(SplitItem, null, clients2 && /* @__PURE__ */ react.createElement(Select, {
      toggleId: `group-${name}`,
      onToggle: () => setClientsOpen(!clientsOpen),
      isOpen: clientsOpen,
      variant: SelectVariant.typeahead,
      typeAheadAriaLabel: t5("selectASourceOfRoles"),
      placeholderText: t5("selectASourceOfRoles"),
      isGrouped: true,
      onFilter: (evt) => {
        const textInput = evt?.target.value || "";
        if (textInput === "") {
          return createSelectGroup(clients2);
        } else {
          return createSelectGroup(clients2.filter((client2) => client2.name.toLowerCase().includes(textInput.toLowerCase())));
        }
      },
      selections: selectedClient?.clientId,
      onClear: () => onClear(onChange),
      onSelect: (_23, value) => {
        onClear(onChange);
        setSelectedClient(value);
        setClientsOpen(false);
      }
    }, createSelectGroup(clients2))), /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(Select, {
      toggleId: `role-${name}`,
      onToggle: (isExpanded) => setRoleOpen(isExpanded),
      isOpen: roleOpen,
      variant: SelectVariant.typeahead,
      placeholderText: selectedClient?.name !== "realmRoles" ? t5("clientRoles") : t5("selectARole"),
      isDisabled: !selectedClient,
      typeAheadAriaLabel: t5("selectARole"),
      selections: selectedRole?.name,
      onSelect: (_23, value) => {
        const role = value;
        setSelectedRole(role);
        onChange(selectedClient?.name === "realmRoles" ? role.name : `${selectedClient?.clientId}.${role.name}`);
        setRoleOpen(false);
      },
      maxHeight: 200,
      onClear: () => onClear(onChange)
    }, roleSelectOptions())))
  }));
};

// build/components/attribute-input/AttributeInput.js
var AttributeInput = ({name}) => {
  const {t: t5} = useTranslation("common");
  const {control, register: register2, watch} = useFormContext();
  const {fields, append: append2, remove: remove3} = useFieldArray({
    control,
    name
  });
  useEffect(() => {
    if (!fields.length) {
      append2({key: "", value: ""});
    }
  }, []);
  const watchLast = watch(`${name}[${fields.length - 1}].key`, "");
  return /* @__PURE__ */ react.createElement(TableComposable, {
    className: "kc-attributes__table",
    "aria-label": "Role attribute keys and values",
    variant: "compact",
    borders: false
  }, /* @__PURE__ */ react.createElement(Thead, null, /* @__PURE__ */ react.createElement(Tr, null, /* @__PURE__ */ react.createElement(Th2, {
    id: "key",
    width: 40
  }, t5("key")), /* @__PURE__ */ react.createElement(Th2, {
    id: "value",
    width: 40
  }, t5("value")))), /* @__PURE__ */ react.createElement(Tbody, null, fields.map((attribute, rowIndex) => /* @__PURE__ */ react.createElement(Tr, {
    key: attribute.id,
    "data-testid": "attribute-row"
  }, /* @__PURE__ */ react.createElement(Td2, null, /* @__PURE__ */ react.createElement(TextInput, {
    id: `${attribute.id}-key`,
    name: `${name}[${rowIndex}].key`,
    ref: register2(),
    defaultValue: attribute.key,
    "data-testid": "attribute-key-input"
  })), /* @__PURE__ */ react.createElement(Td2, null, /* @__PURE__ */ react.createElement(TextInput, {
    id: `${attribute.id}-value`,
    name: `${name}[${rowIndex}].value`,
    ref: register2(),
    defaultValue: attribute.value,
    "data-testid": "attribute-value-input"
  })), /* @__PURE__ */ react.createElement(Td2, {
    key: "minus-button",
    id: `kc-minus-button-${rowIndex}`
  }, /* @__PURE__ */ react.createElement(Button, {
    id: `minus-button-${rowIndex}`,
    variant: "link",
    className: "kc-attributes__minus-icon",
    onClick: () => remove3(rowIndex)
  }, /* @__PURE__ */ react.createElement(MinusCircleIcon, null))))), /* @__PURE__ */ react.createElement(Tr, null, /* @__PURE__ */ react.createElement(Td2, null, /* @__PURE__ */ react.createElement(Button, {
    "aria-label": t5("roles:addAttributeText"),
    id: "plus-icon",
    variant: "link",
    className: "kc-attributes__plus-icon",
    onClick: () => append2({key: "", value: ""}),
    icon: /* @__PURE__ */ react.createElement(PlusCircleIcon, null),
    isDisabled: !watchLast,
    "data-testid": "attribute-add-row"
  }, t5("roles:addAttributeText"))))));
};

// build/components/dynamic/MapComponent.js
var MapComponent = ({name, label: label2, helpText}) => {
  const {t: t5} = useTranslation("dynamic");
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5(helpText),
      fieldLabelId: `dynamic:${label2}`
    }),
    fieldId: name
  }, /* @__PURE__ */ react.createElement(AttributeInput, {
    name: `config.${name}`
  }));
};

// build/components/dynamic/ScriptComponent.js
var ScriptComponent = ({
  name,
  label: label2,
  helpText,
  defaultValue
}) => {
  const {t: t5} = useTranslation("dynamic");
  const {control} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: /* @__PURE__ */ react.createElement("span", {
        style: {whiteSpace: "pre-wrap"}
      }, helpText),
      fieldLabelId: `dynamic:${label2}`
    }),
    fieldId: name
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: `config.${name}`,
    defaultValue,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(CodeEditor, {
      id: name,
      "data-testid": name,
      type: "text",
      onChange,
      code: value,
      height: "600px",
      language: Language.javascript
    })
  }));
};

// build/components/dynamic/ClientSelectComponent.js
var ClientSelectComponent = ({
  name,
  label: label2,
  helpText,
  defaultValue
}) => {
  const {t: t5} = useTranslation("dynamic");
  const {control} = useFormContext();
  const [open2, setOpen] = useState(false);
  const [clients2, setClients] = useState();
  const [search2, setSearch] = useState("");
  const adminClient = useAdminClient();
  useFetch(() => {
    const params = {
      max: 20
    };
    if (search2) {
      params.clientId = search2;
      params.search = true;
    }
    return adminClient.clients.find(params);
  }, (clients22) => setClients(clients22.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
    key: option.id,
    value: option.clientId
  }))), [search2]);
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5(helpText),
      fieldLabelId: `dynamic:${label2}`
    }),
    fieldId: name
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: `config.${name}`,
    defaultValue: defaultValue || "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: name,
      variant: SelectVariant.typeahead,
      onToggle: (open22) => setOpen(open22),
      isOpen: open2,
      selections: value,
      onFilter: (_23, value2) => {
        setSearch(value2);
        return clients2;
      },
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setOpen(false);
      },
      "aria-label": t5(label2)
    }, clients2)
  }));
};

// build/components/multi-line-input/MultiLineInput.js
var MultiLineInput = ({
  name,
  addButtonLabel,
  ...rest
}) => {
  const {t: t5} = useTranslation();
  const {register: register2, control, reset: reset2} = useFormContext();
  const {fields, append: append2, remove: remove3} = useFieldArray({
    name,
    control
  });
  const currentValues = useWatch({control, name});
  useEffect(() => {
    reset2({
      [name]: [{value: ""}]
    });
  }, []);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, fields.map(({id: id3, value}, index3) => /* @__PURE__ */ react.createElement(Fragment, {
    key: id3
  }, /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(TextInput, {
    id: id3,
    ref: register2(),
    name: `${name}[${index3}].value`,
    defaultValue: value,
    ...rest
  }), /* @__PURE__ */ react.createElement(Button, {
    variant: ButtonVariant.link,
    onClick: () => remove3(index3),
    tabIndex: -1,
    "aria-label": t5("common:remove"),
    isDisabled: index3 === fields.length - 1
  }, /* @__PURE__ */ react.createElement(MinusCircleIcon, null))), index3 === fields.length - 1 && /* @__PURE__ */ react.createElement(Button, {
    variant: ButtonVariant.link,
    onClick: () => append2({}),
    tabIndex: -1,
    "aria-label": t5("common:add"),
    "data-testid": "addValue",
    isDisabled: rest.isDisabled || !currentValues?.[index3]?.value
  }, /* @__PURE__ */ react.createElement(PlusCircleIcon, null), " ", t5(addButtonLabel || "common:add")))));
};

// build/components/dynamic/MultivaluedStringComponent.js
var MultiValuedStringComponent = ({
  name,
  label: label2,
  helpText
}) => {
  const {t: t5} = useTranslation("dynamic");
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5(helpText),
      fieldLabelId: `dynamic:${label2}`
    }),
    fieldId: name
  }, /* @__PURE__ */ react.createElement(MultiLineInput, {
    name: `config.${name}`,
    "aria-label": name,
    addButtonLabel: t5("addMultivaluedLabel", {
      fieldLabel: t5(label2).toLowerCase()
    })
  }));
};

// build/components/dynamic/MultivaluedListComponent.js
var MultiValuedListComponent = ({
  name,
  label: label2,
  helpText,
  defaultValue,
  options
}) => {
  const {t: t5} = useTranslation("dynamic");
  const {control} = useFormContext();
  const [open2, setOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5(helpText),
      fieldLabelId: `dynamic:${label2}`
    }),
    fieldId: name
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: `config.${name}`,
    control,
    defaultValue: defaultValue ? [defaultValue] : [],
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: name,
      "data-testid": name,
      chipGroupProps: {
        numChips: 3,
        expandedText: t5("common:hide"),
        collapsedText: t5("common:showRemaining")
      },
      variant: SelectVariant.typeaheadMulti,
      typeAheadAriaLabel: "Select",
      onToggle: (isOpen) => setOpen(isOpen),
      selections: value,
      onSelect: (_23, v2) => {
        const option = v2.toString();
        if (value.includes(option)) {
          onChange(value.filter((item) => item !== option));
        } else {
          onChange([...value, option]);
        }
      },
      onClear: (event) => {
        event.stopPropagation();
        onChange([]);
      },
      isOpen: open2,
      "aria-label": t5(label2)
    }, options?.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: option,
      value: option
    })))
  }));
};

// build/components/group/GroupPath.js
var MAX_LENGTH = 20;
var PART = 10;
var truncatePath = (path) => {
  if (path && path.length >= MAX_LENGTH) {
    return path.substr(0, PART) + "..." + path.substr(path.length - PART, path.length);
  }
  return path;
};
var GroupPath = ({
  group: {path},
  onMouseEnter: onMouseEnterProp,
  ...props
}) => {
  const [tooltip2, setTooltip] = react.useState("");
  const onMouseEnter = (event) => {
    setTooltip(path);
    onMouseEnterProp?.(event);
  };
  const text = /* @__PURE__ */ react.createElement("span", {
    onMouseEnter,
    ...props
  }, truncatePath(path));
  return tooltip2 !== "" ? /* @__PURE__ */ react.createElement(Tooltip, {
    content: tooltip2,
    isVisible: true
  }, text) : text;
};

// build/components/group/GroupPickerDialog.js
var GroupPickerDialog = ({
  id: id3,
  type,
  filterGroups,
  text,
  onClose,
  onConfirm
}) => {
  const {t: t5} = useTranslation();
  const adminClient = useAdminClient();
  const [selectedRows, setSelectedRows] = useState([]);
  const [navigation, setNavigation] = useState([]);
  const [groups2, setGroups] = useState([]);
  const [filter3, setFilter] = useState("");
  const [joinedGroups, setJoinedGroups] = useState([]);
  const [groupId, setGroupId] = useState();
  const [max2, setMax] = useState(10);
  const [first2, setFirst] = useState(0);
  const currentGroup = () => navigation[navigation.length - 1];
  useFetch(async () => {
    let group;
    let groups22;
    let existingUserGroups;
    if (!groupId) {
      groups22 = await adminClient.groups.find({
        first: first2,
        max: max2 + 1,
        search: filter3
      });
    } else {
      group = await adminClient.groups.findOne({id: groupId});
      if (!group) {
        throw new Error(t5("common:notFound"));
      }
      groups22 = group.subGroups;
    }
    if (id3) {
      existingUserGroups = await adminClient.users.listGroups({
        id: id3
      });
    }
    return {group, groups: groups22, existingUserGroups};
  }, async ({group: selectedGroup, groups: groups22, existingUserGroups}) => {
    setJoinedGroups(existingUserGroups || []);
    if (selectedGroup) {
      setNavigation([...navigation, selectedGroup]);
    }
    groups22.forEach((group) => {
      group.checked = !!selectedRows.find((r3) => r3.id === group.id);
    });
    setGroups(groups22);
  }, [groupId, filter3, first2, max2]);
  const isRowDisabled = (row) => {
    return [
      ...joinedGroups.map((item) => item.name),
      ...filterGroups || []
    ].some((group) => group === row?.name);
  };
  const hasSubgroups = (group) => {
    return group.subGroups.length !== 0;
  };
  const findSubGroup = (group, name) => {
    if (group.name?.includes(name)) {
      return group;
    }
    if (group.subGroups) {
      for (const g2 of group.subGroups) {
        const found = findSubGroup(g2, name);
        return found;
      }
    }
    return group;
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    title: t5(text.title, {
      group1: filterGroups?.[0],
      group2: currentGroup() ? currentGroup().name : t5("root")
    }),
    isOpen: true,
    onClose,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": `${text.ok}-button`,
        key: "confirm",
        variant: "primary",
        form: "group-form",
        onClick: () => {
          onConfirm(type === "selectMany" ? selectedRows : [currentGroup()]);
        },
        isDisabled: type === "selectMany" && selectedRows.length === 0
      }, t5(text.ok))
    ]
  }, /* @__PURE__ */ react.createElement(PaginatingTableToolbar, {
    count: groups2.length,
    first: first2,
    max: max2,
    onNextClick: setFirst,
    onPreviousClick: setFirst,
    onPerPageSelect: (first22, max22) => {
      setFirst(first22);
      setMax(max22);
    },
    inputGroupName: "common:search",
    inputGroupOnEnter: (search2) => {
      setFilter(search2);
      setFirst(0);
      setMax(10);
      setNavigation([]);
    },
    inputGroupPlaceholder: t5("users:searchForGroups")
  }, /* @__PURE__ */ react.createElement(Breadcrumb, null, navigation.length > 0 && /* @__PURE__ */ react.createElement(BreadcrumbItem, {
    key: "home"
  }, /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: () => {
      setGroupId(void 0);
      setNavigation([]);
    }
  }, t5("groups"))), navigation.map((group, i3) => /* @__PURE__ */ react.createElement(BreadcrumbItem, {
    key: i3
  }, navigation.length - 1 !== i3 && /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: () => {
      setGroupId(group.id);
      setNavigation([...navigation].slice(0, i3));
    }
  }, group.name), navigation.length - 1 === i3 && group.name))), /* @__PURE__ */ react.createElement(DataList, {
    "aria-label": t5("groups"),
    isCompact: true
  }, groups2.slice(0, max2).map((group) => /* @__PURE__ */ react.createElement(DataListItem, {
    className: `join-group-dialog-row-${isRowDisabled(group) ? "disabled" : ""}`,
    "aria-labelledby": group.name,
    key: group.id,
    id: group.id,
    onClick: (e2) => {
      const g2 = filter3 !== "" ? findSubGroup(group, filter3) : group;
      if (isRowDisabled(g2))
        return;
      if (type === "selectOne") {
        setGroupId(g2.id);
      } else if (hasSubgroups(group) && filter3 === "" && e2.target.type !== "checkbox") {
        setGroupId(group.id);
      }
    }
  }, /* @__PURE__ */ react.createElement(DataListItemRow, {
    className: `join-group-dialog-row-${isRowDisabled(group) ? "m-disabled" : ""}`,
    "data-testid": group.name
  }, type === "selectMany" && /* @__PURE__ */ react.createElement(DataListCheck, {
    className: "kc-join-group-modal-check",
    "data-testid": `${group.name}-check`,
    checked: group.checked,
    isDisabled: isRowDisabled(group),
    onChange: (checked) => {
      group.checked = checked;
      let newSelectedRows = [];
      if (!group.checked) {
        newSelectedRows = selectedRows.filter((r3) => r3.id !== group.id);
      } else if (group.checked) {
        newSelectedRows = [
          ...selectedRows,
          filter3 === "" ? group : findSubGroup(group, filter3)
        ];
      }
      setSelectedRows(newSelectedRows);
    },
    "aria-labelledby": "data-list-check"
  }), /* @__PURE__ */ react.createElement(DataListItemCells, {
    dataListCells: [
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: `name-${group.id}`
      }, filter3 === "" ? group.name : /* @__PURE__ */ react.createElement(GroupPath, {
        group: findSubGroup(group, filter3)
      }))
    ]
  }), /* @__PURE__ */ react.createElement(DataListAction, {
    "aria-labelledby": `select-${group.name}`,
    id: `select-${group.name}`,
    "aria-label": t5("groupName"),
    isPlainButtonAction: true
  }, (hasSubgroups(group) && filter3 === "" || type === "selectOne") && /* @__PURE__ */ react.createElement(Button, {
    isDisabled: true,
    variant: "link"
  }, /* @__PURE__ */ react.createElement(AngleRightIcon, null)))))), groups2.length === 0 && filter3 === "" && /* @__PURE__ */ react.createElement(ListEmptyState, {
    hasIcon: false,
    message: t5("groups:moveGroupEmpty"),
    instructions: t5("groups:moveGroupEmptyInstructions")
  }), groups2.length === 0 && filter3 !== "" && /* @__PURE__ */ react.createElement(ListEmptyState, {
    message: t5("common:noSearchResults"),
    instructions: t5("common:noSearchResultsInstructions")
  }))));
};

// build/components/dynamic/GroupComponent.js
var GroupComponent = ({name, label: label2, helpText}) => {
  const {t: t5} = useTranslation("dynamic");
  const [open2, setOpen] = useState(false);
  const {control} = useFormContext();
  return /* @__PURE__ */ react.createElement(Controller, {
    name: `config.${name}`,
    defaultValue: "",
    typeAheadAriaLabel: t5("selectGroup"),
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(react.Fragment, null, open2 && /* @__PURE__ */ react.createElement(GroupPickerDialog, {
      type: "selectOne",
      text: {
        title: "dynamic:selectGroup",
        ok: "common:select"
      },
      onConfirm: (groups2) => {
        onChange(groups2[0].path);
        setOpen(false);
      },
      onClose: () => setOpen(false),
      filterGroups: value
    }), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5(label2),
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: t5(helpText),
        fieldLabelId: `dynamic:${label2}`
      }),
      fieldId: name
    }, /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(ChipGroup, null, value && /* @__PURE__ */ react.createElement(Chip, {
      onClick: () => onChange(void 0)
    }, value)), /* @__PURE__ */ react.createElement(Button, {
      id: "kc-join-groups-button",
      onClick: () => setOpen(!open2),
      variant: "secondary",
      "data-testid": "join-groups-button"
    }, t5("selectGroup")))))
  });
};

// build/components/dynamic/components.js
var COMPONENTS = {
  String: StringComponent,
  boolean: BooleanComponent,
  List: ListComponent2,
  Role: RoleComponent,
  Script: ScriptComponent,
  Map: MapComponent,
  Group: GroupComponent,
  ClientList: ClientSelectComponent,
  MultivaluedList: MultiValuedListComponent,
  MultivaluedString: MultiValuedStringComponent
};
var isValidComponentType = (value) => value in COMPONENTS;

// build/components/dynamic/DynamicComponents.js
var DynamicComponents = ({properties}) => /* @__PURE__ */ react.createElement(react.Fragment, null, properties.map((property2) => {
  const componentType = property2.type;
  if (isValidComponentType(componentType) && property2.name !== "scopes") {
    const Component = COMPONENTS[componentType];
    return /* @__PURE__ */ react.createElement(Component, {
      key: property2.name,
      ...property2
    });
  } else {
    console.warn(`There is no editor registered for ${componentType}`);
  }
}));

// build/client-scopes/routes/Mapper.js
var MapperRoute = {
  path: "/:realm/client-scopes/:id/:type/mappers/:mapperId",
  component: lazy(() => Promise.resolve().then(() => require_MappingDetails())),
  breadcrumb: (t5) => t5("common:mappingDetails"),
  access: "view-clients"
};
var toMapper = (params) => ({
  pathname: generatePath(MapperRoute.path, params)
});

// build/client-scopes/routes/ClientScope.js
var ClientScopeRoute = {
  path: "/:realm/client-scopes/:id/:type/:tab",
  component: lazy(() => Promise.resolve().then(() => require_ClientScopeForm())),
  breadcrumb: (t5) => t5("client-scopes:clientScopeDetails"),
  access: "view-clients"
};
var toClientScope = (params) => ({
  pathname: generatePath(ClientScopeRoute.path, params)
});

// build/client-scopes/routes.js
var routes2 = [
  NewClientScopeRoute,
  MapperRoute,
  ClientScopeRoute,
  ClientScopesRoute
];
var routes_default2 = routes2;

// build/components/download-dialog/DownloadDialog.js
var DownloadDialog = ({
  id: id3,
  open: open2,
  toggleDialog,
  protocol = "openid-connect"
}) => {
  const adminClient = useAdminClient();
  const {t: t5} = useTranslation("common");
  const {enabled} = useHelp();
  const serverInfo2 = useServerInfo();
  const configFormats = serverInfo2.clientInstallations[protocol];
  const [selected, setSelected] = useState(configFormats[configFormats.length - 1].id);
  const [snippet, setSnippet] = useState("");
  const [openType, setOpenType] = useState(false);
  const selectedConfig = useMemo(() => configFormats.find((config2) => config2.id === selected) ?? null, [selected]);
  const sanitizeSnippet = (snippet2) => snippet2.replace(/(?<=<PrivateKeyPem>).*(?=<\/PrivateKeyPem>)/gs, t5("clients:privateKeyMask"));
  useFetch(async () => {
    const snippet2 = await adminClient.clients.getInstallationProviders({
      id: id3,
      providerId: selected
    });
    if (typeof snippet2 === "string") {
      return sanitizeSnippet(snippet2);
    } else {
      return prettyPrintJSON(snippet2);
    }
  }, (snippet2) => setSnippet(snippet2), [id3, selected]);
  useEffect(() => setSnippet(""), [id3, selected]);
  return /* @__PURE__ */ react.createElement(ConfirmDialogModal, {
    titleKey: t5("clients:downloadAdaptorTitle"),
    continueButtonLabel: t5("download"),
    onConfirm: () => {
      const config2 = configFormats.find((config22) => config22.id === selected);
      file_saver_default.saveAs(new Blob([snippet], {type: config2.mediaType}), config2.filename);
    },
    open: open2,
    toggleDialog,
    variant: ModalVariant.medium
  }, /* @__PURE__ */ react.createElement(Form, null, /* @__PURE__ */ react.createElement(Stack, {
    hasGutter: true
  }, enabled && /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(Alert, {
    id: id3,
    title: t5("clients:description"),
    variant: AlertVariant.info,
    isInline: true
  }, configFormats.find((configFormat) => configFormat.id === selected)?.helpText)), /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(FormGroup, {
    fieldId: "type",
    label: t5("clients:formatOption"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5("clients-help:downloadType"),
      fieldLabelId: "clients:formatOption"
    })
  }, /* @__PURE__ */ react.createElement(Select, {
    toggleId: "type",
    isOpen: openType,
    onToggle: (isExpanded) => setOpenType(isExpanded),
    variant: SelectVariant.single,
    value: selected,
    selections: selected,
    onSelect: (_23, value) => {
      setSelected(value.toString());
      setOpenType(false);
    },
    "aria-label": "Select Input",
    menuAppendTo: () => document.body
  }, configFormats.map((configFormat) => /* @__PURE__ */ react.createElement(SelectOption, {
    key: configFormat.id,
    value: configFormat.id,
    isSelected: selected === configFormat.id
  }, configFormat.displayType))))), !selectedConfig?.downloadOnly && /* @__PURE__ */ react.createElement(StackItem, {
    isFilled: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    fieldId: "details",
    label: t5("details"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5("clients-help:details"),
      fieldLabelId: "clients:details"
    })
  }, /* @__PURE__ */ react.createElement(TextArea, {
    id: "details",
    readOnly: true,
    rows: 12,
    resizeOrientation: "vertical",
    value: snippet,
    "aria-label": "text area example"
  }))))));
};

// build/components/attribute-form/AttributeForm.js
var AttributesForm = ({form: form2, reset: reset2, save}) => {
  const {t: t5} = useTranslation("roles");
  const noSaveCancelButtons = !save && !reset2;
  const {
    formState: {isDirty},
    handleSubmit
  } = form2;
  return /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    onSubmit: save ? handleSubmit(save) : void 0
  }, /* @__PURE__ */ react.createElement(FormProvider, {
    ...form2
  }, /* @__PURE__ */ react.createElement(AttributeInput, {
    name: "attributes"
  })), !noSaveCancelButtons && /* @__PURE__ */ react.createElement(ActionGroup, {
    className: "kc-attributes__action-group"
  }, /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "save-attributes",
    variant: "primary",
    type: "submit",
    isDisabled: !isDirty
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    onClick: reset2,
    variant: "link",
    isDisabled: !isDirty
  }, t5("common:revert"))));
};

// build/realm-roles/RealmRoleForm.js
var RealmRoleForm = ({
  form: {handleSubmit, errors, register: register2, getValues},
  save,
  editMode,
  reset: reset2
}) => {
  const {t: t5} = useTranslation("roles");
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    onSubmit: handleSubmit(save),
    role: "manage-realm",
    className: "pf-u-mt-lg"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("roleName"),
    fieldId: "kc-name",
    isRequired: true,
    validated: errors.name ? "error" : "default",
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2({required: !editMode}),
    type: "text",
    id: "kc-name",
    name: "name",
    isReadOnly: editMode
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:description"),
    fieldId: "kc-description",
    validated: errors.description ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: errors.description?.message
  }, /* @__PURE__ */ react.createElement(TextArea, {
    name: "description",
    "aria-label": "description",
    isDisabled: getValues().name?.includes("default-roles"),
    ref: register2({
      maxLength: {
        value: 255,
        message: t5("common:maxLength", {length: 255})
      }
    }),
    type: "text",
    validated: errors.description ? ValidatedOptions.error : ValidatedOptions.default,
    id: "kc-role-description"
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    onClick: save,
    "data-testid": "realm-roles-save-button"
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    onClick: () => reset2(),
    variant: "link"
  }, editMode ? t5("common:revert") : t5("common:cancel")))));
};

// build/realm-roles/AssociatedRolesModal.js
var AssociatedRolesModal = ({
  id: id3,
  toggleDialog,
  onConfirm,
  omitComposites
}) => {
  const {t: t5} = useTranslation("roles");
  const [name, setName] = useState("");
  const adminClient = useAdminClient();
  const [selectedRows, setSelectedRows] = useState([]);
  const [compositeRoles, setCompositeRoles] = useState();
  const [isFilterDropdownOpen, setIsFilterDropdownOpen] = useState(false);
  const [filterType, setFilterType] = useState("roles");
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const alphabetize = (rolesList) => {
    return sortBy(rolesList, (role) => role.name?.toUpperCase());
  };
  const loader = async (first2, max2, search2) => {
    const params = {
      first: first2,
      max: max2
    };
    const searchParam = search2 || "";
    if (searchParam) {
      params.search = searchParam;
    }
    return (await adminClient.roles.find(params)).filter((item) => item.name !== name);
  };
  const AliasRenderer = ({id: id22, name: name2, clientId}) => {
    return /* @__PURE__ */ react.createElement(react.Fragment, null, clientId && /* @__PURE__ */ react.createElement(Label, {
      color: "blue",
      key: `label-${id22}`
    }, clientId), " ", name2);
  };
  const clientRolesLoader = async () => {
    const clients2 = await adminClient.clients.find();
    const clientRoles = await Promise.all(clients2.map(async (client2) => {
      const roles2 = await adminClient.clients.listRoles({id: client2.id});
      return roles2.map((role) => ({
        ...role,
        clientId: client2.clientId
      })).filter((item) => item.name !== name);
    }));
    return alphabetize(clientRoles.flat());
  };
  useEffect(() => {
    refresh();
  }, [filterType]);
  useFetch(async () => {
    const [role, compositeRoles2] = await Promise.all([
      adminClient.roles.findOneById({id: id3}),
      !omitComposites ? adminClient.roles.getCompositeRoles({id: id3}) : []
    ]);
    return {role, compositeRoles: compositeRoles2};
  }, ({role, compositeRoles: compositeRoles2}) => {
    setName(role?.name);
    setCompositeRoles(compositeRoles2);
  }, []);
  const onFilterDropdownToggle = () => {
    setIsFilterDropdownOpen(!isFilterDropdownOpen);
  };
  const onFilterDropdownSelect = (filterType2) => {
    if (filterType2 === "roles") {
      setFilterType("clients");
    }
    if (filterType2 === "clients") {
      setFilterType("roles");
    }
    setIsFilterDropdownOpen(!isFilterDropdownOpen);
  };
  if (!compositeRoles) {
    return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
  }
  return /* @__PURE__ */ react.createElement(Modal, {
    "data-testid": "addAssociatedRole",
    title: name ? t5("roles:associatedRolesModalTitle", {name}) : t5("addRole"),
    isOpen: true,
    onClose: toggleDialog,
    variant: ModalVariant.large,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        key: "add",
        "data-testid": "add-associated-roles-button",
        variant: "primary",
        isDisabled: !selectedRows.length,
        onClick: () => {
          toggleDialog();
          onConfirm(selectedRows);
        }
      }, t5("common:add")),
      /* @__PURE__ */ react.createElement(Button, {
        key: "cancel",
        variant: "link",
        onClick: () => {
          toggleDialog();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key,
    loader: filterType === "roles" ? loader : clientRolesLoader,
    ariaLabelKey: "roles:roleList",
    searchPlaceholderKey: "roles:searchFor",
    isPaginated: filterType === "roles",
    isRowDisabled: (r3) => compositeRoles.some((o) => o.name === r3.name),
    searchTypeComponent: /* @__PURE__ */ react.createElement(Dropdown, {
      onSelect: () => onFilterDropdownSelect(filterType),
      "data-testid": "filter-type-dropdown",
      toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
        id: "toggle-id-9",
        onToggle: onFilterDropdownToggle,
        toggleIndicator: CaretDownIcon,
        icon: /* @__PURE__ */ react.createElement(FilterIcon, null)
      }, "Filter by ", filterType),
      isOpen: isFilterDropdownOpen,
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          "data-testid": "filter-type-dropdown-item",
          key: "filter-type"
        }, filterType === "roles" ? t5("filterByClients") : t5("filterByRoles"), " ")
      ]
    }),
    canSelectAll: true,
    onSelect: (rows) => {
      setSelectedRows(rows.map((r3) => omit(r3, "clientId")));
    },
    columns: [
      {
        name: "name",
        displayKey: "roles:roleName",
        cellRenderer: AliasRenderer
      },
      {
        name: "description",
        displayKey: "common:description"
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      hasIcon: true,
      message: t5("noRoles"),
      instructions: t5("noRolesInstructions"),
      primaryActionText: t5("createRole")
    })
  }));
};

// build/components/scroll-form/FormPanel.js
var FormPanel = ({
  title: title3,
  children: children2,
  scrollId,
  className
}) => {
  return /* @__PURE__ */ react.createElement(Card, {
    className,
    isFlat: true
  }, /* @__PURE__ */ react.createElement(CardHeader, {
    className: "kc-form-panel__header"
  }, /* @__PURE__ */ react.createElement(CardTitle, {
    tabIndex: 0
  }, /* @__PURE__ */ react.createElement(Title, {
    headingLevel: "h1",
    size: "xl",
    className: "kc-form-panel__title",
    id: scrollId,
    tabIndex: 0
  }, title3))), /* @__PURE__ */ react.createElement(CardBody, {
    className: "kc-form-panel__body"
  }, children2));
};

// build/realm-settings/AddUserEmailModal.js
var AddUserEmailModal = ({callback}) => {
  const {t: t5} = useTranslation("groups");
  const adminClient = useAdminClient();
  const {whoAmI: whoAmI2} = useWhoAmI();
  const {register: register2, errors, handleSubmit, watch} = useForm({
    defaultValues: {email: ""}
  });
  const watchEmailInput = watch("email", "");
  const cancel = () => callback(false);
  const proceed = () => callback(true);
  const save = async (formData) => {
    await adminClient.users.update({id: whoAmI2.getUserId()}, formData);
    proceed();
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    title: t5("realm-settings:provideEmailTitle"),
    isOpen: true,
    onClose: cancel,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "modal-test-connection-button",
        key: "confirm",
        variant: "primary",
        type: "submit",
        form: "email-form",
        isDisabled: !watchEmailInput
      }, t5("common:testConnection")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: cancel
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(TextContent, {
    className: "kc-provide-email-text"
  }, t5("realm-settings:provideEmail")), /* @__PURE__ */ react.createElement(Form, {
    id: "email-form",
    isHorizontal: true,
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    className: "kc-email-form-group",
    name: "add-email-address",
    fieldId: "email-id",
    helperTextInvalid: t5("users:emailInvalid"),
    validated: errors.email ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    "data-testid": "email-address-input",
    ref: register2({required: true, pattern: emailRegexPattern}),
    autoFocus: true,
    type: "text",
    id: "add-email",
    name: "email",
    validated: errors.email ? ValidatedOptions.error : ValidatedOptions.default
  }))));
};

// build/realm-settings/EmailTab.js
var RealmSettingsEmailTab = ({
  realm: initialRealm
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const adminClient = useAdminClient();
  const {realm: realmName} = useRealm();
  const {addAlert, addError} = useAlerts();
  const {whoAmI: whoAmI2} = useWhoAmI();
  const [realm2, setRealm] = useState(initialRealm);
  const [callback, setCallback] = useState();
  const {
    register: register2,
    control,
    handleSubmit,
    errors,
    watch,
    reset: resetForm,
    getValues
  } = useForm({defaultValues: realm2});
  const reset2 = () => resetForm(realm2);
  const watchFromValue = watch("smtpServer.from", "");
  const watchHostValue = watch("smtpServer.host", "");
  const authenticationEnabled = useWatch({
    control,
    name: "smtpServer.authentication",
    defaultValue: ""
  });
  const save = async (form2) => {
    try {
      const registered = await registerEmailIfNeeded();
      if (!registered) {
        return;
      }
      const savedRealm = {...realm2, ...form2};
      await adminClient.realms.update({realm: realmName}, savedRealm);
      setRealm(savedRealm);
      addAlert(t5("saveSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("realm-settings:saveError", error2);
    }
  };
  const testConnection = async () => {
    const serverSettings = {...getValues()["smtpServer"]};
    if (typeof serverSettings.port === "string") {
      serverSettings.port = Number(serverSettings.port);
    }
    if (typeof serverSettings.ssl === "string") {
      serverSettings.ssl = serverSettings.ssl === true.toString();
    }
    if (typeof serverSettings.starttls === "string") {
      serverSettings.starttls = serverSettings.starttls === true.toString();
    }
    if (serverSettings.authentication === true.toString()) {
      serverSettings.auth = true;
    }
    try {
      const registered = await registerEmailIfNeeded();
      if (!registered) {
        return;
      }
      await adminClient.realms.testSMTPConnection({realm: realm2.realm}, serverSettings);
      addAlert(t5("testConnectionSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("realm-settings:testConnectionError", error2);
    }
  };
  const registerEmailIfNeeded = async () => {
    const user = await adminClient.users.findOne({id: whoAmI2.getUserId()});
    if (!user) {
      throw new Error("Unable to find user.");
    }
    if (user.email) {
      return true;
    }
    return new Promise((resolve2) => {
      const callback2 = (registered) => {
        setCallback(void 0);
        resolve2(registered);
      };
      setCallback(() => callback2);
    });
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, callback && /* @__PURE__ */ react.createElement(AddUserEmailModal, {
    callback
  }), /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(FormPanel, {
    title: t5("template"),
    className: "kc-email-template"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "pf-u-mt-lg",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("from"),
    fieldId: "kc-display-name",
    isRequired: true,
    validated: errors.smtpServer?.from ? "error" : "default",
    helperTextInvalid: t5("users:emailInvalid")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "email",
    id: "kc-sender-email-address",
    "data-testid": "sender-email-address",
    name: "smtpServer.from",
    ref: register2({
      pattern: emailRegexPattern,
      required: true
    }),
    placeholder: "Sender email address",
    validated: errors.smtpServer?.from ? "error" : "default"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("fromDisplayName"),
    fieldId: "kc-from-display-name",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:fromDisplayName",
      fieldLabelId: "realm-settings:authentication"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-from-display-name",
    "data-testid": "from-display-name",
    name: "smtpServer.fromDisplayName",
    ref: register2,
    placeholder: "Display name for Sender email address"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("replyTo"),
    fieldId: "kc-reply-to",
    validated: errors.smtpServer?.replyTo ? "error" : "default",
    helperTextInvalid: t5("users:emailInvalid")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "email",
    id: "kc-reply-to",
    name: "smtpServer.replyTo",
    ref: register2({
      pattern: emailRegexPattern
    }),
    placeholder: "Reply to email address",
    validated: errors.smtpServer?.replyTo ? "error" : "default"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("replyToDisplayName"),
    fieldId: "kc-reply-to-display-name",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:replyToDisplayName",
      fieldLabelId: "realm-settings:replyToDisplayName"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-reply-to-display-name",
    name: "smtpServer.replyToDisplayName",
    ref: register2,
    placeholder: 'Display name for "reply to" email address'
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("envelopeFrom"),
    fieldId: "kc-envelope-from",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:envelopeFrom",
      fieldLabelId: "realm-settings:envelopeFrom"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-envelope-from",
    name: "smtpServer.envelopeFrom",
    ref: register2,
    placeholder: "Sender envelope email address"
  })))), /* @__PURE__ */ react.createElement(FormPanel, {
    className: "kc-email-connection",
    title: t5("connectionAndAuthentication")
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "pf-u-mt-lg",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("host"),
    fieldId: "kc-host",
    isRequired: true,
    validated: errors.smtpServer?.host ? "error" : "default",
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-host",
    name: "smtpServer.host",
    ref: register2({required: true}),
    placeholder: "SMTP host",
    validated: errors.smtpServer?.host ? "error" : "default"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("port"),
    fieldId: "kc-port"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-port",
    name: "smtpServer.port",
    ref: register2,
    placeholder: "SMTP port (defaults to 25)"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("encryption"),
    fieldId: "kc-html-display-name"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "smtpServer.ssl",
    control,
    defaultValue: "false",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Checkbox, {
      id: "kc-enable-ssl",
      "data-testid": "enable-ssl",
      label: t5("enableSSL"),
      ref: register2,
      isChecked: value === "true",
      onChange: (value2) => onChange("" + value2)
    })
  }), /* @__PURE__ */ react.createElement(Controller, {
    name: "smtpServer.starttls",
    control,
    defaultValue: "false",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Checkbox, {
      id: "kc-enable-start-tls",
      "data-testid": "enable-start-tls",
      label: t5("enableStartTLS"),
      ref: register2,
      isChecked: value === "true",
      onChange: (value2) => onChange("" + value2)
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("authentication"),
    fieldId: "kc-authentication"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "smtpServer.authentication",
    control,
    defaultValue: "",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-authentication-switch",
      "data-testid": "email-authentication-switch",
      label: t5("common:enabled"),
      labelOff: t5("common:disabled"),
      isChecked: value === "true",
      onChange: (value2) => {
        onChange("" + value2);
      }
    })
  })), authenticationEnabled === "true" && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("username"),
    fieldId: "kc-username",
    isRequired: true,
    validated: errors.smtpServer?.user ? "error" : "default",
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-username",
    "data-testid": "username-input",
    name: "smtpServer.user",
    ref: register2({required: true}),
    placeholder: "Login username",
    validated: errors.smtpServer?.user ? "error" : "default"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("password"),
    fieldId: "kc-username",
    isRequired: true,
    validated: errors.smtpServer?.password ? "error" : "default",
    helperTextInvalid: t5("common:required"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:password",
      fieldLabelId: "realm-settings:password"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "password",
    id: "kc-password",
    "data-testid": "password-input",
    name: "smtpServer.password",
    ref: register2({required: true}),
    placeholder: "Login password",
    validated: errors.smtpServer?.password ? "error" : "default"
  }))), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    type: "submit",
    "data-testid": "email-tab-save"
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    onClick: () => testConnection(),
    "data-testid": "test-connection-button",
    isDisabled: !(emailRegexPattern.test(watchFromValue) && watchHostValue)
  }, t5("common:testConnection")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert")))))));
};

// build/realm-settings/event-config/EventConfigForm.js
var EventConfigForm = ({
  type,
  form: form2,
  reset: reset2,
  clear
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const {
    control,
    watch,
    setValue,
    formState: {isDirty}
  } = form2;
  const eventKey = type === "admin" ? "adminEventsEnabled" : "eventsEnabled";
  const eventsEnabled = watch(eventKey);
  const [toggleDisableDialog, DisableConfirm] = useConfirmDialog({
    titleKey: "realm-settings:events-disable-title",
    messageKey: "realm-settings:events-disable-confirm",
    continueButtonLabel: "realm-settings:confirm",
    onConfirm: () => setValue(eventKey, false)
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DisableConfirm, null), /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("saveEvents"),
    fieldId: eventKey,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: `realm-settings-help:save-${type}-events`,
      fieldLabelId: "realm-settings:saveEvents"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: eventKey,
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      "data-testid": eventKey,
      id: `${eventKey}-switch`,
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange: (value2) => {
        if (!value2) {
          toggleDisableDialog();
        } else {
          onChange(value2);
        }
      }
    })
  })), eventsEnabled && /* @__PURE__ */ react.createElement(react.Fragment, null, type === "admin" && /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("includeRepresentation"),
    fieldId: "includeRepresentation",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:includeRepresentation",
      fieldLabelId: "realm-settings:includeRepresentation"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "adminEventsDetailsEnabled",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      "data-testid": "includeRepresentation",
      id: "includeRepresentation",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange
    })
  })), type === "user" && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("expiration"),
    fieldId: "expiration",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:expiration",
      fieldLabelId: "realm-settings:expiration"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "eventsExpiration",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  }))), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    type: "submit",
    id: `save-${type}`,
    "data-testid": `save-${type}`,
    isDisabled: !isDirty
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert"))), /* @__PURE__ */ react.createElement(Divider, null), /* @__PURE__ */ react.createElement(FormGroup, {
    label: type === "user" ? t5("clearUserEvents") : t5("clearAdminEvents"),
    fieldId: `clear-${type}-events`,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: `realm-settings-help:${type}-clearEvents`,
      fieldLabelId: `realm-settings:clear-${type}-events`
    })
  }, /* @__PURE__ */ react.createElement(Button, {
    variant: "danger",
    id: `clear-${type}-events`,
    "data-testid": `clear-${type}-events`,
    onClick: () => clear()
  }, type === "user" ? t5("clearUserEvents") : t5("clearAdminEvents"))));
};

// build/realm-settings/event-config/EventsTypeTable.js
function EventsTypeTable({
  loader,
  addTypes,
  onSelect,
  onDelete
}) {
  const {t: t5} = useTranslation("realm-settings");
  const DescriptionCell = (event) => /* @__PURE__ */ react.createElement(Fragment, {
    key: event.id
  }, t5(`eventTypes.${event.id}.description`));
  return /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    ariaLabelKey: "userEventsRegistered",
    searchPlaceholderKey: "realm-settings:searchEventType",
    loader,
    onSelect: onSelect ? onSelect : void 0,
    canSelectAll: !!onSelect,
    toolbarItem: addTypes && /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      id: "addTypes",
      onClick: addTypes,
      "data-testid": "addTypes"
    }, t5("addSavedTypes"))),
    actions: !onDelete ? [] : [
      {
        title: t5("common:delete"),
        onRowClick: onDelete
      }
    ],
    columns: [
      {
        name: "id",
        displayKey: "realm-settings:eventType",
        cellFormatters: [
          (data2) => t5(`eventTypes.${data2}.name`)
        ]
      },
      {
        name: "description",
        displayKey: "description",
        cellRenderer: DescriptionCell
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      message: t5("emptyEvents"),
      instructions: t5("emptyEventsInstructions")
    })
  });
}

// build/realm-settings/event-config/AddEventTypesDialog.js
var AddEventTypesDialog = ({
  onConfirm,
  onClose,
  configured
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const {enums} = useServerInfo();
  const [selectedTypes, setSelectedTypes] = useState([]);
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.medium,
    title: t5("addTypes"),
    isOpen: true,
    onClose,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "addEventTypeConfirm",
        key: "confirm",
        variant: "primary",
        onClick: () => onConfirm(selectedTypes)
      }, t5("common:add")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "moveCancel",
        key: "cancel",
        variant: "link",
        onClick: onClose
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(EventsTypeTable, {
    onSelect: (selected) => setSelectedTypes(selected),
    loader: () => Promise.resolve(enums["eventType"].filter((type) => !configured.includes(type)).map((id3) => {
      return {id: id3};
    }))
  }));
};

// build/realm-settings/event-config/EventListenersForm.js
var EventListenersForm = ({
  form: form2,
  reset: reset2
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const {
    control,
    formState: {isDirty}
  } = form2;
  const [selectEventListenerOpen, setSelectEventListenerOpen] = useState(false);
  const serverInfo2 = useServerInfo();
  const eventListeners2 = serverInfo2.providers?.eventsListener.providers;
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("eventListeners"),
    fieldId: "kc-eventListeners",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5("eventListenersHelpText"),
      fieldLabelId: "realm-settings:eventListeners"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "eventsListeners",
    defaultValue: "",
    control,
    render: ({
      onChange,
      value
    }) => /* @__PURE__ */ react.createElement(Select, {
      name: "eventsListeners",
      className: "kc_eventListeners_select",
      "data-testid": "eventListeners-select",
      chipGroupProps: {
        numChips: 3,
        expandedText: t5("common:hide"),
        collapsedText: t5("common:showRemaining")
      },
      variant: SelectVariant.typeaheadMulti,
      typeAheadAriaLabel: "Select",
      onToggle: (isOpen) => setSelectEventListenerOpen(isOpen),
      selections: value,
      onSelect: (_23, selectedValue) => {
        const option = selectedValue.toString();
        const changedValue = value.includes(option) ? value.filter((item) => item !== option) : [...value, option];
        onChange(changedValue);
      },
      onClear: (operation) => {
        operation.stopPropagation();
        onChange([]);
      },
      isOpen: selectEventListenerOpen,
      "aria-labelledby": "eventsListeners"
    }, Object.keys(eventListeners2).map((event) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: event,
      value: event
    })))
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    type: "submit",
    "data-testid": "saveEventListenerBtn",
    isDisabled: !isDirty
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    "data-testid": "revertEventListenerBtn",
    onClick: reset2
  }, t5("common:revert"))));
};

// build/realm-settings/event-config/EventsTab.js
var EventsTab = () => {
  const {t: t5} = useTranslation("realm-settings");
  const form2 = useForm();
  const {setValue, handleSubmit, watch, reset: reset2} = form2;
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const [tableKey, setTableKey] = useState(0);
  const reload = () => setTableKey(new Date().getTime());
  const [activeTab, setActiveTab] = useState("event");
  const [events, setEvents] = useState();
  const [type, setType] = useState();
  const [addEventType, setAddEventType] = useState(false);
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {realm: realm2} = useRealm();
  const setupForm = (eventConfig) => {
    reset2(eventConfig);
    setEvents(eventConfig);
    Object.entries(eventConfig || {}).forEach((entry) => setValue(entry[0], entry[1]));
  };
  const clear = async (type2) => {
    setType(type2);
    toggleDeleteDialog();
  };
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: "realm-settings:deleteEvents",
    messageKey: "realm-settings:deleteEventsConfirm",
    continueButtonLabel: "common:clear",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        switch (type) {
          case "admin":
            await adminClient.realms.clearAdminEvents({realm: realm2});
            break;
          case "user":
            await adminClient.realms.clearEvents({realm: realm2});
            break;
        }
        addAlert(t5(`${type}-events-cleared`), AlertVariant.success);
      } catch (error2) {
        addError(`realm-settings:${type}-events-cleared-error`, error2);
      }
    }
  });
  useFetch(() => adminClient.realms.getConfigEvents({realm: realm2}), (eventConfig) => {
    setupForm(eventConfig);
    reload();
  }, [key]);
  const save = async (eventConfig) => {
    const updatedEventListener = events?.eventsListeners !== eventConfig.eventsListeners;
    try {
      await adminClient.realms.updateConfigEvents({realm: realm2}, eventConfig);
      setupForm({...events, ...eventConfig});
      addAlert(updatedEventListener ? t5("realm-settings:saveEventListenersSuccess") : t5("realm-settings:eventConfigSuccessfully"), AlertVariant.success);
    } catch (error2) {
      addError(updatedEventListener ? t5("realm-settings:saveEventListenersError") : t5("realm-settings:eventConfigError"), error2);
    }
  };
  const addEventTypes = async (eventTypes) => {
    const eventsTypes = eventTypes.map((type2) => type2.id);
    const enabledEvents = events.enabledEventTypes?.concat(eventsTypes);
    await addEvents(enabledEvents);
  };
  const addEvents = async (events2 = []) => {
    const eventConfig = {...form2.getValues(), enabledEventTypes: events2};
    await save(eventConfig);
    setAddEventType(false);
    refresh();
  };
  const eventsEnabled = watch("eventsEnabled") || false;
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), addEventType && /* @__PURE__ */ react.createElement(AddEventTypesDialog, {
    onConfirm: (eventTypes) => addEventTypes(eventTypes),
    configured: events?.enabledEventTypes || [],
    onClose: () => setAddEventType(false)
  }), /* @__PURE__ */ react.createElement(Tabs, {
    activeKey: activeTab,
    onSelect: (_23, key2) => setActiveTab(key2)
  }, /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "event",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("eventListeners")),
    "data-testid": "rs-event-listeners-tab"
  }, /* @__PURE__ */ react.createElement(PageSection, null, /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-events",
    isHorizontal: true,
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(EventListenersForm, {
    form: form2,
    reset: () => setupForm(events)
  })))), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "user",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("userEventsSettings")),
    "data-testid": "rs-events-tab"
  }, /* @__PURE__ */ react.createElement(PageSection, null, /* @__PURE__ */ react.createElement(Title, {
    headingLevel: "h1",
    size: "xl"
  }, t5("userEventsConfig"))), /* @__PURE__ */ react.createElement(PageSection, null, /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-events",
    isHorizontal: true,
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(EventConfigForm, {
    type: "user",
    form: form2,
    reset: () => setupForm(events),
    clear: () => clear("user")
  }))), eventsEnabled && /* @__PURE__ */ react.createElement(PageSection, null, /* @__PURE__ */ react.createElement(EventsTypeTable, {
    key: tableKey,
    addTypes: () => setAddEventType(true),
    loader: () => Promise.resolve(events?.enabledEventTypes?.map((id3) => {
      return {id: id3};
    }) || []),
    onDelete: (value) => {
      const enabledEventTypes = events?.enabledEventTypes?.filter((e2) => e2 !== value.id);
      addEvents(enabledEventTypes);
      setEvents({...events, enabledEventTypes});
    }
  }))), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "admin",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("adminEventsSettings")),
    "data-testid": "rs-admin-events-tab"
  }, /* @__PURE__ */ react.createElement(PageSection, null, /* @__PURE__ */ react.createElement(Title, {
    headingLevel: "h4",
    size: "xl"
  }, t5("adminEventsConfig"))), /* @__PURE__ */ react.createElement(PageSection, null, /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-events",
    isHorizontal: true,
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(EventConfigForm, {
    type: "admin",
    form: form2,
    reset: () => setupForm(events),
    clear: () => clear("admin")
  }))))));
};

// build/realm-settings/GeneralTab.js
var RealmSettingsGeneralTab = ({
  save,
  reset: reset2
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const adminClient = useAdminClient();
  const {realm: realmName} = useRealm();
  const {
    register: register2,
    control,
    handleSubmit,
    formState: {isDirty}
  } = useFormContext();
  const [open2, setOpen] = useState(false);
  const baseUrl = getBaseUrl(adminClient);
  const requireSslTypes = ["all", "external", "none"];
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "pf-u-mt-lg",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("realmId"),
    fieldId: "kc-realm-id",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "realm",
    control,
    defaultValue: "",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(ClipboardCopy, {
      onChange
    }, value)
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("displayName"),
    fieldId: "kc-display-name"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-display-name",
    name: "displayName",
    ref: register2
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("htmlDisplayName"),
    fieldId: "kc-html-display-name"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-html-display-name",
    name: "displayNameHtml",
    ref: register2
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("frontendUrl"),
    fieldId: "kc-frontend-url",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:frontendUrl",
      fieldLabelId: "realm-settings:frontendUrl"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-frontend-url",
    name: "attributes.frontendUrl",
    ref: register2
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("requireSsl"),
    fieldId: "kc-require-ssl",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:requireSsl",
      fieldLabelId: "realm-settings:requireSsl"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "sslRequired",
    defaultValue: "none",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-require-ssl",
      onToggle: () => setOpen(!open2),
      onSelect: (_23, value2) => {
        onChange(value2);
        setOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("requireSsl"),
      isOpen: open2
    }, requireSslTypes.map((sslType) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: sslType === value,
      key: sslType,
      value: sslType
    }, t5(`sslType.${sslType}`))))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("userManagedAccess"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:userManagedAccess",
      fieldLabelId: "realm-settings:userManagedAccess"
    }),
    fieldId: "kc-user-manged-access"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "userManagedAccessAllowed",
    control,
    defaultValue: false,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-user-managed-access",
      "data-testid": "user-managed-access-switch",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("endpoints"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:endpoints",
      fieldLabelId: "realm-settings:endpoints"
    }),
    fieldId: "kc-endpoints"
  }, /* @__PURE__ */ react.createElement(Stack, null, /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(FormattedLink, {
    href: `${baseUrl}realms/${realmName}/.well-known/openid-configuration`,
    title: t5("openIDEndpointConfiguration")
  })), /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(FormattedLink, {
    href: `${baseUrl}realms/${realmName}/protocol/saml/descriptor`,
    title: t5("samlIdentityProviderMetadata")
  })))), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    type: "submit",
    "data-testid": "general-tab-save",
    isDisabled: !isDirty
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert")))));
};

// build/realm-settings/KeysListTab.js
var KeysListTab = ({realmComponents}) => {
  const {t: t5} = useTranslation("roles");
  const history = useHistory();
  const {url} = useRouteMatch();
  const [key, setKey] = useState(0);
  const [publicKey, setPublicKey] = useState("");
  const [certificate, setCertificate] = useState("");
  const [filterDropdownOpen, setFilterDropdownOpen] = useState(false);
  const [filterType, setFilterType] = useState("Active keys");
  const refresh = () => {
    setKey(new Date().getTime());
  };
  const adminClient = useAdminClient();
  const {realm: realmName} = useRealm();
  const loader = async () => {
    const keysMetaData = await adminClient.realms.getKeys({
      realm: realmName
    });
    const keys2 = keysMetaData.keys;
    return keys2?.map((key2) => {
      const provider = realmComponents.find((component) => component.id === key2.providerId);
      return {...key2, provider: provider?.name};
    });
  };
  const activeKeysLoader = async () => {
    const keysMetaData = await adminClient.realms.getKeys({
      realm: realmName
    });
    const keys2 = keysMetaData.keys;
    const activeKeysCopy = keys2.filter((i3) => i3.status === "ACTIVE");
    return activeKeysCopy?.map((key2) => {
      const provider = realmComponents.find((component) => component.id === key2.providerId);
      return {...key2, provider: provider?.name};
    });
  };
  const passiveKeysLoader = async () => {
    const keysMetaData = await adminClient.realms.getKeys({
      realm: realmName
    });
    const keys2 = keysMetaData.keys;
    const passiveKeys = keys2.filter((i3) => i3.status === "PASSIVE");
    return passiveKeys?.map((key2) => {
      const provider = realmComponents.find((component) => component.id === key2.providerId);
      return {...key2, provider: provider?.name};
    });
  };
  const disabledKeysLoader = async () => {
    const keysMetaData = await adminClient.realms.getKeys({
      realm: realmName
    });
    const keys2 = keysMetaData.keys;
    const disabledKeys = keys2.filter((i3) => i3.status === "DISABLED");
    return disabledKeys?.map((key2) => {
      const provider = realmComponents.find((component) => component.id === key2.providerId);
      return {...key2, provider: provider?.name};
    });
  };
  const [togglePublicKeyDialog, PublicKeyDialog] = useConfirmDialog({
    titleKey: t5("realm-settings:publicKeys").slice(0, -1),
    messageKey: publicKey,
    continueButtonLabel: "common:close",
    continueButtonVariant: ButtonVariant.primary,
    onConfirm: () => Promise.resolve()
  });
  const [toggleCertificateDialog, CertificateDialog] = useConfirmDialog({
    titleKey: t5("realm-settings:certificate"),
    messageKey: certificate,
    continueButtonLabel: "common:close",
    continueButtonVariant: ButtonVariant.primary,
    onConfirm: () => Promise.resolve()
  });
  const goToCreate = () => history.push(`${url}/add-role`);
  const ProviderRenderer = ({provider}) => provider;
  const ButtonRenderer = ({type, publicKey: publicKey2, certificate: certificate2}) => {
    if (type === "EC") {
      return /* @__PURE__ */ react.createElement(Button, {
        onClick: () => {
          togglePublicKeyDialog();
          setPublicKey(publicKey2);
        },
        variant: "secondary",
        id: "kc-public-key"
      }, t5("realm-settings:publicKeys").slice(0, -1));
    } else if (type === "RSA") {
      return /* @__PURE__ */ react.createElement("div", {
        className: "button-wrapper"
      }, /* @__PURE__ */ react.createElement(Button, {
        onClick: () => {
          togglePublicKeyDialog();
          setPublicKey(publicKey2);
        },
        variant: "secondary",
        id: "kc-rsa-public-key"
      }, t5("realm-settings:publicKeys").slice(0, -1)), /* @__PURE__ */ react.createElement(Button, {
        onClick: () => {
          toggleCertificateDialog();
          setCertificate(certificate2);
        },
        variant: "secondary",
        id: "kc-certificate"
      }, t5("realm-settings:certificate")));
    }
  };
  const options = [
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: 1,
      "data-testid": "active-keys-option",
      value: t5("realm-settings:activeKeys"),
      isPlaceholder: true
    }),
    /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "passive-keys-option",
      key: 2,
      value: t5("realm-settings:passiveKeys")
    }),
    /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "disabled-keys-option",
      key: 3,
      value: t5("realm-settings:disabledKeys")
    })
  ];
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light",
    padding: {default: "noPadding"}
  }, /* @__PURE__ */ react.createElement(PublicKeyDialog, null), /* @__PURE__ */ react.createElement(CertificateDialog, null), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    isNotCompact: true,
    key,
    loader: filterType === "Active keys" ? activeKeysLoader : filterType === "Passive keys" ? passiveKeysLoader : filterType === "Disabled keys" ? disabledKeysLoader : loader,
    ariaLabelKey: "realm-settings:keysList",
    searchPlaceholderKey: "realm-settings:searchKey",
    searchTypeComponent: /* @__PURE__ */ react.createElement(Select, {
      width: 300,
      "data-testid": "filter-type-select",
      isOpen: filterDropdownOpen,
      className: "kc-filter-type-select",
      variant: SelectVariant.single,
      onToggle: () => setFilterDropdownOpen(!filterDropdownOpen),
      toggleIcon: /* @__PURE__ */ react.createElement(FilterIcon, null),
      onSelect: (_23, value) => {
        setFilterType(value);
        refresh();
        setFilterDropdownOpen(false);
      },
      selections: filterType
    }, options),
    canSelectAll: true,
    columns: [
      {
        name: "algorithm",
        displayKey: "realm-settings:algorithm",
        cellFormatters: [emptyFormatter()],
        transforms: [cellWidth(15)]
      },
      {
        name: "type",
        displayKey: "realm-settings:type",
        cellFormatters: [emptyFormatter()],
        transforms: [cellWidth(10)]
      },
      {
        name: "kid",
        displayKey: "realm-settings:kid",
        cellFormatters: [emptyFormatter()],
        transforms: [cellWidth(10)]
      },
      {
        name: "provider",
        displayKey: "realm-settings:provider",
        cellRenderer: ProviderRenderer,
        cellFormatters: [emptyFormatter()],
        transforms: [cellWidth(10)]
      },
      {
        name: "publicKeys",
        displayKey: "realm-settings:publicKeys",
        cellRenderer: ButtonRenderer,
        cellFormatters: [],
        transforms: [cellWidth(20)]
      }
    ],
    isSearching: !!filterType,
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      hasIcon: true,
      message: t5("realm-settings:noKeys"),
      instructions: t5(`realm-settings:noKeysDescription`) + `${filterType.toLocaleLowerCase()}.`,
      primaryActionText: t5("createRole"),
      onPrimaryAction: goToCreate
    })
  }));
};

// build/realm-settings/key-providers/aes-generated/AESGeneratedModal.js
var import_AESGeneratedForm = require_AESGeneratedForm();
var AESGeneratedModal = ({
  providerType,
  handleModalToggle,
  open: open2,
  refresh
}) => {
  const {t: t5} = useTranslation("realm-settings");
  return /* @__PURE__ */ react.createElement(Modal, {
    className: "add-provider-modal",
    variant: ModalVariant.medium,
    title: t5("addProvider"),
    isOpen: open2,
    onClose: handleModalToggle
  }, /* @__PURE__ */ react.createElement(import_AESGeneratedForm.AESGeneratedForm, {
    providerType,
    handleModalToggle,
    refresh
  }));
};

// build/realm-settings/key-providers/java-keystore/JavaKeystoreModal.js
var import_JavaKeystoreForm = require_JavaKeystoreForm();
var JavaKeystoreModal = ({
  providerType,
  handleModalToggle,
  open: open2,
  refresh
}) => {
  const {t: t5} = useTranslation("realm-settings");
  return /* @__PURE__ */ react.createElement(Modal, {
    className: "add-provider-modal",
    variant: ModalVariant.medium,
    title: t5("addProvider"),
    isOpen: open2,
    onClose: handleModalToggle
  }, /* @__PURE__ */ react.createElement(import_JavaKeystoreForm.JavaKeystoreForm, {
    providerType,
    handleModalToggle,
    refresh
  }));
};

// build/realm-settings/key-providers/hmac-generated/HMACGeneratedModal.js
var import_HMACGeneratedForm = require_HMACGeneratedForm();
var HMACGeneratedModal = ({
  providerType,
  handleModalToggle,
  open: open2,
  refresh
}) => {
  const {t: t5} = useTranslation("realm-settings");
  return /* @__PURE__ */ react.createElement(Modal, {
    className: "add-provider-modal",
    variant: ModalVariant.medium,
    title: t5("addProvider"),
    isOpen: open2,
    onClose: handleModalToggle
  }, /* @__PURE__ */ react.createElement(import_HMACGeneratedForm.HMACGeneratedForm, {
    providerType,
    handleModalToggle,
    refresh
  }));
};

// build/realm-settings/key-providers/ecdsa-generated/ECDSAGeneratedModal.js
var import_ECDSAGeneratedForm = require_ECDSAGeneratedForm();
var ECDSAGeneratedModal = ({
  providerType,
  handleModalToggle,
  open: open2,
  refresh
}) => {
  const {t: t5} = useTranslation("realm-settings");
  return /* @__PURE__ */ react.createElement(Modal, {
    className: "add-provider-modal",
    variant: ModalVariant.medium,
    title: t5("addProvider"),
    isOpen: open2,
    onClose: handleModalToggle
  }, /* @__PURE__ */ react.createElement(import_ECDSAGeneratedForm.ECDSAGeneratedForm, {
    providerType,
    handleModalToggle,
    refresh
  }));
};

// build/realm-settings/RSAModal.js
var RSAModal = ({
  providerType,
  handleModalToggle,
  open: open2,
  refresh
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const serverInfo2 = useServerInfo();
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {handleSubmit, control} = useForm({});
  const [isRSAalgDropdownOpen, setIsRSAalgDropdownOpen] = useState(false);
  const {id: id3} = useParams();
  const [keyFileName, setKeyFileName] = useState("");
  const [certificateFileName, setCertificateFileName] = useState("");
  const allComponentTypes = serverInfo2.componentTypes?.[KEY_PROVIDER_TYPE] ?? [];
  const save = async (component) => {
    try {
      if (id3) {
        await adminClient.components.update({id: id3}, {
          ...component,
          parentId: component.parentId,
          providerId: providerType,
          providerType: KEY_PROVIDER_TYPE
        });
        addAlert(t5("saveProviderSuccess"), AlertVariant.success);
      } else {
        await adminClient.components.create({
          ...component,
          parentId: component.parentId,
          providerId: providerType,
          providerType: KEY_PROVIDER_TYPE,
          config: {priority: ["0"]}
        });
        handleModalToggle();
        addAlert(t5("saveProviderSuccess"), AlertVariant.success);
        refresh();
      }
    } catch (error2) {
      addError("realm-settings:saveProviderError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    className: "add-provider-modal",
    variant: ModalVariant.medium,
    title: t5("addProvider"),
    isOpen: open2,
    onClose: handleModalToggle,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "add-provider-button",
        key: "confirm",
        variant: "primary",
        type: "submit",
        form: "add-provider"
      }, t5("common:Add")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          handleModalToggle();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true,
    id: "add-provider",
    className: "pf-u-mt-lg",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("consoleDisplayName"),
    fieldId: "kc-console-display-name",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:displayName",
      fieldLabelId: "realm-settings:consoleDisplayName"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "name",
    control,
    defaultValue: providerType,
    render: ({onChange}) => /* @__PURE__ */ react.createElement(TextInput, {
      "aria-label": t5("consoleDisplayName"),
      defaultValue: providerType,
      onChange: (value) => {
        onChange(value);
      },
      "data-testid": "display-name-input"
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:enabled"),
    fieldId: "kc-enabled",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5("realm-settings-help:enabled"),
      fieldLabelId: "enabled"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.enabled",
    control,
    defaultValue: ["true"],
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-enabled",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value[0] === "true",
      "data-testid": value[0] === "true" ? "internationalization-enabled" : "internationalization-disabled",
      onChange: (value2) => {
        onChange([value2 + ""]);
      }
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("active"),
    fieldId: "kc-active",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:active",
      fieldLabelId: "realm-settings:active"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.active",
    control,
    defaultValue: ["true"],
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-active",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value[0] === "true",
      "data-testid": value[0] === "true" ? "internationalization-enabled" : "internationalization-disabled",
      onChange: (value2) => {
        onChange([value2 + ""]);
      }
    })
  })), providerType === "rsa" && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("algorithm"),
    fieldId: "kc-algorithm",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:algorithm",
      fieldLabelId: "realm-settings:algorithm"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "algorithm",
    defaultValue: "",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-rsa-algorithm",
      onToggle: () => setIsRSAalgDropdownOpen(!isRSAalgDropdownOpen),
      onSelect: (_23, value2) => {
        onChange(value2);
        setIsRSAalgDropdownOpen(false);
      },
      selections: [value + ""],
      variant: SelectVariant.single,
      "aria-label": t5("algorithm"),
      isOpen: isRSAalgDropdownOpen,
      "data-testid": "select-rsa-algorithm"
    }, allComponentTypes[4].properties[3].options.map((p2, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: p2 === value,
      key: `rsa-algorithm-${idx}`,
      value: p2
    })))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("privateRSAKey"),
    fieldId: "kc-private-rsa-key",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:privateRSAKey",
      fieldLabelId: "realm-settings:privateRSAKey"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.privateKey",
    control,
    defaultValue: [],
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(FileUpload, {
      id: "importPrivateKey",
      type: "text",
      value: value[0],
      filenamePlaceholder: "Upload a PEM file or paste key below",
      filename: keyFileName,
      onChange: (value2, fileName) => {
        setKeyFileName(fileName);
        onChange([value2]);
      }
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("x509Certificate"),
    fieldId: "kc-aes-keysize",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:x509Certificate",
      fieldLabelId: "realm-settings:x509Certificate"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.certificate",
    control,
    defaultValue: [],
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(FileUpload, {
      id: "importCertificate",
      type: "text",
      value: value[0],
      filenamePlaceholder: "Upload a PEM file or paste key below",
      filename: certificateFileName,
      onChange: (value2, fileName) => {
        setCertificateFileName(fileName);
        onChange([value2]);
      }
    })
  })))));
};

// build/realm-settings/key-providers/rsa-generated/RSAGeneratedModal.js
var import_RSAGeneratedForm = require_RSAGeneratedForm();
var RSAGeneratedModal = ({
  providerType,
  handleModalToggle,
  open: open2,
  refresh
}) => {
  const {t: t5} = useTranslation("realm-settings");
  return /* @__PURE__ */ react.createElement(Modal, {
    className: "add-provider-modal",
    variant: ModalVariant.medium,
    title: t5("addProvider"),
    isOpen: open2,
    onClose: handleModalToggle
  }, /* @__PURE__ */ react.createElement(import_RSAGeneratedForm.RSAGeneratedForm, {
    providerType,
    handleModalToggle,
    refresh
  }));
};

// build/realm-settings/KeysProvidersTab.js
var KeysTabInner = ({components: components3, refresh}) => {
  const {t: t5} = useTranslation("realm-settings");
  const {addAlert, addError} = useAlerts();
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const {url} = useRouteMatch();
  const [id3, setId] = useState("");
  const [searchVal, setSearchVal] = useState("");
  const [filteredComponents, setFilteredComponents] = useState([]);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const serverInfo2 = useServerInfo();
  const providerTypes = (serverInfo2.componentTypes?.[KEY_PROVIDER_TYPE] ?? []).map((item) => item.id);
  const [itemOrder, setItemOrder] = useState([]);
  const [providerDropdownOpen, setProviderDropdownOpen] = useState(false);
  const [defaultConsoleDisplayName, setDefaultConsoleDisplayName] = useState("");
  const [selectedComponent, setSelectedComponent] = useState();
  const [liveText, setLiveText] = useState("");
  useEffect(() => {
    const itemIds = components3.map((component) => component.id);
    setItemOrder(["data", ...itemIds]);
  }, [components3, searchVal]);
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: "realm-settings:deleteProviderTitle",
    messageKey: t5("deleteProviderConfirm") + selectedComponent?.name + "?",
    continueButtonLabel: "common:delete",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        await adminClient.components.del({
          id: selectedComponent.id,
          realm: realm2
        });
        refresh();
        addAlert(t5("deleteProviderSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("realm-settings:deleteProviderError", error2);
      }
    }
  });
  const onDragStart = async (id22) => {
    setLiveText(t5("common:onDragStart", {item: id22}));
    setId(id22);
  };
  const onDragMove = () => {
    setLiveText(t5("common:onDragMove", {item: id3}));
  };
  const onDragCancel = () => {
    setLiveText(t5("common:onDragCancel"));
  };
  const onDragFinish = async (itemOrder2) => {
    setItemOrder(itemOrder2);
    setLiveText(t5("common:onDragFinish"));
    const updateAll = components3.map((component) => {
      const componentToSave = {...component};
      delete componentToSave.providerDescription;
      return adminClient.components.update({id: component.id}, {
        ...componentToSave,
        config: {
          priority: [
            (itemOrder2.length - itemOrder2.indexOf(component.id) + 100).toString()
          ]
        }
      });
    });
    try {
      await Promise.all(updateAll);
      refresh();
      addAlert(t5("realm-settings:saveProviderListSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("realm-settings:saveProviderError", error2);
    }
  };
  const onSearch = () => {
    if (searchVal !== "") {
      setSearchVal(searchVal);
      const x2 = components3.filter((v2) => {
        return v2.name?.includes(searchVal) || v2.providerId?.includes(searchVal);
      });
      setFilteredComponents(x2);
    } else {
      setSearchVal("");
      setFilteredComponents(components3);
    }
  };
  const handleKeyDown = (e2) => {
    if (e2.key === "Enter") {
      onSearch();
    }
  };
  const handleInputChange = (value) => {
    setSearchVal(value);
  };
  const handleModalToggle = () => {
    setIsCreateModalOpen(!isCreateModalOpen);
  };
  const [actionListOpen, setActionListOpen] = useState(components3.map(() => false));
  const toggleActionList = (index3) => {
    actionListOpen[index3] = !actionListOpen[index3];
    setActionListOpen([...actionListOpen]);
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, defaultConsoleDisplayName === "aes-generated" && /* @__PURE__ */ react.createElement(AESGeneratedModal, {
    handleModalToggle,
    providerType: defaultConsoleDisplayName,
    refresh,
    open: isCreateModalOpen
  }), defaultConsoleDisplayName === "ecdsa-generated" && /* @__PURE__ */ react.createElement(ECDSAGeneratedModal, {
    handleModalToggle,
    providerType: defaultConsoleDisplayName,
    refresh,
    open: isCreateModalOpen
  }), defaultConsoleDisplayName === "hmac-generated" && /* @__PURE__ */ react.createElement(HMACGeneratedModal, {
    handleModalToggle,
    providerType: defaultConsoleDisplayName,
    refresh,
    open: isCreateModalOpen
  }), defaultConsoleDisplayName === "java-keystore" && /* @__PURE__ */ react.createElement(JavaKeystoreModal, {
    handleModalToggle,
    providerType: defaultConsoleDisplayName,
    refresh,
    open: isCreateModalOpen
  }), defaultConsoleDisplayName === "rsa" && /* @__PURE__ */ react.createElement(RSAModal, {
    handleModalToggle,
    providerType: defaultConsoleDisplayName,
    refresh,
    open: isCreateModalOpen
  }), defaultConsoleDisplayName === "rsa-generated" && /* @__PURE__ */ react.createElement(RSAGeneratedModal, {
    handleModalToggle,
    providerType: defaultConsoleDisplayName,
    refresh,
    open: isCreateModalOpen
  }), /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light",
    padding: {default: "noPadding"}
  }, /* @__PURE__ */ react.createElement(Toolbar, null, /* @__PURE__ */ react.createElement(ToolbarGroup, {
    className: "providers-toolbar"
  }, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(TextInput, {
    name: "inputGroupName",
    id: "inputGroupName",
    type: "search",
    "aria-label": t5("common:search"),
    placeholder: t5("common:search"),
    onChange: handleInputChange,
    onKeyDown: handleKeyDown
  }), /* @__PURE__ */ react.createElement(Button, {
    variant: ButtonVariant.control,
    "aria-label": t5("common:search")
  }, /* @__PURE__ */ react.createElement(SearchIcon, null)))), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Dropdown, {
    "data-testid": "addProviderDropdown",
    className: "add-provider-dropdown",
    isOpen: providerDropdownOpen,
    toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
      onToggle: (val) => setProviderDropdownOpen(val),
      isPrimary: true
    }, t5("realm-settings:addProvider")),
    dropdownItems: [
      providerTypes.map((item) => /* @__PURE__ */ react.createElement(DropdownItem, {
        onClick: () => {
          handleModalToggle();
          setProviderDropdownOpen(false);
          setDefaultConsoleDisplayName(item);
        },
        "data-testid": `option-${item}`,
        key: item
      }, item))
    ]
  })))), /* @__PURE__ */ react.createElement(DataList, {
    "aria-label": t5("common:groups"),
    onDragFinish,
    onDragStart,
    onDragMove,
    onDragCancel,
    itemOrder,
    isCompact: true
  }, /* @__PURE__ */ react.createElement(DataListItem, {
    "aria-labelledby": "aria",
    id: "data",
    key: "data"
  }, /* @__PURE__ */ react.createElement(DataListItemRow, {
    className: "test",
    "data-testid": "data-list-row"
  }, /* @__PURE__ */ react.createElement(DataListDragButton, {
    className: "header-drag-button",
    "aria-label": "Reorder",
    "aria-describedby": t5("common-help:dragHelp"),
    "aria-pressed": "false",
    isDisabled: true
  }), /* @__PURE__ */ react.createElement(DataListItemCells, {
    className: "data-list-cells",
    dataListCells: [
      /* @__PURE__ */ react.createElement(DataListCell, {
        className: "name",
        key: "name"
      }, /* @__PURE__ */ react.createElement(react.Fragment, null, t5("realm-settings:name"))),
      /* @__PURE__ */ react.createElement(DataListCell, {
        className: "provider",
        key: "provider"
      }, /* @__PURE__ */ react.createElement(react.Fragment, null, t5("realm-settings:provider"))),
      /* @__PURE__ */ react.createElement(DataListCell, {
        className: "provider-description",
        key: "provider-description"
      }, /* @__PURE__ */ react.createElement(react.Fragment, null, t5("realm-settings:providerDescription")))
    ]
  }))), (filteredComponents.length === 0 ? components3 : filteredComponents).map((component, idx) => /* @__PURE__ */ react.createElement(DataListItem, {
    draggable: true,
    "aria-labelledby": "aria",
    key: component.id,
    id: component.id
  }, /* @__PURE__ */ react.createElement(DataListItemRow, {
    "data-testid": "data-list-row"
  }, /* @__PURE__ */ react.createElement(DataListControl, null, /* @__PURE__ */ react.createElement(Tooltip, {
    content: t5("dragInstruction"),
    position: "top"
  }, /* @__PURE__ */ react.createElement(DataListDragButton, {
    className: "kc-row-drag-button",
    "aria-label": "Reorder",
    "aria-describedby": t5("common-help:dragHelp"),
    "aria-pressed": "false"
  }))), /* @__PURE__ */ react.createElement(DataListItemCells, {
    dataListCells: [
      /* @__PURE__ */ react.createElement(DataListCell, {
        "data-testid": "provider-name",
        key: `name-${idx}`
      }, /* @__PURE__ */ react.createElement(Link, {
        key: component.name,
        "data-testid": "provider-name-link",
        to: `${url}/${component.id}/${component.providerId}/settings`
      }, component.name)),
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: `providerId-${idx}`
      }, component.providerId),
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: `providerDescription-${idx}`
      }, component.providerDescription),
      /* @__PURE__ */ react.createElement(DataListAction, {
        "aria-labelledby": "data-list-action",
        "aria-label": "Actions",
        isPlainButtonAction: true,
        key: `data-action-list-${idx}`,
        id: `data-action-list-${idx}`
      }, /* @__PURE__ */ react.createElement(Dropdown, {
        isPlain: true,
        position: DropdownPosition.right,
        isOpen: actionListOpen[idx],
        toggle: /* @__PURE__ */ react.createElement(KebabToggle, {
          "data-testid": "provider-action",
          onToggle: () => {
            toggleActionList(idx);
          }
        }),
        dropdownItems: [
          /* @__PURE__ */ react.createElement(DropdownItem, {
            key: "action",
            component: "button",
            "data-testid": "delete-action",
            onClick: () => {
              setSelectedComponent(component);
              toggleDeleteDialog();
              toggleActionList(idx);
            }
          }, t5("common:delete"))
        ]
      }))
    ]
  }))))), /* @__PURE__ */ react.createElement("div", {
    className: "pf-screen-reader",
    "aria-live": "assertive"
  }, liveText)));
};
var KeysProvidersTab = ({
  keyProviderComponentTypes,
  realmComponents,
  refresh,
  ...props
}) => {
  return /* @__PURE__ */ react.createElement(KeysTabInner, {
    components: realmComponents?.map((component) => {
      const provider = keyProviderComponentTypes.find((componentType) => component.providerId === componentType.id);
      return {
        ...component,
        providerDescription: provider?.helpText
      };
    }),
    keyProviderComponentTypes,
    refresh,
    realmComponents,
    ...props
  });
};

// build/realm-settings/LoginTab.js
var RealmSettingsLoginTab = ({
  save,
  realm: realm2,
  refresh
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const form2 = useForm({mode: "onChange"});
  const updateSwitchValue = (onChange, value, name) => {
    save({...realm2, [name]: value});
    onChange(value);
    refresh();
  };
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(FormPanel, {
    className: "kc-login-screen",
    title: "Login screen customization"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("userRegistration"),
    fieldId: "kc-user-reg",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5("userRegistrationHelpText"),
      fieldLabelId: "realm-settings:userRegistration"
    }),
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "registrationAllowed",
    defaultValue: realm2.registrationAllowed,
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-user-reg-switch",
      "data-testid": "user-reg-switch",
      name: "registrationAllowed",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange: (value2) => {
        updateSwitchValue(onChange, value2, "registrationAllowed");
      }
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("forgotPassword"),
    fieldId: "kc-forgot-pw",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings:forgotPasswordHelpText",
      fieldLabelId: "realm-settings:forgotPassword"
    }),
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "resetPasswordAllowed",
    defaultValue: realm2.resetPasswordAllowed,
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-forgot-pw-switch",
      "data-testid": "forgot-pw-switch",
      name: "resetPasswordAllowed",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange: (value2) => {
        updateSwitchValue(onChange, value2, "resetPasswordAllowed");
      }
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("rememberMe"),
    fieldId: "kc-remember-me",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings:rememberMeHelpText",
      fieldLabelId: "realm-settings:rememberMe"
    }),
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "rememberMe",
    defaultValue: realm2.rememberMe,
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-remember-me-switch",
      "data-testid": "remember-me-switch",
      name: "rememberMe",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange: (value2) => {
        updateSwitchValue(onChange, value2, "rememberMe");
      }
    })
  })))), /* @__PURE__ */ react.createElement(FormPanel, {
    className: "kc-email-settings",
    title: "Email settings"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("emailAsUsername"),
    fieldId: "kc-email-as-username",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings:emailAsUsernameHelpText",
      fieldLabelId: "realm-settings:emailAsUsername"
    }),
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "registrationEmailAsUsername",
    defaultValue: realm2.registrationEmailAsUsername,
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-email-as-username-switch",
      "data-testid": "email-as-username-switch",
      name: "registrationEmailAsUsername",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange: (value2) => {
        updateSwitchValue(onChange, value2, "registrationEmailAsUsername");
      }
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("loginWithEmail"),
    fieldId: "kc-login-with-email",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings:loginWithEmailHelpText",
      fieldLabelId: "realm-settings:loginWithEmail"
    }),
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "loginWithEmailAllowed",
    defaultValue: realm2.loginWithEmailAllowed,
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-login-with-email-switch",
      "data-testid": "login-with-email-switch",
      name: "loginWithEmailAllowed",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange: (value2) => {
        updateSwitchValue(onChange, value2, "loginWithEmailAllowed");
      }
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("duplicateEmails"),
    fieldId: "kc-duplicate-emails",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings:duplicateEmailsHelpText",
      fieldLabelId: "realm-settings:duplicateEmails"
    }),
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "duplicateEmailsAllowed",
    defaultValue: realm2.duplicateEmailsAllowed,
    control: form2.control,
    render: ({onChange}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-duplicate-emails-switch",
      "data-testid": "duplicate-emails-switch",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      name: "duplicateEmailsAllowed",
      isChecked: form2.getValues().duplicateEmailsAllowed && !form2.getValues().loginWithEmailAllowed && !form2.getValues().registrationEmailAsUsername,
      onChange: (value) => {
        updateSwitchValue(onChange, value, "duplicateEmailsAllowed");
      },
      isDisabled: form2.getValues().loginWithEmailAllowed || form2.getValues().registrationEmailAsUsername
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("verifyEmail"),
    fieldId: "kc-verify-email",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings:verifyEmailHelpText",
      fieldLabelId: "realm-settings:verifyEmail"
    }),
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "verifyEmail",
    defaultValue: realm2.verifyEmail,
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-verify-email-switch",
      "data-testid": "verify-email-switch",
      name: "verifyEmail",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange: (value2) => {
        updateSwitchValue(onChange, value2, "verifyEmail");
      }
    })
  })))));
};

// build/realm-settings/security-defences/HelpLinkTextInput.js
var HelpLinkTextInput = ({
  fieldName,
  url
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const {register: register2} = useFormContext();
  const name = fieldName.substr(fieldName.indexOf(".") + 1);
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(name),
    fieldId: name,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: /* @__PURE__ */ react.createElement(Trans, {
        i18nKey: `realm-settings-help:${name}`
      }, "Default value prevents pages from being included", /* @__PURE__ */ react.createElement(FormattedLink, {
        href: url,
        title: t5("common:learnMore")
      })),
      fieldLabelId: name
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: name,
    name: fieldName,
    ref: register2
  }));
};

// build/realm-settings/security-defences/HeadersForm.js
var HeadersForm = ({save, reset: reset2}) => {
  const {t: t5} = useTranslation();
  const {
    formState: {isDirty},
    handleSubmit
  } = useFormContext();
  return /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "keycloak__security-defences__form",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(HelpLinkTextInput, {
    fieldName: "browserSecurityHeaders.xFrameOptions",
    url: "http://tools.ietf.org/html/rfc7034"
  }), /* @__PURE__ */ react.createElement(HelpLinkTextInput, {
    fieldName: "browserSecurityHeaders.contentSecurityPolicy",
    url: "http://www.w3.org/TR/CSP/"
  }), /* @__PURE__ */ react.createElement(HelpLinkTextInput, {
    fieldName: "browserSecurityHeaders.contentSecurityPolicyReportOnly",
    url: "http://www.w3.org/TR/CSP/"
  }), /* @__PURE__ */ react.createElement(HelpLinkTextInput, {
    fieldName: "browserSecurityHeaders.xContentTypeOptions",
    url: "https://www.owasp.org/index.php/List_of_useful_HTTP_headers"
  }), /* @__PURE__ */ react.createElement(HelpLinkTextInput, {
    fieldName: "browserSecurityHeaders.xRobotsTag",
    url: "https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag"
  }), /* @__PURE__ */ react.createElement(HelpLinkTextInput, {
    fieldName: "browserSecurityHeaders.xXSSProtection",
    url: "https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#xxxsp"
  }), /* @__PURE__ */ react.createElement(HelpLinkTextInput, {
    fieldName: "browserSecurityHeaders.strictTransportSecurity",
    url: "https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#hsts"
  }), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    type: "submit",
    "data-testid": "headers-form-tab-save",
    isDisabled: !isDirty
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert"))));
};

// build/realm-settings/security-defences/Time.js
var Time = ({
  name,
  style
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const {control, errors} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormGroup, {
    style,
    label: t5(name),
    fieldId: name,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: `realm-settings-help:${name}`,
      fieldLabelId: `realm-settings:${name}`
    }),
    validated: errors[name] ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(Controller, {
    name,
    defaultValue: "",
    control,
    rules: {required: true},
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      "data-testid": name,
      value,
      onChange,
      validated: errors[name] ? ValidatedOptions.error : ValidatedOptions.default
    })
  }));
};

// build/realm-settings/security-defences/BruteForceDetection.js
var BruteForceDetection = ({
  save,
  reset: reset2
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const {
    handleSubmit,
    control,
    formState: {isDirty}
  } = useFormContext();
  const enable = useWatch({
    control,
    name: "bruteForceProtected"
  });
  const permanentLockout = useWatch({
    control,
    name: "permanentLockout"
  });
  return /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true,
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:enabled"),
    fieldId: "bruteForceProtected",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "bruteForceProtected",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "bruteForceProtected",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("failureFactor"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:failureFactor",
      fieldLabelId: "realm-settings:failureFactor"
    }),
    fieldId: "failureFactor",
    style: enable ? {} : {display: "none"}
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "failureFactor",
    defaultValue: 0,
    control,
    rules: {required: true},
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(NumberInput, {
      type: "text",
      id: "failureFactor",
      value,
      onPlus: () => onChange(value + 1),
      onMinus: () => onChange(value - 1),
      onChange: (event) => onChange(Number(event.target.value))
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("permanentLockout"),
    fieldId: "permanentLockout",
    hasNoPaddingTop: true,
    style: enable ? {} : {display: "none"}
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "permanentLockout",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "permanentLockout",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange
    })
  })), /* @__PURE__ */ react.createElement(Time, {
    name: "waitIncrementSeconds",
    style: enable && !permanentLockout ? {} : {display: "none"}
  }), /* @__PURE__ */ react.createElement(Time, {
    name: "maxFailureWaitSeconds",
    style: enable && !permanentLockout ? {} : {display: "none"}
  }), /* @__PURE__ */ react.createElement(Time, {
    name: "maxDeltaTimeSeconds",
    style: enable && !permanentLockout ? {} : {display: "none"}
  }), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("quickLoginCheckMilliSeconds"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:quickLoginCheckMilliSeconds",
      fieldLabelId: "realm-settings:quickLoginCheckMilliSeconds"
    }),
    fieldId: "quickLoginCheckMilliSeconds",
    style: enable ? {} : {display: "none"}
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "quickLoginCheckMilliSeconds",
    defaultValue: 0,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(NumberInput, {
      type: "text",
      id: "quickLoginCheckMilliSeconds",
      value,
      onPlus: () => onChange(value + 1),
      onMinus: () => onChange(value - 1),
      onChange: (event) => onChange(Number(event.target.value))
    })
  })), /* @__PURE__ */ react.createElement(Time, {
    name: "minimumQuickLoginWaitSeconds",
    style: enable ? {} : {display: "none"}
  }), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    type: "submit",
    "data-testid": "brute-force-tab-save",
    isDisabled: !isDirty
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert"))));
};

// build/realm-settings/security-defences/SecurityDefences.js
var SecurityDefences = ({save, reset: reset2}) => {
  const {t: t5} = useTranslation("realm-settings");
  const [activeTab, setActiveTab] = useState(10);
  return /* @__PURE__ */ react.createElement(Tabs, {
    activeKey: activeTab,
    onSelect: (_23, key) => setActiveTab(key)
  }, /* @__PURE__ */ react.createElement(Tab, {
    id: "headers",
    eventKey: 10,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("headers"))
  }, /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(HeadersForm, {
    save,
    reset: reset2
  }))), /* @__PURE__ */ react.createElement(Tab, {
    id: "bruteForce",
    eventKey: 20,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("bruteForceDetection"))
  }, /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(BruteForceDetection, {
    save,
    reset: reset2
  }))));
};

// build/realm-settings/SessionsTab.js
var RealmSettingsSessionsTab = ({
  realm: realm2,
  save
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const {
    control,
    handleSubmit,
    reset: resetForm,
    formState
  } = useFormContext();
  const offlineSessionMaxEnabled = useWatch({
    control,
    name: "offlineSessionMaxLifespanEnabled"
  });
  const reset2 = () => {
    if (realm2) {
      resetForm(realm2);
    }
  };
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(FormPanel, {
    title: t5("SSOSessionSettings"),
    className: "kc-sso-session-template"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("SSOSessionIdle"),
    fieldId: "SSOSessionIdle",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:ssoSessionIdle",
      fieldLabelId: "realm-settings:SSOSessionIdle"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "ssoSessionIdleTimeout",
    defaultValue: realm2.ssoSessionIdleTimeout,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-sso-session-idle",
      "data-testid": "sso-session-idle-input",
      "aria-label": "sso-session-idle-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("SSOSessionMax"),
    fieldId: "SSOSessionMax",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:ssoSessionMax",
      fieldLabelId: "realm-settings:SSOSessionMax"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "ssoSessionMaxLifespan",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-sso-session-max",
      "data-testid": "sso-session-max-input",
      "aria-label": "sso-session-max-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("SSOSessionIdleRememberMe"),
    fieldId: "SSOSessionIdleRememberMe",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:ssoSessionIdleRememberMe",
      fieldLabelId: "realm-settings:SSOSessionIdleRememberMe"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "ssoSessionIdleTimeoutRememberMe",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-sso-session-idle-remember-me",
      "data-testid": "sso-session-idle-remember-me-input",
      "aria-label": "sso-session-idle-remember-me-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("SSOSessionMaxRememberMe"),
    fieldId: "SSOSessionMaxRememberMe",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:ssoSessionMaxRememberMe",
      fieldLabelId: "realm-settings:SSOSessionMaxRememberMe"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "ssoSessionMaxLifespanRememberMe",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-sso-session-max-remember-me",
      "aria-label": "sso-session-max-remember-me-input",
      "data-testid": "sso-session-max-remember-me-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })))), /* @__PURE__ */ react.createElement(FormPanel, {
    title: t5("clientSessionSettings"),
    className: "kc-client-session-template"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "pf-u-mt-lg",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("clientSessionIdle"),
    fieldId: "clientSessionIdle",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:clientSessionIdle",
      fieldLabelId: "realm-settings:clientSessionIdle"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "clientSessionIdleTimeout",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-client-session-idle",
      "data-testid": "client-session-idle-input",
      "aria-label": "client-session-idle-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("clientSessionMax"),
    fieldId: "clientSessionMax",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:clientSessionMax",
      fieldLabelId: "realm-settings:clientSessionMax"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "clientSessionMaxLifespan",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-client-session-max",
      "data-testid": "client-session-max-input",
      "aria-label": "client-session-max-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })))), /* @__PURE__ */ react.createElement(FormPanel, {
    title: t5("offlineSessionSettings"),
    className: "kc-offline-session-template"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "pf-u-mt-lg",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("offlineSessionIdle"),
    fieldId: "offlineSessionIdle",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:offlineSessionIdle",
      fieldLabelId: "realm-settings:offlineSessionIdle"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "offlineSessionIdleTimeout",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-offline-session-idle",
      "data-testid": "offline-session-idle-input",
      "aria-label": "offline-session-idle-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("offlineSessionMaxLimited"),
    fieldId: "kc-offlineSessionMaxLimited",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:offlineSessionMaxLimited",
      fieldLabelId: "realm-settings:offlineSessionMaxLimited"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "offlineSessionMaxLifespanEnabled",
    control,
    defaultValue: false,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-offline-session-max",
      "data-testid": "offline-session-max-switch",
      "aria-label": "offline-session-max-switch",
      label: t5("common:enabled"),
      labelOff: t5("common:disabled"),
      isChecked: value,
      onChange: (value2) => onChange(value2.toString())
    })
  })), offlineSessionMaxEnabled && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("offlineSessionMax"),
    fieldId: "offlineSessionMax",
    id: "offline-session-max-label",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:offlineSessionMax",
      fieldLabelId: "realm-settings:offlineSessionMax"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "offlineSessionMaxLifespan",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-offline-session-max",
      "data-testid": "offline-session-max-input",
      "aria-label": "offline-session-max-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })))), /* @__PURE__ */ react.createElement(FormPanel, {
    className: "kc-login-settings-template",
    title: t5("loginSettings")
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "pf-u-mt-lg",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("loginTimeout"),
    id: "kc-login-timeout-label",
    fieldId: "offlineSessionIdle",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:loginTimeout",
      fieldLabelId: "realm-settings:loginTimeout"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "accessCodeLifespanLogin",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-login-timeout",
      "data-testid": "login-timeout-input",
      "aria-label": "login-timeout-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("loginActionTimeout"),
    fieldId: "loginActionTimeout",
    id: "login-action-timeout-label",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:loginActionTimeout",
      fieldLabelId: "realm-settings:loginActionTimeout"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "accessCodeLifespanUserAction",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-login-action-timeout",
      "data-testid": "login-action-timeout-input",
      "aria-label": "login-action-timeout-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    type: "submit",
    "data-testid": "sessions-tab-save",
    isDisabled: !formState.isDirty
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert"))))));
};

// build/realm-settings/ThemesTab.js
var RealmSettingsThemesTab = ({
  save,
  reset: reset2
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const [loginThemeOpen, setLoginThemeOpen] = useState(false);
  const [accountThemeOpen, setAccountThemeOpen] = useState(false);
  const [adminConsoleThemeOpen, setAdminConsoleThemeOpen] = useState(false);
  const [emailThemeOpen, setEmailThemeOpen] = useState(false);
  const {control, handleSubmit} = useFormContext();
  const themeTypes = useServerInfo().themes;
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "pf-u-mt-lg",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("loginTheme"),
    fieldId: "kc-login-theme",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:loginTheme",
      fieldLabelId: "realm-settings:loginTheme"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "loginTheme",
    control,
    defaultValue: "",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-login-theme",
      onToggle: () => setLoginThemeOpen(!loginThemeOpen),
      onSelect: (_23, value2) => {
        onChange(value2);
        setLoginThemeOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("loginTheme"),
      isOpen: loginThemeOpen,
      placeholderText: "Select a theme",
      "data-testid": "select-login-theme"
    }, themeTypes.login.map((theme, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: theme.name === value,
      key: `login-theme-${idx}`,
      value: theme.name
    }, t5(`${theme.name}`))))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("accountTheme"),
    fieldId: "kc-account-theme",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:accountTheme",
      fieldLabelId: "realm-settings:accountTheme"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "accountTheme",
    control,
    defaultValue: "",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-account-theme",
      onToggle: () => setAccountThemeOpen(!accountThemeOpen),
      onSelect: (_23, value2) => {
        onChange(value2);
        setAccountThemeOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("accountTheme"),
      isOpen: accountThemeOpen,
      placeholderText: "Select a theme",
      "data-testid": "select-account-theme"
    }, themeTypes.account.map((theme, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: theme.name === value,
      key: `account-theme-${idx}`,
      value: theme.name
    }, t5(`${theme.name}`))))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("adminTheme"),
    fieldId: "kc-admin-console-theme",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:adminConsoleTheme",
      fieldLabelId: "realm-settings:adminTheme"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "adminTheme",
    control,
    defaultValue: "",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-admin-console-theme",
      onToggle: () => setAdminConsoleThemeOpen(!adminConsoleThemeOpen),
      onSelect: (_23, value2) => {
        onChange(value2);
        setAdminConsoleThemeOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("adminConsoleTheme"),
      isOpen: adminConsoleThemeOpen,
      placeholderText: "Select a theme",
      "data-testid": "select-admin-theme"
    }, themeTypes.admin.map((theme, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: theme.name === value,
      key: `admin-theme-${idx}`,
      value: theme.name
    }, t5(`${theme.name}`))))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("emailTheme"),
    fieldId: "kc-email-theme",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:emailTheme",
      fieldLabelId: "realm-settings:emailTheme"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "emailTheme",
    control,
    defaultValue: "",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-email-theme",
      onToggle: () => setEmailThemeOpen(!emailThemeOpen),
      onSelect: (_23, value2) => {
        onChange(value2);
        setEmailThemeOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("emailTheme"),
      isOpen: emailThemeOpen,
      placeholderText: "Select a theme",
      "data-testid": "select-email-theme"
    }, themeTypes.email.map((theme, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: theme.name === value,
      key: `email-theme-${idx}`,
      value: theme.name
    }, t5(`${theme.name}`))))
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    type: "submit",
    "data-testid": "themes-tab-save"
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert")))));
};

// build/realm-settings/TokensTab.js
var RealmSettingsTokensTab = ({
  realm: realm2,
  reset: reset2,
  save
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const serverInfo2 = useServerInfo();
  const [defaultSigAlgDrpdwnIsOpen, setDefaultSigAlgDrpdwnOpen] = useState(false);
  const allComponentTypes = serverInfo2.componentTypes?.["org.keycloak.keys.KeyProvider"] ?? [];
  const esOptions = ["ES256", "ES384", "ES512"];
  const hmacAlgorithmOptions = allComponentTypes[2].properties[4].options;
  const javaKeystoreAlgOptions = allComponentTypes[3].properties[3].options;
  const defaultSigAlgOptions = esOptions.concat(hmacAlgorithmOptions, javaKeystoreAlgOptions);
  const form2 = useFormContext();
  const {control} = form2;
  const offlineSessionMaxEnabled = useWatch({
    control,
    name: "offlineSessionMaxLifespanEnabled",
    defaultValue: realm2.offlineSessionMaxLifespanEnabled
  });
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(FormPanel, {
    title: t5("realm-settings:general"),
    className: "kc-sso-session-template"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    onSubmit: form2.handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("defaultSigAlg"),
    fieldId: "kc-default-signature-algorithm",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:defaultSigAlg",
      fieldLabelId: "realm-settings:algorithm"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "defaultSignatureAlgorithm",
    defaultValue: "RS256",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-default-sig-alg",
      onToggle: () => setDefaultSigAlgDrpdwnOpen(!defaultSigAlgDrpdwnIsOpen),
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setDefaultSigAlgDrpdwnOpen(false);
      },
      selections: [value.toString()],
      variant: SelectVariant.single,
      "aria-label": t5("defaultSigAlg"),
      isOpen: defaultSigAlgDrpdwnIsOpen,
      "data-testid": "select-default-sig-alg"
    }, defaultSigAlgOptions.map((p2, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: p2 === value,
      key: `default-sig-alg-${idx}`,
      value: p2
    })))
  })))), /* @__PURE__ */ react.createElement(FormPanel, {
    title: t5("realm-settings:refreshTokens"),
    className: "kc-client-session-template"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "pf-u-mt-lg",
    onSubmit: form2.handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("revokeRefreshToken"),
    fieldId: "kc-revoke-refresh-token",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:revokeRefreshToken",
      fieldLabelId: "realm-settings:revokeRefreshToken"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "revokeRefreshToken",
    control: form2.control,
    defaultValue: false,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-revoke-refresh-token",
      "data-testid": "revoke-refresh-token-switch",
      "aria-label": "revoke-refresh-token-switch",
      label: t5("common:enabled"),
      labelOff: t5("common:disabled"),
      isChecked: value,
      onChange
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("refreshTokenMaxReuse"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:refreshTokenMaxReuse",
      fieldLabelId: "realm-settings:refreshTokenMaxReuse"
    }),
    fieldId: "refreshTokenMaxReuse"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "refreshTokenMaxReuse",
    defaultValue: 0,
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(NumberInput, {
      type: "text",
      id: "refreshTokenMaxReuseMs",
      value,
      onPlus: () => onChange(value + 1),
      onMinus: () => onChange(value - 1),
      onChange: (event) => onChange(Number(event.target.value))
    })
  })))), /* @__PURE__ */ react.createElement(FormPanel, {
    title: t5("realm-settings:accessTokens"),
    className: "kc-offline-session-template"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "pf-u-mt-lg",
    onSubmit: form2.handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("accessTokenLifespan"),
    fieldId: "accessTokenLifespan",
    helperText: `It is recommended for this value to be shorter than the SSO session idle timeout: ${interpolateTimespan(forHumans(realm2.ssoSessionIdleTimeout))}`,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:accessTokenLifespan",
      fieldLabelId: "realm-settings:accessTokenLifespan"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "accessTokenLifespan",
    defaultValue: "",
    helperTextInvalid: t5("common:required"),
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      validated: value > realm2.ssoSessionIdleTimeout ? "warning" : "default",
      className: "kc-access-token-lifespan",
      "data-testid": "access-token-lifespan-input",
      "aria-label": "access-token-lifespan",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("accessTokenLifespanImplicitFlow"),
    fieldId: "accessTokenLifespanImplicitFlow",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:accessTokenLifespanImplicitFlow",
      fieldLabelId: "realm-settings:accessTokenLifespanImplicitFlow"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "accessTokenLifespanForImplicitFlow",
    defaultValue: "",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-access-token-lifespan-implicit",
      "data-testid": "access-token-lifespan-implicit-input",
      "aria-label": "access-token-lifespan-implicit",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("clientLoginTimeout"),
    fieldId: "clientLoginTimeout",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:clientLoginTimeout",
      fieldLabelId: "realm-settings:clientLoginTimeout"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "accessCodeLifespan",
    defaultValue: "",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-client-login-timeout",
      "data-testid": "client-login-timeout-input",
      "aria-label": "client-login-timeout",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), offlineSessionMaxEnabled && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("offlineSessionMax"),
    fieldId: "offlineSessionMax",
    id: "offline-session-max-label",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:offlineSessionMax",
      fieldLabelId: "realm-settings:offlineSessionMax"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "offlineSessionMaxLifespan",
    defaultValue: "",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-offline-session-max",
      "data-testid": "offline-session-max-input",
      "aria-label": "offline-session-max-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })))), /* @__PURE__ */ react.createElement(FormPanel, {
    className: "kc-login-settings-template",
    title: t5("actionTokens")
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "pf-u-mt-lg",
    onSubmit: form2.handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("userInitiatedActionLifespan"),
    id: "kc-user-initiated-action-lifespan",
    fieldId: "userInitiatedActionLifespan",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:userInitiatedActionLifespan",
      fieldLabelId: "realm-settings:userInitiatedActionLifespan"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "actionTokenGeneratedByUserLifespan",
    defaultValue: "",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-user-initiated-action-lifespan",
      "data-testid": "user-initiated-action-lifespan",
      "aria-label": "user-initiated-action-lifespan",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("defaultAdminInitiated"),
    fieldId: "defaultAdminInitiated",
    id: "default-admin-initiated-label",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:defaultAdminInitiatedActionLifespan",
      fieldLabelId: "realm-settings:defaultAdminInitiated"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "actionTokenGeneratedByAdminLifespan",
    defaultValue: "",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-default-admin-initiated",
      "data-testid": "default-admin-initated-input",
      "aria-label": "default-admin-initated-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(Text, {
    className: "kc-override-action-tokens-subtitle",
    component: TextVariants.h1
  }, t5("overrideActionTokens")), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("emailVerification"),
    fieldId: "emailVerification",
    id: "email-verification"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.actionTokenGeneratedByUserLifespan-verify-email",
    defaultValue: "",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-email-verification",
      "data-testid": "email-verification-input",
      "aria-label": "email-verification-input",
      value,
      onChange: (value2) => onChange(value2.toString()),
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("idpAccountEmailVerification"),
    fieldId: "idpAccountEmailVerification",
    id: "idp-acct-label"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.actionTokenGeneratedByUserLifespan-idp-verify-account-via-email",
    defaultValue: "",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-idp-email-verification",
      "data-testid": "idp-email-verification-input",
      "aria-label": "idp-email-verification",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("forgotPassword"),
    fieldId: "forgotPassword",
    id: "forgot-password-label"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.actionTokenGeneratedByUserLifespan-reset-credentials",
    defaultValue: "",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-forgot-pw",
      "data-testid": "forgot-pw-input",
      "aria-label": "forgot-pw-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("executeActions"),
    fieldId: "executeActions",
    id: "execute-actions"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.actionTokenGeneratedByUserLifespan-execute-actions",
    defaultValue: "",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      className: "kc-execute-actions",
      "data-testid": "execute-actions-input",
      "aria-label": "execute-actions-input",
      value,
      onChange,
      units: ["minutes", "hours", "days"]
    })
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    type: "submit",
    "data-testid": "tokens-tab-save",
    isDisabled: !form2.formState.isDirty
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert"))))));
};

// build/realm-settings/routes/ClientProfile.js
var import_RealmSettingsSection6 = require_RealmSettingsSection();
var ClientProfileRoute = {
  path: "/:realm/realm-settings/clientPolicies/:profileName/edit-profile",
  component: lazy(() => Promise.resolve().then(() => require_ClientProfileForm())),
  breadcrumb: () => import_RealmSettingsSection6.EditProfileCrumb,
  access: ["view-realm", "view-users"]
};
var toClientProfile = (params) => ({
  pathname: generatePath(ClientProfileRoute.path, params)
});

// build/realm-settings/routes/AddExecutor.js
var AddExecutorRoute = {
  path: "/:realm/realm-settings/clientPolicies/:profileName/add-executor",
  component: lazy(() => Promise.resolve().then(() => require_ExecutorForm())),
  breadcrumb: (t5) => t5("realm-settings:addExecutor"),
  access: "manage-realm"
};
var toAddExecutor = (params) => ({
  pathname: generatePath(AddExecutorRoute.path, params)
});

// build/realm-settings/routes/Executor.js
var import_RealmSettingsSection7 = require_RealmSettingsSection();
var ExecutorRoute = {
  path: "/:realm/realm-settings/clientPolicies/:profileName/edit-profile/:executorName",
  component: lazy(() => Promise.resolve().then(() => require_ExecutorForm())),
  breadcrumb: () => import_RealmSettingsSection7.EditExecutorCrumb,
  access: ["manage-realm"]
};
var toExecutor = (params) => ({
  pathname: generatePath(ExecutorRoute.path, params)
});

// build/realm-settings/routes/ClientPolicies.js
var ClientPoliciesRoute = {
  path: "/:realm/realm-settings/clientPolicies",
  component: lazy(() => Promise.resolve().then(() => require_ProfilesTab())),
  breadcrumb: (t5) => t5("realm-settings:allClientPolicies"),
  access: "view-realm"
};
var toClientPolicies = (params) => ({
  pathname: generatePath(ClientPoliciesRoute.path, params)
});

// build/realm-settings/routes/AddClientProfile.js
var AddClientProfileRoute = {
  path: "/:realm/realm-settings/clientPolicies/add-profile",
  component: lazy(() => Promise.resolve().then(() => require_ClientProfileForm())),
  breadcrumb: (t5) => t5("realm-settings:newClientProfile"),
  access: "manage-realm"
};
var toAddClientProfile = (params) => ({
  pathname: generatePath(AddClientProfileRoute.path, params)
});

// build/realm-settings/RealmSettingsTabs.js
var import_ProfilesTab = require_ProfilesTab();

// build/realm-settings/routes/AddClientPolicy.js
var import_RealmSettingsSection9 = require_RealmSettingsSection();

// build/realm-settings/routes/EditClientPolicy.js
var import_RealmSettingsSection8 = require_RealmSettingsSection();
var EditClientPolicyRoute = {
  path: "/:realm/realm-settings/clientPolicies/:policyName/edit-policy",
  component: lazy(() => Promise.resolve().then(() => require_NewClientPolicyForm())),
  access: "manage-realm",
  breadcrumb: () => import_RealmSettingsSection8.EditPolicyCrumb
};
var toEditClientPolicy = (params) => ({
  pathname: generatePath(EditClientPolicyRoute.path, params)
});

// build/clients/scopes/AddScopeDialog.js
var FilterType;
(function(FilterType2) {
  FilterType2["Name"] = "Name";
  FilterType2["Protocol"] = "Protocol";
})(FilterType || (FilterType = {}));
var ProtocolType;
(function(ProtocolType2) {
  ProtocolType2["All"] = "All";
  ProtocolType2["SAML"] = "SAML";
  ProtocolType2["OpenIDConnect"] = "OpenID Connect";
})(ProtocolType || (ProtocolType = {}));
var AddScopeDialog = ({
  clientScopes: clientScopes2,
  clientName,
  open: open2,
  toggleDialog,
  onAdd: onAdd2,
  isClientScopesConditionType
}) => {
  const {t: t5} = useTranslation("clients");
  const [addToggle, setAddToggle] = useState(false);
  const [rows, setRows] = useState([]);
  const [filterType, setFilterType] = useState(FilterType.Name);
  const [protocolType, setProtocolType] = useState(ProtocolType.All);
  const [key, setKey] = useState(0);
  const refresh = () => setKey(key + 1);
  const [isFilterTypeDropdownOpen, toggleIsFilterTypeDropdownOpen] = useToggle();
  const [isProtocolTypeDropdownOpen, toggleIsProtocolTypeDropdownOpen] = useToggle(false);
  useEffect(() => {
    refresh();
  }, [filterType, protocolType]);
  const loader = async () => {
    if (protocolType === ProtocolType.OpenIDConnect) {
      return clientScopes2.filter((item) => item.protocol === "openid-connect");
    } else if (protocolType === ProtocolType.SAML) {
      return clientScopes2.filter((item) => item.protocol === "saml");
    }
    return clientScopes2;
  };
  const action = (scope) => {
    const scopes = rows.map((row) => {
      return {scope: row, type: scope};
    });
    onAdd2(scopes);
    setAddToggle(false);
    toggleDialog();
  };
  const onFilterTypeDropdownSelect = (filterType2) => {
    if (filterType2 === FilterType.Name) {
      setFilterType(FilterType.Protocol);
    } else if (filterType2 === FilterType.Protocol) {
      setFilterType(FilterType.Name);
    }
    toggleIsFilterTypeDropdownOpen();
  };
  const onProtocolTypeDropdownSelect = (protocolType2) => {
    if (protocolType2 === ProtocolType.SAML) {
      setProtocolType(ProtocolType.SAML);
    } else if (protocolType2 === ProtocolType.OpenIDConnect) {
      setProtocolType(ProtocolType.OpenIDConnect);
    } else if (protocolType2 === ProtocolType.All) {
      setProtocolType(ProtocolType.All);
    }
    toggleIsProtocolTypeDropdownOpen();
  };
  const protocolTypeOptions = [
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: 1,
      value: ProtocolType.SAML
    }, t5("protocolTypes.saml")),
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: 2,
      value: ProtocolType.OpenIDConnect
    }, t5("protocolTypes.openIdConnect")),
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: 3,
      value: ProtocolType.All,
      isPlaceholder: true
    }, t5("protocolTypes.all"))
  ];
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.medium,
    title: isClientScopesConditionType ? t5("addClientScope") : t5("addClientScopesTo", {clientName}),
    isOpen: open2,
    onClose: toggleDialog,
    actions: isClientScopesConditionType ? [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-add",
        "data-testid": "modalConfirm",
        key: "add",
        variant: ButtonVariant.primary,
        onClick: () => {
          const scopes = rows.map((scope) => ({scope}));
          onAdd2(scopes);
          toggleDialog();
        }
      }, t5("common:add")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          setRows([]);
          toggleDialog();
        }
      }, t5("common:cancel"))
    ] : [
      /* @__PURE__ */ react.createElement(Dropdown, {
        className: "keycloak__client-scopes-add__add-dropdown",
        id: "add-dropdown",
        key: "add-dropdown",
        direction: DropdownDirection.up,
        isOpen: addToggle,
        toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
          isDisabled: rows.length === 0,
          onToggle: () => setAddToggle(!addToggle),
          isPrimary: true,
          toggleIndicator: CaretUpIcon,
          id: "add-scope-toggle"
        }, t5("common:add")),
        dropdownItems: clientScopeTypesDropdown(t5, action)
      }),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          setRows([]);
          toggleDialog();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    loader,
    ariaLabelKey: "client-scopes:chooseAMapperType",
    searchPlaceholderKey: filterType === FilterType.Name ? "client-scopes:searchFor" : void 0,
    searchTypeComponent: /* @__PURE__ */ react.createElement(Dropdown, {
      onSelect: () => {
        onFilterTypeDropdownSelect(filterType);
      },
      "data-testid": "filter-type-dropdown",
      toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
        id: "toggle-id-9",
        onToggle: toggleIsFilterTypeDropdownOpen,
        toggleIndicator: CaretDownIcon,
        icon: /* @__PURE__ */ react.createElement(FilterIcon, null)
      }, filterType),
      isOpen: isFilterTypeDropdownOpen,
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          "data-testid": "filter-type-dropdown-item",
          key: "filter-type"
        }, filterType === FilterType.Name ? t5("protocol") : t5("common:name"))
      ]
    }),
    key,
    toolbarItem: filterType === FilterType.Protocol && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Dropdown, {
      onSelect: () => {
        onFilterTypeDropdownSelect(filterType);
      },
      "data-testid": "filter-type-dropdown",
      toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
        id: "toggle-id-9",
        onToggle: toggleIsFilterTypeDropdownOpen,
        toggleIndicator: CaretDownIcon,
        icon: /* @__PURE__ */ react.createElement(FilterIcon, null)
      }, filterType),
      isOpen: isFilterTypeDropdownOpen,
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          "data-testid": "filter-type-dropdown-item",
          key: "filter-type"
        }, t5("common:name"))
      ]
    }), /* @__PURE__ */ react.createElement(Select, {
      variant: SelectVariant.single,
      className: "kc-protocolType-select",
      "aria-label": "Select Input",
      onToggle: toggleIsProtocolTypeDropdownOpen,
      onSelect: (_23, value) => onProtocolTypeDropdownSelect(value.toString()),
      selections: protocolType,
      isOpen: isProtocolTypeDropdownOpen,
      direction: SelectDirection.down
    }, protocolTypeOptions)),
    canSelectAll: true,
    onSelect: (rows2) => setRows(rows2),
    columns: [
      {
        name: "name"
      },
      {name: "protocol", displayKey: "Protocol"},
      {
        name: "protocol",
        displayKey: "clients:protocol",
        cellRenderer: (client2) => getProtocolName(t5, client2.protocol ?? "openid-connect")
      },
      {
        name: "description"
      }
    ]
  }));
};

// build/components/dynamic/MultivaluedChipsComponent.js
var MultivaluedChipsComponent = ({
  defaultValue,
  name,
  label: label2,
  helpText
}) => {
  const {t: t5} = useTranslation("dynamic");
  const {control} = useFormContext();
  const {conditionName} = useParams();
  const adminClient = useAdminClient();
  const [open2, setOpen] = useState(false);
  const [clientScopes2, setClientScopes] = useState([]);
  useFetch(() => adminClient.clientScopes.find(), (clientScopes22) => {
    setClientScopes(clientScopes22);
  }, []);
  const toggleModal = () => {
    setOpen(!open2);
  };
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5(helpText),
      fieldLabelId: `dynamic:${label2}`
    }),
    fieldId: name
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: `config.${name}`,
    control,
    defaultValue: [defaultValue],
    rules: {required: true},
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(react.Fragment, null, open2 && name === "scopes" && /* @__PURE__ */ react.createElement(AddScopeDialog, {
      clientScopes: clientScopes2.filter((scope) => !value.includes(scope.name)),
      isClientScopesConditionType: true,
      open: open2,
      toggleDialog: () => setOpen(!open2),
      onAdd: (scopes) => {
        onChange([
          ...value,
          ...scopes.map((scope) => scope.scope).map((item) => item.name)
        ]);
      }
    }), open2 && name === "groups" && /* @__PURE__ */ react.createElement(GroupPickerDialog, {
      type: "selectMany",
      text: {
        title: "users:selectGroups",
        ok: "users:join"
      },
      onConfirm: (groups2) => {
        onChange([...value, ...groups2.map((group) => group.name)]);
        setOpen(false);
      },
      onClose: () => {
        setOpen(false);
      },
      filterGroups: value
    }), value.length === 0 && !conditionName && /* @__PURE__ */ react.createElement(TextInput, {
      type: "text",
      id: "kc-scopes",
      value,
      "data-testid": "client-scope-input",
      name: "config.client-scopes",
      isDisabled: true
    }), /* @__PURE__ */ react.createElement(ChipGroup, {
      className: "kc-client-scopes-chip-group",
      isClosable: true,
      onClick: () => {
        onChange([]);
      }
    }, value.map((currentChip) => /* @__PURE__ */ react.createElement(Chip, {
      key: currentChip,
      onClick: () => {
        onChange(value.filter((item) => item !== currentChip));
      }
    }, currentChip))), /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "select-scope-button",
      variant: "secondary",
      onClick: () => {
        toggleModal();
      }
    }, t5("common:select")))
  }));
};

// build/components/dynamic/MultivaluedRoleComponent.js
var MultivaluedRoleComponent = ({
  name,
  label: label2,
  helpText
}) => {
  const {t: t5} = useTranslation("dynamic");
  const {whoAmI: whoAmI2} = useWhoAmI();
  const fieldName = `config.${name}`;
  const adminClient = useAdminClient();
  const {control} = useFormContext();
  const [clientRoles, setClientRoles] = useState([]);
  const [open2, setOpen] = useState(false);
  useFetch(async () => {
    const clients2 = await adminClient.clients.find();
    const clientRoles2 = await Promise.all(clients2.map(async (client2) => {
      const roles2 = await adminClient.clients.listRoles({id: client2.id});
      return roles2.map((role) => ({
        ...role
      }));
    }));
    return clientRoles2.flat();
  }, (clientRoles2) => {
    setClientRoles(clientRoles2);
  }, []);
  const alphabetizedClientRoles = sortedUniq(clientRoles.map((item) => item.name)).sort((a2, b2) => a2.localeCompare(b2, whoAmI2.getLocale(), {ignorePunctuation: true}));
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5(helpText),
      fieldLabelId: `dynamic:${label2}`
    }),
    fieldId: name
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: fieldName,
    defaultValue: [],
    control,
    rules: {required: true},
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      onToggle: (isExpanded) => setOpen(isExpanded),
      isOpen: open2,
      className: "kc-role-select",
      "data-testid": "multivalued-role-select",
      variant: SelectVariant.typeaheadMulti,
      placeholderText: t5("selectARole"),
      chipGroupProps: {
        numChips: 5,
        expandedText: t5("common:hide"),
        collapsedText: t5("common:showRemaining")
      },
      typeAheadAriaLabel: t5("selectARole"),
      selections: value.map((v2) => v2.value),
      isCreatable: true,
      onSelect: (_23, v2) => {
        const option = v2.toString();
        if (value.map((v22) => v22.value).includes(option)) {
          onChange(value.filter((item) => item.value !== option));
        } else {
          onChange([...value, {value: option}]);
        }
      },
      maxHeight: 200,
      onClear: () => onChange([])
    }, alphabetizedClientRoles.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: option,
      value: option
    })))
  }));
};

// build/realm-settings/routes/AddCondition.js
var NewClientPolicyConditionRoute = {
  path: "/:realm/realm-settings/clientPolicies/:policyName?/edit-policy/create-condition",
  component: lazy(() => Promise.resolve().then(() => require_NewClientPolicyCondition())),
  breadcrumb: (t5) => t5("realm-settings:addCondition"),
  access: "manage-clients"
};
var toNewClientPolicyCondition = (params) => ({
  pathname: generatePath(NewClientPolicyConditionRoute.path, params)
});

// build/realm-settings/routes/EditCondition.js
var import_NewClientPolicyCondition = require_NewClientPolicyCondition();
var EditClientPolicyConditionRoute = {
  path: "/:realm/realm-settings/clientPolicies/:policyName?/edit-policy/:conditionName/edit-condition",
  component: import_NewClientPolicyCondition.default,
  breadcrumb: (t5) => t5("realm-settings:editCondition"),
  access: "manage-clients"
};
var toEditClientPolicyCondition = (params) => ({
  pathname: generatePath(EditClientPolicyConditionRoute.path, params)
});

// build/realm-settings/AddClientProfileModal.js
var AddClientProfileModal = (props) => {
  const {t: t5} = useTranslation("roles");
  const adminClient = useAdminClient();
  const [selectedRows, setSelectedRows] = useState([]);
  const [tableProfiles, setTableProfiles] = useState();
  useFetch(() => adminClient.clientPolicies.listProfiles({
    includeGlobalProfiles: true
  }), (allProfiles) => {
    const globalProfiles = allProfiles.globalProfiles?.map((globalProfiles2) => ({
      ...globalProfiles2,
      global: true
    }));
    const profiles = allProfiles.profiles?.map((profiles2) => ({
      ...profiles2,
      global: false
    }));
    setTableProfiles([...globalProfiles ?? [], ...profiles ?? []]);
  }, []);
  const loader = async () => tableProfiles ?? [];
  if (!tableProfiles) {
    return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
  }
  const AliasRenderer = ({name}) => /* @__PURE__ */ react.createElement(react.Fragment, null, name && /* @__PURE__ */ react.createElement(Label, {
    color: "blue"
  }, name), " ", name);
  return /* @__PURE__ */ react.createElement(Modal, {
    "data-testid": "addClientProfile",
    title: t5("realm-settings:addClientProfile"),
    isOpen: props.open,
    onClose: props.toggleDialog,
    variant: ModalVariant.large,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        key: "add",
        "data-testid": "add-client-profile-button",
        variant: "primary",
        isDisabled: !selectedRows.length,
        onClick: () => {
          props.toggleDialog();
          props.onConfirm(selectedRows);
        }
      }, t5("common:add")),
      /* @__PURE__ */ react.createElement(Button, {
        key: "cancel",
        variant: "link",
        onClick: () => {
          props.toggleDialog();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    loader,
    isRowDisabled: (value) => props.allProfiles.includes(value.name) || false,
    ariaLabelKey: "realm-settings:profilesList",
    searchPlaceholderKey: "realm-settings:searchProfile",
    canSelectAll: true,
    onSelect: (rows) => {
      setSelectedRows([...rows]);
    },
    columns: [
      {
        name: "name",
        displayKey: "realm-settings:clientProfileName",
        cellRenderer: AliasRenderer
      },
      {
        name: "description",
        displayKey: "common:description"
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      hasIcon: true,
      message: t5("noRoles"),
      instructions: t5("noRolesInstructions"),
      primaryActionText: t5("createRole")
    })
  }));
};

// build/realm-settings/routes/AddClientPolicy.js
var AddClientPolicyRoute = {
  path: "/:realm/realm-settings/clientPolicies/add-client-policy",
  component: lazy(() => Promise.resolve().then(() => require_NewClientPolicyForm())),
  breadcrumb: () => import_RealmSettingsSection9.NewPolicyCrumb,
  access: "manage-clients"
};
var toAddClientPolicy = (params) => ({
  pathname: generatePath(AddClientPolicyRoute.path, params)
});

// build/realm-settings/PoliciesTab.js
var PoliciesTab = () => {
  const {t: t5} = useTranslation("realm-settings");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {realm: realm2} = useRealm();
  const history = useHistory();
  const [show2, setShow] = useState(false);
  const [policies, setPolicies] = useState();
  const [selectedPolicy, setSelectedPolicy] = useState();
  const [key, setKey] = useState(0);
  const [code2, setCode] = useState();
  const [tablePolicies, setTablePolicies] = useState();
  const refresh = () => setKey(key + 1);
  const form2 = useForm({mode: "onChange"});
  useFetch(() => adminClient.clientPolicies.listPolicies(), (policies2) => {
    setPolicies(policies2.policies), setTablePolicies(policies2.policies || []), setCode(prettyPrintJSON(policies2.policies));
  }, [key]);
  const loader = async () => policies ?? [];
  const saveStatus = async () => {
    const switchValues = form2.getValues();
    const updatedPolicies = policies?.map((policy) => {
      const enabled = switchValues[policy.name];
      return {
        ...policy,
        enabled
      };
    });
    try {
      await adminClient.clientPolicies.updatePolicy({
        policies: updatedPolicies
      });
      history.push(toClientPolicies({realm: realm2}));
      addAlert(t5("realm-settings:updateClientPolicySuccess"), AlertVariant.success);
    } catch (error2) {
      addError("realm-settings:updateClientPolicyError", error2);
    }
  };
  const ClientPolicyDetailLink = ({name}) => /* @__PURE__ */ react.createElement(Link, {
    to: toEditClientPolicy({realm: realm2, policyName: name})
  }, name);
  const SwitchRenderer = (clientPolicy) => {
    return /* @__PURE__ */ react.createElement(Controller, {
      name: clientPolicy.name,
      "data-testid": `${clientPolicy.name}-switch`,
      defaultValue: clientPolicy.enabled,
      control: form2.control,
      render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
        label: t5("common:enabled"),
        labelOff: t5("common:disabled"),
        isChecked: value,
        onChange: (value2) => {
          onChange(value2);
          saveStatus();
        }
      })
    });
  };
  const save = async () => {
    if (!code2) {
      return;
    }
    try {
      const obj = JSON.parse(code2);
      try {
        await adminClient.clientPolicies.updatePolicy({
          policies: obj
        });
        addAlert(t5("realm-settings:updateClientPoliciesSuccess"), AlertVariant.success);
        refresh();
      } catch (error2) {
        addError("realm-settings:updateClientPoliciesError", error2);
      }
    } catch (error2) {
      console.warn("Invalid json, ignoring value using {}");
      addError("realm-settings:updateClientPoliciesError", error2);
    }
  };
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: t5("deleteClientPolicyConfirmTitle"),
    messageKey: t5("deleteClientPolicyConfirm", {
      policyName: selectedPolicy?.name
    }),
    continueButtonLabel: t5("delete"),
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      const updatedPolicies = policies?.filter((policy) => policy.name !== selectedPolicy?.name);
      try {
        await adminClient.clientPolicies.updatePolicy({
          policies: updatedPolicies
        });
        addAlert(t5("deleteClientPolicySuccess"), AlertVariant.success);
        refresh();
      } catch (error2) {
        addError(t5("deleteClientPolicyError"), error2);
      }
    }
  });
  if (!policies) {
    return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
  }
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(PageSection, null, /* @__PURE__ */ react.createElement(Flex, {
    className: "kc-policies-config-section"
  }, /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Title, {
    headingLevel: "h1",
    size: "md"
  }, t5("policiesConfigType"))), /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Radio, {
    isChecked: !show2,
    name: "policiesView",
    onChange: () => setShow(false),
    label: t5("policiesConfigTypes.formView"),
    id: "formView-policiesView",
    "data-testid": "formView-policiesView",
    className: "kc-form-radio-btn pf-u-mr-sm pf-u-ml-sm"
  })), /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Radio, {
    isChecked: show2,
    name: "policiesView",
    onChange: () => setShow(true),
    label: t5("policiesConfigTypes.jsonEditor"),
    id: "jsonEditor-policiesView",
    "data-testid": "jsonEditor-policiesView",
    className: "kc-editor-radio-btn"
  })))), /* @__PURE__ */ react.createElement(Divider, null), !show2 ? /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key: policies.length,
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      message: t5("realm-settings:noClientPolicies"),
      instructions: t5("realm-settings:noClientPoliciesInstructions"),
      primaryActionText: t5("realm-settings:createClientPolicy"),
      onPrimaryAction: () => history.push(toAddClientPolicy({realm: realm2}))
    }),
    ariaLabelKey: "realm-settings:clientPolicies",
    searchPlaceholderKey: "realm-settings:clientPolicySearch",
    loader,
    toolbarItem: /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      id: "createPolicy",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toAddClientPolicy({realm: realm2})
      }),
      "data-testid": "createPolicy"
    }, t5("createClientPolicy"))),
    actions: [
      {
        title: t5("common:delete"),
        onRowClick: (item) => {
          toggleDeleteDialog();
          setSelectedPolicy(item);
        }
      }
    ],
    columns: [
      {
        name: "name",
        cellRenderer: ClientPolicyDetailLink
      },
      {
        name: "enabled",
        displayKey: "realm-settings:status",
        cellRenderer: SwitchRenderer
      },
      {
        name: "description"
      }
    ]
  }) : /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement("div", {
    className: "pf-u-mt-md pf-u-ml-lg"
  }, /* @__PURE__ */ react.createElement(CodeEditor, {
    isLineNumbersVisible: true,
    isLanguageLabelVisible: true,
    isReadOnly: false,
    code: code2,
    language: Language.json,
    height: "30rem",
    onChange: (value) => {
      setCode(value ?? "");
    }
  })), /* @__PURE__ */ react.createElement("div", {
    className: "pf-u-mt-md"
  }, /* @__PURE__ */ react.createElement(Button, {
    variant: ButtonVariant.primary,
    className: "pf-u-mr-md pf-u-ml-lg",
    "data-testid": "jsonEditor-policies-saveBtn",
    onClick: save
  }, t5("save")), /* @__PURE__ */ react.createElement(Button, {
    variant: ButtonVariant.secondary,
    "data-testid": "jsonEditor-reloadBtn",
    onClick: () => {
      setCode(prettyPrintJSON(tablePolicies));
    }
  }, " ", t5("reload")))));
};

// build/realm-settings/PartialImport.js
var INITIAL_RESOURCES = {
  users: false,
  clients: false,
  groups: false,
  identityProviders: false,
  realmRoles: false,
  clientRoles: false
};
var PartialImportDialog = (props) => {
  const tRealm = useTranslation("realm-settings").t;
  const {t: t5} = useTranslation("partial-import");
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const [importedFile, setImportedFile] = useState();
  const isFileSelected = !!importedFile;
  const [isRealmSelectOpen, setIsRealmSelectOpen] = useState(false);
  const [isCollisionSelectOpen, setIsCollisionSelectOpen] = useState(false);
  const [importInProgress, setImportInProgress] = useState(false);
  const [collisionOption, setCollisionOption] = useState("FAIL");
  const [targetRealm, setTargetRealm] = useState({});
  const [importResponse, setImportResponse] = useState();
  const {addError} = useAlerts();
  const [resourcesToImport, setResourcesToImport] = useState(INITIAL_RESOURCES);
  const isAnyResourceChecked = Object.values(resourcesToImport).some((checked) => checked);
  const resetResourcesToImport = () => {
    setResourcesToImport(INITIAL_RESOURCES);
  };
  const resetInputState = () => {
    setImportedFile(void 0);
    setTargetRealm({});
    setCollisionOption("FAIL");
    resetResourcesToImport();
  };
  useEffect(() => {
    setImportInProgress(false);
    setImportResponse(void 0);
    resetInputState();
  }, [props.open]);
  const handleFileChange = (value) => {
    resetInputState();
    setImportedFile(value);
    if (!Array.isArray(value)) {
      setTargetRealm(value);
    } else if (value.length > 0) {
      setTargetRealm(value[0]);
    }
  };
  const handleRealmSelect = (realm22) => {
    setTargetRealm(realm22);
    setIsRealmSelectOpen(false);
    resetResourcesToImport();
  };
  const handleResourceCheckBox = (checked, event) => {
    const resource2 = event.currentTarget.name;
    setResourcesToImport({
      ...resourcesToImport,
      [resource2]: checked
    });
  };
  const realmSelectOptions = (realms2) => realms2.map((realm22) => /* @__PURE__ */ react.createElement(SelectOption, {
    key: realm22.id,
    value: realm22,
    "data-testid": realm22.id + "-select-option"
  }, realm22.realm || realm22.id));
  const handleCollisionSelect = (event, option) => {
    setCollisionOption(option);
    setIsCollisionSelectOpen(false);
  };
  const collisionOptions = () => {
    return [
      /* @__PURE__ */ react.createElement(SelectOption, {
        key: "fail",
        value: "FAIL"
      }, t5("FAIL")),
      /* @__PURE__ */ react.createElement(SelectOption, {
        key: "skip",
        value: "SKIP"
      }, t5("SKIP")),
      /* @__PURE__ */ react.createElement(SelectOption, {
        key: "overwrite",
        value: "OVERWRITE"
      }, t5("OVERWRITE"))
    ];
  };
  const targetHasResources = () => {
    return targetHasResource("users") || targetHasResource("groups") || targetHasResource("clients") || targetHasResource("identityProviders") || targetHasRealmRoles() || targetHasClientRoles();
  };
  const targetHasResource = (resource2) => {
    const value = targetRealm[resource2];
    return value !== void 0 && value.length > 0;
  };
  const targetHasRealmRoles = () => {
    const value = targetRealm.roles?.realm;
    return value !== void 0 && value.length > 0;
  };
  const targetHasClientRoles = () => {
    const value = targetRealm.roles?.client;
    return value !== void 0 && Object.keys(value).length > 0;
  };
  const itemCount = (resource2) => {
    if (!isFileSelected)
      return 0;
    if (resource2 === "realmRoles") {
      return targetRealm.roles?.realm?.length ?? 0;
    }
    if (resource2 === "clientRoles") {
      return targetHasClientRoles() ? clientRolesCount(targetRealm.roles.client) : 0;
    }
    return targetRealm[resource2]?.length ?? 0;
  };
  const clientRolesCount = (clientRoles) => Object.values(clientRoles).reduce((total, role) => total + role.length, 0);
  const resourceDataListItem = (resource2, resourceDisplayName) => {
    return /* @__PURE__ */ react.createElement(DataListItem, {
      "aria-labelledby": `${resource2}-list-item`
    }, /* @__PURE__ */ react.createElement(DataListItemRow, null, /* @__PURE__ */ react.createElement(DataListItemCells, {
      dataListCells: [
        /* @__PURE__ */ react.createElement(DataListCell, {
          key: resource2
        }, /* @__PURE__ */ react.createElement(Checkbox, {
          id: `${resource2}-checkbox`,
          label: `${itemCount(resource2)} ${resourceDisplayName}`,
          "aria-labelledby": `${resource2}-checkbox`,
          name: resource2,
          isChecked: resourcesToImport[resource2],
          onChange: handleResourceCheckBox,
          "data-testid": resource2 + "-checkbox"
        }))
      ]
    })));
  };
  const jsonForImport = () => {
    const jsonToImport = {
      ifResourceExists: collisionOption,
      id: targetRealm.id,
      realm: targetRealm.realm
    };
    if (resourcesToImport["users"])
      jsonToImport.users = targetRealm.users;
    if (resourcesToImport["groups"])
      jsonToImport.groups = targetRealm.groups;
    if (resourcesToImport["identityProviders"])
      jsonToImport.identityProviders = targetRealm.identityProviders;
    if (resourcesToImport["clients"])
      jsonToImport.clients = targetRealm.clients;
    if (resourcesToImport["realmRoles"] || resourcesToImport["clientRoles"]) {
      jsonToImport.roles = targetRealm.roles;
      if (!resourcesToImport["realmRoles"])
        delete jsonToImport.roles?.realm;
      if (!resourcesToImport["clientRoles"])
        delete jsonToImport.roles?.client;
    }
    return jsonToImport;
  };
  async function doImport() {
    if (importInProgress)
      return;
    setImportInProgress(true);
    try {
      const importResults = await adminClient.realms.partialImport({
        realm: realm2,
        rep: jsonForImport()
      });
      setImportResponse(importResults);
    } catch (error2) {
      addError("partial-import:importFail", error2);
    }
    setImportInProgress(false);
  }
  const importModal = () => {
    return /* @__PURE__ */ react.createElement(Modal, {
      variant: ModalVariant.medium,
      title: tRealm("partialImport"),
      isOpen: props.open,
      onClose: props.toggleDialog,
      actions: [
        /* @__PURE__ */ react.createElement(Button, {
          id: "modal-import",
          "data-testid": "import-button",
          key: "import",
          isDisabled: !isAnyResourceChecked,
          onClick: () => {
            doImport();
          }
        }, t5("import")),
        /* @__PURE__ */ react.createElement(Button, {
          id: "modal-cancel",
          "data-testid": "cancel-button",
          key: "cancel",
          variant: ButtonVariant.link,
          onClick: () => {
            props.toggleDialog();
          }
        }, t5("common:cancel"))
      ]
    }, /* @__PURE__ */ react.createElement(Stack, {
      hasGutter: true
    }, /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, null, t5("partialImportHeaderText")))), /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(JsonFileUpload, {
      id: "partial-import-file",
      allowEditingUploadedText: true,
      onChange: handleFileChange
    })), isFileSelected && targetHasResources() && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(Divider, null)), Array.isArray(importedFile) && importedFile.length > 1 && /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(Text, null, t5("selectRealm"), ":"), /* @__PURE__ */ react.createElement(Select, {
      toggleId: "realm-selector",
      isOpen: isRealmSelectOpen,
      onToggle: () => setIsRealmSelectOpen(!isRealmSelectOpen),
      onSelect: (_23, value) => handleRealmSelect(value),
      placeholderText: targetRealm.realm || targetRealm.id
    }, realmSelectOptions(importedFile))), /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(Text, null, t5("chooseResources"), ":"), /* @__PURE__ */ react.createElement(DataList, {
      "aria-label": t5("resourcesToImport"),
      isCompact: true
    }, targetHasResource("users") && resourceDataListItem("users", t5("common:users")), targetHasResource("groups") && resourceDataListItem("groups", t5("common:groups")), targetHasResource("clients") && resourceDataListItem("clients", t5("common:clients")), targetHasResource("identityProviders") && resourceDataListItem("identityProviders", t5("common:identityProviders")), targetHasRealmRoles() && resourceDataListItem("realmRoles", t5("common:realmRoles")), targetHasClientRoles() && resourceDataListItem("clientRoles", t5("common:clientRoles")))), /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(Text, null, t5("selectIfResourceExists"), ":"), /* @__PURE__ */ react.createElement(Select, {
      isOpen: isCollisionSelectOpen,
      direction: "up",
      onToggle: () => {
        setIsCollisionSelectOpen(!isCollisionSelectOpen);
      },
      onSelect: handleCollisionSelect,
      placeholderText: t5(collisionOption)
    }, collisionOptions())))));
  };
  const importCompleteMessage = () => {
    return `${t5("importAdded", {
      count: importResponse?.added
    })}  ${t5("importSkipped", {
      count: importResponse?.skipped
    })} ${t5("importOverwritten", {
      count: importResponse?.overwritten
    })}`;
  };
  const loader = async (first2 = 0, max2 = 15) => {
    if (!importResponse) {
      return [];
    }
    const last2 = Math.min(first2 + max2, importResponse.results.length);
    return importResponse.results.slice(first2, last2);
  };
  const ActionLabel = (importRecord) => {
    switch (importRecord.action) {
      case "ADDED":
        return /* @__PURE__ */ react.createElement(Label, {
          key: importRecord.id,
          color: "green"
        }, t5("added"));
      case "SKIPPED":
        return /* @__PURE__ */ react.createElement(Label, {
          key: importRecord.id,
          color: "orange"
        }, t5("skipped"));
      case "OVERWRITTEN":
        return /* @__PURE__ */ react.createElement(Label, {
          key: importRecord.id,
          color: "purple"
        }, t5("overwritten"));
    }
  };
  const TypeRenderer = (importRecord) => {
    const typeMap = new Map([
      ["CLIENT", t5("common:clients")],
      ["REALM_ROLE", t5("common:realmRoles")],
      ["USER", t5("common:users")],
      ["CLIENT_ROLE", t5("common:clientRoles")],
      ["IDP", t5("common:identityProviders")]
    ]);
    return /* @__PURE__ */ react.createElement("span", null, typeMap.get(importRecord.resourceType));
  };
  const importCompletedModal = () => {
    return /* @__PURE__ */ react.createElement(Modal, {
      variant: ModalVariant.medium,
      title: tRealm("partialImport"),
      isOpen: props.open,
      onClose: props.toggleDialog,
      actions: [
        /* @__PURE__ */ react.createElement(Button, {
          id: "modal-close",
          "data-testid": "close-button",
          key: "close",
          variant: ButtonVariant.primary,
          onClick: () => {
            props.toggleDialog();
          }
        }, t5("common:close"))
      ]
    }, /* @__PURE__ */ react.createElement(Alert, {
      variant: "success",
      isInline: true,
      title: importCompleteMessage()
    }), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
      loader,
      isPaginated: true,
      ariaLabelKey: "realm-settings:partialImport",
      columns: [
        {
          name: "action",
          displayKey: "common:action",
          cellRenderer: ActionLabel
        },
        {
          name: "resourceType",
          displayKey: "common:type",
          cellRenderer: TypeRenderer
        },
        {
          name: "resourceName",
          displayKey: "common:name"
        },
        {
          name: "id",
          displayKey: "common:id"
        }
      ]
    }));
  };
  if (!importResponse) {
    return importModal();
  }
  return importCompletedModal();
};

// build/realm-settings/PartialExport.js
var PartialExportDialog = ({
  isOpen,
  onClose
}) => {
  const {t: t5} = useTranslation();
  const {realm: realm2} = useRealm();
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [exportGroupsAndRoles, setExportGroupsAndRoles] = useState(false);
  const [exportClients, setExportClients] = useState(false);
  const [isExporting, setIsExporting] = useState(false);
  const showWarning = exportGroupsAndRoles || exportClients;
  async function exportRealm() {
    setIsExporting(true);
    try {
      const realmExport = await adminClient.realms.export({
        realm: realm2,
        exportClients,
        exportGroupsAndRoles
      });
      file_saver_default.saveAs(new Blob([prettyPrintJSON(realmExport)], {
        type: "application/json"
      }), "realm-export.json");
      addAlert(t5("partial-export:exportSuccess"), AlertVariant.success);
      onClose();
    } catch (error2) {
      addError("partial-export:exportFail", error2);
    }
    setIsExporting(false);
  }
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    title: t5("realm-settings:partialExport"),
    isOpen,
    onClose,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        key: "export",
        "data-testid": "export-button",
        isDisabled: isExporting,
        onClick: exportRealm
      }, t5("common:export")),
      /* @__PURE__ */ react.createElement(Button, {
        key: "cancel",
        "data-testid": "cancel-button",
        variant: ButtonVariant.link,
        onClick: onClose
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(Stack, {
    hasGutter: true
  }, /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, null, t5("partial-export:partialExportHeaderText")))), /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(Checkbox, {
    id: "include-groups-and-roles-check",
    label: t5("partial-export:includeGroupsAndRoles"),
    isChecked: exportGroupsAndRoles,
    onChange: setExportGroupsAndRoles
  })), /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(Checkbox, {
    id: "include-clients-check",
    label: t5("partial-export:includeClients"),
    isChecked: exportClients,
    onChange: setExportClients
  })), showWarning && /* @__PURE__ */ react.createElement(StackItem, null, /* @__PURE__ */ react.createElement(Alert, {
    "data-testid": "warning-message",
    variant: "warning",
    title: t5("partial-export:exportWarningTitle"),
    isInline: true
  }, t5("partial-export:exportWarningDescription")))));
};

// build/realm-settings/AddMessageBundleModal.js
var AddMessageBundleModal = ({
  handleModalToggle,
  save
}) => {
  const {t: t5} = useTranslation("groups");
  const {register: register2, errors, handleSubmit} = useForm();
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    title: t5("realm-settings:addMessageBundle"),
    isOpen: true,
    onClose: handleModalToggle,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "add-bundle-confirm-button",
        key: "confirm",
        variant: "primary",
        type: "submit",
        form: "bundle-form"
      }, t5("common:create")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          handleModalToggle();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(Form, {
    id: "bundle-form",
    isHorizontal: true,
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("realm-settings:key"),
    name: "key",
    fieldId: "email-id",
    helperTextInvalid: t5("users:emailInvalid"),
    validated: errors.email ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    "data-testid": "key-input",
    ref: register2({required: true}),
    autoFocus: true,
    type: "text",
    id: "add-key",
    name: "key",
    validated: errors.email ? ValidatedOptions.error : ValidatedOptions.default
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("realm-settings:value"),
    name: "add-value",
    fieldId: "value-id",
    helperTextInvalid: t5("users:emailInvalid"),
    validated: errors.email ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    "data-testid": "value-input",
    ref: register2({required: true}),
    autoFocus: true,
    type: "text",
    id: "add-value",
    name: "value",
    validated: errors.email ? ValidatedOptions.error : ValidatedOptions.default
  }))));
};

// build/realm-settings/LocalizationTab.js
var LocalizationTab = ({
  save,
  reset: reset2,
  realm: realm2
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const adminClient = useAdminClient();
  const [addMessageBundleModalOpen, setAddMessageBundleModalOpen] = useState(false);
  const [supportedLocalesOpen, setSupportedLocalesOpen] = useState(false);
  const [defaultLocaleOpen, setDefaultLocaleOpen] = useState(false);
  const [filterDropdownOpen, setFilterDropdownOpen] = useState(false);
  const [selectMenuLocale, setSelectMenuLocale] = useState(DEFAULT_LOCALE);
  const {getValues, control, handleSubmit, formState} = useFormContext();
  const [selectMenuValueSelected, setSelectMenuValueSelected] = useState(false);
  const themeTypes = useServerInfo().themes;
  const bundleForm = useForm({mode: "onChange"});
  const {addAlert, addError} = useAlerts();
  const {realm: currentRealm} = useRealm();
  const watchSupportedLocales = useWatch({
    control,
    name: "supportedLocales"
  });
  const internationalizationEnabled = useWatch({
    control,
    name: "internationalizationEnabled",
    defaultValue: false
  });
  const loader = async () => {
    try {
      const result = await adminClient.realms.getRealmLocalizationTexts({
        realm: realm2.realm,
        selectedLocale: selectMenuLocale || getValues("defaultLocale") || DEFAULT_LOCALE
      });
      return Object.entries(result);
    } catch (error2) {
      return [];
    }
  };
  const tableLoader = async () => {
    try {
      const result = await adminClient.realms.getRealmLocalizationTexts({
        realm: currentRealm,
        selectedLocale: selectMenuLocale
      });
      return Object.entries(result);
    } catch (error2) {
      return [];
    }
  };
  const handleModalToggle = () => {
    setAddMessageBundleModalOpen(!addMessageBundleModalOpen);
  };
  const options = [
    /* @__PURE__ */ react.createElement(SelectGroup, {
      label: t5("defaultLocale"),
      key: "group1"
    }, watchSupportedLocales?.filter((item) => item === realm2.defaultLocale).map((locale) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: locale,
      value: locale
    }, t5(`allSupportedLocales.${locale}`)))),
    /* @__PURE__ */ react.createElement(Divider, {
      key: "divider"
    }),
    /* @__PURE__ */ react.createElement(SelectGroup, {
      label: t5("supportedLocales"),
      key: "group2"
    }, watchSupportedLocales?.filter((item) => item !== realm2.defaultLocale).map((locale) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: locale,
      value: locale
    }, t5(`allSupportedLocales.${locale}`))))
  ];
  const [tableKey, setTableKey] = useState(0);
  const refreshTable = () => {
    setTableKey(new Date().getTime());
  };
  const addKeyValue = async (pair) => {
    try {
      adminClient.setConfig({
        requestConfig: {headers: {"Content-Type": "text/plain"}}
      });
      await adminClient.realms.addLocalization({
        realm: currentRealm,
        selectedLocale: selectMenuLocale || getValues("defaultLocale") || DEFAULT_LOCALE,
        key: pair.key
      }, pair.value);
      adminClient.setConfig({
        realmName: currentRealm
      });
      refreshTable();
      addAlert(t5("pairCreatedSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("realm-settings:pairCreatedError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, addMessageBundleModalOpen && /* @__PURE__ */ react.createElement(AddMessageBundleModal, {
    handleModalToggle,
    save: (pair) => {
      addKeyValue(pair);
      handleModalToggle();
    },
    form: bundleForm
  }), /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-realm",
    className: "pf-u-mt-lg",
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("internationalization"),
    fieldId: "kc-internationalization",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings-help:internationalization",
      fieldLabelId: "realm-settings:internationalization"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "internationalizationEnabled",
    control,
    defaultValue: false,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-l-internationalization",
      label: t5("common:enabled"),
      labelOff: t5("common:disabled"),
      isChecked: internationalizationEnabled,
      "data-testid": value ? "internationalization-enabled" : "internationalization-disabled",
      onChange
    })
  })), internationalizationEnabled && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("supportedLocales"),
    fieldId: "kc-l-supported-locales"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "supportedLocales",
    control,
    defaultValue: [DEFAULT_LOCALE],
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-l-supported-locales",
      onToggle: (open2) => {
        setSupportedLocalesOpen(open2);
      },
      onSelect: (_23, v2) => {
        const option = v2;
        if (value.includes(option)) {
          onChange(value.filter((item) => item !== option || option === DEFAULT_LOCALE));
        } else {
          onChange([...value, option]);
        }
      },
      onClear: () => {
        onChange([]);
      },
      selections: value,
      variant: SelectVariant.typeaheadMulti,
      "aria-label": t5("supportedLocales"),
      isOpen: supportedLocalesOpen,
      placeholderText: t5("selectLocales")
    }, themeTypes.login[0].locales.map((locale, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: value.includes(locale),
      key: `locale-${idx}`,
      value: locale
    }, t5(`allSupportedLocales.${locale}`))))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("defaultLocale"),
    fieldId: "kc-l-default-locale"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "defaultLocale",
    control,
    defaultValue: DEFAULT_LOCALE,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-default-locale",
      onToggle: () => setDefaultLocaleOpen(!defaultLocaleOpen),
      onSelect: (_23, value2) => {
        onChange(value2);
        setDefaultLocaleOpen(false);
      },
      selections: value ? t5(`allSupportedLocales.${value}`) : realm2.defaultLocale !== "" ? t5(`allSupportedLocales.${realm2.defaultLocale || DEFAULT_LOCALE}`) : t5("placeholderText"),
      variant: SelectVariant.single,
      "aria-label": t5("defaultLocale"),
      isOpen: defaultLocaleOpen,
      placeholderText: t5("placeholderText"),
      "data-testid": "select-default-locale"
    }, watchSupportedLocales?.map((locale, idx) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: `default-locale-${idx}`,
      value: locale
    }, t5(`allSupportedLocales.${locale}`))))
  }))), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    isDisabled: !formState.isDirty,
    type: "submit",
    "data-testid": "localization-tab-save"
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert")))), /* @__PURE__ */ react.createElement(FormPanel, {
    className: "kc-message-bundles",
    title: "Edit message bundles"
  }, /* @__PURE__ */ react.createElement(TextContent, {
    className: "messageBundleDescription"
  }, t5("messageBundleDescription")), /* @__PURE__ */ react.createElement("div", {
    className: "tableBorder"
  }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key: tableKey,
    loader: selectMenuValueSelected ? tableLoader : loader,
    ariaLabelKey: "realm-settings:localization",
    searchTypeComponent: /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Select, {
      width: 180,
      "data-testid": "filter-by-locale-select",
      isOpen: filterDropdownOpen,
      className: "kc-filter-by-locale-select",
      variant: SelectVariant.single,
      isDisabled: !formState.isSubmitSuccessful,
      onToggle: (isExpanded) => setFilterDropdownOpen(isExpanded),
      onSelect: (_23, value) => {
        setSelectMenuLocale(value.toString());
        setSelectMenuValueSelected(true);
        refreshTable();
        setFilterDropdownOpen(false);
      },
      selections: selectMenuValueSelected ? t5(`allSupportedLocales.${selectMenuLocale}`) : realm2.defaultLocale !== "" ? t5(`allSupportedLocales.${DEFAULT_LOCALE}`) : t5("placeholderText")
    }, options)),
    toolbarItem: /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "add-bundle-button",
      isDisabled: !formState.isSubmitSuccessful,
      onClick: () => setAddMessageBundleModalOpen(true)
    }, t5("addMessageBundle")),
    searchPlaceholderKey: " ",
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      hasIcon: true,
      message: t5("noMessageBundles"),
      instructions: t5("noMessageBundlesInstructions"),
      onPrimaryAction: handleModalToggle,
      primaryActionText: t5("addMessageBundle")
    }),
    canSelectAll: true,
    columns: [
      {
        name: "Key",
        cellRenderer: (row) => row[0]
      },
      {
        name: "Value",
        cellRenderer: (row) => row[1]
      }
    ]
  })))));
};

// build/realm-settings/UserRegistration.js
var UserRegistration = () => {
  const {t: t5} = useTranslation("realm-settings");
  const [realm2, setRealm] = useState();
  const [activeTab, setActiveTab] = useState(10);
  const [key, setKey] = useState(0);
  const adminClient = useAdminClient();
  const {realm: realmName} = useRealm();
  useFetch(() => adminClient.realms.findOne({realm: realmName}), setRealm, []);
  if (!realm2) {
    return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
  }
  return /* @__PURE__ */ react.createElement(Tabs, {
    key,
    activeKey: activeTab,
    onSelect: (_23, key2) => setActiveTab(key2)
  }, /* @__PURE__ */ react.createElement(Tab, {
    id: "roles",
    eventKey: 10,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("defaultRoles"))
  }, /* @__PURE__ */ react.createElement(AssociatedRolesTab, {
    parentRole: {...realm2.defaultRole, attributes: []},
    refresh: () => setKey(key + 1)
  })), /* @__PURE__ */ react.createElement(Tab, {
    id: "groups",
    eventKey: 20,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("defaultGroups"))
  }, /* @__PURE__ */ react.createElement("h1", null, "Work in progress")));
};

// build/realm-settings/UserProfileTab.js
var UserProfileTab = () => {
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const {t: t5} = useTranslation("realm-settings");
  const {addAlert, addError} = useAlerts();
  const [activeTab, setActiveTab] = useState("attributes");
  const [profiles, setProfiles] = useState();
  const [isSaving, setIsSaving] = useState(false);
  const [refreshCount, setRefreshCount] = useState(0);
  useFetch(() => adminClient.clientPolicies.listProfiles({
    includeGlobalProfiles: true,
    realm: realm2
  }), (profiles2) => setProfiles(profiles2), [refreshCount]);
  async function onSave(updatedProfiles) {
    setIsSaving(true);
    try {
      await adminClient.clientPolicies.createProfiles({
        ...updatedProfiles,
        realm: realm2
      });
      setRefreshCount(refreshCount + 1);
      addAlert(t5("userProfileSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("realm-settings:userProfileError", error2);
    }
    setIsSaving(false);
  }
  return /* @__PURE__ */ react.createElement(Tabs, {
    activeKey: activeTab,
    onSelect: (_23, key) => setActiveTab(key.toString()),
    mountOnEnter: true
  }, /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "attributes",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("attributes"))
  }), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "attributesGroup",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("attributesGroup"))
  }), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "jsonEditor",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("jsonEditor"))
  }, /* @__PURE__ */ react.createElement(JsonEditorTab, {
    profiles,
    onSave,
    isSaving
  })));
};
var JsonEditorTab = ({profiles, onSave, isSaving}) => {
  const {t: t5} = useTranslation();
  const {addError} = useAlerts();
  const [editor2, setEditor] = useState();
  useEffect(() => resetCode(), [profiles, editor2]);
  function resetCode() {
    editor2?.setValue(profiles ? prettyPrintJSON(profiles) : "");
  }
  function save() {
    const value = editor2?.getValue();
    if (!value) {
      return;
    }
    try {
      onSave(JSON.parse(value));
    } catch (error2) {
      addError("realm-settings:invalidJsonError", error2);
      return;
    }
  }
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(CodeEditor, {
    language: Language.json,
    height: "30rem",
    onEditorDidMount: (editor22) => setEditor(editor22),
    isLanguageLabelVisible: true
  }), /* @__PURE__ */ react.createElement(Form, null, /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    onClick: save,
    isDisabled: isSaving
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: resetCode,
    isDisabled: isSaving
  }, t5("common:revert")))));
};

// build/realm-settings/RealmSettingsTabs.js
var RealmSettingsHeader = ({
  save,
  onChange,
  value,
  realmName,
  refresh
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const adminClient = useAdminClient();
  const {refresh: refreshRealms} = useRealms();
  const {addAlert, addError} = useAlerts();
  const history = useHistory();
  const [partialImportOpen, setPartialImportOpen] = useState(false);
  const [partialExportOpen, setPartialExportOpen] = useState(false);
  const [toggleDisableDialog, DisableConfirm] = useConfirmDialog({
    titleKey: "realm-settings:disableConfirmTitle",
    messageKey: "realm-settings:disableConfirm",
    continueButtonLabel: "common:disable",
    onConfirm: () => {
      onChange(!value);
      save();
    }
  });
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: "realm-settings:deleteConfirmTitle",
    messageKey: "realm-settings:deleteConfirm",
    continueButtonLabel: "common:delete",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        await adminClient.realms.del({realm: realmName});
        addAlert(t5("deletedSuccess"), AlertVariant.success);
        await refreshRealms();
        history.push(toDashboard({realm: environment_default.masterRealm}));
        refresh();
      } catch (error2) {
        addError("realm-settings:deleteError", error2);
      }
    }
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DisableConfirm, null), /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(PartialImportDialog, {
    open: partialImportOpen,
    toggleDialog: () => setPartialImportOpen(!partialImportOpen)
  }), /* @__PURE__ */ react.createElement(PartialExportDialog, {
    isOpen: partialExportOpen,
    onClose: () => setPartialExportOpen(false)
  }), /* @__PURE__ */ react.createElement(ViewHeader, {
    titleKey: toUpperCase(realmName),
    divider: false,
    dropdownItems: [
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "import",
        "data-testid": "openPartialImportModal",
        onClick: () => {
          setPartialImportOpen(true);
        }
      }, t5("partialImport")),
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "export",
        "data-testid": "openPartialExportModal",
        onClick: () => setPartialExportOpen(true)
      }, t5("partialExport")),
      /* @__PURE__ */ react.createElement(DropdownSeparator, {
        key: "separator"
      }),
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: "delete",
        onClick: toggleDeleteDialog
      }, t5("common:delete"))
    ],
    isEnabled: value,
    onToggle: (value2) => {
      if (!value2) {
        toggleDisableDialog();
      } else {
        onChange(value2);
        save();
      }
    }
  }));
};
var RealmSettingsTabs = ({
  realm: realm2,
  realmComponents,
  refresh
}) => {
  const {t: t5} = useTranslation("realm-settings");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {realm: realmName} = useRealm();
  const {refresh: refreshRealms} = useRealms();
  const history = useHistory();
  const kpComponentTypes = useServerInfo().componentTypes?.[KEY_PROVIDER_TYPE] ?? [];
  const form2 = useForm({mode: "onChange", shouldUnregister: false});
  const {control, getValues, setValue, reset: resetForm} = form2;
  const [activeTab, setActiveTab] = useState(0);
  const [key, setKey] = useState(0);
  const refreshHeader = () => {
    setKey(new Date().getTime());
  };
  const setupForm = (r3 = realm2) => {
    convertToFormValues(r3, setValue);
    resetForm(getValues());
  };
  useEffect(() => {
    setupForm();
  }, []);
  const save = async (realm22) => {
    try {
      realm22 = convertFormValuesToObject(realm22);
      await adminClient.realms.update({realm: realmName}, {
        ...realm22,
        id: realmName
      });
      setupForm(realm22);
      const isRealmRenamed = realmName !== realm22.realm;
      if (isRealmRenamed) {
        await refreshRealms();
        history.push(toRealmSettings({realm: realm22.realm}));
      }
      addAlert(t5("saveSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("realm-settings:saveError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Controller, {
    name: "enabled",
    defaultValue: true,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(RealmSettingsHeader, {
      value,
      onChange,
      realmName,
      refresh: refreshHeader,
      save: () => save(getValues())
    })
  }), /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light",
    className: "pf-u-p-0"
  }, /* @__PURE__ */ react.createElement(FormProvider, {
    ...form2
  }, /* @__PURE__ */ react.createElement(KeycloakTabs, {
    isBox: true
  }, /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "general",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("general")),
    "data-testid": "rs-general-tab",
    "aria-label": "general-tab"
  }, /* @__PURE__ */ react.createElement(RealmSettingsGeneralTab, {
    save,
    reset: () => resetForm(realm2)
  })), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "login",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("login")),
    "data-testid": "rs-login-tab",
    "aria-label": "login-tab"
  }, /* @__PURE__ */ react.createElement(RealmSettingsLoginTab, {
    refresh,
    save,
    realm: realm2
  })), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "email",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("email")),
    "data-testid": "rs-email-tab",
    "aria-label": "email-tab"
  }, /* @__PURE__ */ react.createElement(RealmSettingsEmailTab, {
    realm: realm2
  })), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "themes",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("themes")),
    "data-testid": "rs-themes-tab",
    "aria-label": "themes-tab"
  }, /* @__PURE__ */ react.createElement(RealmSettingsThemesTab, {
    save,
    reset: () => resetForm(realm2)
  })), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "keys",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("realm-settings:keys")),
    "data-testid": "rs-keys-tab",
    "aria-label": "keys-tab"
  }, /* @__PURE__ */ react.createElement(Tabs, {
    activeKey: activeTab,
    onSelect: (_23, key2) => setActiveTab(Number(key2))
  }, /* @__PURE__ */ react.createElement(Tab, {
    id: "keysList",
    eventKey: 0,
    "data-testid": "rs-keys-list-tab",
    "aria-label": "keys-list-subtab",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("keysList"))
  }, /* @__PURE__ */ react.createElement(KeysListTab, {
    realmComponents
  })), /* @__PURE__ */ react.createElement(Tab, {
    id: "providers",
    "data-testid": "rs-providers-tab",
    "aria-label": "rs-providers-tab",
    eventKey: 1,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("providers"))
  }, /* @__PURE__ */ react.createElement(KeysProvidersTab, {
    realmComponents,
    keyProviderComponentTypes: kpComponentTypes,
    refresh
  })))), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "events",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("events")),
    "data-testid": "rs-realm-events-tab",
    "aria-label": "realm-events-tab"
  }, /* @__PURE__ */ react.createElement(EventsTab, null)), /* @__PURE__ */ react.createElement(Tab, {
    id: "localization",
    eventKey: "localization",
    "data-testid": "rs-localization-tab",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("localization"))
  }, /* @__PURE__ */ react.createElement(LocalizationTab, {
    key,
    refresh,
    save,
    reset: () => resetForm(realm2),
    realm: realm2
  })), /* @__PURE__ */ react.createElement(Tab, {
    id: "securityDefences",
    eventKey: "securityDefences",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("securityDefences"))
  }, /* @__PURE__ */ react.createElement(SecurityDefences, {
    save,
    reset: () => resetForm(realm2)
  })), /* @__PURE__ */ react.createElement(Tab, {
    id: "sessions",
    eventKey: "sessions",
    "data-testid": "rs-sessions-tab",
    "aria-label": "sessions-tab",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("realm-settings:sessions"))
  }, /* @__PURE__ */ react.createElement(RealmSettingsSessionsTab, {
    key,
    realm: realm2,
    save
  })), /* @__PURE__ */ react.createElement(Tab, {
    id: "tokens",
    eventKey: "tokens",
    "data-testid": "rs-tokens-tab",
    "aria-label": "tokens-tab",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("realm-settings:tokens"))
  }, /* @__PURE__ */ react.createElement(RealmSettingsTokensTab, {
    save,
    realm: realm2,
    reset: () => resetForm(realm2)
  })), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "clientPolicies",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("realm-settings:clientPolicies")),
    "data-testid": "rs-clientPolicies-tab",
    "aria-label": t5("clientPoliciesTab")
  }, /* @__PURE__ */ react.createElement(Tabs, {
    activeKey: activeTab,
    onSelect: (_23, key2) => setActiveTab(Number(key2))
  }, /* @__PURE__ */ react.createElement(Tab, {
    id: "profiles",
    eventKey: 0,
    "data-testid": "rs-policies-clientProfiles-tab",
    "aria-label": t5("clientProfilesSubTab"),
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("profiles"), /* @__PURE__ */ react.createElement("span", {
      className: "kc-help-text"
    }, /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings:clientPoliciesProfilesHelpText",
      fieldLabelId: "realm-settings:clientPoliciesProfiles"
    })))
  }, /* @__PURE__ */ react.createElement(import_ProfilesTab.default, null)), /* @__PURE__ */ react.createElement(Tab, {
    id: "policies",
    "data-testid": "rs-policies-clientPolicies-tab",
    "aria-label": t5("clientPoliciesSubTab"),
    eventKey: 1,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("policies"), /* @__PURE__ */ react.createElement("span", {
      className: "kc-help-text"
    }, /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "realm-settings:clientPoliciesPoliciesHelpText",
      fieldLabelId: "realm-settings:clientPoliciesPolicies"
    })))
  }, /* @__PURE__ */ react.createElement(PoliciesTab, null)))), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "userProfile",
    "data-testid": "rs-user-profile-tab",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("realm-settings:userProfile"))
  }, /* @__PURE__ */ react.createElement(UserProfileTab, null)), /* @__PURE__ */ react.createElement(Tab, {
    eventKey: "userRegistration",
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("userRegistration")),
    "data-testid": "rs-userRegistration-tab",
    "aria-label": t5("userRegistrationTab")
  }, /* @__PURE__ */ react.createElement(UserRegistration, null))))));
};

// build/realm-settings/routes/RealmSettings.js
var RealmSettingsRoute = {
  path: "/:realm/realm-settings/:tab?",
  component: lazy(() => Promise.resolve().then(() => require_RealmSettingsSection())),
  breadcrumb: (t5) => t5("realmSettings"),
  access: "view-realm"
};
var toRealmSettings = (params) => ({
  pathname: generatePath(RealmSettingsRoute.path, params)
});

// build/realm-roles/routes/RealmRole.js
var RealmRoleRoute = {
  path: "/:realm/roles/:id/:tab?",
  component: lazy(() => Promise.resolve().then(() => require_RealmRoleTabs())),
  breadcrumb: (t5) => t5("roles:roleDetails"),
  access: ["view-realm", "view-users"]
};
var toRealmRole = (params) => ({
  pathname: generatePath(RealmRoleRoute.path, params)
});

// build/realm-roles/AssociatedRolesTab.js
var AssociatedRolesTab = ({
  parentRole,
  refresh: refreshParent
}) => {
  const {t: t5} = useTranslation("roles");
  const history = useHistory();
  const {addAlert, addError} = useAlerts();
  const {id: id3, realm: realm2} = useParams();
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const [selectedRows, setSelectedRows] = useState([]);
  const [isInheritedHidden, setIsInheritedHidden] = useState(false);
  const [count, setCount] = useState(0);
  const [open2, setOpen] = useState(false);
  const adminClient = useAdminClient();
  const clientRoleRouteMatch = useRouteMatch(ClientRoleRoute.path);
  const realmSettingsMatch = useRouteMatch(RealmSettingsRoute.path);
  const subRoles = async (result, roles2) => {
    const promises = roles2.map(async (r3) => {
      if (result.find((o) => o.id === r3.id))
        return result;
      result.push(r3);
      if (r3.composite) {
        const subList = await adminClient.roles.getCompositeRoles({
          id: r3.id
        });
        subList.map((o) => o.inherited = r3.name);
        result.concat(await subRoles(result, subList));
      }
      return result;
    });
    await Promise.all(promises);
    return [...result];
  };
  const loader = async (first2, max2, search2) => {
    const compositeRoles = await adminClient.roles.getCompositeRoles({
      id: parentRole.id,
      first: first2,
      max: max2,
      search: search2
    });
    setCount(compositeRoles.length);
    if (!isInheritedHidden) {
      const children2 = await subRoles([], compositeRoles);
      compositeRoles.splice(0, compositeRoles.length);
      compositeRoles.push(...children2);
    }
    await Promise.all(compositeRoles.map(async (role) => {
      if (role.clientRole) {
        role.containerId = (await adminClient.clients.findOne({
          id: role.containerId
        }))?.clientId;
      }
    }));
    return compositeRoles;
  };
  const toRolesTab = (tab = "associated-roles") => {
    const to = clientRoleRouteMatch ? toClientRole({...clientRoleRouteMatch.params, tab}) : !realmSettingsMatch ? toRealmRole({
      realm: realm2,
      id: id3,
      tab
    }) : void 0;
    if (to)
      history.push(to);
  };
  const AliasRenderer = ({id: id22, name, clientRole, containerId}) => {
    return /* @__PURE__ */ react.createElement(react.Fragment, null, clientRole && /* @__PURE__ */ react.createElement(Label, {
      color: "blue",
      key: `label-${id22}`
    }, containerId), " ", name);
  };
  const toggleModal = () => {
    setOpen(!open2);
  };
  const reload = () => {
    if (selectedRows.length >= count) {
      refreshParent();
      toRolesTab("details");
    } else {
      refresh();
    }
  };
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: "roles:roleRemoveAssociatedRoleConfirm",
    messageKey: t5("roles:roleRemoveAssociatedText", {
      role: selectedRows.map((r3) => r3.name),
      roleName: parentRole.name
    }),
    continueButtonLabel: "common:remove",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        await adminClient.roles.delCompositeRoles({id: parentRole.id}, selectedRows);
        reload();
        setSelectedRows([]);
        addAlert(t5("associatedRolesRemoved"), AlertVariant.success);
      } catch (error2) {
        addError("roles:roleDeleteError", error2);
      }
    }
  });
  const [toggleDeleteAssociatedRolesDialog, DeleteAssociatedRolesConfirm] = useConfirmDialog({
    titleKey: t5("roles:removeAssociatedRoles") + "?",
    messageKey: t5("roles:removeAllAssociatedRolesConfirmDialog", {
      name: parentRole.name || t5("createRole")
    }),
    continueButtonLabel: "common:remove",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        await adminClient.roles.delCompositeRoles({id: parentRole.id}, selectedRows);
        addAlert(t5("associatedRolesRemoved"), AlertVariant.success);
        reload();
      } catch (error2) {
        addError("roles:roleDeleteError", error2);
      }
    }
  });
  const addComposites = async (composites) => {
    const compositeArray = composites;
    try {
      await adminClient.roles.createComposite({roleId: parentRole.id, realm: realm2}, compositeArray);
      toRolesTab();
      refresh();
      addAlert(t5("addAssociatedRolesSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("roles:addAssociatedRolesError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light",
    padding: {default: "noPadding"}
  }, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(DeleteAssociatedRolesConfirm, null), open2 && /* @__PURE__ */ react.createElement(AssociatedRolesModal, {
    id: parentRole.id,
    toggleDialog: toggleModal,
    onConfirm: addComposites
  }), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key,
    loader,
    ariaLabelKey: "roles:roleList",
    searchPlaceholderKey: "roles:searchFor",
    canSelectAll: true,
    isPaginated: isInheritedHidden,
    onSelect: (rows) => {
      setSelectedRows([
        ...rows.map((r3) => {
          delete r3.inherited;
          return r3;
        })
      ]);
    },
    toolbarItem: /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Checkbox, {
      label: "Hide inherited roles",
      key: "associated-roles-check",
      id: "kc-hide-inherited-roles-checkbox",
      onChange: () => {
        setIsInheritedHidden(!isInheritedHidden);
        refresh();
      },
      isChecked: isInheritedHidden
    })), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      key: "add-role-button",
      onClick: () => toggleModal(),
      "data-testid": "add-role-button"
    }, t5("addRole"))), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      isDisabled: selectedRows.length === 0,
      key: "remove-role-button",
      onClick: () => {
        toggleDeleteAssociatedRolesDialog();
      }
    }, t5("removeRoles")))),
    actions: [
      {
        title: t5("common:remove"),
        onRowClick: (role) => {
          setSelectedRows([role]);
          toggleDeleteDialog();
        }
      }
    ],
    columns: [
      {
        name: "name",
        displayKey: "roles:roleName",
        cellRenderer: AliasRenderer,
        cellFormatters: [emptyFormatter()]
      },
      {
        name: "inherited",
        displayKey: "roles:inheritedFrom",
        cellFormatters: [emptyFormatter()]
      },
      {
        name: "description",
        displayKey: "common:description",
        cellFormatters: [emptyFormatter()]
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      hasIcon: true,
      message: t5("noRolesAssociated"),
      instructions: t5("noRolesAssociatedInstructions"),
      primaryActionText: t5("addRole"),
      onPrimaryAction: () => setOpen(true)
    })
  }));
};

// build/realm-roles/UsersInRoleTab.js
var UsersInRoleTab = () => {
  const history = useHistory();
  const {realm: realm2} = useRealm();
  const {t: t5} = useTranslation("roles");
  const {id: id3, clientId} = useParams();
  const adminClient = useAdminClient();
  const loader = async (first2, max2) => {
    const role = await adminClient.roles.findOneById({id: id3});
    if (!role) {
      throw new Error(t5("common:notFound"));
    }
    if (role.clientRole) {
      return adminClient.clients.findUsersWithRole({
        roleName: role.name,
        id: clientId,
        first: first2,
        max: max2
      });
    }
    return adminClient.roles.findUsersWithRole({
      name: role.name,
      first: first2,
      max: max2
    });
  };
  const {enabled} = useHelp();
  return /* @__PURE__ */ react.createElement(PageSection, {
    "data-testid": "users-page",
    variant: "light"
  }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    isPaginated: true,
    loader,
    ariaLabelKey: "roles:roleList",
    searchPlaceholderKey: "",
    toolbarItem: enabled && /* @__PURE__ */ react.createElement(Popover, {
      "aria-label": "Basic popover",
      position: "bottom",
      bodyContent: /* @__PURE__ */ react.createElement("div", null, t5("roles:whoWillAppearPopoverText"), /* @__PURE__ */ react.createElement(Button, {
        className: "kc-groups-link",
        variant: "link",
        onClick: () => history.push(`/${realm2}/groups`)
      }, t5("common:groups")), t5("or"), /* @__PURE__ */ react.createElement(Button, {
        className: "kc-users-link",
        variant: "link",
        onClick: () => history.push(`/${realm2}/users`)
      }, t5("users"), ".")),
      footerContent: t5("roles:whoWillAppearPopoverFooterText")
    }, /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      className: "kc-who-will-appear-button",
      key: "who-will-appear-button",
      icon: /* @__PURE__ */ react.createElement(QuestionCircleIcon, null)
    }, t5("roles:whoWillAppearLinkText"))),
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      hasIcon: true,
      message: t5("noDirectUsers"),
      instructions: /* @__PURE__ */ react.createElement("div", null, t5("noUsersEmptyStateDescription"), /* @__PURE__ */ react.createElement(Button, {
        className: "kc-groups-link-empty-state",
        variant: "link",
        onClick: () => history.push(`/${realm2}/groups`)
      }, t5("common:groups")), t5("or"), /* @__PURE__ */ react.createElement(Button, {
        className: "kc-users-link-empty-state",
        variant: "link",
        onClick: () => history.push(`/${realm2}/users`)
      }, t5("users")), t5("noUsersEmptyStateDescriptionContinued"))
    }),
    columns: [
      {
        name: "username",
        displayKey: "roles:userName",
        cellFormatters: [emptyFormatter()]
      },
      {
        name: "email",
        displayKey: "roles:email",
        cellFormatters: [emptyFormatter()]
      },
      {
        name: "lastName",
        displayKey: "roles:lastName",
        cellFormatters: [emptyFormatter()]
      },
      {
        name: "firstName",
        displayKey: "roles:firstName",
        cellFormatters: [upperCaseFormatter(), emptyFormatter()]
      }
    ]
  }));
};

// build/realm-roles/routes/ClientRole.js
var ClientRoleRoute = {
  path: "/:realm/clients/:clientId/roles/:id/:tab?",
  component: lazy(() => Promise.resolve().then(() => require_RealmRoleTabs())),
  breadcrumb: (t5) => t5("roles:roleDetails"),
  access: "view-realm"
};
var toClientRole = (params) => ({
  pathname: generatePath(ClientRoleRoute.path, params)
});

// build/realm-roles/RolesList.js
var RoleLink = ({children: children2, role}) => {
  const {realm: realm2} = useRealm();
  const clientRouteMatch = useRouteMatch(ClientRoute.path);
  const to = clientRouteMatch ? toClientRole({...clientRouteMatch.params, id: role.id, tab: "details"}) : toRealmRole({realm: realm2, id: role.id, tab: "details"});
  return /* @__PURE__ */ react.createElement(Link, {
    to
  }, children2);
};
var RolesList = ({
  loader,
  paginated = true,
  parentRoleId,
  messageBundle = "roles"
}) => {
  const {t: t5} = useTranslation(messageBundle);
  const history = useHistory();
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {url} = useRouteMatch();
  const {realm: realmName} = useRealm();
  const [realm2, setRealm] = useState();
  const [selectedRole, setSelectedRole] = useState();
  useFetch(() => adminClient.realms.findOne({realm: realmName}), (realm22) => {
    setRealm(realm22);
  }, []);
  const RoleDetailLink = (role) => role.name !== realm2?.defaultRole?.name ? /* @__PURE__ */ react.createElement(RoleLink, {
    role
  }, role.name) : /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Link, {
    to: toRealmSettings({realm: realmName, tab: "userRegistration"})
  }, role.name, " "), /* @__PURE__ */ react.createElement(HelpItem, {
    helpText: `${messageBundle}:defaultRole`,
    fieldLabelId: "defaultRole"
  }));
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: "roles:roleDeleteConfirm",
    messageKey: t5("roles:roleDeleteConfirmDialog", {
      selectedRoleName: selectedRole ? selectedRole.name : ""
    }),
    continueButtonLabel: "common:delete",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        if (!parentRoleId) {
          await adminClient.roles.delById({
            id: selectedRole.id
          });
        } else {
          await adminClient.roles.delCompositeRoles({id: parentRoleId}, [
            selectedRole
          ]);
        }
        setSelectedRole(void 0);
        addAlert(t5("roleDeletedSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("roles:roleDeleteError", error2);
      }
    }
  });
  const goToCreate = () => history.push(`${url}/add-role`);
  if (!realm2) {
    return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
  }
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key: selectedRole ? selectedRole.id : "roleList",
    loader,
    ariaLabelKey: "roles:roleList",
    searchPlaceholderKey: "roles:searchFor",
    isPaginated: paginated,
    toolbarItem: /* @__PURE__ */ react.createElement(Button, {
      onClick: goToCreate
    }, t5("createRole")),
    actions: [
      {
        title: t5("common:delete"),
        onRowClick: (role) => {
          setSelectedRole(role);
          if (role.name === realm2.defaultRole.name) {
            addAlert(t5("defaultRoleDeleteError"), AlertVariant.danger);
          } else
            toggleDeleteDialog();
        }
      }
    ],
    columns: [
      {
        name: "name",
        displayKey: "roles:roleName",
        cellRenderer: RoleDetailLink
      },
      {
        name: "composite",
        displayKey: "roles:composite",
        cellFormatters: [upperCaseFormatter(), emptyFormatter()]
      },
      {
        name: "description",
        displayKey: "common:description",
        cellFormatters: [emptyFormatter()]
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      hasIcon: true,
      message: t5("noRoles"),
      instructions: t5("noRolesInstructions"),
      primaryActionText: t5("createRole"),
      onPrimaryAction: goToCreate
    })
  }));
};

// build/clients/AdvancedTab.js
var import_moment = __toModule(require_moment());

// build/components/scroll-form/ScrollPanel.js
var ScrollPanel = (props) => {
  const {title: title3, children: children2, scrollId, ...rest} = props;
  return /* @__PURE__ */ react.createElement("section", {
    ...rest,
    className: "kc-form-panel__panel"
  }, /* @__PURE__ */ react.createElement(Title, {
    headingLevel: "h1",
    size: "xl",
    className: "kc-form-panel__title",
    id: scrollId,
    tabIndex: 0
  }, title3), children2);
};

// build/components/scroll-form/ScrollForm.js
var spacesToHyphens = (string2) => {
  return string2.replace(/\s+/g, "-");
};
var ScrollForm = ({
  sections,
  borders = false,
  children: children2,
  ...rest
}) => {
  const {t: t5} = useTranslation("common");
  const nodes = Children.toArray(children2);
  return /* @__PURE__ */ react.createElement(Grid, {
    hasGutter: true,
    ...rest
  }, /* @__PURE__ */ react.createElement(GridItem, {
    span: 8
  }, sections.map((cat, index3) => {
    const scrollId = spacesToHyphens(cat.toLowerCase());
    return /* @__PURE__ */ react.createElement(Fragment, {
      key: cat
    }, !borders && /* @__PURE__ */ react.createElement(ScrollPanel, {
      scrollId,
      title: cat
    }, nodes[index3]), borders && /* @__PURE__ */ react.createElement(FormPanel, {
      scrollId,
      title: cat,
      className: "kc-form-panel__panel"
    }, nodes[index3]));
  })), /* @__PURE__ */ react.createElement(GridItem, {
    span: 4
  }, /* @__PURE__ */ react.createElement(PageSection, {
    className: "kc-scroll-form--sticky"
  }, /* @__PURE__ */ react.createElement(JumpLinks, {
    isVertical: true,
    scrollableSelector: `#${mainPageContentId}`,
    label: t5("jumpToSection"),
    offset: 100
  }, sections.map((cat) => {
    const scrollId = spacesToHyphens(cat.toLowerCase());
    return /* @__PURE__ */ react.createElement(JumpLinksItem, {
      key: cat,
      href: `#${scrollId}`,
      "data-testid": `jump-link-${scrollId}`
    }, cat);
  })))));
};

// build/clients/advanced/AddHostDialog.js
var AddHostDialog = ({
  clientId: id3,
  isOpen,
  onAdded,
  onClose
}) => {
  const {t: t5} = useTranslation("clients");
  const {register: register2, getValues} = useForm();
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  return /* @__PURE__ */ react.createElement(Modal, {
    title: t5("addNode"),
    isOpen,
    onClose,
    variant: "small",
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        id: "add-node-confirm",
        key: "confirm",
        onClick: async () => {
          try {
            const node = getValues("node");
            await adminClient.clients.addClusterNode({
              id: id3,
              node
            });
            onAdded(node);
            addAlert(t5("addedNodeSuccess"), AlertVariant.success);
          } catch (error2) {
            addError("clients:addedNodeFail", error2);
          }
          onClose();
        }
      }, t5("common:save")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "add-node-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => onClose()
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("nodeHost"),
    fieldId: "nodeHost"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    id: "nodeHost",
    ref: register2,
    name: "node"
  }))));
};

// build/clients/advanced/TokenLifespan.js
var never = "tokenLifespan.never";
var expires = "tokenLifespan.expires";
var TokenLifespan = ({
  id: id3,
  name,
  defaultValue,
  control,
  units
}) => {
  const {t: t5} = useTranslation("clients");
  const [open2, setOpen] = useState(false);
  const [focused, setFocused] = useState(false);
  const onFocus = () => setFocused(true);
  const onBlur = () => setFocused(false);
  const isExpireSet = (value) => typeof value === "number" && value !== -1 || focused;
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(id3),
    fieldId: id3,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: `clients-help:${id3}`,
      fieldLabelId: `clients:${id3}`
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name,
    defaultValue,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Split, {
      hasGutter: true
    }, /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(Select, {
      variant: SelectVariant.single,
      onToggle: setOpen,
      isOpen: open2,
      onSelect: (_23, value2) => {
        onChange(value2);
        setOpen(false);
      },
      selections: [isExpireSet(value) ? t5(expires) : t5(never)]
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      value: -1
    }, t5(never)), /* @__PURE__ */ react.createElement(SelectOption, {
      value: 60
    }, t5(expires)))), /* @__PURE__ */ react.createElement(SplitItem, null, isExpireSet(value) && /* @__PURE__ */ react.createElement(TimeSelector, {
      units,
      value,
      onChange,
      onFocus,
      onBlur,
      min: 1
    })))
  }));
};

// build/clients/advanced/AdvancedSettings.js
var AdvancedSettings = ({
  control,
  save,
  reset: reset2,
  protocol
}) => {
  const {t: t5} = useTranslation("clients");
  const [open2, setOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true
  }, protocol !== "openid-connect" && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("assertionLifespan"),
    fieldId: "assertionLifespan",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:assertionLifespan",
      fieldLabelId: "clients:assertionLifespan"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.saml.assertion.lifespan",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      units: ["minutes", "days", "hours"],
      value,
      onChange
    })
  })), protocol === "openid-connect" && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(TokenLifespan, {
    id: "accessTokenLifespan",
    name: "attributes.access.token.lifespan",
    defaultValue: "",
    units: ["minutes", "days", "hours"],
    control
  }), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("oAuthMutual"),
    fieldId: "oAuthMutual",
    hasNoPaddingTop: true,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:oAuthMutual",
      fieldLabelId: "clients:oAuthMutual"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.tls-client-certificate-bound-access-tokens",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "oAuthMutual-switch",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value === "true",
      onChange: (value2) => onChange("" + value2)
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("keyForCodeExchange"),
    fieldId: "keyForCodeExchange",
    hasNoPaddingTop: true,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:keyForCodeExchange",
      fieldLabelId: "clients:keyForCodeExchange"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.pkce.code.challenge.method",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "keyForCodeExchange",
      variant: SelectVariant.single,
      onToggle: setOpen,
      isOpen: open2,
      onSelect: (_23, value2) => {
        onChange(value2);
        setOpen(false);
      },
      selections: [value || t5("common:choose")]
    }, ["", "S256", "plain"].map((v2) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: v2,
      value: v2
    }, v2 || t5("common:choose"))))
  }))), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    onClick: save
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert"))));
};

// build/clients/advanced/AuthenticationOverrides.js
var AuthenticationOverrides = ({
  protocol,
  control,
  save,
  reset: reset2
}) => {
  const adminClient = useAdminClient();
  const {t: t5} = useTranslation("clients");
  const [flows, setFlows] = useState([]);
  const [browserFlowOpen, setBrowserFlowOpen] = useState(false);
  const [directGrantOpen, setDirectGrantOpen] = useState(false);
  useFetch(() => adminClient.authenticationManagement.getFlows(), (flows2) => {
    let filteredFlows = [
      ...flows2.filter((flow) => flow.providerId !== "client-flow")
    ];
    filteredFlows = lodash.sortBy(filteredFlows, [(f2) => f2.alias]);
    setFlows([
      /* @__PURE__ */ react.createElement(SelectOption, {
        key: "empty",
        value: ""
      }, t5("common:choose")),
      ...filteredFlows.map((flow) => /* @__PURE__ */ react.createElement(SelectOption, {
        key: flow.id,
        value: flow.id
      }, flow.alias))
    ]);
  }, []);
  return /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-clients",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("browserFlow"),
    fieldId: "browserFlow",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:browserFlow",
      fieldLabelId: "clients:browserFlow"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "authenticationFlowBindingOverrides.browser",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "browserFlow",
      variant: SelectVariant.single,
      onToggle: setBrowserFlowOpen,
      isOpen: browserFlowOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setBrowserFlowOpen(false);
      },
      selections: [value]
    }, flows)
  })), protocol === "openid-connect" && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("directGrant"),
    fieldId: "directGrant",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:directGrant",
      fieldLabelId: "clients:directGrant"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "authenticationFlowBindingOverrides.direct_grant",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "directGrant",
      variant: SelectVariant.single,
      onToggle: setDirectGrantOpen,
      isOpen: directGrantOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setDirectGrantOpen(false);
      },
      selections: [value]
    }, flows)
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    onClick: save
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert"))));
};

// build/clients/advanced/FineGrainOpenIdConnect.js
var FineGrainOpenIdConnect = ({
  control,
  save,
  reset: reset2
}) => {
  const {t: t5} = useTranslation("clients");
  const providers = useServerInfo().providers;
  const clientSignatureProviders = providers?.clientSignature.providers;
  const contentEncryptionProviders = providers?.contentencryption.providers;
  const cekManagementProviders = providers?.cekmanagement.providers;
  const signatureProviders = providers?.signature.providers;
  const [accessTokenOpen, setAccessTokenOpen] = useState(false);
  const [idTokenOpen, setIdTokenOpen] = useState(false);
  const [idTokenKeyManagementOpen, setIdTokenKeyManagementOpen] = useState(false);
  const [idTokenContentOpen, setIdTokenContentOpen] = useState(false);
  const [userInfoSignedResponseOpen, setUserInfoSignedResponseOpen] = useState(false);
  const [requestObjectSignatureOpen, setRequestObjectSignatureOpen] = useState(false);
  const [requestObjectRequiredOpen, setRequestObjectRequiredOpen] = useState(false);
  const keyOptions = [
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: "empty",
      value: ""
    }, t5("common:choose")),
    ...sortProviders(clientSignatureProviders).map((p2) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: p2,
      value: p2
    }))
  ];
  const cekManagementOptions = [
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: "empty",
      value: ""
    }, t5("common:choose")),
    ...sortProviders(cekManagementProviders).map((p2) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: p2,
      value: p2
    }))
  ];
  const signatureOptions = [
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: "unsigned",
      value: ""
    }, t5("unsigned")),
    ...sortProviders(signatureProviders).map((p2) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: p2,
      value: p2
    }))
  ];
  const contentOptions = [
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: "empty",
      value: ""
    }, t5("common:choose")),
    ...sortProviders(contentEncryptionProviders).map((p2) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: p2,
      value: p2
    }))
  ];
  const requestObjectOptions = [
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: "any",
      value: "any"
    }, t5("common:any")),
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: "none",
      value: "none"
    }, t5("common:none")),
    ...sortProviders(clientSignatureProviders).map((p2) => /* @__PURE__ */ react.createElement(SelectOption, {
      key: p2,
      value: p2
    }))
  ];
  const requestObjectRequiredOptions = [
    "not required",
    "request or request_uri",
    "request only",
    "request_uri only"
  ].map((p2) => /* @__PURE__ */ react.createElement(SelectOption, {
    key: p2,
    value: p2
  }, t5(`requestObject.${p2}`)));
  return /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-clients",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("accessTokenSignatureAlgorithm"),
    fieldId: "accessTokenSignatureAlgorithm",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:accessTokenSignatureAlgorithm",
      fieldLabelId: "clients:accessTokenSignatureAlgorithm"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.access.token.signed.response.alg",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "accessTokenSignatureAlgorithm",
      variant: SelectVariant.single,
      onToggle: setAccessTokenOpen,
      isOpen: accessTokenOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setAccessTokenOpen(false);
      },
      selections: value
    }, keyOptions)
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("idTokenSignatureAlgorithm"),
    fieldId: "kc-id-token-signature",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:idTokenSignatureAlgorithm",
      fieldLabelId: "clients:idTokenSignatureAlgorithm"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.id.token.signed.response.alg",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "idTokenSignatureAlgorithm",
      variant: SelectVariant.single,
      onToggle: setIdTokenOpen,
      isOpen: idTokenOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setIdTokenOpen(false);
      },
      selections: value
    }, keyOptions)
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("idTokenEncryptionKeyManagementAlgorithm"),
    fieldId: "idTokenEncryptionKeyManagementAlgorithm",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:idTokenEncryptionKeyManagementAlgorithm",
      fieldLabelId: "clients:idTokenEncryptionKeyManagementAlgorithm"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.id.token.encrypted.response.alg",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "idTokenEncryptionKeyManagementAlgorithm",
      variant: SelectVariant.single,
      onToggle: setIdTokenKeyManagementOpen,
      isOpen: idTokenKeyManagementOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setIdTokenKeyManagementOpen(false);
      },
      selections: value
    }, cekManagementOptions)
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("idTokenEncryptionContentEncryptionAlgorithm"),
    fieldId: "idTokenEncryptionContentEncryptionAlgorithm",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:idTokenEncryptionContentEncryptionAlgorithm",
      fieldLabelId: "clients:idTokenEncryptionContentEncryptionAlgorithm"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.id.token.encrypted.response.enc",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "idTokenEncryptionContentEncryptionAlgorithm",
      variant: SelectVariant.single,
      onToggle: setIdTokenContentOpen,
      isOpen: idTokenContentOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setIdTokenContentOpen(false);
      },
      selections: value
    }, contentOptions)
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("userInfoSignedResponseAlgorithm"),
    fieldId: "userInfoSignedResponseAlgorithm",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:userInfoSignedResponseAlgorithm",
      fieldLabelId: "clients:userInfoSignedResponseAlgorithm"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.user.info.response.signature.alg",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "userInfoSignedResponseAlgorithm",
      variant: SelectVariant.single,
      onToggle: setUserInfoSignedResponseOpen,
      isOpen: userInfoSignedResponseOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setUserInfoSignedResponseOpen(false);
      },
      selections: value
    }, signatureOptions)
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("requestObjectSignatureAlgorithm"),
    fieldId: "requestObjectSignatureAlgorithm",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:requestObjectSignatureAlgorithm",
      fieldLabelId: "clients:requestObjectSignatureAlgorithm"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.request_object_signature_alg",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "requestObjectSignatureAlgorithm",
      variant: SelectVariant.single,
      onToggle: setRequestObjectSignatureOpen,
      isOpen: requestObjectSignatureOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setRequestObjectSignatureOpen(false);
      },
      selections: value
    }, requestObjectOptions)
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("requestObjectRequired"),
    fieldId: "requestObjectRequired",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:requestObjectRequired",
      fieldLabelId: "clients:requestObjectRequired"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.request.object.required",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "requestObjectRequired",
      variant: SelectVariant.single,
      onToggle: setRequestObjectRequiredOpen,
      isOpen: requestObjectRequiredOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setRequestObjectRequiredOpen(false);
      },
      selections: value
    }, requestObjectRequiredOptions)
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    id: "fineGrainSave",
    onClick: save
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    id: "fineGrainRevert",
    variant: "link",
    onClick: reset2
  }, t5("common:revert"))));
};

// build/clients/advanced/FineGrainSamlEndpointConfig.js
var FineGrainSamlEndpointConfig = ({
  control: {register: register2},
  save,
  reset: reset2
}) => {
  const {t: t5} = useTranslation("clients");
  return /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("assertionConsumerServicePostBindingURL"),
    fieldId: "assertionConsumerServicePostBindingURL",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:assertionConsumerServicePostBindingURL",
      fieldLabelId: "clients:assertionConsumerServicePostBindingURL"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2(),
    type: "text",
    id: "assertionConsumerServicePostBindingURL",
    name: "attributes.saml_assertion_consumer_url_post"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("assertionConsumerServiceRedirectBindingURL"),
    fieldId: "assertionConsumerServiceRedirectBindingURL",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:assertionConsumerServiceRedirectBindingURL",
      fieldLabelId: "clients:assertionConsumerServiceRedirectBindingURL"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2(),
    type: "text",
    id: "assertionConsumerServiceRedirectBindingURL",
    name: "attributes.saml_assertion_consumer_url_redirect"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("logoutServicePostBindingURL"),
    fieldId: "logoutServicePostBindingURL",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:logoutServicePostBindingURL",
      fieldLabelId: "clients:logoutServicePostBindingURL"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2(),
    type: "text",
    id: "logoutServicePostBindingURL",
    name: "attributes.saml_single_logout_service_url_post"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("logoutServiceRedirectBindingURL"),
    fieldId: "logoutServiceRedirectBindingURL",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:logoutServiceRedirectBindingURL",
      fieldLabelId: "clients:logoutServiceRedirectBindingURL"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2(),
    type: "text",
    id: "logoutServiceRedirectBindingURL",
    name: "attributes.saml_single_logout_service_url_redirect"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("logoutServiceArtifactBindingUrl"),
    fieldId: "logoutServiceArtifactBindingUrl",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:logoutServiceArtifactBindingUrl",
      fieldLabelId: "clients:logoutServiceArtifactBindingUrl"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2(),
    type: "text",
    id: "logoutServiceArtifactBindingUrl",
    name: "attributes.saml_single_logout_service_url_redirect"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("artifactBindingUrl"),
    fieldId: "artifactBindingUrl",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:artifactBindingUrl",
      fieldLabelId: "clients:artifactBindingUrl"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2(),
    type: "text",
    id: "artifactBindingUrl",
    name: "attributes.saml_artifact_binding_url"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("artifactResolutionService"),
    fieldId: "artifactResolutionService",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:artifactResolutionService",
      fieldLabelId: "clients:artifactResolutionService"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2(),
    type: "text",
    id: "artifactResolutionService",
    name: "attributes.saml_artifact_resolution_service_url"
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "tertiary",
    onClick: save
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert"))));
};

// build/clients/advanced/OpenIdConnectCompatibilityModes.js
var OpenIdConnectCompatibilityModes = ({
  control,
  save,
  reset: reset2
}) => {
  const {t: t5} = useTranslation("clients");
  return /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("excludeSessionStateFromAuthenticationResponse"),
    fieldId: "excludeSessionStateFromAuthenticationResponse",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:excludeSessionStateFromAuthenticationResponse",
      fieldLabelId: "clients:excludeSessionStateFromAuthenticationResponse"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.exclude-session-state-from-auth-response",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "excludeSessionStateFromAuthenticationResponse-switch",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value === "true",
      onChange: (value2) => onChange("" + value2)
    })
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    onClick: save
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    variant: "link",
    onClick: reset2
  }, t5("common:revert"))));
};

// build/clients/AdvancedTab.js
var AdvancedTab = ({
  save,
  client: {
    id: id3,
    registeredNodes,
    attributes,
    protocol,
    authenticationFlowBindingOverrides,
    adminUrl
  }
}) => {
  const {t: t5} = useTranslation("clients");
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const {addAlert, addError} = useAlerts();
  const revocationFieldName = "notBefore";
  const openIdConnect = "openid-connect";
  const {getValues, setValue, register: register2, control, reset: reset2} = useFormContext();
  const [expanded, setExpanded] = useState(false);
  const [selectedNode, setSelectedNode] = useState("");
  const [addNodeOpen, setAddNodeOpen] = useState(false);
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const [nodes, setNodes] = useState(registeredNodes || {});
  const pushRevocationButtonRef = useRef();
  const setNotBefore = (time2, messageKey) => {
    setValue(revocationFieldName, time2);
    save({messageKey});
  };
  const parseResult = (result, prefixKey) => {
    const successCount = result.successRequests?.length || 0;
    const failedCount = result.failedRequests?.length || 0;
    if (successCount === 0 && failedCount === 0) {
      addAlert(t5("noAdminUrlSet"), AlertVariant.warning);
    } else if (failedCount > 0) {
      addAlert(t5(prefixKey + "Success", {successNodes: result.successRequests}), AlertVariant.success);
      addAlert(t5(prefixKey + "Fail", {failedNodes: result.failedRequests}), AlertVariant.danger);
    } else {
      addAlert(t5(prefixKey + "Success", {successNodes: result.successRequests}), AlertVariant.success);
    }
  };
  const resetFields = (names) => {
    const values2 = {};
    for (const name of names) {
      values2[`attributes.${name}`] = attributes?.[name];
    }
    reset2(values2);
  };
  const push = async () => {
    const result = await adminClient.clients.pushRevocation({
      id: id3
    });
    parseResult(result, "notBeforePush");
  };
  const testCluster = async () => {
    const result = await adminClient.clients.testNodesAvailable({id: id3});
    parseResult(result, "testCluster");
  };
  const [toggleDeleteNodeConfirm, DeleteNodeConfirm] = useConfirmDialog({
    titleKey: "clients:deleteNode",
    messageKey: t5("deleteNodeBody", {
      node: selectedNode
    }),
    continueButtonLabel: "common:delete",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        await adminClient.clients.deleteClusterNode({
          id: id3,
          node: selectedNode
        });
        setNodes({
          ...Object.keys(nodes).reduce((object, key2) => {
            if (key2 !== selectedNode) {
              object[key2] = nodes[key2];
            }
            return object;
          }, {})
        });
        refresh();
        addAlert(t5("deleteNodeSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("clients:deleteNodeFail", error2);
      }
    }
  });
  useEffect(() => {
    register2(revocationFieldName);
  }, [register2]);
  const formatDate = () => {
    const date = getValues(revocationFieldName);
    if (date > 0) {
      return (0, import_moment.default)(date * 1e3).format("LLL");
    } else {
      return t5("common:none");
    }
  };
  const sections = [
    t5("revocation"),
    t5("clustering"),
    protocol === openIdConnect ? t5("fineGrainOpenIdConnectConfiguration") : t5("fineGrainSamlEndpointConfig"),
    t5("advancedSettings"),
    t5("authenticationOverrides")
  ];
  if (protocol === openIdConnect) {
    sections.splice(3, 0, t5("openIdConnectCompatibilityModes"));
  }
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light",
    className: "pf-u-py-0"
  }, /* @__PURE__ */ react.createElement(ScrollForm, {
    sections,
    borders: true
  }, /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Text, {
    className: "pf-u-pb-lg"
  }, /* @__PURE__ */ react.createElement(Trans, {
    i18nKey: "clients-help:notBeforeIntro"
  }, "In order to successfully push setup url on", /* @__PURE__ */ react.createElement(Link, {
    to: toClient({realm: realm2, clientId: id3, tab: "settings"})
  }, t5("settings")), "tab")), /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-clients",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("notBefore"),
    fieldId: "kc-not-before",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:notBefore",
      fieldLabelId: "clients:notBefore"
    })
  }, /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-not-before",
    name: "notBefore",
    isReadOnly: true,
    value: formatDate()
  }), /* @__PURE__ */ react.createElement(Button, {
    id: "setToNow",
    variant: "control",
    onClick: () => {
      setNotBefore(import_moment.default.now() / 1e3, "notBeforeSetToNow");
    }
  }, t5("setToNow")), /* @__PURE__ */ react.createElement(Button, {
    id: "clear",
    variant: "control",
    onClick: () => {
      setNotBefore(0, "notBeforeNowClear");
    }
  }, t5("clear")))), /* @__PURE__ */ react.createElement(ActionGroup, null, !adminUrl && /* @__PURE__ */ react.createElement(Tooltip, {
    reference: pushRevocationButtonRef,
    content: t5("clients-help:notBeforeTooltip")
  }), /* @__PURE__ */ react.createElement(Button, {
    id: "push",
    variant: "secondary",
    onClick: push,
    isAriaDisabled: !adminUrl,
    ref: pushRevocationButtonRef
  }, t5("push"))))), /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-clients",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("nodeReRegistrationTimeout"),
    fieldId: "kc-node-reregistration-timeout",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:nodeReRegistrationTimeout",
      fieldLabelId: "clients:nodeReRegistrationTimeout"
    })
  }, /* @__PURE__ */ react.createElement(Split, {
    hasGutter: true
  }, /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(Controller, {
    name: "nodeReRegistrationTimeout",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(TimeSelector, {
      value,
      onChange
    })
  })), /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(Button, {
    variant: ButtonVariant.secondary,
    onClick: () => save()
  }, t5("common:save")))))), /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteNodeConfirm, null), /* @__PURE__ */ react.createElement(AddHostDialog, {
    clientId: id3,
    isOpen: addNodeOpen,
    onAdded: (node) => {
      nodes[node] = import_moment.default.now() / 1e3;
      refresh();
    },
    onClose: () => setAddNodeOpen(false)
  }), /* @__PURE__ */ react.createElement(ExpandableSection, {
    toggleText: t5("registeredClusterNodes"),
    onToggle: setExpanded,
    isExpanded: expanded
  }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key,
    ariaLabelKey: "registeredClusterNodes",
    loader: () => Promise.resolve(Object.entries(nodes || {}).map((entry) => {
      return {host: entry[0], registration: entry[1]};
    })),
    toolbarItem: /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      id: "testClusterAvailability",
      onClick: testCluster,
      variant: ButtonVariant.secondary,
      isDisabled: Object.keys(nodes).length === 0
    }, t5("testClusterAvailability"))), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      id: "registerNodeManually",
      onClick: () => setAddNodeOpen(true),
      variant: ButtonVariant.tertiary
    }, t5("registerNodeManually")))),
    actions: [
      {
        title: t5("common:delete"),
        onRowClick: (node) => {
          setSelectedNode(node.host);
          toggleDeleteNodeConfirm();
        }
      }
    ],
    columns: [
      {
        name: "host",
        displayKey: "clients:nodeHost"
      },
      {
        name: "registration",
        displayKey: "clients:lastRegistration",
        cellFormatters: [
          (value) => value ? (0, import_moment.default)(parseInt(value.toString()) * 1e3).format("LLL") : ""
        ]
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      message: t5("noNodes"),
      instructions: t5("noNodesInstructions"),
      primaryActionText: t5("registerNodeManually"),
      onPrimaryAction: () => setAddNodeOpen(true)
    })
  })))), /* @__PURE__ */ react.createElement(react.Fragment, null, protocol === openIdConnect && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Text, {
    className: "pf-u-pb-lg"
  }, t5("clients-help:fineGrainOpenIdConnectConfiguration")), /* @__PURE__ */ react.createElement(FineGrainOpenIdConnect, {
    control,
    save: () => save(),
    reset: () => convertToFormValues(attributes, (key2, value) => setValue(`attributes.${key2}`, value))
  })), protocol !== openIdConnect && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Text, {
    className: "pf-u-pb-lg"
  }, t5("clients-help:fineGrainSamlEndpointConfig")), /* @__PURE__ */ react.createElement(FineGrainSamlEndpointConfig, {
    control,
    save: () => save(),
    reset: () => convertToFormValues(attributes, (key2, value) => setValue(`attributes.${key2}`, value))
  }))), protocol === openIdConnect && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Text, {
    className: "pf-u-pb-lg"
  }, t5("clients-help:openIdConnectCompatibilityModes")), /* @__PURE__ */ react.createElement(OpenIdConnectCompatibilityModes, {
    control,
    save: () => save(),
    reset: () => resetFields(["exclude.session.state.from.auth.response"])
  })), /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Text, {
    className: "pf-u-pb-lg"
  }, t5("clients-help:advancedSettings" + toUpperCase(protocol || ""))), /* @__PURE__ */ react.createElement(AdvancedSettings, {
    protocol,
    control,
    save: () => save(),
    reset: () => {
      resetFields([
        "saml.assertion.lifespan",
        "access.token.lifespan",
        "tls.client.certificate.bound.access.tokens",
        "pkce.code.challenge.method"
      ]);
    }
  })), /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Text, {
    className: "pf-u-pb-lg"
  }, t5("clients-help:authenticationOverrides")), /* @__PURE__ */ react.createElement(AuthenticationOverrides, {
    protocol,
    control,
    save: () => save(),
    reset: () => {
      setValue("authenticationFlowBindingOverrides.browser", authenticationFlowBindingOverrides?.browser);
      setValue("authenticationFlowBindingOverrides.direct_grant", authenticationFlowBindingOverrides?.direct_grant);
    }
  }))));
};

// build/clients/ClientDescription.js
var ClientDescription = () => {
  const {t: t5} = useTranslation("clients");
  const {register: register2, errors} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-clients",
    unWrap: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:clientId",
      fieldLabelId: "clientId"
    }),
    label: t5("common:clientId"),
    fieldId: "kc-client-id",
    helperTextInvalid: t5("common:required"),
    validated: errors.clientId ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2({required: true}),
    type: "text",
    id: "kc-client-id",
    name: "clientId",
    validated: errors.clientId ? ValidatedOptions.error : ValidatedOptions.default
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:clientName",
      fieldLabelId: "name"
    }),
    label: t5("common:name"),
    fieldId: "kc-name"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2(),
    type: "text",
    id: "kc-name",
    name: "name"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:description",
      fieldLabelId: "description"
    }),
    label: t5("common:description"),
    fieldId: "kc-description",
    validated: errors.description ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: errors.description?.message
  }, /* @__PURE__ */ react.createElement(TextArea, {
    ref: register2({
      maxLength: {
        value: 255,
        message: t5("common:maxLength", {length: 255})
      }
    }),
    type: "text",
    id: "kc-description",
    name: "description",
    validated: errors.description ? ValidatedOptions.error : ValidatedOptions.default
  })));
};

// build/clients/add/CapabilityConfig.js
var CapabilityConfig = ({
  unWrap,
  protocol: type
}) => {
  const {t: t5} = useTranslation("clients");
  const {control, watch, setValue} = useFormContext();
  const protocol = type || watch("protocol");
  const clientAuthentication = watch("publicClient");
  const authorization = watch("authorizationServicesEnabled");
  return /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-clients",
    unWrap,
    className: "keycloak__capability-config__form",
    "data-testid": "capability-config-form"
  }, protocol === "openid-connect" && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("clientAuthentication"),
    fieldId: "kc-authentication",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:authentication",
      fieldLabelId: "clients:authentication"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "publicClient",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      "data-testid": "authentication",
      id: "kc-authentication-switch",
      name: "publicClient",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: !value,
      onChange: (value2) => {
        onChange(!value2);
        if (!value2) {
          setValue("authorizationServicesEnabled", false);
          setValue("serviceAccountsEnabled", false);
        }
      }
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("clientAuthorization"),
    fieldId: "kc-authorization",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:authorization",
      fieldLabelId: "clients:authorization"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "authorizationServicesEnabled",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      "data-testid": "authorization",
      id: "kc-authorization-switch",
      name: "authorizationServicesEnabled",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value && !clientAuthentication,
      onChange: (value2) => {
        onChange(value2);
        if (value2) {
          setValue("serviceAccountsEnabled", true);
        }
      },
      isDisabled: clientAuthentication
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("authenticationFlow"),
    fieldId: "kc-flow"
  }, /* @__PURE__ */ react.createElement(Grid, null, /* @__PURE__ */ react.createElement(GridItem, {
    lg: 4,
    sm: 6
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "standardFlowEnabled",
    defaultValue: true,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(Checkbox, {
      "data-testid": "standard",
      label: t5("standardFlow"),
      id: "kc-flow-standard",
      name: "standardFlowEnabled",
      isChecked: value,
      onChange
    }), /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:standardFlow",
      fieldLabelId: "clients:standardFlow"
    }))
  })), /* @__PURE__ */ react.createElement(GridItem, {
    lg: 8,
    sm: 6
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "directAccessGrantsEnabled",
    defaultValue: true,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(Checkbox, {
      "data-testid": "direct",
      label: t5("directAccess"),
      id: "kc-flow-direct",
      name: "directAccessGrantsEnabled",
      isChecked: value,
      onChange
    }), /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:directAccess",
      fieldLabelId: "clients:directAccess"
    }))
  })), /* @__PURE__ */ react.createElement(GridItem, {
    lg: 4,
    sm: 6
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "implicitFlowEnabled",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(Checkbox, {
      "data-testid": "implicit",
      label: t5("implicitFlow"),
      id: "kc-flow-implicit",
      name: "implicitFlowEnabled",
      isChecked: value,
      onChange
    }), /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:implicitFlow",
      fieldLabelId: "clients:implicitFlow"
    }))
  })), /* @__PURE__ */ react.createElement(GridItem, {
    lg: 8,
    sm: 6
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "serviceAccountsEnabled",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(Checkbox, {
      "data-testid": "service-account",
      label: t5("serviceAccount"),
      id: "kc-flow-service-account",
      name: "serviceAccountsEnabled",
      isChecked: value || clientAuthentication && authorization,
      onChange,
      isDisabled: clientAuthentication && !authorization || !clientAuthentication && authorization
    }), /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:serviceAccount",
      fieldLabelId: "clients:serviceAccount"
    }))
  }))))), protocol === "saml" && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:encryptAssertions",
      fieldLabelId: "clients:encryptAssertions"
    }),
    label: t5("encryptAssertions"),
    fieldId: "kc-encrypt",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.saml.encrypt",
    control,
    defaultValue: "false",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      "data-testid": "encrypt",
      id: "kc-encrypt",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value === "true",
      onChange: (value2) => onChange("" + value2)
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:clientSignature",
      fieldLabelId: "clients:clientSignature"
    }),
    label: t5("clientSignature"),
    fieldId: "kc-client-signature",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.saml.client.signature",
    control,
    defaultValue: "false",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      "data-testid": "client-signature",
      id: "kc-client-signature",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value === "true",
      onChange: (value2) => onChange("" + value2)
    })
  }))));
};

// build/clients/advanced/SaveReset.js
var SaveReset = ({name, save, reset: reset2, ...rest}) => {
  const {t: t5} = useTranslation("common");
  return /* @__PURE__ */ react.createElement(ActionGroup, {
    ...rest
  }, /* @__PURE__ */ react.createElement(Button, {
    "data-testid": name + "Save",
    onClick: save
  }, t5("save")), /* @__PURE__ */ react.createElement(Button, {
    "data-testid": name + "Revert",
    variant: "link",
    onClick: reset2
  }, t5("revert")));
};

// build/clients/add/SamlConfig.js
var Toggle2 = ({name, label: label2}) => {
  const {t: t5} = useTranslation("clients");
  const {control} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5(label2),
    fieldId: label2,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5(`clients-help:${label2}`),
      fieldLabelId: `clients:${label2}`
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name,
    defaultValue: "false",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: name,
      "data-testid": label2,
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value === "true",
      onChange: (value2) => onChange(value2.toString())
    })
  }));
};
var SamlConfig = () => {
  const {t: t5} = useTranslation("clients");
  const {control} = useFormContext();
  const [nameFormatOpen, setNameFormatOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-clients",
    className: "keycloak__capability-config__form"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("nameIdFormat"),
    fieldId: "nameIdFormat",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:nameIdFormat",
      fieldLabelId: "clients:nameIdFormat"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.saml_name_id_format",
    defaultValue: "username",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "samlNameIdFormat",
      onToggle: setNameFormatOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setNameFormatOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("nameIdFormat"),
      isOpen: nameFormatOpen
    }, ["username", "email", "transient", "persistent"].map((name) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: name === value,
      key: name,
      value: name
    })))
  })), /* @__PURE__ */ react.createElement(Toggle2, {
    name: "attributes.saml.force.name.id.format",
    label: "forceNameIdFormat"
  }), /* @__PURE__ */ react.createElement(Toggle2, {
    name: "attributes.saml.force.post.binding",
    label: "forcePostBinding"
  }), /* @__PURE__ */ react.createElement(Toggle2, {
    name: "attributes.saml.artifact.binding",
    label: "forceArtifactBinding"
  }), /* @__PURE__ */ react.createElement(Toggle2, {
    name: "attributes.saml.onetimeuse.condition",
    label: "includeOneTimeUseCondition"
  }), /* @__PURE__ */ react.createElement(Toggle2, {
    name: "attributes.saml.server.signature.keyinfo.ext",
    label: "optimizeLookup"
  }));
};

// build/clients/add/SamlSignature.js
var SIGNATURE_ALGORITHMS = [
  "RSA_SHA1",
  "RSA_SHA256",
  "RSA_SHA256_MGF1",
  "RSA_SHA512",
  "RSA_SHA512_MGF1",
  "DSA_SHA1"
];
var KEYNAME_TRANSFORMER = ["NONE", "KEY_ID", "CERT_SUBJECT"];
var CANONICALIZATION = [
  {name: "EXCLUSIVE", value: "http://www.w3.org/2001/10/xml-exc-c14n#"},
  {
    name: "EXCLUSIVE_WITH_COMMENTS",
    value: "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"
  },
  {
    name: "INCLUSIVE",
    value: "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
  },
  {
    name: "INCLUSIVE_WITH_COMMENTS",
    value: "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"
  }
];
var SamlSignature = () => {
  const {t: t5} = useTranslation("clients");
  const [algOpen, setAlgOpen] = useState(false);
  const [keyOpen, setKeyOpen] = useState(false);
  const [canOpen, setCanOpen] = useState(false);
  const {control, watch} = useFormContext();
  const signDocs = watch("attributes.saml.server.signature");
  const signAssertion = watch("attributes.saml.assertion.signature");
  return /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-clients",
    className: "keycloak__capability-config__form"
  }, /* @__PURE__ */ react.createElement(Toggle2, {
    name: "attributes.saml.server.signature",
    label: "signDocuments"
  }), /* @__PURE__ */ react.createElement(Toggle2, {
    name: "attributes.saml.assertion.signature",
    label: "signAssertions"
  }), (signDocs === "true" || signAssertion === "true") && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("signatureAlgorithm"),
    fieldId: "signatureAlgorithm",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:signatureAlgorithm",
      fieldLabelId: "clients:signatureAlgorithm"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.saml.signature.algorithm",
    defaultValue: SIGNATURE_ALGORITHMS[0],
    Key: true,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "signatureAlgorithm",
      onToggle: setAlgOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setAlgOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("signatureAlgorithm"),
      isOpen: algOpen
    }, SIGNATURE_ALGORITHMS.map((algorithm) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: algorithm === value,
      key: algorithm,
      value: algorithm
    })))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("signatureKeyName"),
    fieldId: "signatureKeyName",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:signatureKeyName",
      fieldLabelId: "clients:signatureKeyName"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.saml.server.signature.keyinfo.xmlSigKeyInfoKeyNameTransformer",
    defaultValue: KEYNAME_TRANSFORMER[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "signatureKeyName",
      onToggle: setKeyOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setKeyOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("signatureKeyName"),
      isOpen: keyOpen
    }, KEYNAME_TRANSFORMER.map((key) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: key === value,
      key,
      value: key
    })))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("canonicalization"),
    fieldId: "canonicalization",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:canonicalization",
      fieldLabelId: "clients:canonicalization"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.saml_signature_canonicalization_method",
    defaultValue: CANONICALIZATION[0].value,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "canonicalization",
      onToggle: setCanOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setCanOpen(false);
      },
      selections: CANONICALIZATION.find((can) => can.value === value)?.name,
      variant: SelectVariant.single,
      "aria-label": t5("canonicalization"),
      isOpen: canOpen
    }, CANONICALIZATION.map((can) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: can.value === value,
      key: can.name,
      value: can.value
    }, can.name)))
  }))));
};

// build/clients/ClientSettings.js
var ClientSettings = ({
  client: client2,
  save,
  reset: reset2
}) => {
  const {register: register2, control, watch} = useFormContext();
  const {t: t5} = useTranslation("clients");
  const [loginThemeOpen, setLoginThemeOpen] = useState(false);
  const loginThemes = useServerInfo().themes["login"];
  const consentRequired = watch("consentRequired");
  const displayOnConsentScreen = watch("attributes.display.on.consent.screen");
  const protocol = watch("protocol");
  const sections = useMemo(() => {
    let result = ["generalSettings"];
    if (protocol === "saml") {
      result = [...result, "samlCapabilityConfig", "signatureAndEncryption"];
    } else if (!client2.bearerOnly) {
      result = [...result, "capabilityConfig"];
    }
    return [...result, "accessSettings", "loginSettings"];
  }, [protocol, client2]);
  return /* @__PURE__ */ react.createElement(ScrollForm, {
    className: "pf-u-px-lg",
    sections: sections.map((section) => t5(section))
  }, /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(ClientDescription, null)), protocol === "saml" ? /* @__PURE__ */ react.createElement(SamlConfig, null) : !client2.bearerOnly && /* @__PURE__ */ react.createElement(CapabilityConfig, null), protocol === "saml" && /* @__PURE__ */ react.createElement(SamlSignature, null), /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-clients"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("rootUrl"),
    fieldId: "kc-root-url",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:rootUrl",
      fieldLabelId: "clients:rootUrl"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-root-url",
    name: "rootUrl",
    ref: register2
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("validRedirectUri"),
    fieldId: "kc-redirect",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:validRedirectURIs",
      fieldLabelId: "clients:validRedirectUri"
    })
  }, /* @__PURE__ */ react.createElement(MultiLineInput, {
    name: "redirectUris",
    "aria-label": t5("validRedirectUri"),
    addButtonLabel: "clients:addRedirectUri"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("homeURL"),
    fieldId: "kc-home-url",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:homeURL",
      fieldLabelId: "clients:homeURL"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-home-url",
    name: "baseUrl",
    ref: register2
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("webOrigins"),
    fieldId: "kc-web-origins",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:webOrigins",
      fieldLabelId: "clients:webOrigins"
    })
  }, /* @__PURE__ */ react.createElement(MultiLineInput, {
    name: "webOrigins",
    "aria-label": t5("webOrigins"),
    addButtonLabel: "clients:addWebOrigins"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("adminURL"),
    fieldId: "kc-admin-url",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:adminURL",
      fieldLabelId: "clients:adminURL"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-admin-url",
    name: "adminUrl",
    ref: register2
  }))), /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-clients"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("loginTheme"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:loginTheme",
      fieldLabelId: "clients:loginTheme"
    }),
    fieldId: "loginTheme"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.login_theme",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "loginTheme",
      onToggle: setLoginThemeOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setLoginThemeOpen(false);
      },
      selections: value || t5("common:choose"),
      variant: SelectVariant.single,
      "aria-label": t5("loginTheme"),
      isOpen: loginThemeOpen
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      key: "empty",
      value: ""
    }, t5("common:choose")), /* @__PURE__ */ react.createElement(react.Fragment, null, loginThemes.map((theme) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: theme.name === value,
      key: theme.name,
      value: theme.name
    }))))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("consentRequired"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:consentRequired",
      fieldLabelId: "clients:consentRequired"
    }),
    fieldId: "kc-consent",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "consentRequired",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-consent-switch",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("displayOnClient"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:displayOnClient",
      fieldLabelId: "clients:displayOnClient"
    }),
    fieldId: "kc-display-on-client",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.display.on.consent.screen",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-display-on-client-switch",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value === "true",
      onChange: (value2) => onChange("" + value2),
      isDisabled: !consentRequired
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("consentScreenText"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:consentScreenText",
      fieldLabelId: "clients:consentScreenText"
    }),
    fieldId: "kc-consent-screen-text"
  }, /* @__PURE__ */ react.createElement(TextArea, {
    id: "kc-consent-screen-text",
    name: "attributes.consent.screen.text",
    ref: register2,
    isDisabled: !(consentRequired && displayOnConsentScreen === "true")
  })), /* @__PURE__ */ react.createElement(SaveReset, {
    className: "keycloak__form_actions",
    name: "settings",
    save,
    reset: reset2
  })));
};

// build/clients/credentials/ClientSecret.js
var ClientSecret = ({secret, toggle}) => {
  const {t: t5} = useTranslation("clients");
  const {formState} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("clientSecret"),
    fieldId: "kc-client-secret"
  }, /* @__PURE__ */ react.createElement(Split, {
    hasGutter: true
  }, /* @__PURE__ */ react.createElement(SplitItem, {
    isFilled: true
  }, /* @__PURE__ */ react.createElement(ClipboardCopy, {
    id: "kc-client-secret",
    isReadOnly: true
  }, secret)), /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    onClick: toggle,
    isDisabled: formState.isDirty
  }, t5("regenerate")))));
};

// build/clients/credentials/SignedJWT.js
var SignedJWT = () => {
  const {control} = useFormContext();
  const providers = sortProviders(useServerInfo().providers.clientSignature.providers);
  const {t: t5} = useTranslation("clients");
  const [open2, isOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("signatureAlgorithm"),
    fieldId: "kc-signature-algorithm",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:signature-algorithm",
      fieldLabelId: "clients:signatureAlgorithm"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.token.endpoint.auth.signing.alg",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      maxHeight: 200,
      toggleId: "kc-signature-algorithm",
      onToggle: isOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        isOpen(false);
      },
      selections: value || t5("anyAlgorithm"),
      variant: SelectVariant.single,
      "aria-label": t5("signatureAlgorithm"),
      isOpen: open2
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      selected: value === "",
      key: "any",
      value: ""
    }, t5("anyAlgorithm")), /* @__PURE__ */ react.createElement(react.Fragment, null, providers.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      key: option,
      value: option
    }))))
  }));
};

// build/clients/credentials/X509.js
var X509 = () => {
  const {t: t5} = useTranslation("clients");
  const {register: register2, errors} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("subject"),
    fieldId: "kc-subject",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:subject",
      fieldLabelId: "clients:subject"
    }),
    helperTextInvalid: t5("common:required"),
    validated: errors.attributes?.["x509.subjectdn"] ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2({required: true}),
    type: "text",
    id: "kc-subject",
    name: "attributes.x509.subjectdn",
    validated: errors.attributes?.["x509.subjectdn"] ? ValidatedOptions.error : ValidatedOptions.default
  }));
};

// build/clients/credentials/Credentials.js
var Credentials = ({clientId, save}) => {
  const {t: t5} = useTranslation("clients");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [providers, setProviders] = useState([]);
  const {
    control,
    formState: {isDirty}
  } = useFormContext();
  const clientAuthenticatorType = useWatch({
    control,
    name: "clientAuthenticatorType",
    defaultValue: ""
  });
  const [secret, setSecret] = useState("");
  const [accessToken, setAccessToken] = useState("");
  const [open2, isOpen] = useState(false);
  useFetch(async () => {
    const providers2 = await adminClient.authenticationManagement.getClientAuthenticatorProviders();
    const secret2 = await adminClient.clients.getClientSecret({
      id: clientId
    });
    return {
      providers: providers2,
      secret: secret2.value
    };
  }, ({providers: providers2, secret: secret2}) => {
    setProviders(providers2);
    setSecret(secret2);
  }, []);
  async function regenerate(call, message) {
    try {
      const data2 = await call(clientId);
      addAlert(t5(`${message}Success`), AlertVariant.success);
      return data2;
    } catch (error2) {
      addError(`clients:${message}Error`, error2);
    }
  }
  const regenerateClientSecret = async () => {
    const secret2 = await regenerate((clientId2) => adminClient.clients.generateNewClientSecret({id: clientId2}), "clientSecret");
    setSecret(secret2?.value || "");
  };
  const [toggleClientSecretConfirm, ClientSecretConfirm] = useConfirmDialog({
    titleKey: "clients:confirmClientSecretTitle",
    messageKey: "clients:confirmClientSecretBody",
    continueButtonLabel: "common:yes",
    cancelButtonLabel: "common:no",
    onConfirm: regenerateClientSecret
  });
  const regenerateAccessToken = async () => {
    const accessToken2 = await regenerate((clientId2) => adminClient.clients.generateRegistrationAccessToken({id: clientId2}), "accessToken");
    setAccessToken(accessToken2?.registrationAccessToken || "");
  };
  const [toggleAccessTokenConfirm, AccessTokenConfirm] = useConfirmDialog({
    titleKey: "clients:confirmAccessTokenTitle",
    messageKey: "clients:confirmAccessTokenBody",
    continueButtonLabel: "common:yes",
    cancelButtonLabel: "common:no",
    onConfirm: regenerateAccessToken
  });
  return /* @__PURE__ */ react.createElement(PageSection, null, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    className: "pf-u-mt-md",
    role: "manage-clients"
  }, /* @__PURE__ */ react.createElement(ClientSecretConfirm, null), /* @__PURE__ */ react.createElement(AccessTokenConfirm, null), /* @__PURE__ */ react.createElement(Card, {
    isFlat: true
  }, /* @__PURE__ */ react.createElement(CardBody, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("clientAuthenticator"),
    fieldId: "kc-client-authenticator-type",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:client-authenticator-type",
      fieldLabelId: "clients:clientAuthenticator"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "clientAuthenticatorType",
    control,
    defaultValue: "",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-client-authenticator-type",
      required: true,
      onToggle: isOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        isOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("clientAuthenticator"),
      isOpen: open2
    }, providers.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option.id === value,
      key: option.id,
      value: option.id
    }, option.displayName)))
  })), clientAuthenticatorType === "client-jwt" && /* @__PURE__ */ react.createElement(SignedJWT, null), clientAuthenticatorType === "client-x509" && /* @__PURE__ */ react.createElement(X509, null), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "primary",
    onClick: () => save(),
    isDisabled: !isDirty
  }, t5("common:save")))), (clientAuthenticatorType === "client-secret" || clientAuthenticatorType === "client-secret-jwt") && /* @__PURE__ */ react.createElement(Divider, null), (clientAuthenticatorType === "client-secret" || clientAuthenticatorType === "client-secret-jwt") && /* @__PURE__ */ react.createElement(CardBody, null, /* @__PURE__ */ react.createElement(ClientSecret, {
    secret,
    toggle: toggleClientSecretConfirm
  }))), /* @__PURE__ */ react.createElement(Card, {
    isFlat: true
  }, /* @__PURE__ */ react.createElement(CardBody, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("registrationAccessToken"),
    fieldId: "kc-access-token",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:registration-access-token",
      fieldLabelId: "clients:registrationAccessToken"
    })
  }, /* @__PURE__ */ react.createElement(Split, {
    hasGutter: true
  }, /* @__PURE__ */ react.createElement(SplitItem, {
    isFilled: true
  }, /* @__PURE__ */ react.createElement(ClipboardCopy, {
    id: "kc-access-token",
    isReadOnly: true
  }, accessToken)), /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    onClick: toggleAccessTokenConfirm,
    isDisabled: isDirty
  }, t5("regenerate")))))))));
};

// build/components/password-input/PasswordInput.js
var PasswordInputBase = ({
  hasReveal = true,
  innerRef,
  ...rest
}) => {
  const {t: t5} = useTranslation("common-help");
  const [hidePassword, setHidePassword] = useState(true);
  return /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(TextInput, {
    ...rest,
    type: hidePassword ? "password" : "text",
    ref: innerRef
  }), hasReveal && /* @__PURE__ */ react.createElement(Button, {
    variant: "control",
    "aria-label": t5("showPassword"),
    onClick: () => setHidePassword(!hidePassword)
  }, hidePassword ? /* @__PURE__ */ react.createElement(EyeIcon, null) : /* @__PURE__ */ react.createElement(EyeSlashIcon, null)));
};
var PasswordInput = react.forwardRef((props, ref) => /* @__PURE__ */ react.createElement(PasswordInputBase, {
  ...props,
  innerRef: ref
}));
PasswordInput.displayName = "PasswordInput";

// build/clients/keys/StoreSettings.js
var StoreSettings = ({
  register: register2,
  hidePassword = false
}) => {
  const {t: t5} = useTranslation("clients");
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("keyAlias"),
    fieldId: "keyAlias",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:keyAlias",
      fieldLabelId: "clients:keyAlias"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    "data-testid": "keyAlias",
    type: "text",
    id: "keyAlias",
    name: "keyAlias",
    ref: register2
  })), !hidePassword && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("keyPassword"),
    fieldId: "keyPassword",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:keyPassword",
      fieldLabelId: "clients:keyPassword"
    })
  }, /* @__PURE__ */ react.createElement(PasswordInput, {
    "data-testid": "keyPassword",
    id: "keyPassword",
    name: "keyPassword",
    ref: register2
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("storePassword"),
    fieldId: "storePassword",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:storePassword",
      fieldLabelId: "clients:storePassword"
    })
  }, /* @__PURE__ */ react.createElement(PasswordInput, {
    "data-testid": "storePassword",
    id: "storePassword",
    name: "storePassword",
    ref: register2
  })));
};

// build/clients/keys/GenerateKeyDialog.js
var KeyForm = ({
  register: register2,
  control,
  useFile = false
}) => {
  const {t: t5} = useTranslation("clients");
  const [filename, setFilename] = useState();
  const [openArchiveFormat, setOpenArchiveFormat] = useState(false);
  return /* @__PURE__ */ react.createElement(Form, {
    className: "pf-u-pt-lg"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("archiveFormat"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:archiveFormat",
      fieldLabelId: "clients:archiveFormat"
    }),
    fieldId: "archiveFormat"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "format",
    defaultValue: "JKS",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "archiveFormat",
      onToggle: setOpenArchiveFormat,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setOpenArchiveFormat(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("archiveFormat"),
      isOpen: openArchiveFormat
    }, ["JKS", "PKCS12"].map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      key: option,
      value: option
    })))
  })), useFile && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("importFile"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:importFile",
      fieldLabelId: "clients:importFile"
    }),
    fieldId: "importFile"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "file",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(FileUpload, {
      id: "importFile",
      value,
      filename,
      browseButtonText: t5("browse"),
      onChange: (value2, filename2) => {
        setFilename(filename2);
        onChange(value2);
      }
    })
  })), /* @__PURE__ */ react.createElement(StoreSettings, {
    register: register2,
    hidePassword: useFile
  }));
};
var GenerateKeyDialog = ({
  save,
  toggleDialog
}) => {
  const {t: t5} = useTranslation("clients");
  const {register: register2, control, handleSubmit} = useForm();
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.medium,
    title: t5("generateKeys"),
    isOpen: true,
    onClose: toggleDialog,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-confirm",
        key: "confirm",
        "data-testid": "confirm",
        onClick: () => {
          handleSubmit((config2) => {
            save(config2);
            toggleDialog();
          })();
        }
      }, t5("generate")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        "data-testid": "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          toggleDialog();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, null, t5("clients-help:generateKeysDescription"))), /* @__PURE__ */ react.createElement(KeyForm, {
    register: register2,
    control
  }));
};

// build/clients/keys/ImportKeyDialog.js
var baseFormats = ["JKS", "PKCS12"];
var formats = baseFormats.concat([
  "Certificate PEM",
  "Public Key PEM",
  "JSON Web Key Set"
]);
var ImportKeyDialog = ({
  save,
  toggleDialog
}) => {
  const {t: t5} = useTranslation("clients");
  const {register: register2, control, handleSubmit} = useForm();
  const [openArchiveFormat, setOpenArchiveFormat] = useState(false);
  const format2 = useWatch({
    control,
    name: "keystoreFormat",
    defaultValue: "JKS"
  });
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.medium,
    title: t5("generateKeys"),
    isOpen: true,
    onClose: toggleDialog,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-confirm",
        key: "confirm",
        onClick: () => {
          handleSubmit((importFile) => {
            save(importFile);
            toggleDialog();
          })();
        }
      }, t5("import")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          toggleDialog();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, null, t5("clients-help:generateKeysDescription"))), /* @__PURE__ */ react.createElement(Form, {
    className: "pf-u-pt-lg"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("archiveFormat"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:archiveFormat",
      fieldLabelId: "clients:archiveFormat"
    }),
    fieldId: "archiveFormat"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "keystoreFormat",
    control,
    defaultValue: "JKS",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "archiveFormat",
      onToggle: setOpenArchiveFormat,
      onSelect: (_23, value2) => {
        onChange(value2);
        setOpenArchiveFormat(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("archiveFormat"),
      isOpen: openArchiveFormat
    }, formats.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      key: option,
      value: option
    })))
  })), baseFormats.includes(format2) && /* @__PURE__ */ react.createElement(StoreSettings, {
    register: register2,
    hidePassword: true
  }), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("importFile"),
    fieldId: "importFile"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "file",
    control,
    defaultValue: "",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(FileUpload, {
      id: "importFile",
      value: value.value,
      filename: value.filename,
      onChange: (value2, filename) => onChange({value: value2, filename})
    })
  }))));
};

// build/clients/keys/Certificate.js
var CertificateDisplay = ({id: id3, keyInfo}) => /* @__PURE__ */ react.createElement(TextArea, {
  readOnly: true,
  rows: 5,
  id: id3,
  "data-testid": "certificate",
  value: keyInfo?.certificate
});
var Certificate = ({keyInfo, plain = false}) => {
  const {t: t5} = useTranslation("clients");
  return /* @__PURE__ */ react.createElement(GenerateId, {
    prefix: "certificate"
  }, (id3) => plain ? /* @__PURE__ */ react.createElement(CertificateDisplay, {
    id: id3,
    keyInfo
  }) : /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("certificate"),
    fieldId: id3,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:certificate",
      fieldLabelId: `clients:${id3}`
    })
  }, /* @__PURE__ */ react.createElement(CertificateDisplay, {
    id: id3,
    keyInfo
  })));
};

// build/clients/keys/Keys.js
var attr = "jwt.credential";
var Keys = ({clientId, save}) => {
  const {t: t5} = useTranslation("clients");
  const {
    control,
    register: register2,
    formState: {isDirty}
  } = useFormContext();
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [keyInfo, setKeyInfo] = useState();
  const [openGenerateKeys, toggleOpenGenerateKeys, setOpenGenerateKeys] = useToggle();
  const [openImportKeys, toggleOpenImportKeys, setOpenImportKeys] = useToggle();
  const useJwksUrl = useWatch({
    control,
    name: "attributes.use.jwks.url",
    defaultValue: "false"
  });
  useFetch(() => adminClient.clients.getKeyInfo({id: clientId, attr}), (info2) => setKeyInfo(info2), []);
  const generate = async (config2) => {
    try {
      const keyStore = await adminClient.clients.generateAndDownloadKey({
        id: clientId,
        attr
      }, config2);
      file_saver_default.saveAs(new Blob([keyStore], {type: "application/octet-stream"}), `keystore.${config2.format == "PKCS12" ? "p12" : "jks"}`);
      addAlert(t5("generateSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("clients:generateError", error2);
    }
  };
  const importKey = async (importFile) => {
    try {
      const formData = new FormData();
      const {file, ...rest} = importFile;
      Object.entries(rest).map((entry) => formData.append(entry[0], entry[1]));
      formData.append("file", file.value);
      await adminClient.clients.uploadCertificate({id: clientId, attr}, formData);
      addAlert(t5("importSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("clients:importError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light",
    className: "keycloak__form"
  }, openGenerateKeys && /* @__PURE__ */ react.createElement(GenerateKeyDialog, {
    toggleDialog: toggleOpenGenerateKeys,
    save: generate
  }), openImportKeys && /* @__PURE__ */ react.createElement(ImportKeyDialog, {
    toggleDialog: toggleOpenImportKeys,
    save: importKey
  }), /* @__PURE__ */ react.createElement(Card, {
    isFlat: true
  }, /* @__PURE__ */ react.createElement(CardHeader, null, /* @__PURE__ */ react.createElement(CardTitle, null, t5("jwksUrlConfig"))), /* @__PURE__ */ react.createElement(CardBody, null, /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, null, t5("keysIntro")))), /* @__PURE__ */ react.createElement(CardBody, null, /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-clients",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("useJwksUrl"),
    fieldId: "useJwksUrl",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:useJwksUrl",
      fieldLabelId: "clients:useJwksUrl"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "attributes.use.jwks.url",
    defaultValue: "false",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      "data-testid": "useJwksUrl",
      id: "useJwksUrl-switch",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value === "true",
      onChange: (value2) => onChange(`${value2}`)
    })
  })), useJwksUrl !== "true" && (keyInfo ? /* @__PURE__ */ react.createElement(Certificate, {
    plain: true,
    keyInfo
  }) : "No client certificate configured"), useJwksUrl === "true" && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("jwksUrl"),
    fieldId: "jwksUrl",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:jwksUrl",
      fieldLabelId: "clients:jwksUrl"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "jwksUrl",
    name: "attributes.jwks.url",
    ref: register2
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "saveKeys",
    onClick: save,
    isDisabled: !isDirty
  }, t5("common:save")), /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "generate",
    variant: "secondary",
    onClick: () => setOpenGenerateKeys(true)
  }, t5("generateNewKeys")), /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "import",
    variant: "secondary",
    onClick: () => setOpenImportKeys(true),
    isDisabled: useJwksUrl === "true"
  }, t5("import")))))));
};

// build/clients/initial-access/InitialAccessTokenList.js
var import_moment2 = __toModule(require_moment());

// build/clients/initial-access/AccessTokenDialog.js
var AccessTokenDialog = ({
  token: token2,
  toggleDialog
}) => {
  const {t: t5} = useTranslation("clients");
  return /* @__PURE__ */ react.createElement(Modal, {
    title: t5("initialAccessTokenDetails"),
    isOpen: true,
    onClose: toggleDialog,
    variant: ModalVariant.medium
  }, /* @__PURE__ */ react.createElement(Alert, {
    title: t5("copyInitialAccessToken"),
    isInline: true,
    variant: AlertVariant.warning
  }), /* @__PURE__ */ react.createElement(Form, {
    className: "pf-u-mt-md"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("initialAccessToken"),
    fieldId: "initialAccessToken"
  }, /* @__PURE__ */ react.createElement(ClipboardCopy, {
    id: "initialAccessToken",
    isReadOnly: true
  }, token2))));
};

// build/clients/routes/CreateInitialAccessToken.js
var CreateInitialAccessTokenRoute = {
  path: "/:realm/clients/initialAccessToken/create",
  component: lazy(() => Promise.resolve().then(() => require_CreateInitialAccessToken())),
  breadcrumb: (t5) => t5("clients:createToken"),
  access: "manage-clients"
};
var toCreateInitialAccessToken = (params) => ({
  pathname: generatePath(CreateInitialAccessTokenRoute.path, params)
});

// build/clients/initial-access/InitialAccessTokenList.js
var InitialAccessTokenList = () => {
  const {t: t5} = useTranslation("clients");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {realm: realm2} = useRealm();
  const history = useHistory();
  const [token2, setToken] = useState();
  const loader = async () => await adminClient.realms.getClientsInitialAccess({realm: realm2});
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: "clients:tokenDeleteConfirmTitle",
    messageKey: t5("tokenDeleteConfirm", token2),
    continueButtonLabel: "common:delete",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        await adminClient.realms.delClientsInitialAccess({
          realm: realm2,
          id: token2.id
        });
        addAlert(t5("tokenDeleteSuccess"), AlertVariant.success);
        setToken(void 0);
      } catch (error2) {
        addError("tokenDeleteError", error2);
      }
    }
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key: token2?.id,
    ariaLabelKey: "clients:initialAccessToken",
    searchPlaceholderKey: "clients:searchInitialAccessToken",
    loader,
    toolbarItem: /* @__PURE__ */ react.createElement(Button, {
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toCreateInitialAccessToken({realm: realm2})
      })
    }, t5("common:create")),
    actions: [
      {
        title: t5("common:delete"),
        onRowClick: (token22) => {
          setToken(token22);
          toggleDeleteDialog();
        }
      }
    ],
    columns: [
      {
        name: "id",
        displayKey: "common:id"
      },
      {
        name: "timestamp",
        displayKey: "clients:timestamp",
        cellRenderer: (row) => (0, import_moment2.default)(row.timestamp * 1e3).format("LLL")
      },
      {
        name: "expiration",
        displayKey: "clients:expires",
        cellRenderer: (row) => (0, import_moment2.default)(row.timestamp * 1e3 + row.expiration * 1e3).format("LLL")
      },
      {
        name: "count",
        displayKey: "clients:count"
      },
      {
        name: "remainingCount",
        displayKey: "clients:remainingCount",
        transforms: [wrappable]
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      message: t5("noTokens"),
      instructions: t5("noTokensInstructions"),
      primaryActionText: t5("common:create"),
      onPrimaryAction: () => history.push(toCreateInitialAccessToken({realm: realm2}))
    })
  }));
};

// build/clients/routes/ImportClient.js
var ImportClientRoute = {
  path: "/:realm/clients/import-client",
  component: lazy(() => Promise.resolve().then(() => require_ImportForm())),
  breadcrumb: (t5) => t5("clients:importClient"),
  access: "manage-clients"
};
var toImportClient = (params) => ({
  pathname: generatePath(ImportClientRoute.path, params)
});

// build/clients/routes/Clients.js
var ClientsRoute = {
  path: "/:realm/clients/:tab?",
  component: lazy(() => Promise.resolve().then(() => require_ClientsSection())),
  breadcrumb: (t5) => t5("clients:clientList"),
  access: "query-clients"
};
var toClients = (params) => ({
  pathname: generatePath(ClientsRoute.path, params)
});

// build/clients/scopes/ClientScopes.js
var ClientScopes = ({
  clientId,
  protocol,
  clientName
}) => {
  const {t: t5} = useTranslation("clients");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [searchType, setSearchType] = useState("name");
  const [searchTypeType, setSearchTypeType] = useState(AllClientScopes.none);
  const [addDialogOpen, setAddDialogOpen] = useState(false);
  const [kebabOpen, setKebabOpen] = useState(false);
  const [rest, setRest] = useState();
  const [selectedRows, setSelectedRows] = useState([]);
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const loader = async (first2, max2, search2) => {
    const defaultClientScopes = await adminClient.clients.listDefaultClientScopes({id: clientId});
    const optionalClientScopes = await adminClient.clients.listOptionalClientScopes({id: clientId});
    const clientScopes2 = await adminClient.clientScopes.find();
    const find3 = (id3) => clientScopes2.find((clientScope) => id3 === clientScope.id);
    const optional2 = optionalClientScopes.map((c3) => {
      const scope = find3(c3.id);
      const row = {
        ...c3,
        type: ClientScope.optional,
        description: scope.description
      };
      return row;
    });
    const defaultScopes = defaultClientScopes.map((c3) => {
      const scope = find3(c3.id);
      const row = {
        ...c3,
        type: ClientScope.default,
        description: scope.description
      };
      return row;
    });
    const rows = [...optional2, ...defaultScopes];
    const names = rows.map((row) => row.name);
    setRest(clientScopes2.filter((scope) => !names.includes(scope.name)).filter((scope) => scope.protocol === protocol));
    const filter3 = searchType === "name" ? nameFilter(search2) : typeFilter(searchTypeType);
    return rows.filter(filter3).slice(first2, Number(first2) + Number(max2));
  };
  const TypeSelector = (scope) => /* @__PURE__ */ react.createElement(CellDropdown, {
    clientScope: scope,
    type: scope.type,
    onSelect: async (value) => {
      try {
        await changeClientScope(adminClient, clientId, scope, scope.type, value);
        addAlert(t5("clientScopeSuccess"), AlertVariant.success);
        refresh();
      } catch (error2) {
        addError("clients:clientScopeError", error2);
      }
    }
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, rest && /* @__PURE__ */ react.createElement(AddScopeDialog, {
    clientScopes: rest,
    clientName,
    open: addDialogOpen,
    toggleDialog: () => setAddDialogOpen(!addDialogOpen),
    onAdd: async (scopes) => {
      try {
        await Promise.all(scopes.map(async (scope) => await addClientScope(adminClient, clientId, scope.scope, scope.type)));
        addAlert(t5("clientScopeSuccess"), AlertVariant.success);
        refresh();
      } catch (error2) {
        addError("clients:clientScopeError", error2);
      }
    }
  }), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key,
    loader,
    ariaLabelKey: "clients:clientScopeList",
    searchPlaceholderKey: searchType === "name" ? "clients:searchByName" : void 0,
    canSelectAll: true,
    isPaginated: true,
    isSearching: searchType === "type",
    onSelect: (rows) => setSelectedRows([...rows]),
    searchTypeComponent: /* @__PURE__ */ react.createElement(SearchDropdown, {
      searchType,
      onSelect: (searchType2) => setSearchType(searchType2)
    }),
    toolbarItem: /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(SearchToolbar, {
      searchType,
      type: searchTypeType,
      onSelect: (searchType2) => setSearchType(searchType2),
      onType: (value) => {
        setSearchTypeType(value);
        refresh();
      }
    }), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      onClick: () => setAddDialogOpen(true)
    }, t5("addClientScope"))), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(ChangeTypeDropdown, {
      clientId,
      selectedRows,
      refresh
    })), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Dropdown, {
      toggle: /* @__PURE__ */ react.createElement(KebabToggle, {
        onToggle: () => setKebabOpen(!kebabOpen)
      }),
      isOpen: kebabOpen,
      isPlain: true,
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "deleteAll",
          isDisabled: selectedRows.length === 0,
          onClick: async () => {
            try {
              await Promise.all(selectedRows.map(async (row) => {
                await removeClientScope(adminClient, clientId, {...row}, row.type);
              }));
              setKebabOpen(false);
              addAlert(t5("clientScopeRemoveSuccess"), AlertVariant.success);
              refresh();
            } catch (error2) {
              addError("clients:clientScopeRemoveError", error2);
            }
          }
        }, t5("common:remove"))
      ]
    }))),
    columns: [
      {
        name: "name",
        displayKey: "clients:assignedClientScope"
      },
      {
        name: "type",
        displayKey: "clients:assignedType",
        cellRenderer: TypeSelector
      },
      {name: "description"}
    ],
    actions: [
      {
        title: t5("common:remove"),
        onRowClick: async (row) => {
          try {
            await removeClientScope(adminClient, clientId, row, row.type);
            addAlert(t5("clientScopeRemoveSuccess"), AlertVariant.success);
            refresh();
          } catch (error2) {
            addError("clients:clientScopeRemoveError", error2);
          }
          return true;
        }
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      message: t5("clients:emptyClientScopes"),
      instructions: t5("clients:emptyClientScopesInstructions"),
      primaryActionText: t5("clients:emptyClientScopesPrimaryAction"),
      onPrimaryAction: () => setAddDialogOpen(true)
    })
  }));
};

// build/clients/scopes/EvaluateScopes.js
var ProtocolMappers = ({
  protocolMappers
}) => {
  const [key, setKey] = useState(0);
  useEffect(() => {
    setKey(key + 1);
  }, [protocolMappers]);
  return /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key,
    loader: () => Promise.resolve(protocolMappers),
    ariaLabelKey: "clients:effectiveProtocolMappers",
    searchPlaceholderKey: "clients:searchForProtocol",
    columns: [
      {
        name: "mapperName",
        displayKey: "common:name"
      },
      {
        name: "containerName",
        displayKey: "clients:parentClientScope"
      },
      {
        name: "type.category",
        displayKey: "common:category"
      },
      {
        name: "type.priority",
        displayKey: "common:priority"
      }
    ]
  });
};
var EffectiveRoles = ({
  effectiveRoles
}) => {
  const [key, setKey] = useState(0);
  useEffect(() => {
    setKey(key + 1);
  }, [effectiveRoles]);
  return /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key,
    loader: () => Promise.resolve(effectiveRoles),
    ariaLabelKey: "client:effectiveRoleScopeMappings",
    searchPlaceholderKey: "clients:searchForRole",
    columns: [
      {
        name: "name",
        displayKey: "clients:role"
      },
      {
        name: "containerId",
        displayKey: "clients:origin"
      }
    ]
  });
};
var EvaluateScopes = ({clientId, protocol}) => {
  const prefix2 = "openid";
  const {t: t5} = useTranslation("clients");
  const {enabled} = useHelp();
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const mapperTypes = useServerInfo().protocolMapperTypes[protocol];
  const [selectableScopes, setSelectableScopes] = useState([]);
  const [isScopeOpen, setIsScopeOpen] = useState(false);
  const [isUserOpen, setIsUserOpen] = useState(false);
  const [selected, setSelected] = useState([prefix2]);
  const [activeTab, setActiveTab] = useState(0);
  const [userItems, setUserItems] = useState([]);
  const [userSearch, setUserSearch] = useState("");
  const [user, setUser] = useState();
  const [key, setKey] = useState("");
  const refresh = () => setKey(`${new Date().getTime()}`);
  const [effectiveRoles, setEffectiveRoles] = useState([]);
  const [protocolMappers, setProtocolMappers] = useState([]);
  const [accessToken, setAccessToken] = useState("");
  const tabContent1 = useRef(null);
  const tabContent2 = useRef(null);
  const tabContent3 = useRef(null);
  useFetch(() => adminClient.clients.listOptionalClientScopes({id: clientId}), (optionalClientScopes) => setSelectableScopes(optionalClientScopes), []);
  const toString5 = (user2) => {
    return t5("common:fullName", {
      givenName: user2.firstName,
      familyName: user2.lastName
    }).trim() || user2.username || "";
  };
  useFetch(() => {
    if (userSearch.length > 2) {
      return adminClient.users.find({search: userSearch});
    } else {
      return Promise.resolve([]);
    }
  }, (users2) => setUserItems(users2.map((user2) => {
    user2.toString = function() {
      return toString5(this);
    };
    return user2;
  }).map((user2) => /* @__PURE__ */ react.createElement(SelectOption, {
    key: user2.id,
    value: user2
  }))), [userSearch]);
  useFetch(async () => {
    const scope = selected.join(" ");
    const effectiveRoles2 = await adminClient.clients.evaluatePermission({
      id: clientId,
      roleContainer: realm2,
      scope,
      type: "granted"
    });
    const mapperList = await adminClient.clients.evaluateListProtocolMapper({
      id: clientId,
      scope
    });
    return {
      mapperList,
      effectiveRoles: effectiveRoles2
    };
  }, ({mapperList, effectiveRoles: effectiveRoles2}) => {
    setEffectiveRoles(effectiveRoles2);
    mapperList.map((mapper) => {
      mapper.type = mapperTypes.filter((type) => type.id === mapper.protocolMapper)[0];
    });
    setProtocolMappers(mapperList);
    refresh();
  }, [selected]);
  useFetch(() => {
    const scope = selected.join(" ");
    if (user) {
      return adminClient.clients.evaluateGenerateAccessToken({
        id: clientId,
        userId: user.id,
        scope
      });
    } else {
      return Promise.resolve({});
    }
  }, (accessToken2) => {
    setAccessToken(prettyPrintJSON(accessToken2));
  }, [user, selected]);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, enabled && /* @__PURE__ */ react.createElement(TextContent, {
    className: "keycloak__scopes_evaluate__intro"
  }, /* @__PURE__ */ react.createElement(Text, null, /* @__PURE__ */ react.createElement(QuestionCircleIcon, null), " ", t5("clients-help:evaluateExplain"))), /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("scopeParameter"),
    fieldId: "scopeParameter",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:scopeParameter",
      fieldLabelId: "clients:scopeParameter"
    })
  }, /* @__PURE__ */ react.createElement(Split, {
    hasGutter: true
  }, /* @__PURE__ */ react.createElement(SplitItem, {
    isFilled: true
  }, /* @__PURE__ */ react.createElement(Select, {
    toggleId: "scopeParameter",
    variant: SelectVariant.typeaheadMulti,
    typeAheadAriaLabel: t5("scopeParameter"),
    onToggle: () => setIsScopeOpen(!isScopeOpen),
    isOpen: isScopeOpen,
    selections: selected,
    onSelect: (_23, value) => {
      const option = value;
      if (selected.includes(option)) {
        if (option !== prefix2) {
          setSelected(selected.filter((item) => item !== option));
        }
      } else {
        setSelected([...selected, option]);
      }
    },
    "aria-labelledby": t5("scopeParameter"),
    placeholderText: t5("scopeParameterPlaceholder")
  }, selectableScopes.map((option, index3) => /* @__PURE__ */ react.createElement(SelectOption, {
    key: index3,
    value: option.name
  })))), /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(ClipboardCopy, {
    className: "keycloak__scopes_evaluate__clipboard-copy"
  }, selected.join(" "))))), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("user"),
    fieldId: "user",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:user",
      fieldLabelId: "clients:user"
    })
  }, /* @__PURE__ */ react.createElement(Select, {
    toggleId: "user",
    variant: SelectVariant.typeahead,
    typeAheadAriaLabel: t5("user"),
    onToggle: () => setIsUserOpen(!isUserOpen),
    onFilter: (e2) => {
      const value = e2?.target.value || "";
      setUserSearch(value);
      return userItems;
    },
    onClear: () => {
      setUser(void 0);
      setUserSearch("");
    },
    selections: [user],
    onSelect: (_23, value) => {
      setUser(value);
      setUserSearch("");
      setIsUserOpen(false);
    },
    isOpen: isUserOpen
  })))), /* @__PURE__ */ react.createElement(Grid, {
    hasGutter: true,
    className: "keycloak__scopes_evaluate__tabs"
  }, /* @__PURE__ */ react.createElement(GridItem, {
    span: 8
  }, /* @__PURE__ */ react.createElement(TabContent, {
    "aria-labelledby": "pf-tab-0-effectiveProtocolMappers",
    eventKey: 0,
    id: "effectiveProtocolMappers",
    ref: tabContent1
  }, /* @__PURE__ */ react.createElement(ProtocolMappers, {
    protocolMappers
  })), /* @__PURE__ */ react.createElement(TabContent, {
    "aria-labelledby": "pf-tab-0-effectiveRoleScopeMappings",
    eventKey: 1,
    id: "effectiveRoleScopeMappings",
    ref: tabContent2,
    hidden: true
  }, /* @__PURE__ */ react.createElement(EffectiveRoles, {
    effectiveRoles
  })), /* @__PURE__ */ react.createElement(TabContent, {
    "aria-labelledby": "pf-tab-0-generatedAccessToken",
    eventKey: 2,
    id: "generatedAccessToken",
    ref: tabContent3,
    hidden: true
  }, user && /* @__PURE__ */ react.createElement(TextArea, {
    rows: 20,
    id: "accessToken",
    value: accessToken
  }), !user && /* @__PURE__ */ react.createElement(EmptyState, {
    variant: "large"
  }, /* @__PURE__ */ react.createElement(Title, {
    headingLevel: "h4",
    size: "lg"
  }, t5("noGeneratedAccessToken")), /* @__PURE__ */ react.createElement(EmptyStateBody, null, t5("generatedAccessTokenIsDisabled"))))), /* @__PURE__ */ react.createElement(GridItem, {
    span: 4
  }, /* @__PURE__ */ react.createElement(Tabs, {
    id: "tabs",
    key,
    isVertical: true,
    activeKey: activeTab,
    onSelect: (_23, key2) => setActiveTab(key2)
  }, /* @__PURE__ */ react.createElement(Tab, {
    id: "effectiveProtocolMappers",
    "aria-controls": "effectiveProtocolMappers",
    eventKey: 0,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("effectiveProtocolMappers"), " ", /* @__PURE__ */ react.createElement(HelpItem, {
      fieldLabelId: "clients:effectiveProtocolMappers",
      helpText: "clients-help:effectiveProtocolMappers",
      noVerticalAlign: false,
      unWrap: true
    })),
    tabContentRef: tabContent1
  }), /* @__PURE__ */ react.createElement(Tab, {
    id: "effectiveRoleScopeMappings",
    "aria-controls": "effectiveRoleScopeMappings",
    eventKey: 1,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("effectiveRoleScopeMappings"), " ", /* @__PURE__ */ react.createElement(HelpItem, {
      fieldLabelId: "clients:effectiveRoleScopeMappings",
      helpText: "clients-help:effectiveRoleScopeMappings",
      noVerticalAlign: false,
      unWrap: true
    })),
    tabContentRef: tabContent2
  }), /* @__PURE__ */ react.createElement(Tab, {
    id: "generatedAccessToken",
    "aria-controls": "generatedAccessToken",
    eventKey: 2,
    title: /* @__PURE__ */ react.createElement(TabTitleText, null, t5("generatedAccessToken"), " ", /* @__PURE__ */ react.createElement(HelpItem, {
      fieldLabelId: "clients:generatedAccessToken",
      helpText: "clients-help:generatedAccessToken",
      noVerticalAlign: false,
      unWrap: true
    })),
    tabContentRef: tabContent3
  })))));
};

// build/clients/service-account/ServiceAccount.js
var ServiceAccount = ({client: client2}) => {
  const {t: t5} = useTranslation("clients");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [hide3, setHide] = useState(false);
  const [serviceAccount, setServiceAccount] = useState();
  useFetch(() => adminClient.clients.getServiceAccountUser({
    id: client2.id
  }), (serviceAccount2) => setServiceAccount(serviceAccount2), []);
  const loader = async () => {
    const serviceAccount2 = await adminClient.clients.getServiceAccountUser({
      id: client2.id
    });
    const id3 = serviceAccount2.id;
    const assignedRoles = (await adminClient.users.listRealmRoleMappings({id: id3})).map((role) => ({role}));
    const effectiveRoles = (await adminClient.users.listCompositeRealmRoleMappings({id: id3})).map((role) => ({role}));
    const clients2 = await adminClient.clients.find();
    const clientRoles = (await Promise.all(clients2.map(async (client22) => {
      const clientAssignedRoles = (await adminClient.users.listClientRoleMappings({
        id: id3,
        clientUniqueId: client22.id
      })).map((role) => ({role, client: client22}));
      const clientEffectiveRoles = (await adminClient.users.listCompositeClientRoleMappings({
        id: id3,
        clientUniqueId: client22.id
      })).map((role) => ({role, client: client22}));
      return mapRoles(clientAssignedRoles, clientEffectiveRoles, hide3);
    }))).flat();
    return [...mapRoles(assignedRoles, effectiveRoles, hide3), ...clientRoles];
  };
  const assignRoles = async (rows) => {
    try {
      const realmRoles = rows.filter((row) => row.client === void 0).map((row) => row.role).flat();
      adminClient.users.addRealmRoleMappings({
        id: serviceAccount?.id,
        roles: realmRoles
      });
      await Promise.all(rows.filter((row) => row.client !== void 0).map((row) => adminClient.users.addClientRoleMappings({
        id: serviceAccount?.id,
        clientUniqueId: row.client.id,
        roles: [row.role]
      })));
      addAlert(t5("roleMappingUpdatedSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("clients:roleMappingUpdatedError", error2);
    }
  };
  return serviceAccount ? /* @__PURE__ */ react.createElement(RoleMapping, {
    name: client2.clientId,
    id: serviceAccount.id,
    type: "service-account",
    loader,
    save: assignRoles,
    onHideRolesToggle: () => setHide(!hide3)
  }) : null;
};

// build/clients/keys/SamlKeysDialog.js
var submitForm = async (form2, id3, attr2, adminClient, callback) => {
  try {
    const formData = new FormData();
    const {file, ...rest} = form2;
    Object.entries(rest).map(([key, value]) => formData.append(key === "format" ? "keystoreFormat" : key, value.toString()));
    formData.append("file", file);
    await adminClient.clients.uploadKey({id: id3, attr: attr2}, formData);
    callback();
  } catch (error2) {
    callback(error2);
  }
};
var SamlKeysDialog = ({
  id: id3,
  attr: attr2,
  onClose,
  onCancel
}) => {
  const {t: t5} = useTranslation("clients");
  const [type, setType] = useState(false);
  const [keys2, setKeys] = useState();
  const {
    register: register2,
    control,
    handleSubmit,
    formState: {isDirty}
  } = useForm();
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const submit = (form2) => {
    submitForm(form2, id3, attr2, adminClient, (error2) => {
      if (error2) {
        addError("clients:importError", error2);
      } else {
        addAlert(t5("importSuccess"), AlertVariant.success);
      }
    });
  };
  const generate = async () => {
    try {
      const key = await adminClient.clients.generateKey({
        id: id3,
        attr: attr2
      });
      setKeys(key);
      file_saver_default.saveAs(new Blob([key.privateKey], {
        type: "application/octet-stream"
      }), "private.key");
      addAlert(t5("generateSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("clients:generateError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.medium,
    "aria-labelledby": t5("enableClientSignatureRequired"),
    header: /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Title, {
      headingLevel: "h1"
    }, t5("enableClientSignatureRequired")), /* @__PURE__ */ react.createElement(Text, null, t5("enableClientSignatureRequiredExplain"))),
    isOpen: true,
    onClose,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-confirm",
        key: "confirm",
        "data-testid": "confirm",
        variant: "primary",
        isDisabled: !isDirty && !keys2,
        onClick: () => {
          if (type) {
            handleSubmit(submit)();
          }
          onClose();
        }
      }, t5("confirm")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        "data-testid": "cancel",
        variant: ButtonVariant.link,
        onClick: onCancel
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("selectMethod"),
    fieldId: "selectMethod",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Flex, null, /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Radio, {
    isChecked: !type,
    name: "selectMethodType",
    onChange: () => setType(false),
    label: t5("selectMethodType.generate"),
    id: "selectMethodType-generate"
  })), /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Radio, {
    isChecked: type,
    name: "selectMethodType",
    onChange: () => setType(true),
    label: t5("selectMethodType.import"),
    id: "selectMethodType-import"
  }))))), !type && /* @__PURE__ */ react.createElement(Form, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("certificate"),
    fieldId: "certificate",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:certificate",
      fieldLabelId: "clients:certificate"
    })
  }, /* @__PURE__ */ react.createElement(Split, {
    hasGutter: true
  }, /* @__PURE__ */ react.createElement(SplitItem, {
    isFilled: true
  }, /* @__PURE__ */ react.createElement(Certificate, {
    plain: true,
    keyInfo: keys2
  })), /* @__PURE__ */ react.createElement(SplitItem, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    "data-testid": "generate",
    onClick: generate
  }, t5("generate")))))), type && /* @__PURE__ */ react.createElement(KeyForm, {
    register: register2,
    control,
    useFile: true
  }));
};

// build/clients/keys/SamlImportKeyDialog.js
var SamlImportKeyDialog = ({
  id: id3,
  attr: attr2,
  onClose
}) => {
  const {t: t5} = useTranslation("clients");
  const {register: register2, control, handleSubmit} = useFormContext();
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const submit = (form2) => {
    submitForm(form2, id3, attr2, adminClient, (error2) => {
      if (error2) {
        addError("clients:importError", error2);
      } else {
        addAlert(t5("importSuccess"), AlertVariant.success);
      }
    });
  };
  return /* @__PURE__ */ react.createElement(ConfirmDialogModal, {
    open: true,
    toggleDialog: onClose,
    continueButtonLabel: "clients:import",
    titleKey: "clients:importKey",
    onConfirm: () => {
      handleSubmit(submit)();
      onClose();
    }
  }, /* @__PURE__ */ react.createElement(KeyForm, {
    register: register2,
    control,
    useFile: true
  }));
};

// build/clients/keys/SamlKeys.js
var KEYS = ["saml.signing", "saml.encryption"];
var KEYS_MAPPING = {
  "saml.signing": {
    name: "attributes.saml.client.signature",
    title: "signingKeysConfig",
    key: "clientSignature"
  },
  "saml.encryption": {
    name: "attributes.saml.encrypt",
    title: "encryptionKeysConfig",
    key: "encryptAssertions"
  }
};
var KeySection = ({
  keyInfo,
  attr: attr2,
  onChanged,
  onGenerate,
  onImport
}) => {
  const {t: t5} = useTranslation("clients");
  const {control, watch} = useFormContext();
  const title3 = KEYS_MAPPING[attr2].title;
  const key = KEYS_MAPPING[attr2].key;
  const name = KEYS_MAPPING[attr2].name;
  const section = watch(name);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormPanel, {
    title: t5(title3),
    className: "kc-form-panel__panel"
  }, /* @__PURE__ */ react.createElement(TextContent, {
    className: "pf-u-pb-lg"
  }, /* @__PURE__ */ react.createElement(Text, null, t5(`${title3}Explain`))), /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-clients",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: `clients-help:${key}`,
      fieldLabelId: `clients:${key}`
    }),
    label: t5(key),
    fieldId: key,
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name,
    control,
    defaultValue: "false",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      "data-testid": key,
      id: key,
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value === "true",
      onChange: (value2) => {
        const v2 = value2.toString();
        if (v2 === "true") {
          onChanged(attr2);
          onChange(v2);
        } else {
          onGenerate(attr2, false);
        }
      }
    })
  })))), keyInfo?.certificate && section === "true" && /* @__PURE__ */ react.createElement(Card, {
    isFlat: true
  }, /* @__PURE__ */ react.createElement(CardBody, {
    className: "kc-form-panel__body"
  }, /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(Certificate, {
    keyInfo
  }), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    onClick: () => onGenerate(attr2, true)
  }, t5("regenerate")), /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    onClick: () => onImport(attr2)
  }, t5("importKey")), /* @__PURE__ */ react.createElement(Button, {
    variant: "tertiary"
  }, t5("common:export")))))));
};
var SamlKeys = ({clientId, save}) => {
  const {t: t5} = useTranslation("clients");
  const [isChanged, setIsChanged] = useState();
  const [keyInfo, setKeyInfo] = useState();
  const [selectedType, setSelectedType] = useState();
  const [openImport, setImportOpen] = useState(false);
  const [refresh, setRefresh] = useState(0);
  const {setValue} = useFormContext();
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  useFetch(() => Promise.all(KEYS.map((attr2) => adminClient.clients.getKeyInfo({id: clientId, attr: attr2}))), (info2) => setKeyInfo(info2), [refresh]);
  const generate = async (attr2) => {
    const index3 = KEYS.indexOf(attr2);
    try {
      const info2 = [...keyInfo || []];
      info2[index3] = await adminClient.clients.generateKey({
        id: clientId,
        attr: attr2
      });
      setKeyInfo(info2);
      file_saver_default.saveAs(new Blob([info2[index3].privateKey], {
        type: "application/octet-stream"
      }), "private.key");
      addAlert(t5("generateSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("clients:generateError", error2);
    }
  };
  const key = selectedType ? KEYS_MAPPING[selectedType].key : "";
  const [toggleDisableDialog, DisableConfirm] = useConfirmDialog({
    titleKey: t5("disableSigning", {
      key: t5(key)
    }),
    messageKey: t5("disableSigningExplain", {
      key: t5(key)
    }),
    continueButtonLabel: "common:yes",
    cancelButtonLabel: "common:no",
    onConfirm: () => {
      setValue(KEYS_MAPPING[selectedType].name, "false");
      save();
    }
  });
  const [toggleReGenerateDialog, ReGenerateConfirm] = useConfirmDialog({
    titleKey: "clients:reGenerateSigning",
    messageKey: "clients:reGenerateSigningExplain",
    continueButtonLabel: "common:yes",
    cancelButtonLabel: "common:no",
    onConfirm: () => {
      generate(selectedType);
    }
  });
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light",
    className: "keycloak__form"
  }, isChanged && /* @__PURE__ */ react.createElement(SamlKeysDialog, {
    id: clientId,
    attr: isChanged,
    onClose: () => {
      setIsChanged(void 0);
      save();
      setRefresh(refresh + 1);
    },
    onCancel: () => {
      setValue(KEYS_MAPPING[selectedType].name, "false");
      setIsChanged(void 0);
    }
  }), /* @__PURE__ */ react.createElement(DisableConfirm, null), /* @__PURE__ */ react.createElement(ReGenerateConfirm, null), KEYS.map((attr2, index3) => /* @__PURE__ */ react.createElement(Fragment, {
    key: attr2
  }, openImport && /* @__PURE__ */ react.createElement(SamlImportKeyDialog, {
    id: clientId,
    attr: attr2,
    onClose: () => setImportOpen(false)
  }), /* @__PURE__ */ react.createElement(KeySection, {
    keyInfo: keyInfo?.[index3],
    attr: attr2,
    onChanged: setIsChanged,
    onGenerate: (type, isNew) => {
      setSelectedType(type);
      if (!isNew) {
        toggleDisableDialog();
      } else {
        toggleReGenerateDialog();
      }
    },
    onImport: () => setImportOpen(true)
  }))));
};

// build/clients/routes/Mapper.js
var MapperRoute2 = {
  path: "/:realm/clients/:id/mappers/:mapperId",
  component: lazy(() => Promise.resolve().then(() => require_MappingDetails())),
  breadcrumb: (t5) => t5("common:mappingDetails"),
  access: "view-clients"
};
var toMapper2 = (params) => ({
  pathname: generatePath(MapperRoute2.path, params)
});

// build/clients/authorization/ImportDialog.js
var ImportDialog = ({onConfirm, closeDialog}) => {
  const {t: t5} = useTranslation("clients");
  const [imported, setImported] = useState({});
  return /* @__PURE__ */ react.createElement(Modal, {
    title: t5("import"),
    isOpen: true,
    variant: "small",
    onClose: closeDialog,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-confirm",
        key: "confirm",
        onClick: () => {
          onConfirm(imported);
          closeDialog();
        },
        "data-testid": "confirm"
      }, t5("confirm")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "cancel",
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          closeDialog();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(Form, null, /* @__PURE__ */ react.createElement(JsonFileUpload, {
    id: "import-resource",
    onChange: setImported
  })), Object.keys(imported).length !== 0 && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Divider, null), /* @__PURE__ */ react.createElement("p", {
    className: "pf-u-my-lg"
  }, t5("importResources")), /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("policyEnforcementMode"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:policyEnforcementMode",
      fieldLabelId: "clients:policyEnforcementMode"
    }),
    fieldId: "policyEnforcementMode",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Radio, {
    id: "policyEnforcementMode",
    name: "policyEnforcementMode",
    label: t5(`policyEnforcementModes.${imported.policyEnforcementMode}`),
    isChecked: true,
    isDisabled: true,
    className: "pf-u-mb-md"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("decisionStrategy"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:decisionStrategy",
      fieldLabelId: "clients:decisionStrategy"
    }),
    fieldId: "decisionStrategy",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Radio, {
    id: "decisionStrategy",
    name: "decisionStrategy",
    isChecked: true,
    isDisabled: true,
    label: t5(`decisionStrategies.${imported.decisionStrategy}`),
    className: "pf-u-mb-md"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("allowRemoteResourceManagement"),
    fieldId: "allowRemoteResourceManagement",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: t5("allowRemoteResourceManagement"),
      fieldLabelId: "clients:allowRemoteResourceManagement"
    })
  }, /* @__PURE__ */ react.createElement(Switch, {
    id: "allowRemoteResourceManagement",
    label: t5("common:on"),
    labelOff: t5("common:off"),
    isChecked: imported.allowRemoteResourceManagement,
    isDisabled: true
  }))), /* @__PURE__ */ react.createElement("div", {
    className: "pf-u-mt-md"
  }, Object.entries(imported).filter(([, value]) => Array.isArray(value)).map(([key, value]) => /* @__PURE__ */ react.createElement(Fragment, {
    key
  }, /* @__PURE__ */ react.createElement(Divider, null), /* @__PURE__ */ react.createElement("p", {
    className: "pf-u-my-sm"
  }, /* @__PURE__ */ react.createElement("strong", null, value.length, " ", t5(key)))))), /* @__PURE__ */ react.createElement(Divider, null), /* @__PURE__ */ react.createElement(Alert, {
    variant: "warning",
    className: "pf-u-mt-lg",
    isInline: true,
    title: t5("importWarning")
  })));
};

// build/clients/authorization/Settings.js
var POLICY_ENFORCEMENT_MODES = [
  "ENFORCING",
  "PERMISSIVE",
  "DISABLED"
];
var DECISION_STRATEGY = ["UNANIMOUS", "AFFIRMATIVE"];
var AuthorizationSettings = ({clientId}) => {
  const {t: t5} = useTranslation("clients");
  const [resource2, setResource] = useState();
  const [importDialog, toggleImportDialog] = useToggle();
  const {control, reset: reset2, handleSubmit} = useForm({
    shouldUnregister: false
  });
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  useFetch(() => adminClient.clients.getResourceServer({id: clientId}), (resource22) => {
    setResource(resource22);
    reset2(resource22);
  }, []);
  const importResource = async (value) => {
    try {
      await adminClient.clients.importResource({id: clientId}, value);
      addAlert(t5("importResourceSuccess"), AlertVariant.success);
      reset2({...value});
    } catch (error2) {
      addError("clients:importResourceError", error2);
    }
  };
  const save = async (resource22) => {
    try {
      await adminClient.clients.updateResourceServer({id: clientId}, resource22);
      addAlert(t5("updateResourceSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("clients:resourceSaveError", error2);
    }
  };
  if (!resource2) {
    return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
  }
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, importDialog && /* @__PURE__ */ react.createElement(ImportDialog, {
    onConfirm: importResource,
    closeDialog: toggleImportDialog
  }), /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-clients",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("import"),
    fieldId: "import",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:import",
      fieldLabelId: "clients:import"
    })
  }, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    onClick: toggleImportDialog
  }, t5("import"))), /* @__PURE__ */ react.createElement(Divider, null), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("policyEnforcementMode"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:policyEnforcementMode",
      fieldLabelId: "clients:policyEnforcementMode"
    }),
    fieldId: "policyEnforcementMode",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "policyEnforcementMode",
    "data-testid": "policyEnforcementMode",
    defaultValue: DECISION_STRATEGY[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(react.Fragment, null, POLICY_ENFORCEMENT_MODES.map((mode) => /* @__PURE__ */ react.createElement(Radio, {
      id: mode,
      key: mode,
      "data-testid": mode,
      isChecked: value === mode,
      name: "policyEnforcementMode",
      onChange: () => onChange(mode),
      label: t5(`policyEnforcementModes.${mode}`),
      className: "pf-u-mb-md"
    })))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("decisionStrategy"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:decisionStrategy",
      fieldLabelId: "clients:decisionStrategy"
    }),
    fieldId: "decisionStrategy",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "decisionStrategy",
    "data-testid": "decisionStrategy",
    defaultValue: DECISION_STRATEGY[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(react.Fragment, null, DECISION_STRATEGY.map((strategy) => /* @__PURE__ */ react.createElement(Radio, {
      id: strategy,
      key: strategy,
      "data-testid": strategy,
      isChecked: value === strategy,
      name: "decisionStrategy",
      onChange: () => onChange(strategy),
      label: t5(`decisionStrategies.${strategy}`),
      className: "pf-u-mb-md"
    })))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("allowRemoteResourceManagement"),
    fieldId: "allowRemoteResourceManagement",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:allowRemoteResourceManagement",
      fieldLabelId: "clients:allowRemoteResourceManagement"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "allowRemoteResourceManagement",
    "data-testid": "allowRemoteResourceManagement",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "allowRemoteResourceManagement",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: value,
      onChange
    })
  })), /* @__PURE__ */ react.createElement(SaveReset, {
    name: "authenticationSettings",
    save: () => handleSubmit(save)(),
    reset: () => reset2(resource2)
  })));
};

// build/clients/authorization/DetailCell.js
var DetailCell = ({id: id3, clientId, uris}) => {
  const {t: t5} = useTranslation("clients");
  const adminClient = useAdminClient();
  const [scope, setScope] = useState();
  const [permissions, setPermissions] = useState();
  useFetch(() => Promise.all([
    adminClient.clients.listScopesByResource({
      id: clientId,
      resourceName: id3
    }),
    adminClient.clients.listPermissionsByResource({
      id: clientId,
      resourceId: id3
    })
  ]), ([scopes, permissions2]) => {
    setScope(scopes);
    setPermissions(permissions2);
  }, []);
  if (!permissions || !scope) {
    return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
  }
  return /* @__PURE__ */ react.createElement(DescriptionList, {
    isHorizontal: true,
    className: "keycloak_resource_details"
  }, /* @__PURE__ */ react.createElement(DescriptionListGroup, null, /* @__PURE__ */ react.createElement(DescriptionListTerm, null, t5("uris")), /* @__PURE__ */ react.createElement(DescriptionListDescription, null, uris?.map((uri) => /* @__PURE__ */ react.createElement("span", {
    key: uri,
    className: "pf-u-pr-sm"
  }, uri)), uris?.length === 0 && /* @__PURE__ */ react.createElement("i", null, t5("common:none")))), /* @__PURE__ */ react.createElement(DescriptionListGroup, null, /* @__PURE__ */ react.createElement(DescriptionListTerm, null, t5("scopes")), /* @__PURE__ */ react.createElement(DescriptionListDescription, null, scope.map((scope2) => /* @__PURE__ */ react.createElement("span", {
    key: scope2.id,
    className: "pf-u-pr-sm"
  }, scope2.name)), scope.length === 0 && /* @__PURE__ */ react.createElement("i", null, t5("common:none")))), /* @__PURE__ */ react.createElement(DescriptionListGroup, null, /* @__PURE__ */ react.createElement(DescriptionListTerm, null, t5("associatedPermissions")), /* @__PURE__ */ react.createElement(DescriptionListDescription, null, permissions.map((permission) => /* @__PURE__ */ react.createElement("span", {
    key: permission.id,
    className: "pf-u-pr-sm"
  }, permission.name)), permissions.length === 0 && /* @__PURE__ */ react.createElement("i", null, t5("common:none")))));
};

// build/clients/routes/Resource.js
var ResourceDetailsRoute = {
  path: "/:realm/clients/:id/authorization/:resourceId?",
  component: lazy(() => Promise.resolve().then(() => require_ResourceDetails())),
  breadcrumb: (t5) => t5("clients:createResource"),
  access: "manage-clients"
};
var toResourceDetails = (params) => ({
  pathname: generatePath(ResourceDetailsRoute.path, params)
});

// build/clients/authorization/ScopePicker.js
var ScopePicker = ({clientId}) => {
  const {t: t5} = useTranslation("clients");
  const {control} = useFormContext();
  const [open2, setOpen] = useState(false);
  const [scopes, setScopes] = useState();
  const [search2, setSearch] = useState("");
  const adminClient = useAdminClient();
  useFetch(() => {
    const params = {
      id: clientId,
      first: 0,
      max: 20,
      deep: false,
      name: search2
    };
    return adminClient.clients.listAllScopes(params);
  }, (scopes2) => setScopes(scopes2.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
    key: option.id,
    value: option
  }, option.name))), [search2]);
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("authorizationScopes"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:scopes",
      fieldLabelId: "clients:scopes"
    }),
    fieldId: "scopes"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "scopes",
    defaultValue: [],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "scopes",
      variant: SelectVariant.typeaheadMulti,
      chipGroupProps: {
        numChips: 3,
        expandedText: t5("common:hide"),
        collapsedText: t5("common:showRemaining")
      },
      onToggle: (open22) => setOpen(open22),
      isOpen: open2,
      selections: value.map((o) => o.name),
      onFilter: (_23, value2) => {
        setSearch(value2);
        return scopes;
      },
      onSelect: (_23, selectedValue) => {
        const option = typeof selectedValue === "string" ? selectedValue : selectedValue.name;
        const changedValue = value.find((o) => o.name === option) ? value.filter((item) => item.name !== option) : [...value, selectedValue];
        onChange(changedValue);
      },
      onClear: (event) => {
        event.stopPropagation();
        setSearch("");
        onChange([]);
      },
      "aria-label": t5("authorizationScopes")
    }, scopes)
  }));
};

// build/clients/routes/NewResource.js
var NewResourceRoute = {
  path: "/:realm/clients/:id/authorization/new",
  component: lazy(() => Promise.resolve().then(() => require_ResourceDetails())),
  breadcrumb: (t5) => t5("clients:createResource"),
  access: "manage-clients"
};
var toCreateResource = (params) => ({
  pathname: generatePath(NewResourceRoute.path, params)
});

// build/clients/authorization/Resources.js
var AuthorizationResources = ({clientId}) => {
  const {t: t5} = useTranslation("clients");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {realm: realm2} = useRealm();
  const [resources, setResources] = useState();
  const [selectedResource, setSelectedResource] = useState();
  const [permissions, setPermission] = useState();
  const [key, setKey] = useState(0);
  const refresh = () => setKey(key + 1);
  const [max2, setMax] = useState(10);
  const [first2, setFirst] = useState(0);
  useFetch(() => {
    const params = {
      first: first2,
      max: max2,
      deep: false
    };
    return adminClient.clients.listResources({
      ...params,
      id: clientId
    });
  }, (resources2) => setResources(resources2.map((resource2) => ({...resource2, isExpanded: false}))), [key]);
  const UriRenderer = ({row}) => /* @__PURE__ */ react.createElement(react.Fragment, null, row.uris?.[0], " ", (row.uris?.length || 0) > 1 && /* @__PURE__ */ react.createElement(Label, {
    color: "blue"
  }, t5("common:more", {count: (row.uris?.length || 1) - 1})));
  const fetchPermissions = async (id3) => {
    return adminClient.clients.listPermissionsByResource({
      id: clientId,
      resourceId: id3
    });
  };
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: "clients:deleteResource",
    children: /* @__PURE__ */ react.createElement(react.Fragment, null, t5("deleteResourceConfirm"), permissions?.length && /* @__PURE__ */ react.createElement(Alert, {
      variant: "warning",
      isInline: true,
      isPlain: true,
      title: t5("deleteResourceWarning"),
      className: "pf-u-pt-lg"
    }, /* @__PURE__ */ react.createElement("p", {
      className: "pf-u-pt-xs"
    }, permissions.map((permission) => /* @__PURE__ */ react.createElement("strong", {
      key: permission.id,
      className: "pf-u-pr-md"
    }, permission.name))))),
    continueButtonLabel: "clients:confirm",
    onConfirm: async () => {
      try {
        await adminClient.clients.delResource({
          id: clientId,
          resourceId: selectedResource?._id
        });
        addAlert(t5("resourceDeletedSuccess"), AlertVariant.success);
        refresh();
      } catch (error2) {
        addError("clients:resourceDeletedError", error2);
      }
    }
  });
  if (!resources) {
    return /* @__PURE__ */ react.createElement(KeycloakSpinner, null);
  }
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light",
    className: "pf-u-p-0"
  }, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(PaginatingTableToolbar, {
    count: resources.length,
    first: first2,
    max: max2,
    onNextClick: setFirst,
    onPreviousClick: setFirst,
    onPerPageSelect: (first22, max22) => {
      setFirst(first22);
      setMax(max22);
    },
    toolbarItem: /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "createResource",
      component: (props) => /* @__PURE__ */ react.createElement(Link, {
        ...props,
        to: toCreateResource({realm: realm2, id: clientId})
      })
    }, t5("createResource")))
  }, /* @__PURE__ */ react.createElement(TableComposable, {
    "aria-label": t5("resources"),
    variant: "compact"
  }, /* @__PURE__ */ react.createElement(Thead, null, /* @__PURE__ */ react.createElement(Tr, null, /* @__PURE__ */ react.createElement(Th2, null), /* @__PURE__ */ react.createElement(Th2, null, t5("common:name")), /* @__PURE__ */ react.createElement(Th2, null, t5("common:type")), /* @__PURE__ */ react.createElement(Th2, null, t5("owner")), /* @__PURE__ */ react.createElement(Th2, null, t5("uris")), /* @__PURE__ */ react.createElement(Th2, null))), resources.map((resource2, rowIndex) => /* @__PURE__ */ react.createElement(Tbody, {
    key: resource2._id,
    isExpanded: resource2.isExpanded
  }, /* @__PURE__ */ react.createElement(Tr, null, /* @__PURE__ */ react.createElement(Td2, {
    expand: {
      rowIndex,
      isExpanded: resource2.isExpanded,
      onToggle: (_23, rowIndex2) => {
        const rows = resources.map((resource22, index3) => index3 === rowIndex2 ? {...resource22, isExpanded: !resource22.isExpanded} : resource22);
        setResources(rows);
      }
    }
  }), /* @__PURE__ */ react.createElement(Td2, {
    "data-testid": `name-column-${resource2.name}`
  }, /* @__PURE__ */ react.createElement(Link, {
    to: toResourceDetails({
      realm: realm2,
      id: clientId,
      resourceId: resource2._id
    })
  }, resource2.name)), /* @__PURE__ */ react.createElement(Td2, null, resource2.type), /* @__PURE__ */ react.createElement(Td2, null, resource2.owner?.name), /* @__PURE__ */ react.createElement(Td2, null, /* @__PURE__ */ react.createElement(UriRenderer, {
    row: resource2
  })), /* @__PURE__ */ react.createElement(Td2, {
    actions: {
      items: [
        {
          title: t5("common:delete"),
          onClick: async () => {
            setSelectedResource(resource2);
            setPermission(await fetchPermissions(resource2._id));
            toggleDeleteDialog();
          }
        },
        {
          title: t5("createPermission"),
          className: "pf-m-link",
          isOutsideDropdown: true
        }
      ]
    }
  })), /* @__PURE__ */ react.createElement(Tr, {
    key: `child-${resource2._id}`,
    isExpanded: resource2.isExpanded
  }, /* @__PURE__ */ react.createElement(Td2, {
    colSpan: 5
  }, /* @__PURE__ */ react.createElement(ExpandableRowContent, null, resource2.isExpanded && /* @__PURE__ */ react.createElement(DetailCell, {
    clientId,
    id: resource2._id,
    uris: resource2.uris
  })))))))));
};

// build/clients/routes/Client.js
var ClientRoute = {
  path: "/:realm/clients/:clientId/:tab",
  component: lazy(() => Promise.resolve().then(() => require_ClientDetails())),
  breadcrumb: (t5) => t5("clients:clientSettings"),
  access: "view-clients"
};
var toClient = (params) => ({
  pathname: generatePath(ClientRoute.path, params)
});

// build/clients/add/GeneralSettings.js
var GeneralSettings = () => {
  const {t: t5} = useTranslation("clients");
  const {errors, control} = useFormContext();
  const providers = useLoginProviders();
  const [open2, isOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "manage-clients"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("clientType"),
    fieldId: "kc-type",
    validated: errors.protocol ? "error" : "default",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "clients-help:clientType",
      fieldLabelId: "clients:clientType"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "protocol",
    defaultValue: "",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      id: "kc-type",
      onToggle: isOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        isOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("selectEncryptionType"),
      isOpen: open2
    }, providers.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      key: option,
      value: option,
      "data-testid": `option-${option}`
    }, getProtocolName(t5, option))))
  })), /* @__PURE__ */ react.createElement(ClientDescription, null));
};

// build/clients/routes/AddClient.js
var AddClientRoute = {
  path: "/:realm/clients/add-client",
  component: lazy(() => Promise.resolve().then(() => require_NewClientForm())),
  breadcrumb: (t5) => t5("clients:createClient"),
  access: "manage-clients"
};
var toAddClient = (params) => ({
  pathname: generatePath(AddClientRoute.path, params)
});

// build/clients/routes.js
var routes3 = [
  AddClientRoute,
  ImportClientRoute,
  ClientsRoute,
  CreateInitialAccessTokenRoute,
  ClientRoute,
  MapperRoute2,
  NewResourceRoute,
  ResourceDetailsRoute
];
var routes_default3 = routes3;

// build/dashboard/routes.js
var routes4 = [DashboardRoute];
var routes_default4 = routes4;

// build/user/UserForm.js
var import_moment3 = __toModule(require_moment());
var UserForm = ({
  user,
  bruteForce: {isBruteForceProtected, isLocked} = {
    isBruteForceProtected: false,
    isLocked: false
  },
  save,
  onGroupsUpdate
}) => {
  const {t: t5} = useTranslation("users");
  const {realm: realm2} = useRealm();
  const [
    isRequiredUserActionsDropdownOpen,
    setRequiredUserActionsDropdownOpen
  ] = useState(false);
  const history = useHistory();
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {handleSubmit, register: register2, errors, watch, control, reset: reset2} = useFormContext();
  const watchUsernameInput = watch("username");
  const [selectedGroups, setSelectedGroups] = useState([]);
  const [open2, setOpen] = useState(false);
  const [locked, setLocked] = useState(isLocked);
  const unLockUser = async () => {
    try {
      await adminClient.attackDetection.del({id: user.id});
      addAlert(t5("unlockSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("users:unlockError", error2);
    }
  };
  const requiredUserActionsOptions = [
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: 0,
      value: "CONFIGURE_TOTP"
    }, t5("configureOTP")),
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: 1,
      value: "UPDATE_PASSWORD"
    }, t5("updatePassword")),
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: 2,
      value: "UPDATE_PROFILE"
    }, t5("updateProfile")),
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: 3,
      value: "VERIFY_EMAIL"
    }, t5("verifyEmail"))
  ];
  const clearSelection = () => {
    setRequiredUserActionsDropdownOpen(false);
  };
  const deleteItem = (id3) => {
    setSelectedGroups(selectedGroups.filter((item) => item.name !== id3));
    onGroupsUpdate(selectedGroups);
  };
  const addChips = async (groups2) => {
    setSelectedGroups([...selectedGroups, ...groups2]);
    onGroupsUpdate([...selectedGroups, ...groups2]);
  };
  const addGroups = async (groups2) => {
    const newGroups = groups2;
    newGroups.forEach(async (group) => {
      try {
        await adminClient.users.addToGroup({
          id: user.id,
          groupId: group.id
        });
        addAlert(t5("users:addedGroupMembership"), AlertVariant.success);
      } catch (error2) {
        addError("users:addedGroupMembershipError", error2);
      }
    });
  };
  const toggleModal = () => {
    setOpen(!open2);
  };
  return /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    onSubmit: handleSubmit(save),
    role: "manage-users",
    className: "pf-u-mt-lg"
  }, open2 && /* @__PURE__ */ react.createElement(GroupPickerDialog, {
    type: "selectMany",
    text: {
      title: "users:selectGroups",
      ok: "users:join"
    },
    onConfirm: (groups2) => {
      user?.id ? addGroups(groups2) : addChips(groups2);
      setOpen(false);
    },
    onClose: () => setOpen(false),
    filterGroups: selectedGroups.map((group) => group.name)
  }), user?.id ? /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:id"),
    fieldId: "kc-id",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    id: user.id,
    value: user.id,
    type: "text",
    isReadOnly: true
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("createdAt"),
    fieldId: "kc-created-at",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    value: (0, import_moment3.default)(user.createdTimestamp).format("MM/DD/YY hh:MM:ss A"),
    type: "text",
    id: "kc-created-at",
    name: "createdTimestamp",
    isReadOnly: true
  }))) : /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("username"),
    fieldId: "kc-username",
    isRequired: true,
    validated: errors.username ? "error" : "default",
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2(),
    type: "text",
    id: "kc-username",
    name: "username",
    isReadOnly: !!user?.id
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("email"),
    fieldId: "kc-description",
    validated: errors.email ? "error" : "default",
    helperTextInvalid: t5("users:emailInvalid")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2({
      pattern: emailRegexPattern
    }),
    type: "email",
    id: "kc-email",
    name: "email",
    "data-testid": "email-input",
    "aria-label": t5("emailInput")
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("emailVerified"),
    fieldId: "kc-email-verified",
    helperTextInvalid: t5("common:required"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-help:emailVerified",
      fieldLabelId: "users:emailVerified"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "emailVerified",
    defaultValue: false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      "data-testid": "email-verified-switch",
      id: "kc-user-email-verified",
      isDisabled: false,
      onChange: (value2) => onChange(value2),
      isChecked: value,
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("firstName"),
    fieldId: "kc-firstname",
    validated: errors.firstName ? "error" : "default",
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2(),
    "data-testid": "firstName-input",
    type: "text",
    id: "kc-firstname",
    name: "firstName"
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("lastName"),
    fieldId: "kc-name",
    validated: errors.lastName ? "error" : "default"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2(),
    "data-testid": "lastName-input",
    type: "text",
    id: "kc-lastname",
    name: "lastName",
    "aria-label": t5("lastName")
  })), isBruteForceProtected && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("temporaryLocked"),
    fieldId: "temporaryLocked",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-help:temporaryLocked",
      fieldLabelId: "users:temporaryLocked"
    })
  }, /* @__PURE__ */ react.createElement(Switch, {
    "data-testid": "user-locked-switch",
    id: "temporaryLocked",
    onChange: (value) => {
      unLockUser();
      setLocked(value);
    },
    isChecked: locked,
    isDisabled: !locked,
    label: t5("common:on"),
    labelOff: t5("common:off")
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:enabled"),
    fieldId: "kc-enabled",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-help:disabled",
      fieldLabelId: "enabled"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "enabled",
    defaultValue: true,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      "data-testid": "user-enabled-switch",
      id: "kc-user-enabled",
      onChange: (value2) => onChange(value2),
      isChecked: value,
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("requiredUserActions"),
    fieldId: "kc-required-user-actions",
    validated: errors.requiredActions ? "error" : "default",
    helperTextInvalid: t5("common:required"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-help:requiredUserActions",
      fieldLabelId: "users:requiredUserActions"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "requiredActions",
    defaultValue: [],
    typeAheadAriaLabel: "Select an action",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      "data-testid": "required-actions-select",
      placeholderText: "Select action",
      toggleId: "kc-required-user-actions",
      onToggle: () => setRequiredUserActionsDropdownOpen(!isRequiredUserActionsDropdownOpen),
      isOpen: isRequiredUserActionsDropdownOpen,
      selections: value,
      onSelect: (_23, v2) => {
        const option = v2;
        if (value.includes(option)) {
          onChange(value.filter((item) => item !== option));
        } else {
          onChange([...value, option]);
        }
      },
      onClear: clearSelection,
      variant: "typeaheadmulti"
    }, requiredUserActionsOptions)
  })), !user?.id && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:groups"),
    fieldId: "kc-groups",
    validated: errors.requiredActions ? "error" : "default",
    helperTextInvalid: t5("common:required"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-help:groups",
      fieldLabelId: "groups"
    })
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "groups",
    defaultValue: [],
    typeAheadAriaLabel: "Select an action",
    control,
    render: () => /* @__PURE__ */ react.createElement(InputGroup, null, /* @__PURE__ */ react.createElement(ChipGroup, {
      categoryName: " "
    }, selectedGroups.map((currentChip) => /* @__PURE__ */ react.createElement(Chip, {
      key: currentChip.id,
      onClick: () => deleteItem(currentChip.name)
    }, currentChip.path))), /* @__PURE__ */ react.createElement(Button, {
      id: "kc-join-groups-button",
      onClick: toggleModal,
      variant: "secondary",
      "data-testid": "join-groups-button"
    }, t5("users:joinGroups")))
  })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
    "data-testid": !user?.id ? "create-user" : "save-user",
    isDisabled: !user?.id && !watchUsernameInput,
    variant: "primary",
    type: "submit"
  }, user?.id ? t5("common:save") : t5("common:create")), /* @__PURE__ */ react.createElement(Button, {
    "data-testid": "cancel-create-user",
    onClick: () => user?.id ? reset2(user) : history.push(`/${realm2}/users`),
    variant: "link"
  }, user?.id ? t5("common:revert") : t5("common:cancel"))));
};

// build/user/UserGroups.js
var UserGroups = ({user}) => {
  const {t: t5} = useTranslation("users");
  const {addAlert, addError} = useAlerts();
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const [selectedGroups, setSelectedGroups] = useState([]);
  const [search2, setSearch] = useState("");
  const [isDirectMembership, setDirectMembership] = useState(true);
  const [directMembershipList, setDirectMembershipList] = useState([]);
  const [open2, setOpen] = useState(false);
  const {enabled} = useHelp();
  const adminClient = useAdminClient();
  const alphabetize = (groupsList) => {
    return sortBy(groupsList, (group) => group.path?.toUpperCase());
  };
  const loader = async (first2, max2, search22) => {
    const params = {
      first: first2,
      max: max2
    };
    const searchParam = search22 || "";
    if (searchParam) {
      params.search = searchParam;
      setSearch(searchParam);
    }
    const joinedUserGroups = await adminClient.users.listGroups({
      ...params,
      id: user.id
    });
    const allCreatedGroups = await adminClient.groups.find();
    const getAllPaths = joinedUserGroups.reduce((acc, cur) => (cur.path && acc.push(cur.path), acc), []);
    const parentGroupNames = [];
    const allGroupMembership = [];
    const slicedGroups = [];
    const rootLevelGroups = [...allCreatedGroups];
    let allPaths = [];
    const getAllSubgroupPaths = (o, f2, context2) => {
      f2(o, context2);
      if (typeof o !== "object")
        return context2;
      if (Array.isArray(o))
        return o.forEach((e2) => getAllSubgroupPaths(e2, f2, context2)), context2;
      for (const prop in o)
        getAllSubgroupPaths(o[prop], f2, context2);
      return context2;
    };
    const arr = getAllSubgroupPaths(rootLevelGroups, (x2, context2) => {
      if (x2?.subGroups)
        context2.push(x2.subGroups);
    }, []);
    const allSubgroups = [].concat(...arr);
    allPaths = [...rootLevelGroups, ...allSubgroups];
    getAllPaths.forEach((item) => {
      const paths = item.split("/");
      const groups2 = [];
      paths.reduce((acc, value) => {
        const path = acc + "/" + value;
        groups2.push(path);
        return path;
      }, "");
      for (let i3 = 1; i3 < groups2.length; i3++) {
        slicedGroups.push(groups2[i3].substring(1));
      }
    });
    allGroupMembership.push(...slicedGroups);
    allPaths.forEach((item) => {
      if (item.subGroups.length !== 0) {
        allPaths.push(...item.subGroups);
      }
    });
    allPaths = allPaths.filter((group) => allGroupMembership.includes(group.path));
    const topLevelGroups = allCreatedGroups.filter((value) => parentGroupNames.includes(value.name));
    const subgroupArray = [];
    topLevelGroups.forEach((group) => subgroupArray.push(group.subGroups));
    const directMembership = joinedUserGroups.filter((value) => !topLevelGroups.includes(value));
    setDirectMembershipList(directMembership);
    const filterDupesfromGroups = allPaths.filter((thing, index3, self2) => index3 === self2.findIndex((t22) => t22.name === thing.name));
    if (!isDirectMembership) {
      return alphabetize(filterDupesfromGroups);
    }
    return alphabetize(directMembership);
  };
  useEffect(() => {
    refresh();
  }, [isDirectMembership]);
  const AliasRenderer = (group) => group.name;
  const toggleModal = () => {
    setOpen(!open2);
  };
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: t5("leaveGroup", {
      count: selectedGroups.length,
      name: selectedGroups[0]?.name
    }),
    messageKey: t5("leaveGroupConfirmDialog", {
      count: selectedGroups.length,
      groupname: selectedGroups[0]?.name,
      username: user.username
    }),
    continueButtonLabel: "leave",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        await Promise.all(selectedGroups.map((group) => adminClient.users.delFromGroup({
          id: user.id,
          groupId: group.id
        })));
        refresh();
        addAlert(t5("removedGroupMembership"), AlertVariant.success);
      } catch (error2) {
        addError("users:removedGroupMembershipError", error2);
      }
    }
  });
  const leave = (group) => {
    setSelectedGroups(group);
    toggleDeleteDialog();
  };
  const LeaveButtonRenderer = (group) => {
    const canLeaveGroup = directMembershipList.some((item) => item.id === group.id) || directMembershipList.length === 0 || isDirectMembership;
    return canLeaveGroup && /* @__PURE__ */ react.createElement(Button, {
      "data-testid": `leave-${group.name}`,
      onClick: () => leave([group]),
      variant: "link"
    }, t5("leave"));
  };
  const addGroups = async (groups2) => {
    const newGroups = groups2;
    newGroups.forEach(async (group) => {
      try {
        await adminClient.users.addToGroup({
          id: user.id,
          groupId: group.id
        });
        refresh();
        addAlert(t5("addedGroupMembership"), AlertVariant.success);
      } catch (error2) {
        addError("users:addedGroupMembershipError", error2);
      }
    });
  };
  const Path = (group) => /* @__PURE__ */ react.createElement(GroupPath, {
    group
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), open2 && /* @__PURE__ */ react.createElement(GroupPickerDialog, {
    id: user.id,
    type: "selectMany",
    text: {
      title: t5("joinGroupsFor", {username: user.username}),
      ok: "users:join"
    },
    onClose: () => setOpen(false),
    onConfirm: (groups2) => {
      addGroups(groups2);
      setOpen(false);
      refresh();
    }
  }), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key,
    loader,
    className: "keycloak_user-section_groups-table",
    isPaginated: true,
    ariaLabelKey: "roles:roleList",
    searchPlaceholderKey: "groups:searchGroup",
    canSelectAll: true,
    onSelect: (groups2) => isDirectMembership ? setSelectedGroups(groups2) : setSelectedGroups(intersectionBy(groups2, directMembershipList, "id")),
    isRowDisabled: (group) => !isDirectMembership && directMembershipList.every((item) => item.id !== group.id),
    toolbarItem: /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Button, {
      className: "kc-join-group-button",
      onClick: toggleModal,
      "data-testid": "add-group-button"
    }, t5("joinGroup")), /* @__PURE__ */ react.createElement(Checkbox, {
      label: t5("directMembership"),
      key: "direct-membership-check",
      id: "kc-direct-membership-checkbox",
      onChange: () => setDirectMembership(!isDirectMembership),
      isChecked: isDirectMembership,
      className: "direct-membership-check"
    }), /* @__PURE__ */ react.createElement(Button, {
      onClick: () => leave(selectedGroups),
      "data-testid": "leave-group-button",
      variant: "link",
      isDisabled: selectedGroups.length === 0
    }, t5("leave")), enabled && /* @__PURE__ */ react.createElement(Popover, {
      "aria-label": "Basic popover",
      position: "bottom",
      bodyContent: /* @__PURE__ */ react.createElement("div", null, t5("whoWillAppearPopoverText"))
    }, /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      className: "kc-who-will-appear-button",
      key: "who-will-appear-button",
      icon: /* @__PURE__ */ react.createElement(QuestionCircleIcon, null)
    }, t5("whoWillAppearLinkText")))),
    columns: [
      {
        name: "groupMembership",
        displayKey: "users:groupMembership",
        cellRenderer: AliasRenderer,
        cellFormatters: [emptyFormatter()],
        transforms: [cellWidth(40)]
      },
      {
        name: "path",
        displayKey: "users:path",
        cellRenderer: Path,
        transforms: [cellWidth(45)]
      },
      {
        name: "",
        cellRenderer: LeaveButtonRenderer,
        cellFormatters: [emptyFormatter()],
        transforms: [cellWidth(20)]
      }
    ],
    emptyState: !search2 ? /* @__PURE__ */ react.createElement(ListEmptyState, {
      hasIcon: true,
      message: t5("noGroups"),
      instructions: t5("noGroupsText"),
      primaryActionText: t5("joinGroup"),
      onPrimaryAction: toggleModal
    }) : ""
  }));
};

// build/user/UserConsents.js
var import_moment4 = __toModule(require_moment());
var UserConsents = () => {
  const [selectedClient, setSelectedClient] = useState();
  const {t: t5} = useTranslation("roles");
  const {addAlert, addError} = useAlerts();
  const [key, setKey] = useState(0);
  const adminClient = useAdminClient();
  const {id: id3} = useParams();
  const alphabetize = (consentsList) => {
    return lodash.sortBy(consentsList, (client2) => client2.clientId?.toUpperCase());
  };
  const refresh = () => setKey(new Date().getTime());
  const loader = async () => {
    const getConsents = await adminClient.users.listConsents({id: id3});
    return alphabetize(getConsents);
  };
  const clientScopesRenderer = ({
    grantedClientScopes
  }) => {
    return /* @__PURE__ */ react.createElement(ChipGroup, {
      className: "kc-consents-chip-group"
    }, grantedClientScopes.map((currentChip) => /* @__PURE__ */ react.createElement(Chip, {
      key: currentChip,
      isReadOnly: true,
      className: "kc-consents-chip",
      id: "consents-chip-text"
    }, currentChip)));
  };
  const createdRenderer = ({createDate}) => {
    return /* @__PURE__ */ react.createElement(react.Fragment, null, (0, import_moment4.default)(createDate).format("MM/DD/YY hh:MM A"));
  };
  const lastUpdatedRenderer = ({
    lastUpdatedDate
  }) => {
    return /* @__PURE__ */ react.createElement(react.Fragment, null, (0, import_moment4.default)(lastUpdatedDate).format("MM/DD/YY hh:MM A"));
  };
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: "users:revokeClientScopesTitle",
    messageKey: t5("users:revokeClientScopes", {
      clientId: selectedClient?.clientId
    }),
    continueButtonLabel: "common:delete",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        await adminClient.users.revokeConsent({
          id: id3,
          clientId: selectedClient.clientId
        });
        refresh();
        addAlert(t5("deleteGrantsSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("roles:deleteGrantsError", error2);
      }
    }
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    loader,
    key,
    ariaLabelKey: "roles:roleList",
    searchPlaceholderKey: " ",
    columns: [
      {
        name: "clientId",
        displayKey: "clients:Client",
        cellFormatters: [emptyFormatter()],
        transforms: [cellWidth(20)]
      },
      {
        name: "grantedClientScopes",
        displayKey: "client-scopes:grantedClientScopes",
        cellFormatters: [emptyFormatter()],
        cellRenderer: clientScopesRenderer,
        transforms: [cellWidth(30)]
      },
      {
        name: "createdDate",
        displayKey: "clients:created",
        cellFormatters: [emptyFormatter()],
        cellRenderer: createdRenderer,
        transforms: [cellWidth(20)]
      },
      {
        name: "lastUpdatedDate",
        displayKey: "clients:lastUpdated",
        cellFormatters: [emptyFormatter()],
        cellRenderer: lastUpdatedRenderer,
        transforms: [cellWidth(10)]
      }
    ],
    actions: [
      {
        title: t5("users:revoke"),
        onRowClick: (client2) => {
          setSelectedClient(client2);
          toggleDeleteDialog();
        }
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      hasIcon: true,
      icon: CubesIcon,
      message: t5("users:noConsents"),
      instructions: t5("users:noConsentsText")
    })
  }));
};

// build/user/UserIdPModal.js
var UserIdpModal = ({
  federatedId,
  handleModalToggle,
  refresh
}) => {
  const {t: t5} = useTranslation("users");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {register: register2, errors, handleSubmit, formState} = useForm({
    mode: "onChange"
  });
  const {id: id3} = useParams();
  const submitForm2 = async (fedIdentity) => {
    try {
      await adminClient.users.addToFederatedIdentity({
        id: id3,
        federatedIdentityId: federatedId,
        federatedIdentity: fedIdentity
      });
      addAlert(t5("users:idpLinkSuccess"), AlertVariant.success);
      handleModalToggle();
      refresh();
    } catch (error2) {
      addError("users:couldNotLinkIdP", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    title: t5("users:linkAccountTitle", {
      provider: lodash.capitalize(federatedId)
    }),
    isOpen: true,
    onClose: handleModalToggle,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": t5("link"),
        key: "confirm",
        variant: "primary",
        type: "submit",
        form: "group-form",
        isDisabled: !formState.isValid
      }, t5("link")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          handleModalToggle();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(Form, {
    id: "group-form",
    onSubmit: handleSubmit(submitForm2)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    name: "idp-name-group",
    label: t5("users:identityProvider"),
    fieldId: "idp-name",
    helperTextInvalid: t5("common:required"),
    validated: errors.identityProvider ? ValidatedOptions.error : ValidatedOptions.default
  }, /* @__PURE__ */ react.createElement(TextInput, {
    "data-testid": "idpNameInput",
    "aria-label": "Identity provider name input",
    ref: register2({required: true}),
    autoFocus: true,
    isReadOnly: true,
    type: "text",
    id: "link-idp-name",
    name: "identityProvider",
    value: lodash.capitalize(federatedId),
    validated: errors.identityProvider ? ValidatedOptions.error : ValidatedOptions.default
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    name: "user-id-group",
    label: t5("users:userID"),
    fieldId: "user-id",
    helperText: t5("users-help:userIdHelperText"),
    helperTextInvalid: t5("common:required"),
    validated: errors.userId ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    "data-testid": "userIdInput",
    "aria-label": "user ID input",
    ref: register2({required: true}),
    autoFocus: true,
    type: "text",
    id: "link-idp-user-id",
    name: "userId",
    validated: errors.userId ? ValidatedOptions.error : ValidatedOptions.default
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    name: "username-group",
    label: t5("users:username"),
    fieldId: "username",
    helperText: t5("users-help:usernameHelperText"),
    helperTextInvalid: t5("common:required"),
    validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    "data-testid": "usernameInput",
    "aria-label": "username input",
    ref: register2({required: true}),
    autoFocus: true,
    type: "text",
    id: "link-idp-username",
    name: "userName",
    validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default
  }))));
};

// build/identity-providers/component/RedirectUrl.js
var RedirectUrl = ({id: id3}) => {
  const {t: t5} = useTranslation("identity-providers");
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const callbackUrl = `${getBaseUrl(adminClient)}realms/${realm2}/broker`;
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("redirectURI"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:redirectURI",
      fieldLabelId: "identity-providers:redirectURI"
    }),
    fieldId: "kc-redirect-uri"
  }, /* @__PURE__ */ react.createElement(ClipboardCopy, {
    isReadOnly: true
  }, `${callbackUrl}/${id3}/endpoint`));
};

// build/identity-providers/component/ClientIdSecret.js
var ClientIdSecret = ({
  secretRequired = true,
  create: create3 = true
}) => {
  const {t: t5} = useTranslation("identity-providers");
  const {register: register2, errors} = useFormContext();
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("clientId"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:clientId",
      fieldLabelId: "identity-providers:clientId"
    }),
    fieldId: "kc-client-id",
    isRequired: true,
    validated: errors.config?.clientId ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    id: "kc-client-id",
    "data-testid": "clientId",
    name: "config.clientId",
    ref: register2({required: true})
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("clientSecret"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:clientSecret",
      fieldLabelId: "identity-providers:clientSecret"
    }),
    fieldId: "kc-client-secret",
    isRequired: secretRequired,
    validated: errors.config?.clientSecret ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:required")
  }, create3 && /* @__PURE__ */ react.createElement(PasswordInput, {
    isRequired: secretRequired,
    id: "kc-client-secret",
    "data-testid": "clientSecret",
    name: "config.clientSecret",
    ref: register2({required: secretRequired})
  }), !create3 && /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: secretRequired,
    type: "password",
    id: "kc-client-secret",
    "data-testid": "clientSecret",
    name: "config.clientSecret",
    ref: register2({required: secretRequired})
  })));
};

// build/identity-providers/component/DisplayOrder.js
var DisplayOrder = () => {
  const {t: t5} = useTranslation("identity-providers");
  const {control} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("displayOrder"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:displayOrder",
      fieldLabelId: "identity-providers:displayOrder"
    }),
    fieldId: "kc-display-order"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.guiOrder",
    control,
    defaultValue: 0,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(NumberInput, {
      value,
      "data-testid": "displayOrder",
      min: 0,
      onMinus: () => onChange(Number.parseInt(value) - 1),
      onChange,
      onPlus: () => onChange(Number.parseInt(value) + 1),
      inputName: "input",
      inputAriaLabel: t5("displayOrder"),
      minusBtnAriaLabel: t5("common:minus"),
      plusBtnAriaLabel: t5("common:plus")
    })
  }));
};

// build/identity-providers/add/GeneralSettings.js
var GeneralSettings2 = ({
  create: create3 = true,
  id: id3
}) => /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(RedirectUrl, {
  id: id3
}), /* @__PURE__ */ react.createElement(ClientIdSecret, {
  create: create3
}), /* @__PURE__ */ react.createElement(DisplayOrder, null));

// build/identity-providers/component/FormGroupField.js
var FormGroupField = ({
  label: label2,
  children: children2
}) => {
  const {t: t5} = useTranslation("identity-providers");
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    fieldId: label2,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: `identity-providers-help:${label2}`,
      fieldLabelId: `identity-providers:${label2}`
    })
  }, children2);
};

// build/identity-providers/component/SwitchField.js
var SwitchField = ({
  label: label2,
  field,
  fieldType = "string",
  isReadOnly = false
}) => {
  const {t: t5} = useTranslation("identity-providers");
  const {control} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormGroupField, {
    label: label2
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: field,
    defaultValue: fieldType === "string" ? "false" : false,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: label2,
      label: t5("common:on"),
      labelOff: t5("common:off"),
      isChecked: fieldType === "string" ? value === "true" : value,
      onChange: (value2) => onChange(fieldType === "string" ? "" + value2 : value2),
      isDisabled: isReadOnly
    })
  }));
};

// build/identity-providers/component/TextField.js
var TextField = ({label: label2, field, isReadOnly = false}) => {
  const {register: register2} = useFormContext();
  return /* @__PURE__ */ react.createElement(FormGroupField, {
    label: label2
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: label2,
    "data-testid": label2,
    name: field,
    ref: register2,
    isReadOnly
  }));
};

// build/identity-providers/add/AdvancedSettings.js
var LoginFlow = ({
  field,
  label: label2,
  defaultValue
}) => {
  const {t: t5} = useTranslation("identity-providers");
  const {control} = useFormContext();
  const adminClient = useAdminClient();
  const [flows, setFlows] = useState();
  const [open2, setOpen] = useState(false);
  useFetch(() => adminClient.authenticationManagement.getFlows(), (flows2) => setFlows(flows2.filter((flow) => flow.providerId === "basic-flow")), []);
  return /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5(label2),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: `identity-providers-help:${label2}`,
      fieldLabelId: `identity-providers:${label2}`
    }),
    fieldId: label2
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: field,
    defaultValue,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: label2,
      required: true,
      onToggle: () => setOpen(!open2),
      onSelect: (_23, value2) => {
        onChange(value2);
        setOpen(false);
      },
      selections: value || t5("common:none"),
      variant: SelectVariant.single,
      "aria-label": t5(label2),
      isOpen: open2
    }, /* @__PURE__ */ react.createElement(react.Fragment, null, defaultValue === "" && /* @__PURE__ */ react.createElement(SelectOption, {
      key: "empty",
      value: defaultValue
    }, t5("common:none"))), /* @__PURE__ */ react.createElement(react.Fragment, null, flows?.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option.alias === value,
      key: option.id,
      value: option.alias
    }, option.alias))))
  }));
};
var syncModes = ["import", "legacy", "force"];
var AdvancedSettings2 = ({isOIDC, isSAML}) => {
  const {t: t5} = useTranslation("identity-providers");
  const {control} = useFormContext();
  const [syncModeOpen, setSyncModeOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, !isOIDC && !isSAML && /* @__PURE__ */ react.createElement(TextField, {
    field: "config.defaultScope",
    label: "scopes"
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "storeToken",
    label: "storeTokens",
    fieldType: "boolean"
  }), (isSAML || isOIDC) && /* @__PURE__ */ react.createElement(SwitchField, {
    field: "addReadTokenRoleOnCreate",
    label: "storedTokensReadable",
    fieldType: "boolean"
  }), !isOIDC && !isSAML && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.acceptsPromptNoneForwardFromClient",
    label: "acceptsPromptNone"
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.disableUserInfo",
    label: "disableUserInfo"
  })), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "trustEmail",
    label: "trustEmail",
    fieldType: "boolean"
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "linkOnly",
    label: "accountLinkingOnly",
    fieldType: "boolean"
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.hideOnLoginPage",
    label: "hideOnLoginPage"
  }), /* @__PURE__ */ react.createElement(LoginFlow, {
    field: "firstBrokerLoginFlowAlias",
    label: "firstBrokerLoginFlowAlias",
    defaultValue: "fist broker login"
  }), /* @__PURE__ */ react.createElement(LoginFlow, {
    field: "postBrokerLoginFlowAlias",
    label: "postBrokerLoginFlowAlias",
    defaultValue: ""
  }), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("syncMode"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:syncMode",
      fieldLabelId: "identity-providers:syncMode"
    }),
    fieldId: "syncMode"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.syncMode",
    defaultValue: syncModes[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "syncMode",
      required: true,
      direction: "up",
      onToggle: () => setSyncModeOpen(!syncModeOpen),
      onSelect: (_23, value2) => {
        onChange(value2);
        setSyncModeOpen(false);
      },
      selections: t5(`syncModes.${value.toLowerCase()}`),
      variant: SelectVariant.single,
      "aria-label": t5("syncMode"),
      isOpen: syncModeOpen
    }, syncModes.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      key: option,
      value: option.toUpperCase()
    }, t5(`syncModes.${option}`))))
  })));
};

// build/identity-providers/add/ExtendedNonDiscoverySettings.js
var promptOptions = [
  "unspecified",
  "none",
  "consent",
  "login",
  "select_account"
];
var ExtendedNonDiscoverySettings = () => {
  const {t: t5} = useTranslation("identity-providers");
  const {control} = useFormContext();
  const [isExpanded, setIsExpanded] = useState(false);
  const [promptOpen, setPromptOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(ExpandableSection, {
    toggleText: t5("advanced"),
    onToggle: () => setIsExpanded(!isExpanded),
    isExpanded
  }, /* @__PURE__ */ react.createElement(Form, {
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(SwitchField, {
    label: "passLoginHint",
    field: "config.loginHint"
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    label: "passCurrentLocale",
    field: "config.uiLocales"
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.backchannelSupported",
    label: "backchannelLogout"
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.disableUserInfo",
    label: "disableUserInfo"
  }), /* @__PURE__ */ react.createElement(TextField, {
    field: "config.defaultScope",
    label: "scopes"
  }), /* @__PURE__ */ react.createElement(FormGroupField, {
    label: "prompt"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.prompt",
    defaultValue: promptOptions[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "prompt",
      required: true,
      onToggle: () => setPromptOpen(!promptOpen),
      onSelect: (_23, value2) => {
        onChange(value2);
        setPromptOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("prompt"),
      isOpen: promptOpen
    }, promptOptions.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      key: option,
      value: option
    }, t5(`prompts.${option}`))))
  })), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.acceptsPromptNoneForwardFromClient",
    label: "acceptsPromptNone"
  }), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("allowedClockSkew"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:allowedClockSkew",
      fieldLabelId: "identity-providers:allowedClockSkew"
    }),
    fieldId: "allowedClockSkew"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.allowedClockSkew",
    control,
    defaultValue: 0,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(NumberInput, {
      value,
      "data-testid": "allowedClockSkew",
      onMinus: () => onChange(value - 1),
      onChange,
      onPlus: () => onChange(value + 1),
      inputName: "input",
      inputAriaLabel: t5("allowedClockSkew"),
      minusBtnAriaLabel: t5("common:minus"),
      plusBtnAriaLabel: t5("common:plus"),
      min: 0,
      unit: t5("common:times.seconds")
    })
  })), /* @__PURE__ */ react.createElement(TextField, {
    field: "config.forwardParameters",
    label: "forwardParameters"
  })));
};

// build/identity-providers/add/DiscoverySettings.js
var Fields = ({readOnly}) => {
  const {t: t5} = useTranslation("identity-providers");
  const {register: register2, control, errors} = useFormContext();
  const validateSignature = useWatch({
    control,
    name: "config.validateSignature"
  });
  const useJwks = useWatch({
    control,
    name: "config.useJwksUrl"
  });
  return /* @__PURE__ */ react.createElement("div", {
    className: "pf-c-form pf-m-horizontal"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("authorizationUrl"),
    fieldId: "kc-authorization-url",
    isRequired: true,
    validated: errors.config?.authorizationUrl ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    "data-testid": "authorizationUrl",
    id: "kc-authorization-url",
    name: "config.authorizationUrl",
    ref: register2({required: true}),
    validated: errors.config?.authorizationUrl ? ValidatedOptions.error : ValidatedOptions.default,
    isReadOnly: readOnly
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("tokenUrl"),
    fieldId: "tokenUrl",
    isRequired: true,
    validated: errors.config?.tokenUrl ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "tokenUrl",
    name: "config.tokenUrl",
    ref: register2({required: true}),
    validated: errors.config?.tokenUrl ? ValidatedOptions.error : ValidatedOptions.default,
    isReadOnly: readOnly
  })), /* @__PURE__ */ react.createElement(TextField, {
    field: "config.logoutUrl",
    label: "logoutUrl",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(TextField, {
    field: "config.userInfoUrl",
    label: "userInfoUrl",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(TextField, {
    field: "config.issuer",
    label: "issuer",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.validateSignature",
    label: "validateSignature",
    isReadOnly: readOnly
  }), validateSignature === "true" && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.useJwksUrl",
    label: "useJwksUrl",
    isReadOnly: readOnly
  }), useJwks === "true" && /* @__PURE__ */ react.createElement(TextField, {
    field: "config.jwksUrl",
    label: "jwksUrl",
    isReadOnly: readOnly
  })));
};
var DiscoverySettings = ({readOnly}) => {
  const {t: t5} = useTranslation("identity-providers");
  const [isExpanded, setIsExpanded] = useState(false);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, readOnly && /* @__PURE__ */ react.createElement(ExpandableSection, {
    className: "keycloak__discovery-settings__metadata",
    toggleText: isExpanded ? t5("hideMetaData") : t5("showMetaData"),
    onToggle: () => setIsExpanded(!isExpanded),
    isExpanded
  }, /* @__PURE__ */ react.createElement(Fields, {
    readOnly
  })), !readOnly && /* @__PURE__ */ react.createElement(Fields, {
    readOnly
  }));
};

// build/identity-providers/add/DescriptorSettings.js
var Fields2 = ({readOnly}) => {
  const {t: t5} = useTranslation("identity-providers");
  const {t: th2} = useTranslation("identity-providers-help");
  const {register: register2, control, errors} = useFormContext();
  const [namedPolicyDropdownOpen, setNamedPolicyDropdownOpen] = useState(false);
  const [principalTypeDropdownOpen, setPrincipalTypeDropdownOpen] = useState(false);
  const [signatureAlgorithmDropdownOpen, setSignatureAlgorithmDropdownOpen] = useState(false);
  const [
    samlSignatureKeyNameDropdownOpen,
    setSamlSignatureKeyNameDropdownOpen
  ] = useState(false);
  const wantAuthnSigned = useWatch({
    control,
    name: "config.wantAuthnRequestsSigned"
  });
  const validateSignature = useWatch({
    control,
    name: "config.validateSignature"
  });
  const principalType = useWatch({
    control,
    name: "config.principalType"
  });
  return /* @__PURE__ */ react.createElement("div", {
    className: "pf-c-form pf-m-horizontal"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("ssoServiceUrl"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: th2("ssoServiceUrl"),
      fieldLabelId: "identity-providers:ssoServiceUrl"
    }),
    fieldId: "kc-sso-service-url",
    isRequired: true,
    validated: errors.config?.authorizationUrl ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    "data-testid": "sso-service-url",
    id: "kc-sso-service-url",
    name: "config.singleSignOnServiceUrl",
    ref: register2({required: true}),
    validated: errors.config?.singleSignOnServiceUrl ? ValidatedOptions.error : ValidatedOptions.default,
    isReadOnly: readOnly
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("singleLogoutServiceUrl"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: th2("singleLogoutServiceUrl"),
      fieldLabelId: "identity-providers:singleLogoutServiceUrl"
    }),
    fieldId: "single-logout-service-url",
    validated: errors.config?.singleLogoutServiceUrl ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "single-logout-service-url",
    name: "config.singleLogoutServiceUrl",
    ref: register2,
    isReadOnly: readOnly
  })), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.backchannelSupported",
    label: "backchannelLogout",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("nameIdPolicyFormat"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: th2("nameIdPolicyFormat"),
      fieldLabelId: "identity-providers:nameIdPolicyFormat"
    }),
    fieldId: "kc-nameIdPolicyFormat",
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.nameIDPolicyFormat",
    defaultValue: t5("persistent"),
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-nameIdPolicyFormat",
      onToggle: (isExpanded) => setNamedPolicyDropdownOpen(isExpanded),
      isOpen: namedPolicyDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setNamedPolicyDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "persistent-option",
      value: "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent",
      isPlaceholder: true
    }, t5("persistent")), /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "transient-option",
      value: "urn:oasis:names:tc:SAML:2.0:nameid-format:transient"
    }, t5("transient")), /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "email-option",
      value: "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
    }, t5("email")), /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "kerberos-option",
      value: "urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos"
    }, t5("kerberos")), /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "x509-option",
      value: "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName"
    }, t5("x509")), /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "windowsDomainQN-option",
      value: "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName"
    }, t5("windowsDomainQN")), /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "unspecified-option",
      value: "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
    }, t5("unspecified")))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("principalType"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: th2("principalType"),
      fieldLabelId: "identity-providers:principalType"
    }),
    fieldId: "kc-principalType",
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.principalType",
    defaultValue: t5("subjectNameId"),
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-principalType",
      onToggle: (isExpanded) => setPrincipalTypeDropdownOpen(isExpanded),
      isOpen: principalTypeDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setPrincipalTypeDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "subjectNameId-option",
      value: "SUBJECT",
      isPlaceholder: true
    }, t5("subjectNameId")), /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "attributeName-option",
      value: "ATTRIBUTE"
    }, t5("attributeName")), /* @__PURE__ */ react.createElement(SelectOption, {
      "data-testid": "attributeFriendlyName-option",
      value: "FRIENDLY_ATTRIBUTE"
    }, t5("attributeFriendlyName")))
  })), principalType?.includes("ATTRIBUTE") && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("principalAttribute"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: th2("principalAttribute"),
      fieldLabelId: "identity-providers:principalAttribute"
    }),
    fieldId: "principalAttribute"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "principalAttribute",
    name: "config.principalAttribute",
    ref: register2,
    isReadOnly: readOnly
  })), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.allowCreate",
    label: "allowCreate",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.postBindingResponse",
    label: "httpPostBindingResponse",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.postBindingAuthnRequest",
    label: "httpPostBindingAuthnRequest",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.postBindingLogout",
    label: "httpPostBindingLogout",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.wantAuthnRequestsSigned",
    label: "wantAuthnRequestsSigned",
    isReadOnly: readOnly
  }), wantAuthnSigned === "true" && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("signatureAlgorithm"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: th2("signatureAlgorithm"),
      fieldLabelId: "identity-providers:signatureAlgorithm"
    }),
    fieldId: "kc-signatureAlgorithm"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.signatureAlgorithm",
    defaultValue: "RSA_SHA256",
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-signatureAlgorithm",
      onToggle: (isExpanded) => setSignatureAlgorithmDropdownOpen(isExpanded),
      isOpen: signatureAlgorithmDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setSignatureAlgorithmDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      value: "RSA_SHA1"
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      value: "RSA_SHA256",
      isPlaceholder: true
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      value: "RSA_SHA256_MGF1"
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      value: "RSA_SHA512"
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      value: "RSA_SHA512_MGF1"
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      value: "DSA_SHA1"
    }))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("samlSignatureKeyName"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: th2("samlSignatureKeyName"),
      fieldLabelId: "identity-providers:samlSignatureKeyName"
    }),
    fieldId: "kc-samlSignatureKeyName"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.xmlSigKeyInfoKeyNameTransformer",
    defaultValue: t5("keyID"),
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-samlSignatureKeyName",
      onToggle: (isExpanded) => setSamlSignatureKeyNameDropdownOpen(isExpanded),
      isOpen: samlSignatureKeyNameDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setSamlSignatureKeyNameDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      value: "NONE"
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      value: t5("keyID"),
      isPlaceholder: true
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      value: t5("certSubject")
    }))
  }))), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.wantAssertionsSigned",
    label: "wantAssertionsSigned",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.wantAssertionsEncrypted",
    label: "wantAssertionsEncrypted",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.forceAuthn",
    label: "forceAuthentication",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.validateSignature",
    label: "validateSignature",
    isReadOnly: readOnly
  }), validateSignature === "true" && /* @__PURE__ */ react.createElement(TextField, {
    field: "config.signingCertificate",
    label: "validatingX509Certs",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.signSpMetadata",
    label: "signServiceProviderMetadata",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(SwitchField, {
    field: "config.loginHint",
    label: "passSubject",
    isReadOnly: readOnly
  }), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("allowedClockSkew"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: th2("allowedClockSkew"),
      fieldLabelId: "identity-providers:allowedClockSkew"
    }),
    fieldId: "allowedClockSkew",
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "number",
    min: "0",
    max: "2147483",
    id: "allowedClockSkew",
    name: "config.allowedClockSkew",
    ref: register2,
    isReadOnly: readOnly
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("attributeConsumingServiceIndex"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: th2("attributeConsumingServiceIndex"),
      fieldLabelId: "identity-providers:attributeConsumingServiceIndex"
    }),
    fieldId: "attributeConsumingServiceIndex",
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "number",
    min: "0",
    max: "65535",
    id: "attributeConsumingServiceIndex",
    name: "config.attributeConsumingServiceIndex",
    ref: register2,
    isReadOnly: readOnly
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("attributeConsumingServiceName"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: th2("attributeConsumingServiceName"),
      fieldLabelId: "identity-providers:attributeConsumingServiceName"
    }),
    fieldId: "attributeConsumingServiceName",
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "attributeConsumingServiceName",
    name: "config.attributeConsumingServiceName",
    ref: register2,
    isReadOnly: readOnly
  })));
};
var DescriptorSettings = ({readOnly}) => {
  const {t: t5} = useTranslation("identity-providers");
  const [isExpanded, setIsExpanded] = useState(false);
  return readOnly ? /* @__PURE__ */ react.createElement(ExpandableSection, {
    className: "keycloak__discovery-settings__metadata",
    toggleText: isExpanded ? t5("hideMetaData") : t5("showMetaData"),
    onToggle: (isOpen) => setIsExpanded(isOpen),
    isExpanded
  }, /* @__PURE__ */ react.createElement(Fields2, {
    readOnly
  })) : /* @__PURE__ */ react.createElement(Fields2, {
    readOnly
  });
};

// build/identity-providers/add/OIDCGeneralSettings.js
var OIDCGeneralSettings = ({id: id3}) => {
  const {t: t5} = useTranslation("identity-providers");
  const {tab} = useParams();
  const {register: register2, errors} = useFormContext();
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(RedirectUrl, {
    id: id3
  }), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("alias"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:alias",
      fieldLabelId: "identity-providers:alias"
    }),
    fieldId: "alias",
    isRequired: true,
    validated: errors.alias ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isReadOnly: tab === "settings",
    isRequired: true,
    type: "text",
    id: "alias",
    "data-testid": "alias",
    name: "alias",
    validated: errors.alias ? ValidatedOptions.error : ValidatedOptions.default,
    ref: register2({required: true})
  })), /* @__PURE__ */ react.createElement(TextField, {
    field: "displayName",
    label: "displayName"
  }), /* @__PURE__ */ react.createElement(DisplayOrder, null));
};

// build/identity-providers/add/SamlGeneralSettings.js
var SamlGeneralSettings = ({id: id3}) => {
  const {t: t5} = useTranslation("identity-providers");
  const {tab} = useParams();
  const {register: register2, errors} = useFormContext();
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(RedirectUrl, {
    id: id3
  }), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("alias"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:alias",
      fieldLabelId: "identity-providers:alias"
    }),
    fieldId: "alias",
    isRequired: true,
    validated: errors.alias ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    id: "alias",
    "data-testid": "alias",
    name: "alias",
    isReadOnly: tab === "settings",
    validated: errors.alias ? ValidatedOptions.error : ValidatedOptions.default,
    ref: register2({required: true})
  })), /* @__PURE__ */ react.createElement(TextField, {
    field: "displayName",
    label: "displayName"
  }), /* @__PURE__ */ react.createElement(DisplayOrder, null));
};

// build/identity-providers/add/OIDCAuthentication.js
var clientAuthenticationTypes = [
  "clientAuth_post",
  "clientAuth_basic",
  "clientAuth_secret_jwt",
  "clientAuth_privatekey_jwt"
];
var OIDCAuthentication = ({create: create3 = true}) => {
  const {t: t5} = useTranslation("identity-providers");
  const {control} = useFormContext();
  const [openClientAuth, setOpenClientAuth] = useState(false);
  const clientAuthMethod = useWatch({
    control,
    name: "config.clientAuthMethod"
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("clientAuthentication"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:clientAuthentication",
      fieldLabelId: "identity-providers:clientAuthentication"
    }),
    fieldId: "clientAuthentication"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.clientAuthMethod",
    defaultValue: clientAuthenticationTypes[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "clientAuthMethod",
      required: true,
      onToggle: () => setOpenClientAuth(!openClientAuth),
      onSelect: (_23, value2) => {
        onChange(value2);
        setOpenClientAuth(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("prompt"),
      isOpen: openClientAuth
    }, clientAuthenticationTypes.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      key: option,
      value: option
    }, t5(`clientAuthentications.${option}`))))
  })), /* @__PURE__ */ react.createElement(ClientIdSecret, {
    secretRequired: clientAuthMethod !== "clientAuth_privatekey_jwt",
    create: create3
  }));
};

// build/identity-providers/add/ReqAuthnConstraintsSettings.js
var comparisonValues = ["exact", "minimum", "maximum", "better"];
var ReqAuthnConstraints = () => {
  const {t: t5} = useTranslation("identity-providers");
  const {control} = useFormContext();
  const [comparisonOpen, setComparisonOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("comparison"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:comparison",
      fieldLabelId: "identity-providers:comparison"
    }),
    fieldId: "comparison"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.authnContextComparisonType",
    defaultValue: comparisonValues[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "comparison",
      required: true,
      direction: "up",
      onToggle: (isExpanded) => setComparisonOpen(isExpanded),
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setComparisonOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "aria-label": t5("comparison"),
      isOpen: comparisonOpen
    }, comparisonValues.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      key: option,
      value: option
    }, t5(option))))
  })), /* @__PURE__ */ react.createElement(TextField, {
    field: "config.authnContextClassRefs",
    label: "authnContextClassRefs"
  }), /* @__PURE__ */ react.createElement(TextField, {
    field: "config.authnContextDeclRefs",
    label: "authnContextDeclRefs"
  }));
};

// build/identity-providers/routes/EditMapper.js
var IdentityProviderEditMapperRoute = {
  path: "/:realm/identity-providers/:providerId/:alias/mappers/:id",
  component: lazy(() => Promise.resolve().then(() => require_AddMapper())),
  access: "manage-identity-providers",
  breadcrumb: (t5) => t5("identity-providers:editIdPMapper")
};
var toIdentityProviderEditMapper = (params) => ({
  pathname: generatePath(IdentityProviderEditMapperRoute.path, params)
});

// build/identity-providers/add/AddMapperForm.js
var AddMapperForm = ({
  mapperTypes,
  mapperType,
  form: form2,
  id: id3,
  updateMapperType
}) => {
  const {t: t5} = useTranslation("identity-providers");
  const {control, register: register2, errors} = form2;
  const [mapperTypeOpen, setMapperTypeOpen] = useState(false);
  const syncModes2 = ["inherit", "import", "legacy", "force"];
  const [syncModeOpen, setSyncModeOpen] = useState(false);
  const serverInfo2 = useServerInfo();
  const mapper = serverInfo2.componentTypes?.["org.keycloak.broker.provider.IdentityProviderMapper"].find((p2) => p2.id === mapperType);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:name"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:addIdpMapperName",
      fieldLabelId: "name"
    }),
    fieldId: "kc-name",
    isRequired: true,
    validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default,
    helperTextInvalid: t5("common:required")
  }, /* @__PURE__ */ react.createElement(TextInput, {
    ref: register2({required: true}),
    type: "text",
    "datatest-id": "name-input",
    id: "kc-name",
    name: "name",
    isDisabled: !!id3,
    validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("syncModeOverride"),
    isRequired: true,
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:syncModeOverride",
      fieldLabelId: "identity-providers:syncModeOverride"
    }),
    fieldId: "syncMode"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.syncMode",
    defaultValue: syncModes2[0].toUpperCase(),
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "syncMode",
      "datatest-id": "syncmode-select",
      required: true,
      direction: "down",
      onToggle: () => setSyncModeOpen(!syncModeOpen),
      onSelect: (_23, value2) => {
        onChange(value2.toString().toUpperCase());
        setSyncModeOpen(false);
      },
      selections: t5(`syncModes.${value.toLowerCase()}`),
      variant: SelectVariant.single,
      "aria-label": t5("syncMode"),
      isOpen: syncModeOpen
    }, syncModes2.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      key: option,
      "data-testid": option,
      value: option.toUpperCase()
    }, t5(`syncModes.${option}`))))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("mapperType"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: mapper?.helpText,
      fieldLabelId: "identity-providers:mapperType"
    }),
    fieldId: "identityProviderMapper"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "identityProviderMapper",
    defaultValue: Object.keys(mapperTypes)[0],
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "identityProviderMapper",
      "data-testid": "idp-mapper-select",
      isDisabled: !!id3,
      required: true,
      onToggle: () => setMapperTypeOpen(!mapperTypeOpen),
      onSelect: (_23, value2) => {
        updateMapperType(value2.toString());
        onChange(value2.toString());
        setMapperTypeOpen(false);
      },
      selections: Object.values(mapperTypes).find((item) => item.id?.toLowerCase() === value)?.name,
      variant: SelectVariant.single,
      "aria-label": t5("syncMode"),
      isOpen: mapperTypeOpen
    }, Object.values(mapperTypes).map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
      selected: option === value,
      "datatest-id": option.id,
      key: option.name,
      value: option.id
    }, option.name)))
  })));
};

// build/identity-providers/routes/AddMapper.js
var IdentityProviderAddMapperRoute = {
  path: "/:realm/identity-providers/:providerId/:alias/:tab/create",
  component: lazy(() => Promise.resolve().then(() => require_AddMapper())),
  access: "manage-identity-providers",
  breadcrumb: (t5) => t5("identity-providers:addIdPMapper")
};
var toIdentityProviderAddMapper = (params) => ({
  pathname: generatePath(IdentityProviderAddMapperRoute.path, params)
});

// build/identity-providers/icons/FontAwesomeIcon.js
var FontAwesomeIcon = ({icon}) => {
  const styles6 = {style: {height: "2em", width: "2em"}};
  switch (icon) {
    case "bitbucket":
      return /* @__PURE__ */ react.createElement("img", {
        src: environment_default.resourceUrl + "./bitbucket-brands.svg",
        ...styles6,
        "aria-label": "bitbucket icon"
      });
    case "microsoft":
      return /* @__PURE__ */ react.createElement("img", {
        src: environment_default.resourceUrl + "./microsoft-brands.svg",
        ...styles6,
        "aria-label": "microsoft icon"
      });
    case "instagram":
      return /* @__PURE__ */ react.createElement("img", {
        src: environment_default.resourceUrl + "./instagram-brands.svg",
        ...styles6,
        "aria-label": "instagram icon"
      });
    case "paypal":
      return /* @__PURE__ */ react.createElement("img", {
        src: environment_default.resourceUrl + "./paypal-brands.svg",
        ...styles6,
        "aria-label": "paypal icon"
      });
    default:
      return null;
  }
};

// build/identity-providers/ProviderIconMapper.js
var ProviderIconMapper = ({provider}) => {
  const defaultProps = {size: "lg"};
  switch (provider.id) {
    case "github":
      return /* @__PURE__ */ react.createElement(GithubIcon, {
        ...defaultProps
      });
    case "facebook":
      return /* @__PURE__ */ react.createElement(FacebookSquareIcon, {
        ...defaultProps
      });
    case "gitlab":
      return /* @__PURE__ */ react.createElement(GitlabIcon, {
        ...defaultProps
      });
    case "google":
      return /* @__PURE__ */ react.createElement(GoogleIcon, {
        ...defaultProps
      });
    case "linkedin":
      return /* @__PURE__ */ react.createElement(LinkedinIcon, {
        ...defaultProps
      });
    case "openshift-v3":
    case "openshift-v4":
      return /* @__PURE__ */ react.createElement(OpenshiftIcon, {
        ...defaultProps
      });
    case "stackoverflow":
      return /* @__PURE__ */ react.createElement(StackOverflowIcon, {
        ...defaultProps
      });
    case "twitter":
      return /* @__PURE__ */ react.createElement(TwitterIcon, {
        ...defaultProps
      });
    case "microsoft":
    case "bitbucket":
    case "instagram":
    case "paypal":
      return /* @__PURE__ */ react.createElement(FontAwesomeIcon, {
        icon: provider.id
      });
    default:
      return /* @__PURE__ */ react.createElement(CubeIcon, {
        ...defaultProps
      });
  }
};

// build/identity-providers/ManageOrderDialog.js
var ManageOderDialog = ({
  providers,
  onClose
}) => {
  const {t: t5} = useTranslation("identity-providers");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [alias, setAlias] = useState("");
  const [liveText, setLiveText] = useState("");
  const [order3, setOrder] = useState(providers.map((provider) => provider.alias));
  const onDragStart = (id3) => {
    setAlias(id3);
    setLiveText(t5("common:onDragStart", {item: id3}));
  };
  const onDragMove = () => {
    setLiveText(t5("common:onDragMove", {item: alias}));
  };
  const onDragCancel = () => {
    setLiveText(t5("common:onDragCancel"));
  };
  const onDragFinish = (providerOrder) => {
    setLiveText(t5("common:onDragFinish", {list: providerOrder}));
    setOrder(providerOrder);
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    title: t5("manageDisplayOrder"),
    isOpen: true,
    onClose,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-confirm",
        key: "confirm",
        onClick: () => {
          order3.map(async (alias2, index3) => {
            const provider = providers.find((p2) => p2.alias === alias2);
            provider.config.guiOrder = index3;
            try {
              await adminClient.identityProviders.update({alias: alias2}, provider);
              addAlert(t5("orderChangeSuccess"), AlertVariant.success);
            } catch (error2) {
              addError("identity-providers:orderChangeError", error2);
            }
          });
          onClose();
        }
      }, t5("common:save")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: onClose
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(TextContent, {
    className: "pf-u-pb-lg"
  }, /* @__PURE__ */ react.createElement(Text, null, t5("oderDialogIntro"))), /* @__PURE__ */ react.createElement(DataList, {
    "aria-label": t5("manageOrderTableAria"),
    "data-testid": "manageOrderDataList",
    isCompact: true,
    onDragFinish,
    onDragStart,
    onDragMove,
    onDragCancel,
    itemOrder: order3
  }, lodash.sortBy(providers, "config.guiOrder").map((provider) => /* @__PURE__ */ react.createElement(DataListItem, {
    "aria-labelledby": provider.alias,
    id: provider.alias,
    key: provider.alias
  }, /* @__PURE__ */ react.createElement(DataListItemRow, null, /* @__PURE__ */ react.createElement(DataListControl, null, /* @__PURE__ */ react.createElement(DataListDragButton, {
    "aria-label": "Reorder",
    "aria-labelledby": provider.alias,
    "aria-describedby": t5("manageOrderItemAria"),
    "aria-pressed": "false"
  })), /* @__PURE__ */ react.createElement(DataListItemCells, {
    dataListCells: [
      /* @__PURE__ */ react.createElement(DataListCell, {
        key: `${provider.alias}-cell`,
        "data-testid": provider.alias
      }, /* @__PURE__ */ react.createElement("span", {
        id: provider.alias
      }, provider.alias))
    ]
  }))))), /* @__PURE__ */ react.createElement("div", {
    className: "pf-screen-reader",
    "aria-live": "assertive"
  }, liveText));
};

// build/identity-providers/routes/IdentityProviderCreate.js
var IdentityProviderCreateRoute = {
  path: "/:realm/identity-providers/:providerId/add",
  component: lazy(() => Promise.resolve().then(() => require_AddIdentityProvider())),
  breadcrumb: (t5) => t5("identity-providers:addProvider"),
  access: "manage-identity-providers"
};
var toIdentityProviderCreate = (params) => ({
  pathname: generatePath(IdentityProviderCreateRoute.path, params)
});

// build/identity-providers/routes/IdentityProviders.js
var IdentityProvidersRoute = {
  path: "/:realm/identity-providers",
  component: lazy(() => Promise.resolve().then(() => require_IdentityProvidersSection())),
  breadcrumb: (t5) => t5("identityProviders"),
  access: "view-identity-providers"
};
var toIdentityProviders = (params) => ({
  pathname: generatePath(IdentityProvidersRoute.path, params)
});

// build/identity-providers/routes/IdentityProvider.js
var IdentityProviderRoute = {
  path: "/:realm/identity-providers/:providerId/:alias/:tab",
  component: lazy(() => Promise.resolve().then(() => require_DetailSettings())),
  breadcrumb: (t5) => t5("identity-providers:providerDetails"),
  access: "manage-identity-providers"
};
var toIdentityProvider = (params) => ({
  pathname: generatePath(IdentityProviderRoute.path, params)
});

// build/user/UserIdentityProviderLinks.js
var UserIdentityProviderLinks = () => {
  const [key, setKey] = useState(0);
  const [federatedId, setFederatedId] = useState("");
  const [isLinkIdPModalOpen, setIsLinkIdPModalOpen] = useState(false);
  const adminClient = useAdminClient();
  const {id: id3} = useParams();
  const {realm: realm2} = useRealm();
  const {addAlert, addError} = useAlerts();
  const {t: t5} = useTranslation("users");
  const refresh = () => setKey(new Date().getTime());
  const handleModalToggle = () => {
    setIsLinkIdPModalOpen(!isLinkIdPModalOpen);
  };
  const identityProviders2 = useServerInfo().identityProviders;
  const getFederatedIdentities = async () => {
    const allProviders = await adminClient.identityProviders.find();
    const allFedIds = await adminClient.users.listFederatedIdentities({
      id: id3
    });
    for (const element of allFedIds) {
      element.providerId = allProviders.find((item) => item.alias === element.identityProvider)?.providerId;
    }
    return allFedIds;
  };
  const getAvailableIdPs = async () => {
    return (await adminClient.realms.findOne({realm: realm2})).identityProviders;
  };
  const linkedIdPsLoader = async () => {
    return getFederatedIdentities();
  };
  const availableIdPsLoader = async () => {
    const linkedNames = (await getFederatedIdentities()).map((x2) => x2.identityProvider);
    return (await getAvailableIdPs())?.filter((item) => !linkedNames.includes(item.alias));
  };
  const [toggleUnlinkDialog, UnlinkConfirm] = useConfirmDialog({
    titleKey: t5("users:unlinkAccountTitle", {
      provider: lodash.capitalize(federatedId)
    }),
    messageKey: t5("users:unlinkAccountConfirm", {
      provider: lodash.capitalize(federatedId)
    }),
    continueButtonLabel: "users:unlink",
    continueButtonVariant: ButtonVariant.primary,
    onConfirm: async () => {
      try {
        await adminClient.users.delFromFederatedIdentity({
          id: id3,
          federatedIdentityId: federatedId
        });
        addAlert(t5("common:mappingDeletedSuccess"), AlertVariant.success);
        refresh();
      } catch (error2) {
        addError("common:mappingDeletedError", error2);
      }
    }
  });
  const idpLinkRenderer = (idp) => {
    return /* @__PURE__ */ react.createElement(Link, {
      to: toIdentityProvider({
        realm: realm2,
        providerId: idp.providerId,
        alias: idp.identityProvider,
        tab: "settings"
      })
    }, lodash.capitalize(idp.identityProvider));
  };
  const badgeRenderer1 = (idp) => {
    const groupName = identityProviders2?.find((provider) => provider["id"] === idp.identityProvider)?.groupName;
    return /* @__PURE__ */ react.createElement(Label, {
      color: groupName === "Social" ? "blue" : "orange"
    }, groupName === "Social" ? "Social" : "Custom");
  };
  const badgeRenderer2 = (idp) => {
    const groupName = identityProviders2?.find((provider) => provider["id"] === idp.providerId)?.groupName;
    return /* @__PURE__ */ react.createElement(Label, {
      color: groupName === "User-defined" ? "orange" : "blue"
    }, groupName === "User-defined" ? "Custom" : groupName);
  };
  const unlinkRenderer = (fedIdentity) => {
    return /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      onClick: () => {
        setFederatedId(fedIdentity.identityProvider);
        toggleUnlinkDialog();
      }
    }, t5("unlinkAccount"));
  };
  const linkRenderer = (idp) => {
    return /* @__PURE__ */ react.createElement(Button, {
      variant: "link",
      onClick: () => {
        setFederatedId(idp.alias);
        setIsLinkIdPModalOpen(true);
      }
    }, t5("linkAccount"));
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, isLinkIdPModalOpen && /* @__PURE__ */ react.createElement(UserIdpModal, {
    federatedId,
    handleModalToggle,
    refresh
  }), /* @__PURE__ */ react.createElement(UnlinkConfirm, null), /* @__PURE__ */ react.createElement(PageSection, {
    variant: "light"
  }, /* @__PURE__ */ react.createElement(FormPanel, {
    title: t5("linkedIdPs"),
    className: "kc-linked-idps"
  }, /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, {
    className: "kc-available-idps-text"
  }, t5("linkedIdPsText"))), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    loader: linkedIdPsLoader,
    key,
    isPaginated: false,
    ariaLabelKey: "users:LinkedIdPs",
    className: "kc-linked-IdPs-table",
    columns: [
      {
        name: "identityProvider",
        displayKey: "common:name",
        cellFormatters: [emptyFormatter()],
        cellRenderer: idpLinkRenderer,
        transforms: [cellWidth(20)]
      },
      {
        name: "type",
        displayKey: "common:type",
        cellFormatters: [emptyFormatter()],
        cellRenderer: badgeRenderer1,
        transforms: [cellWidth(10)]
      },
      {
        name: "userId",
        displayKey: "users:userID",
        cellFormatters: [emptyFormatter()],
        transforms: [cellWidth(30)]
      },
      {
        name: "userName",
        displayKey: "users:username",
        cellFormatters: [emptyFormatter()],
        transforms: [cellWidth(20)]
      },
      {
        name: "",
        cellFormatters: [emptyFormatter()],
        cellRenderer: unlinkRenderer,
        transforms: [cellWidth(20)]
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(TextContent, {
      className: "kc-no-providers-text"
    }, /* @__PURE__ */ react.createElement(Text, null, t5("users:noProvidersLinked")))
  })), /* @__PURE__ */ react.createElement(FormPanel, {
    className: "kc-available-idps",
    title: t5("availableIdPs")
  }, /* @__PURE__ */ react.createElement(TextContent, null, /* @__PURE__ */ react.createElement(Text, {
    className: "kc-available-idps-text"
  }, t5("availableIdPsText"))), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    loader: availableIdPsLoader,
    key,
    isPaginated: false,
    ariaLabelKey: "users:LinkedIdPs",
    className: "kc-linked-IdPs-table",
    columns: [
      {
        name: "alias",
        displayKey: "common:name",
        cellFormatters: [emptyFormatter(), upperCaseFormatter()],
        transforms: [cellWidth(20)]
      },
      {
        name: "type",
        displayKey: "common:type",
        cellFormatters: [emptyFormatter()],
        cellRenderer: badgeRenderer2,
        transforms: [cellWidth(60)]
      },
      {
        name: "",
        cellFormatters: [emptyFormatter()],
        cellRenderer: linkRenderer
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(TextContent, {
      className: "kc-no-providers-text"
    }, /* @__PURE__ */ react.createElement(Text, null, t5("users:noAvailableIdentityProviders")))
  }))));
};

// build/user/routes/AddUser.js
var AddUserRoute = {
  path: "/:realm/users/add-user",
  component: lazy(() => Promise.resolve().then(() => require_UsersTabs())),
  breadcrumb: (t5) => t5("users:createUser"),
  access: "manage-users"
};
var toAddUser = (params) => ({
  pathname: generatePath(AddUserRoute.path, params)
});

// build/user/routes/Users.js
var UsersRoute = {
  path: "/:realm/users",
  component: lazy(() => Promise.resolve().then(() => require_UsersSection())),
  breadcrumb: (t5) => t5("users:title"),
  access: "query-users"
};
var toUsers = (params) => ({
  pathname: generatePath(UsersRoute.path, params)
});

// build/user/UserRoleMapping.js
var UserRoleMapping = ({id: id3, name}) => {
  const {t: t5} = useTranslation("clients");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [hide3, setHide] = useState(false);
  const loader = async () => {
    const [assignedRoles, effectiveRoles] = await Promise.all([
      adminClient.users.listRealmRoleMappings({id: id3}).then((roles2) => roles2.map((role) => ({role}))),
      adminClient.users.listCompositeRealmRoleMappings({id: id3}).then((roles2) => roles2.map((role) => ({role})))
    ]);
    const clients2 = await adminClient.clients.find();
    const clientRoles = (await Promise.all(clients2.map(async (client2) => {
      const [clientAssignedRoles, clientEffectiveRoles] = await Promise.all([
        adminClient.users.listClientRoleMappings({
          id: id3,
          clientUniqueId: client2.id
        }).then((roles2) => roles2.map((role) => ({role, client: client2}))),
        adminClient.users.listCompositeClientRoleMappings({
          id: id3,
          clientUniqueId: client2.id
        }).then((roles2) => roles2.map((role) => ({role, client: client2})))
      ]);
      return mapRoles(clientAssignedRoles, clientEffectiveRoles, hide3);
    }))).flat();
    return [...mapRoles(assignedRoles, effectiveRoles, hide3), ...clientRoles];
  };
  const assignRoles = async (rows) => {
    try {
      const realmRoles = rows.filter((row) => row.client === void 0).map((row) => row.role).flat();
      await adminClient.users.addRealmRoleMappings({
        id: id3,
        roles: realmRoles
      });
      await Promise.all(rows.filter((row) => row.client !== void 0).map((row) => adminClient.users.addClientRoleMappings({
        id: id3,
        clientUniqueId: row.client.id,
        roles: [row.role]
      })));
      addAlert(t5("roleMappingUpdatedSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("clients:roleMappingUpdatedError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(RoleMapping, {
    name,
    id: id3,
    type: "service-account",
    loader,
    save: assignRoles,
    onHideRolesToggle: () => setHide(!hide3)
  });
};

// build/user/UserAttributes.js
var UserAttributes = ({user: defaultUser}) => {
  const {t: t5} = useTranslation("users");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [user, setUser] = useState(defaultUser);
  const form2 = useForm({mode: "onChange"});
  const convertAttributes = (attr2) => {
    return attributesToArray(attr2 || user.attributes);
  };
  useEffect(() => {
    form2.setValue("attributes", convertAttributes());
  }, [user]);
  const save = async (attributeForm) => {
    try {
      const attributes = arrayToAttributes(attributeForm.attributes);
      await adminClient.users.update({id: user.id}, {...user, attributes});
      setUser({...user, attributes});
      addAlert(t5("userSaved"), AlertVariant.success);
    } catch (error2) {
      addError("groups:groupUpdateError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: PageSectionVariants.light
  }, /* @__PURE__ */ react.createElement(AttributesForm, {
    form: form2,
    save,
    reset: () => form2.reset({
      attributes: convertAttributes()
    })
  }));
};

// build/user/UserCredentials.js
var credFormDefaultValues = {
  password: "",
  passwordConfirmation: "",
  temporaryPassword: true
};
var userLabelDefaultValues = {
  userLabel: ""
};
var DisplayDialog = ({
  titleKey,
  onClose,
  children: children2
}) => {
  const {t: t5} = useTranslation("users");
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.medium,
    title: t5(titleKey),
    isOpen: true,
    onClose
  }, children2);
};
var UserCredentials = ({user}) => {
  const {t: t5} = useTranslation("users");
  const {whoAmI: whoAmI2} = useWhoAmI();
  const {addAlert, addError} = useAlerts();
  const [key, setKey] = useState(0);
  const refresh = () => setKey(key + 1);
  const [open2, setOpen] = useState(false);
  const [openSaveConfirm, setOpenSaveConfirm] = useState(false);
  const [kebabOpen, setKebabOpen] = useState({
    status: false,
    rowKey: ""
  });
  const adminClient = useAdminClient();
  const form2 = useForm({
    defaultValues: credFormDefaultValues
  });
  const userLabelForm = useForm({
    defaultValues: userLabelDefaultValues
  });
  const {control, errors, handleSubmit, register: register2} = form2;
  const {
    getValues: getValues1,
    handleSubmit: handleSubmit1,
    register: register1
  } = userLabelForm;
  const [credentials, setCredentials] = useState();
  const [userCredentials, setUserCredentials] = useState([]);
  const [selectedCredential, setSelectedCredential] = useState({});
  const [isResetPassword, setIsResetPassword] = useState(false);
  const [showData, setShowData] = useState(false);
  const [editedUserCredential, setEditedUserCredential] = useState({});
  const [isUserLabelEdit, setIsUserLabelEdit] = useState();
  useFetch(() => adminClient.users.getCredentials({id: user.id}), (credentials2) => {
    setUserCredentials(credentials2);
  }, [key]);
  const passwordTypeFinder = userCredentials.find((credential) => credential.type === "password");
  const passwordWatcher = useWatch({
    control,
    name: "password"
  });
  const passwordConfirmationWatcher = useWatch({
    control,
    name: "passwordConfirmation"
  });
  const isNotDisabled = passwordWatcher !== "" && passwordConfirmationWatcher !== "";
  const toggleModal = () => {
    setOpen(!open2);
  };
  const toggleConfirmSaveModal = () => {
    setOpenSaveConfirm(!openSaveConfirm);
  };
  const saveUserPassword = async () => {
    if (!credentials) {
      return;
    }
    const passwordsMatch = credentials.password === credentials.passwordConfirmation;
    if (!passwordsMatch) {
      addAlert(isResetPassword ? t5("resetPasswordNotMatchError") : t5("savePasswordNotMatchError"), AlertVariant.danger);
    } else {
      try {
        await adminClient.users.resetPassword({
          id: user.id,
          credential: {
            temporary: credentials.temporaryPassword,
            type: "password",
            value: credentials.password
          }
        });
        refresh();
        addAlert(isResetPassword ? t5("resetCredentialsSuccess") : t5("savePasswordSuccess"), AlertVariant.success);
        setIsResetPassword(false);
        setOpenSaveConfirm(false);
      } catch (error2) {
        addError(isResetPassword ? "users:resetPasswordError" : "users:savePasswordError", error2);
      }
    }
  };
  const resetPassword = () => {
    setIsResetPassword(true);
    setOpen(true);
  };
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: t5("deleteCredentialsConfirmTitle"),
    messageKey: t5("deleteCredentialsConfirm"),
    continueButtonLabel: t5("common:delete"),
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        await adminClient.users.deleteCredential({
          id: user.id,
          credentialId: selectedCredential.id
        });
        addAlert(t5("deleteCredentialsSuccess"), AlertVariant.success);
        setKey((key2) => key2 + 1);
      } catch (error2) {
        addError("users:deleteCredentialsError", error2);
      }
    }
  });
  const rows = useMemo(() => {
    if (!selectedCredential.credentialData) {
      return [];
    }
    const credentialData = JSON.parse(selectedCredential.credentialData);
    const locale = whoAmI2.getLocale();
    return Object.entries(credentialData).sort(([a2], [b2]) => a2.localeCompare(b2, locale)).map(([key2, value]) => {
      if (typeof value === "string") {
        return [key2, value];
      }
      return [key2, JSON.stringify(value)];
    });
  }, [selectedCredential.credentialData]);
  const saveUserLabel = async () => {
    const credentialToEdit = userCredentials.find((credential) => credential.id === editedUserCredential.id);
    const userLabelFormValue = getValues1();
    if (!credentialToEdit) {
      return;
    }
    try {
      await adminClient.users.updateCredentialLabel({
        id: user.id,
        credentialId: credentialToEdit.id
      }, userLabelFormValue.userLabel || "");
      refresh();
      addAlert(t5("updateCredentialUserLabelSuccess"), AlertVariant.success);
      setEditedUserCredential({});
    } catch (error2) {
      addError("users:updateCredentialUserLabelError", error2);
    }
    setIsUserLabelEdit({
      status: false,
      rowKey: credentialToEdit.id
    });
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, open2 && /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    width: 600,
    title: isResetPassword ? `${t5("resetPasswordFor")} ${user.username}` : `${t5("setPasswordFor")} ${user.username}`,
    isOpen: true,
    onClose: () => {
      setIsResetPassword(false);
      setOpen(false);
    },
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "okBtn",
        key: `confirmBtn-${user.id}`,
        variant: "primary",
        form: "userCredentials-form",
        onClick: () => {
          setOpen(false);
          setCredentials(form2.getValues());
          toggleConfirmSaveModal();
        },
        isDisabled: !isNotDisabled
      }, t5("save")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "cancelBtn",
        key: `cancelBtn-${user.id}`,
        variant: "link",
        form: "userCredentials-form",
        onClick: () => {
          setIsResetPassword(false);
          setOpen(false);
        }
      }, t5("cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(Form, {
    id: "userCredentials-form",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    name: "password",
    label: t5("password"),
    fieldId: "password",
    helperTextInvalid: t5("common:required"),
    validated: errors.password ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement("div", {
    className: "kc-password"
  }, /* @__PURE__ */ react.createElement(PasswordInput, {
    name: "password",
    "aria-label": "password",
    ref: register2({required: true})
  }))), /* @__PURE__ */ react.createElement(FormGroup, {
    name: "passwordConfirmation",
    label: isResetPassword ? t5("resetPasswordConfirmation") : t5("passwordConfirmation"),
    fieldId: "passwordConfirmation",
    helperTextInvalid: t5("common:required"),
    validated: errors.passwordConfirmation ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement("div", {
    className: "kc-passwordConfirmation"
  }, /* @__PURE__ */ react.createElement(PasswordInput, {
    name: "passwordConfirmation",
    "aria-label": "passwordConfirm",
    ref: register2({required: true})
  }))), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("common:temporaryPassword"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "temporaryPasswordHelpText",
      fieldLabelId: "temporaryPassword"
    }),
    fieldId: "kc-temporaryPassword"
  }, " ", /* @__PURE__ */ react.createElement(Controller, {
    name: "temporaryPassword",
    defaultValue: true,
    control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      className: "kc-temporaryPassword",
      onChange: (value2) => onChange(value2),
      isChecked: value,
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  })))), openSaveConfirm && /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    width: 600,
    title: isResetPassword ? t5("resetPasswordConfirm") : t5("setPasswordConfirm"),
    isOpen: true,
    onClose: () => setOpenSaveConfirm(false),
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "setPasswordBtn",
        key: `confirmSaveBtn-${user.id}`,
        variant: "danger",
        form: "userCredentials-form",
        onClick: () => {
          handleSubmit(saveUserPassword)();
        }
      }, isResetPassword ? t5("resetPassword") : t5("savePassword")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "cancelSetPasswordBtn",
        key: `cancelConfirmBtn-${user.id}`,
        variant: "link",
        form: "userCredentials-form",
        onClick: () => {
          setOpenSaveConfirm(false);
        }
      }, t5("cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(Text, {
    component: TextVariants.h3
  }, isResetPassword ? `${t5("resetPasswordConfirmText")} ${user.username} ${t5("questionMark")}` : `${t5("setPasswordConfirmText")} ${user.username} ${t5("questionMark")}`)), /* @__PURE__ */ react.createElement(DeleteConfirm, null), showData && Object.keys(selectedCredential).length !== 0 && /* @__PURE__ */ react.createElement(DisplayDialog, {
    titleKey: t5("passwordDataTitle"),
    onClose: () => {
      setShowData(false);
      setSelectedCredential({});
    }
  }, /* @__PURE__ */ react.createElement(Table, {
    "aria-label": "password-data",
    "data-testid": "password-data-dialog",
    variant: TableVariant.compact,
    cells: [t5("showPasswordDataName"), t5("showPasswordDataValue")],
    rows
  }, /* @__PURE__ */ react.createElement(TableHeader, null), /* @__PURE__ */ react.createElement(TableBody, null))), userCredentials.length !== 0 && passwordTypeFinder === void 0 && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Button, {
    key: `confirmSaveBtn-table-${user.id}`,
    className: "setPasswordBtn-table",
    "data-testid": "setPasswordBtn-table",
    variant: "primary",
    form: "userCredentials-form",
    onClick: () => {
      setOpen(true);
    }
  }, t5("savePassword")), /* @__PURE__ */ react.createElement(Divider, null)), userCredentials.length !== 0 ? /* @__PURE__ */ react.createElement(TableComposable, {
    "aria-label": "password-data-table",
    variant: "compact"
  }, /* @__PURE__ */ react.createElement(Thead, null, /* @__PURE__ */ react.createElement(Tr, null, /* @__PURE__ */ react.createElement(Th2, null, /* @__PURE__ */ react.createElement(HelpItem, {
    helpText: "users:userCredentialsHelpText",
    fieldLabelId: "users:userCredentialsHelpTextLabel"
  })), /* @__PURE__ */ react.createElement(Th2, null, t5("type")), /* @__PURE__ */ react.createElement(Th2, null, t5("userLabel")), /* @__PURE__ */ react.createElement(Th2, null, t5("data")), /* @__PURE__ */ react.createElement(Th2, null), /* @__PURE__ */ react.createElement(Th2, null))), /* @__PURE__ */ react.createElement(Tbody, null, userCredentials.map((credential) => /* @__PURE__ */ react.createElement(Tr, {
    key: `table-${credential.id}`
  }, /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Td2, {
    draggableRow: {
      id: `draggable-row-${credential.id}`
    }
  }), /* @__PURE__ */ react.createElement(Td2, {
    key: `table-item-${credential.id}`,
    dataLabel: `columns-${credential.id}`
  }, credential.type?.charAt(0).toUpperCase() + credential.type?.slice(1)), /* @__PURE__ */ react.createElement(Td2, null, /* @__PURE__ */ react.createElement(FormAccess, {
    isHorizontal: true,
    role: "view-users"
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    fieldId: "kc-userLabel",
    className: "kc-userLabel-row"
  }, /* @__PURE__ */ react.createElement("div", {
    className: "kc-form-group-userLabel"
  }, isUserLabelEdit?.status && isUserLabelEdit.rowKey === credential.id ? /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(TextInput, {
    name: "userLabel",
    ref: register1(),
    type: "text",
    className: "kc-userLabel",
    "aria-label": t5("userLabel"),
    "data-testid": "user-label-fld"
  }), /* @__PURE__ */ react.createElement("div", {
    className: "kc-userLabel-actionBtns"
  }, /* @__PURE__ */ react.createElement(Button, {
    key: `editUserLabel-accept-${credential.id}`,
    variant: "link",
    className: "kc-editUserLabel-acceptBtn",
    onClick: () => {
      handleSubmit1(saveUserLabel)();
      setIsUserLabelEdit({
        status: false,
        rowKey: credential.id
      });
    },
    "data-testid": "editUserLabel-acceptBtn",
    icon: /* @__PURE__ */ react.createElement(CheckIcon, null)
  }), /* @__PURE__ */ react.createElement(Button, {
    key: `editUserLabel-cancel-${credential.id}`,
    variant: "link",
    className: "kc-editUserLabel-cancelBtn",
    onClick: () => setIsUserLabelEdit({
      status: false,
      rowKey: credential.id
    }),
    "data-testid": "editUserLabel-cancelBtn",
    icon: /* @__PURE__ */ react.createElement(TimesIcon, null)
  }))) : /* @__PURE__ */ react.createElement(react.Fragment, null, credential.userLabel ?? "", /* @__PURE__ */ react.createElement(Button, {
    key: `editUserLabel-${credential.id}`,
    variant: "link",
    className: "kc-editUserLabel-btn",
    onClick: () => {
      setEditedUserCredential(credential);
      setIsUserLabelEdit({
        status: true,
        rowKey: credential.id
      });
    },
    "data-testid": "editUserLabelBtn",
    icon: /* @__PURE__ */ react.createElement(PencilAltIcon, null)
  })))))), /* @__PURE__ */ react.createElement(Td2, null, /* @__PURE__ */ react.createElement(Button, {
    className: "kc-showData-btn",
    variant: "link",
    "data-testid": "showDataBtn",
    onClick: () => {
      setShowData(true);
      setSelectedCredential(credential);
    }
  }, t5("showDataBtn"))), credential.type === "password" ? /* @__PURE__ */ react.createElement(Td2, null, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    "data-testid": "resetPasswordBtn",
    onClick: resetPassword
  }, t5("resetPasswordBtn"))) : /* @__PURE__ */ react.createElement(Td2, null), /* @__PURE__ */ react.createElement(Td2, null, /* @__PURE__ */ react.createElement(Dropdown, {
    isPlain: true,
    position: DropdownPosition.right,
    toggle: /* @__PURE__ */ react.createElement(KebabToggle, {
      onToggle: (status) => setKebabOpen({
        status,
        rowKey: credential.id
      })
    }),
    isOpen: kebabOpen.status && kebabOpen.rowKey === credential.id,
    onSelect: () => {
      setSelectedCredential(credential);
    },
    dropdownItems: [
      /* @__PURE__ */ react.createElement(DropdownItem, {
        key: `delete-dropdown-item-${credential.id}`,
        "data-testid": "deleteDropdownItem",
        component: "button",
        onClick: () => {
          toggleDeleteDialog();
          setKebabOpen({
            status: false,
            rowKey: credential.id
          });
        }
      }, t5("deleteBtn"))
    ]
  }))))))) : /* @__PURE__ */ react.createElement(ListEmptyState, {
    hasIcon: true,
    message: t5("noCredentials"),
    instructions: t5("noCredentialsText"),
    primaryActionText: t5("setPassword"),
    onPrimaryAction: toggleModal
  }));
};

// build/user/routes/User.js
var UserRoute = {
  path: "/:realm/users/:id/:tab",
  component: lazy(() => Promise.resolve().then(() => require_UsersTabs())),
  breadcrumb: (t5) => t5("users:userDetails"),
  access: "manage-users"
};
var toUser = (params) => ({
  pathname: generatePath(UserRoute.path, params)
});

// build/events/AdminEvents.js
var import_moment5 = __toModule(require_moment());
var defaultValues = {
  resourceTypes: [],
  operationTypes: [],
  resourcePath: "",
  dateFrom: "",
  dateTo: "",
  authClient: "",
  authUser: "",
  authRealm: "",
  authIpAddress: ""
};
var DisplayDialog2 = ({
  titleKey,
  onClose,
  children: children2
}) => {
  const {t: t5} = useTranslation("events");
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.medium,
    title: t5(titleKey),
    isOpen: true,
    onClose
  }, children2);
};
var MAX_TEXT_LENGTH = 38;
var Truncate = ({
  text,
  children: children2
}) => {
  const definedText = text || "";
  const needsTruncation = definedText.length > MAX_TEXT_LENGTH;
  const truncatedText = definedText.substr(0, MAX_TEXT_LENGTH);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, needsTruncation && /* @__PURE__ */ react.createElement(Tooltip, {
    content: text
  }, children2(truncatedText + "...")), !needsTruncation && /* @__PURE__ */ react.createElement(react.Fragment, null, children2(definedText)));
};
var AdminEvents = () => {
  const {t: t5} = useTranslation("events");
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const serverInfo2 = useServerInfo();
  const resourceTypes = serverInfo2.enums?.["resourceType"];
  const operationTypes = serverInfo2.enums?.["operationType"];
  const [key, setKey] = useState(0);
  const [searchDropdownOpen, setSearchDropdownOpen] = useState(false);
  const [selectResourceTypesOpen, setSelectResourceTypesOpen] = useState(false);
  const [selectOperationTypesOpen, setSelectOperationTypesOpen] = useState(false);
  const [activeFilters, setActiveFilters] = useState({});
  const [authEvent, setAuthEvent] = useState();
  const [representationEvent, setRepresentationEvent] = useState();
  const filterLabels = {
    resourceTypes: t5("resourceTypes"),
    operationTypes: t5("operationTypes"),
    resourcePath: t5("resourcePath"),
    dateFrom: t5("dateFrom"),
    dateTo: t5("dateTo"),
    authClient: t5("client"),
    authUser: t5("userId"),
    authRealm: t5("realm"),
    authIpAddress: t5("ipAddress")
  };
  const {
    getValues,
    register: register2,
    reset: reset2,
    formState: {isDirty},
    control
  } = useForm({
    shouldUnregister: false,
    mode: "onChange",
    defaultValues
  });
  function loader(first2, max2) {
    return adminClient.realms.findAdminEvents({
      ...activeFilters,
      realm: realm2,
      first: first2,
      max: max2
    });
  }
  function submitSearch() {
    setSearchDropdownOpen(false);
    commitFilters();
  }
  function removeFilter(key2) {
    const formValues = {...getValues()};
    delete formValues[key2];
    reset2({...defaultValues, ...formValues});
    commitFilters();
  }
  function removeFilterValue(key2, valueToRemove) {
    const formValues = getValues();
    const fieldValue = formValues[key2];
    const newFieldValue = Array.isArray(fieldValue) ? fieldValue.filter((val) => val !== valueToRemove) : fieldValue;
    reset2({...formValues, [key2]: newFieldValue});
    commitFilters();
  }
  function commitFilters() {
    const newFilters = pickBy(getValues(), (value) => value !== "" || Array.isArray(value) && value.length > 0);
    setActiveFilters(newFilters);
    setKey(key + 1);
  }
  function refresh() {
    commitFilters();
  }
  const LinkResource = (row) => /* @__PURE__ */ react.createElement(Truncate, {
    text: row.resourcePath
  }, (text) => /* @__PURE__ */ react.createElement(react.Fragment, null, row.resourceType !== "COMPONENT" && /* @__PURE__ */ react.createElement(Link, {
    to: `/${realm2}/${row.resourcePath}${row.resourceType !== "GROUP" ? "/settings" : ""}`
  }, text), row.resourceType === "COMPONENT" && /* @__PURE__ */ react.createElement("span", null, text)));
  const adminEventSearchFormDisplay = () => {
    return /* @__PURE__ */ react.createElement(Flex, {
      direction: {default: "column"},
      spaceItems: {default: "spaceItemsNone"}
    }, /* @__PURE__ */ react.createElement(FlexItem, null, /* @__PURE__ */ react.createElement(Dropdown, {
      id: "admin-events-search-select",
      "data-testid": "AdminEventsSearchSelector",
      className: "pf-u-ml-md",
      toggle: /* @__PURE__ */ react.createElement(DropdownToggle, {
        "data-testid": "adminEventsSearchSelectorToggle",
        onToggle: (isOpen) => setSearchDropdownOpen(isOpen),
        className: "keycloak__events_search_selector_dropdown__toggle"
      }, t5("searchForAdminEvent")),
      isOpen: searchDropdownOpen
    }, /* @__PURE__ */ react.createElement(Form, {
      isHorizontal: true,
      className: "keycloak__events_search__form",
      "data-testid": "searchForm"
    }, /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("resourceTypes"),
      fieldId: "kc-resourceTypes",
      className: "keycloak__events_search__form_label"
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "resourceTypes",
      control,
      render: ({
        onChange,
        value
      }) => /* @__PURE__ */ react.createElement(Select, {
        className: "keycloak__events_search__type_select",
        name: "resourceTypes",
        "data-testid": "resource-types-searchField",
        chipGroupProps: {
          numChips: 1,
          expandedText: t5("common:hide"),
          collapsedText: t5("common:showRemaining")
        },
        variant: SelectVariant.typeaheadMulti,
        typeAheadAriaLabel: "Select",
        onToggle: (isOpen) => setSelectResourceTypesOpen(isOpen),
        selections: value,
        onSelect: (_23, selectedValue) => {
          const option = selectedValue.toString();
          const changedValue = value.includes(option) ? value.filter((item) => item !== option) : [...value, option];
          onChange(changedValue);
        },
        onClear: (resource2) => {
          resource2.stopPropagation();
          onChange([]);
        },
        isOpen: selectResourceTypesOpen,
        "aria-labelledby": "resourceTypes",
        chipGroupComponent: /* @__PURE__ */ react.createElement(ChipGroup, null, value.map((chip2) => /* @__PURE__ */ react.createElement(Chip, {
          key: chip2,
          onClick: (resource2) => {
            resource2.stopPropagation();
            onChange(value.filter((val) => val !== chip2));
          }
        }, chip2)))
      }, resourceTypes?.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
        key: option,
        value: option
      })))
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("operationTypes"),
      fieldId: "kc-operationTypes",
      className: "keycloak__events_search__form_label"
    }, /* @__PURE__ */ react.createElement(Controller, {
      name: "operationTypes",
      control,
      render: ({
        onChange,
        value
      }) => /* @__PURE__ */ react.createElement(Select, {
        className: "keycloak__events_search__type_select",
        name: "operationTypes",
        "data-testid": "operation-types-searchField",
        chipGroupProps: {
          numChips: 1,
          expandedText: t5("common:hide"),
          collapsedText: t5("common:showRemaining")
        },
        variant: SelectVariant.typeaheadMulti,
        typeAheadAriaLabel: "Select",
        onToggle: (isOpen) => setSelectOperationTypesOpen(isOpen),
        selections: value,
        onSelect: (_23, selectedValue) => {
          const option = selectedValue.toString();
          const changedValue = value.includes(option) ? value.filter((item) => item !== option) : [...value, option];
          onChange(changedValue);
        },
        onClear: (operation) => {
          operation.stopPropagation();
          onChange([]);
        },
        isOpen: selectOperationTypesOpen,
        "aria-labelledby": "operationTypes",
        chipGroupComponent: /* @__PURE__ */ react.createElement(ChipGroup, null, value.map((chip2) => /* @__PURE__ */ react.createElement(Chip, {
          key: chip2,
          onClick: (operation) => {
            operation.stopPropagation();
            onChange(value.filter((val) => val !== chip2));
          }
        }, chip2)))
      }, operationTypes?.map((option) => /* @__PURE__ */ react.createElement(SelectOption, {
        key: option,
        value: option
      })))
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("resourcePath"),
      fieldId: "kc-resourcePath",
      className: "keycloak__events_search__form_label"
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: register2(),
      type: "text",
      id: "kc-resourcePath",
      name: "resourcePath",
      "data-testid": "resourcePath-searchField"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("realm"),
      fieldId: "kc-realm",
      className: "keycloak__events_search__form_label"
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: register2(),
      type: "text",
      id: "kc-realm",
      name: "authRealm",
      "data-testid": "realm-searchField"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("client"),
      fieldId: "kc-client",
      className: "keycloak__events_search__form_label"
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: register2(),
      type: "text",
      id: "kc-client",
      name: "authClient",
      "data-testid": "client-searchField"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("user"),
      fieldId: "kc-user",
      className: "keycloak__events_search__form_label"
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: register2(),
      type: "text",
      id: "kc-user",
      name: "authUser",
      "data-testid": "user-searchField"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("ipAddress"),
      fieldId: "kc-ipAddress",
      className: "keycloak__events_search__form_label"
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: register2(),
      type: "text",
      id: "kc-ipAddress",
      name: "authIpAddress",
      "data-testid": "ipAddress-searchField"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("dateFrom"),
      fieldId: "kc-dateFrom",
      className: "keycloak__events_search__form_label"
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: register2(),
      type: "text",
      id: "kc-dateFrom",
      name: "dateFrom",
      className: "pf-c-form-control pf-m-icon pf-m-calendar",
      placeholder: "yyyy-MM-dd",
      "data-testid": "dateFrom-searchField"
    })), /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("dateTo"),
      fieldId: "kc-dateTo",
      className: "keycloak__events_search__form_label"
    }, /* @__PURE__ */ react.createElement(TextInput, {
      ref: register2(),
      type: "text",
      id: "kc-dateTo",
      name: "dateTo",
      className: "pf-c-form-control pf-m-icon pf-m-calendar",
      placeholder: "yyyy-MM-dd",
      "data-testid": "dateTo-searchField"
    })), /* @__PURE__ */ react.createElement(ActionGroup, null, /* @__PURE__ */ react.createElement(Button, {
      className: "keycloak__user_events_search__form_btn",
      variant: "primary",
      onClick: submitSearch,
      "data-testid": "search-events-btn",
      isDisabled: !isDirty
    }, t5("searchAdminEventsBtn"))))), /* @__PURE__ */ react.createElement(Button, {
      className: "pf-u-ml-md",
      onClick: refresh,
      "data-testid": "refresh-btn"
    }, t5("refresh"))), /* @__PURE__ */ react.createElement(FlexItem, null, Object.entries(activeFilters).length > 0 && /* @__PURE__ */ react.createElement("div", {
      className: "keycloak__searchChips pf-u-ml-md"
    }, Object.entries(activeFilters).map((filter3) => {
      const [key2, value] = filter3;
      return /* @__PURE__ */ react.createElement(ChipGroup, {
        className: "pf-u-mt-md pf-u-mr-md",
        key: key2,
        categoryName: filterLabels[key2],
        isClosable: true,
        onClick: () => removeFilter(key2)
      }, typeof value === "string" ? /* @__PURE__ */ react.createElement(Chip, {
        isReadOnly: true
      }, value) : value.map((entry) => /* @__PURE__ */ react.createElement(Chip, {
        key: entry,
        onClick: () => removeFilterValue(key2, entry)
      }, entry)));
    }))));
  };
  const rows = [
    [t5("realm"), authEvent?.authDetails?.realmId],
    [t5("client"), authEvent?.authDetails?.clientId],
    [t5("user"), authEvent?.authDetails?.userId],
    [t5("ipAddress"), authEvent?.authDetails?.ipAddress]
  ];
  const code2 = useMemo(() => representationEvent?.representation ? prettyPrintJSON(JSON.parse(representationEvent.representation)) : "", [representationEvent?.representation]);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, authEvent && /* @__PURE__ */ react.createElement(DisplayDialog2, {
    titleKey: "auth",
    onClose: () => setAuthEvent(void 0)
  }, /* @__PURE__ */ react.createElement(Table, {
    "aria-label": "authData",
    "data-testid": "auth-dialog",
    variant: TableVariant.compact,
    cells: [t5("attribute"), t5("value")],
    rows
  }, /* @__PURE__ */ react.createElement(TableHeader, null), /* @__PURE__ */ react.createElement(TableBody, null))), representationEvent && /* @__PURE__ */ react.createElement(DisplayDialog2, {
    titleKey: "representation",
    "data-testid": "representation-dialog",
    onClose: () => setRepresentationEvent(void 0)
  }, /* @__PURE__ */ react.createElement(CodeEditor, {
    isLineNumbersVisible: true,
    isReadOnly: true,
    code: code2,
    language: Language.json,
    height: "8rem"
  })), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key,
    loader,
    isPaginated: true,
    ariaLabelKey: "events:adminEvents",
    toolbarItem: adminEventSearchFormDisplay(),
    actions: [
      {
        title: t5("auth"),
        onRowClick: (event) => setAuthEvent(event)
      },
      {
        title: t5("representation"),
        onRowClick: (event) => setRepresentationEvent(event)
      }
    ],
    columns: [
      {
        name: "time",
        displayKey: "events:time",
        cellRenderer: (row) => (0, import_moment5.default)(row.time).format("LLL")
      },
      {
        name: "resourcePath",
        displayKey: "events:resourcePath",
        cellRenderer: LinkResource
      },
      {
        name: "resourceType",
        displayKey: "events:resourceType"
      },
      {
        name: "operationType",
        displayKey: "events:operationType",
        transforms: [cellWidth(10)]
      },
      {
        name: "",
        displayKey: "events:user",
        cellRenderer: (event) => event.authDetails?.userId
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      message: t5("emptyEvents"),
      instructions: t5("emptyEventsInstructions")
    }),
    isSearching: Object.keys(activeFilters).length > 0
  }));
};

// build/events/routes/Events.js
var EventsRoute = {
  path: "/:realm/events/:tab?",
  component: lazy(() => Promise.resolve().then(() => require_EventsSection())),
  breadcrumb: (t5) => t5("events:title"),
  access: "view-events"
};

// build/events/routes.js
var routes5 = [EventsRoute];
var routes_default5 = routes5;

// build/groups/SubGroupsContext.js
var SubGroupContext = createContext(void 0);
var SubGroups = ({children: children2}) => {
  const [subGroups, setSubGroups] = useState([]);
  const clear = () => setSubGroups([]);
  const remove3 = (group) => setSubGroups(subGroups.slice(0, subGroups.findIndex((g2) => g2.id === group.id) + 1));
  const currentGroup = () => subGroups[subGroups.length - 1];
  return /* @__PURE__ */ react.createElement(SubGroupContext.Provider, {
    value: {subGroups, setSubGroups, clear, remove: remove3, currentGroup}
  }, children2);
};
var useSubGroups = () => useRequiredContext(SubGroupContext);

// build/groups/GroupsModal.js
var GroupsModal = ({
  id: id3,
  rename,
  handleModalToggle,
  refresh
}) => {
  const {t: t5} = useTranslation("groups");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {register: register2, errors, handleSubmit} = useForm({
    defaultValues: {name: rename}
  });
  const submitForm2 = async (group) => {
    group.name = group.name?.trim();
    try {
      if (!id3) {
        await adminClient.groups.create(group);
      } else if (rename) {
        await adminClient.groups.update({id: id3}, group);
      } else {
        await adminClient.groups.setOrCreateChild({id: id3}, group);
      }
      refresh(rename ? group : void 0);
      handleModalToggle();
      addAlert(t5(rename ? "groupUpdated" : "groupCreated"), AlertVariant.success);
    } catch (error2) {
      addError("groups:couldNotCreateGroup", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    title: t5(rename ? "renameAGroup" : "createAGroup"),
    isOpen: true,
    onClose: handleModalToggle,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": `${rename ? "rename" : "create"}Group`,
        key: "confirm",
        variant: "primary",
        type: "submit",
        form: "group-form"
      }, t5(rename ? "rename" : "create")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          handleModalToggle();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(Form, {
    id: "group-form",
    isHorizontal: true,
    onSubmit: handleSubmit(submitForm2)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    name: "create-modal-group",
    label: t5("common:name"),
    fieldId: "group-id",
    helperTextInvalid: t5("common:required"),
    validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    "data-testid": "groupNameInput",
    "aria-label": "group name input",
    ref: register2({required: true}),
    autoFocus: true,
    type: "text",
    id: "create-group-name",
    name: "name",
    validated: errors.name ? ValidatedOptions.error : ValidatedOptions.default
  }))));
};

// build/groups/groupIdUtils.js
var getId = (pathname) => {
  const pathParts = pathname.substr(1).split("/");
  return pathParts.length > 1 ? pathParts.splice(2) : void 0;
};
var getLastId = (pathname) => {
  const pathParts = getId(pathname);
  return pathParts ? pathParts[pathParts.length - 1] : void 0;
};

// build/groups/GroupTable.js
var GroupTable = () => {
  const {t: t5} = useTranslation("groups");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {realm: realm2} = useRealm();
  const [isKebabOpen, setIsKebabOpen] = useState(false);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [selectedRows, setSelectedRows] = useState([]);
  const [move, setMove] = useState();
  const {subGroups, setSubGroups} = useSubGroups();
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const history = useHistory();
  const location2 = useLocation();
  const id3 = getLastId(location2.pathname);
  const loader = async () => {
    let groupsData = void 0;
    if (id3) {
      const group = await adminClient.groups.findOne({id: id3});
      if (!group) {
        throw new Error(t5("common:notFound"));
      }
      groupsData = group.subGroups;
    } else {
      groupsData = await adminClient.groups.find({
        briefRepresentation: false
      });
    }
    if (!groupsData) {
      history.push(toGroups({realm: realm2}));
    }
    return groupsData || [];
  };
  const multiDelete = async () => {
    try {
      for (const group of selectedRows) {
        await adminClient.groups.del({
          id: group.id
        });
      }
      addAlert(t5("groupDeleted", {count: selectedRows.length}), AlertVariant.success);
      setSelectedRows([]);
    } catch (error2) {
      addError("groups:groupDeleteError", error2);
    }
    refresh();
  };
  const GroupNameCell = (group) => /* @__PURE__ */ react.createElement(Link, {
    key: group.id,
    to: `${location2.pathname}/${group.id}`,
    onClick: () => {
      setSubGroups([...subGroups, group]);
    }
  }, group.name);
  const handleModalToggle = () => {
    setIsCreateModalOpen(!isCreateModalOpen);
  };
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: t5("deleteConfirmTitle", {count: selectedRows.length}),
    messageKey: t5("deleteConfirm", {count: selectedRows.length}),
    continueButtonLabel: "common:delete",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: multiDelete
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key: `${id3}${key}`,
    onSelect: (rows) => setSelectedRows([...rows]),
    canSelectAll: false,
    loader,
    ariaLabelKey: "groups:groups",
    searchPlaceholderKey: "groups:searchForGroups",
    toolbarItem: /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "openCreateGroupModal",
      variant: "primary",
      onClick: handleModalToggle
    }, t5("createGroup"))), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Dropdown, {
      toggle: /* @__PURE__ */ react.createElement(KebabToggle, {
        onToggle: () => setIsKebabOpen(!isKebabOpen),
        isDisabled: selectedRows.length === 0
      }),
      isOpen: isKebabOpen,
      isPlain: true,
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "action",
          component: "button",
          onClick: () => {
            toggleDeleteDialog();
            setIsKebabOpen(false);
          }
        }, t5("common:delete"))
      ]
    }))),
    actions: [
      {
        title: t5("moveTo"),
        onRowClick: async (group) => {
          setMove(group);
          return false;
        }
      },
      {
        title: t5("common:delete"),
        onRowClick: async (group) => {
          setSelectedRows([group]);
          toggleDeleteDialog();
          return true;
        }
      }
    ],
    columns: [
      {
        name: "name",
        displayKey: "groups:groupName",
        cellRenderer: GroupNameCell,
        transforms: [cellWidth(90)]
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      hasIcon: true,
      message: t5(`noGroupsInThis${id3 ? "SubGroup" : "Realm"}`),
      instructions: t5(`noGroupsInThis${id3 ? "SubGroup" : "Realm"}Instructions`),
      primaryActionText: t5("createGroup"),
      onPrimaryAction: handleModalToggle
    })
  }), isCreateModalOpen && /* @__PURE__ */ react.createElement(GroupsModal, {
    id: id3,
    handleModalToggle,
    refresh
  }), move && /* @__PURE__ */ react.createElement(GroupPickerDialog, {
    type: "selectOne",
    filterGroups: [move.name],
    text: {
      title: "groups:moveToGroup",
      ok: "groups:moveHere"
    },
    onClose: () => setMove(void 0),
    onConfirm: async (group) => {
      try {
        try {
          if (group[0].id) {
            await adminClient.groups.setOrCreateChild({id: group[0].id}, move);
          } else {
            await adminClient.groups.create(move);
          }
        } catch (error2) {
          if (error2.response) {
            throw error2;
          }
        }
        setMove(void 0);
        refresh();
        addAlert(t5("moveGroupSuccess"), AlertVariant.success);
      } catch (error2) {
        addError("groups:moveGroupError", error2);
      }
    }
  }));
};

// build/groups/MembersModal.js
var MemberModal = ({groupId, onClose}) => {
  const {t: t5} = useTranslation("groups");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [selectedRows, setSelectedRows] = useState([]);
  const history = useHistory();
  const {realm: realm2} = useRealm();
  const goToCreate = () => history.push(toAddUser({realm: realm2}));
  const loader = async (first2, max2, search2) => {
    const members = await adminClient.groups.listMembers({id: groupId});
    const params = {
      first: first2,
      max: max2 + members.length,
      search: search2 || ""
    };
    try {
      const users2 = await adminClient.users.find({...params});
      return lodash.differenceBy(users2, members, "id").slice(0, max2);
    } catch (error2) {
      addError("groups:noUsersFoundError", error2);
      return [];
    }
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.large,
    title: t5("addMember"),
    isOpen: true,
    onClose,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "add",
        key: "confirm",
        variant: "primary",
        onClick: async () => {
          try {
            await Promise.all(selectedRows.map((user) => adminClient.users.addToGroup({id: user.id, groupId})));
            onClose();
            addAlert(t5("usersAdded", {count: selectedRows.length}), AlertVariant.success);
          } catch (error2) {
            addError("groups:usersAddedError", error2);
          }
        }
      }, t5("common:add")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "cancel",
        key: "cancel",
        variant: "link",
        onClick: onClose
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    loader,
    isPaginated: true,
    ariaLabelKey: "users:title",
    searchPlaceholderKey: "users:searchForUser",
    canSelectAll: true,
    onSelect: (rows) => setSelectedRows([...rows]),
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      message: t5("users:noUsersFound"),
      instructions: t5("users:emptyInstructions"),
      primaryActionText: t5("users:createNewUser"),
      onPrimaryAction: goToCreate
    }),
    columns: [
      {
        name: "username",
        displayKey: "users:username"
      },
      {
        name: "email",
        displayKey: "users:email"
      },
      {
        name: "lastName",
        displayKey: "users:lastName",
        cellFormatters: [emptyFormatter()]
      },
      {
        name: "firstName",
        displayKey: "users:firstName",
        cellFormatters: [emptyFormatter()]
      }
    ]
  }));
};

// build/groups/Members.js
var Members = () => {
  const {t: t5} = useTranslation("groups");
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const {addAlert, addError} = useAlerts();
  const location2 = useLocation();
  const id3 = getLastId(location2.pathname);
  const [includeSubGroup, setIncludeSubGroup] = useState(false);
  const {currentGroup} = useSubGroups();
  const [addMembers, setAddMembers] = useState(false);
  const [isKebabOpen, setIsKebabOpen] = useState(false);
  const [selectedRows, setSelectedRows] = useState([]);
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const getMembership = async (id22) => await adminClient.users.listGroups({id: id22});
  const getSubGroups = (groups2) => {
    let subGroups = [];
    for (const group of groups2) {
      subGroups.push(group);
      const subs = getSubGroups(group.subGroups);
      subGroups = subGroups.concat(subs);
    }
    return subGroups;
  };
  const loader = async (first2, max2) => {
    let members = await adminClient.groups.listMembers({
      id: id3,
      first: first2,
      max: max2
    });
    if (includeSubGroup) {
      const subGroups = getSubGroups(currentGroup().subGroups);
      for (const group of subGroups) {
        members = members.concat(await adminClient.groups.listMembers({id: group.id}));
      }
      members = lodash.uniqBy(members, (member) => member.username);
    }
    const memberOfPromises = await Promise.all(members.map((member) => getMembership(member.id)));
    return members.map((member, i3) => {
      return {...member, membership: memberOfPromises[i3]};
    });
  };
  const MemberOfRenderer = (member) => {
    return /* @__PURE__ */ react.createElement(react.Fragment, null, member.membership.map((group, index3) => /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(GroupPath, {
      key: group.id,
      group
    }), member.membership[index3 + 1] ? ", " : "")));
  };
  const UserDetailLink = (user) => /* @__PURE__ */ react.createElement(Link, {
    key: user.id,
    to: toUser({realm: realm2, id: user.id, tab: "settings"})
  }, user.username);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, addMembers && /* @__PURE__ */ react.createElement(MemberModal, {
    groupId: id3,
    onClose: () => {
      setAddMembers(false);
      refresh();
    }
  }), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    "data-testid": "members-table",
    key: `${id3}${key}${includeSubGroup}`,
    loader,
    ariaLabelKey: "groups:members",
    isPaginated: true,
    canSelectAll: true,
    onSelect: (rows) => setSelectedRows([...rows]),
    toolbarItem: /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "addMember",
      variant: "primary",
      onClick: () => setAddMembers(true)
    }, t5("addMember"))), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Checkbox, {
      "data-testid": "includeSubGroupsCheck",
      label: t5("includeSubGroups"),
      id: "kc-include-sub-groups",
      isChecked: includeSubGroup,
      onChange: () => setIncludeSubGroup(!includeSubGroup)
    })), /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Dropdown, {
      toggle: /* @__PURE__ */ react.createElement(KebabToggle, {
        onToggle: () => setIsKebabOpen(!isKebabOpen),
        isDisabled: selectedRows.length === 0
      }),
      isOpen: isKebabOpen,
      isPlain: true,
      dropdownItems: [
        /* @__PURE__ */ react.createElement(DropdownItem, {
          key: "action",
          component: "button",
          onClick: async () => {
            try {
              await Promise.all(selectedRows.map((user) => adminClient.users.delFromGroup({
                id: user.id,
                groupId: id3
              })));
              setIsKebabOpen(false);
              addAlert(t5("usersLeft", {count: selectedRows.length}), AlertVariant.success);
            } catch (error2) {
              addError("groups:usersLeftError", error2);
            }
            refresh();
          }
        }, t5("leave"))
      ]
    }))),
    actions: [
      {
        title: t5("leave"),
        onRowClick: async (user) => {
          try {
            await adminClient.users.delFromGroup({
              id: user.id,
              groupId: id3
            });
            addAlert(t5("usersLeft", {count: 1}), AlertVariant.success);
          } catch (error2) {
            addError("groups:usersLeftError", error2);
          }
          return true;
        }
      }
    ],
    columns: [
      {
        name: "username",
        displayKey: "common:name",
        cellRenderer: UserDetailLink
      },
      {
        name: "email",
        displayKey: "groups:email",
        cellFormatters: [emptyFormatter()]
      },
      {
        name: "firstName",
        displayKey: "groups:firstName",
        cellFormatters: [emptyFormatter()]
      },
      {
        name: "lastName",
        displayKey: "groups:lastName",
        cellFormatters: [emptyFormatter()]
      },
      {
        name: "membership",
        displayKey: "groups:membership",
        cellRenderer: MemberOfRenderer
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      message: t5("users:noUsersFound"),
      instructions: t5("users:emptyInstructions"),
      primaryActionText: t5("addMember"),
      onPrimaryAction: () => setAddMembers(true)
    })
  }));
};

// build/groups/GroupAttributes.js
var GroupAttributes = () => {
  const {t: t5} = useTranslation("groups");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const form2 = useForm({
    mode: "onChange",
    shouldUnregister: false
  });
  const location2 = useLocation();
  const id3 = getLastId(location2.pathname);
  const {currentGroup, subGroups, setSubGroups} = useSubGroups();
  const convertAttributes = (attr2) => {
    return attributesToArray(attr2 || currentGroup().attributes);
  };
  useEffect(() => {
    form2.setValue("attributes", convertAttributes());
  }, [subGroups]);
  const save = async (attributeForm) => {
    try {
      const group = currentGroup();
      const attributes = arrayToAttributes(attributeForm.attributes);
      await adminClient.groups.update({id: id3}, {...group, attributes});
      setSubGroups([
        ...subGroups.slice(0, subGroups.length - 1),
        {...group, attributes}
      ]);
      addAlert(t5("groupUpdated"), AlertVariant.success);
    } catch (error2) {
      addError("groups:groupUpdateError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(PageSection, {
    variant: PageSectionVariants.light
  }, /* @__PURE__ */ react.createElement(AttributesForm, {
    form: form2,
    save,
    reset: () => form2.reset({
      attributes: convertAttributes()
    })
  }));
};

// build/groups/routes/GroupsSearch.js
var GroupsSearchRoute = {
  path: "/:realm/groups/search",
  component: lazy(() => Promise.resolve().then(() => require_SearchGroups())),
  breadcrumb: (t5) => t5("groups:searchGroups"),
  access: "query-groups"
};
var toGroupsSearch = (params) => ({
  pathname: generatePath(GroupsSearchRoute.path, params)
});

// build/groups/GroupRoleMapping.js
var GroupRoleMapping = ({id: id3, name}) => {
  const {t: t5} = useTranslation("clients");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const [hide3, setHide] = useState(false);
  const loader = async () => {
    const [assignedRoles, effectiveRoles] = await Promise.all([
      adminClient.groups.listRealmRoleMappings({id: id3}).then((roles2) => roles2.map((role) => ({role}))),
      adminClient.groups.listCompositeRealmRoleMappings({id: id3}).then((roles2) => roles2.map((role) => ({role})))
    ]);
    const clients2 = await adminClient.clients.find();
    const clientRoles = (await Promise.all(clients2.map(async (client2) => {
      const [clientAssignedRoles, clientEffectiveRoles] = await Promise.all([
        adminClient.groups.listClientRoleMappings({
          id: id3,
          clientUniqueId: client2.id
        }).then((roles2) => roles2.map((role) => ({role, client: client2}))),
        adminClient.groups.listCompositeClientRoleMappings({
          id: id3,
          clientUniqueId: client2.id
        }).then((roles2) => roles2.map((role) => ({role, client: client2})))
      ]);
      return mapRoles(clientAssignedRoles, clientEffectiveRoles, hide3);
    }))).flat();
    return [...mapRoles(assignedRoles, effectiveRoles, hide3), ...clientRoles];
  };
  const assignRoles = async (rows) => {
    try {
      const realmRoles = rows.filter((row) => row.client === void 0).map((row) => row.role).flat();
      await adminClient.groups.addRealmRoleMappings({
        id: id3,
        roles: realmRoles
      });
      await Promise.all(rows.filter((row) => row.client !== void 0).map((row) => adminClient.groups.addClientRoleMappings({
        id: id3,
        clientUniqueId: row.client.id,
        roles: [row.role]
      })));
      addAlert(t5("roleMappingUpdatedSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("clients:roleMappingUpdatedError", error2);
    }
  };
  return /* @__PURE__ */ react.createElement(RoleMapping, {
    name,
    id: id3,
    type: "group",
    loader,
    save: assignRoles,
    onHideRolesToggle: () => setHide(!hide3)
  });
};

// build/groups/routes/Groups.js
var GroupsRoute = {
  path: "/:realm/groups",
  component: lazy(() => Promise.resolve().then(() => require_GroupsSection())),
  access: "query-groups",
  matchOptions: {
    exact: false
  }
};
var toGroups = (params) => ({
  pathname: generatePath(GroupsRoute.path, params)
});

// build/groups/routes.js
var routes6 = [GroupsSearchRoute, GroupsRoute];
var routes_default6 = routes6;

// build/identity-providers/component/DiscoveryEndpointField.js
var DiscoveryEndpointField = ({
  id: id3,
  fileUpload: fileUpload2,
  children: children2
}) => {
  const {t: t5} = useTranslation("identity-providers");
  const adminClient = useAdminClient();
  const {setValue, register: register2, errors, setError, watch, clearErrors} = useFormContext();
  const discoveryUrl = watch("discoveryEndpoint");
  const [discovery, setDiscovery] = useState(true);
  const [discovering, setDiscovering] = useState(false);
  const [discoveryResult, setDiscoveryResult] = useState();
  const setupForm = (result) => {
    Object.keys(result).map((k2) => setValue(`config.${k2}`, result[k2]));
  };
  useEffect(() => {
    if (!discoveryUrl) {
      setDiscovering(false);
      return;
    }
    (async () => {
      clearErrors("discoveryError");
      try {
        const result = await adminClient.identityProviders.importFromUrl({
          providerId: id3,
          fromUrl: discoveryUrl
        });
        setupForm(result);
        setDiscoveryResult(result);
      } catch (error2) {
        setError("discoveryError", {
          type: "manual",
          message: error2.message
        });
      }
      setDiscovering(false);
    })();
  }, [discovering]);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("useDiscoveryEndpoint"),
    fieldId: "kc-discovery-endpoint-switch",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:useDiscoveryEndpoint",
      fieldLabelId: "identity-providers:discoveryEndpoint"
    })
  }, /* @__PURE__ */ react.createElement(Switch, {
    id: "kc-discovery-endpoint-switch",
    label: t5("common:on"),
    labelOff: t5("common:off"),
    isChecked: discovery,
    onChange: setDiscovery
  })), discovery && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("discoveryEndpoint"),
    fieldId: "kc-discovery-endpoint",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:discoveryEndpoint",
      fieldLabelId: "identity-providers:discoveryEndpoint"
    }),
    validated: errors.discoveryError || errors.discoveryEndpoint ? "error" : !discoveryResult ? "default" : "success",
    helperTextInvalid: errors.discoveryEndpoint ? t5("common:required") : t5("noValidMetaDataFound"),
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    name: "discoveryEndpoint",
    "data-testid": "discoveryEndpoint",
    id: "kc-discovery-endpoint",
    placeholder: id3 === "oidc" ? "https://hostname/auth/realms/master/.well-known/openid-configuration" : "https://hostname/context/saml/discovery",
    onBlur: () => setDiscovering(true),
    validated: errors.discoveryError || errors.discoveryEndpoint ? "error" : !discoveryResult ? "default" : "success",
    customIconUrl: discovering ? environment_default.resourceUrl + "./discovery-load-indicator.svg" : "",
    ref: register2({required: true})
  })), !discovery && fileUpload2, discovery && !errors.discoveryError && children2(true), !discovery && children2(false));
};

// build/identity-providers/add/OpenIdConnectSettings.js
var OpenIdConnectSettings = () => {
  const {t: t5} = useTranslation("identity-providers");
  const id3 = "oidc";
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const {setValue, errors, setError} = useFormContext();
  const setupForm = (result) => {
    Object.keys(result).map((k2) => setValue(`config.${k2}`, result[k2]));
  };
  const fileUpload2 = async (obj) => {
    if (obj) {
      const formData = new FormData();
      formData.append("providerId", id3);
      formData.append("file", new Blob([JSON.stringify(obj)]));
      try {
        const response = await fetch(`${getBaseUrl(adminClient)}admin/realms/${realm2}/identity-provider/import-config`, {
          method: "POST",
          body: formData,
          headers: {
            Authorization: `bearer ${await adminClient.getAccessToken()}`
          }
        });
        const result = await response.json();
        setupForm(result);
      } catch (error2) {
        setError("discoveryError", {
          type: "manual",
          message: error2.message
        });
      }
    }
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Title, {
    headingLevel: "h4",
    size: "xl",
    className: "kc-form-panel__title"
  }, t5("oidcSettings")), /* @__PURE__ */ react.createElement(DiscoveryEndpointField, {
    id: "oidc",
    fileUpload: /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("importConfig"),
      fieldId: "kc-import-config",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "identity-providers-help:importConfig",
        fieldLabelId: "identity-providers:importConfig"
      }),
      validated: errors.discoveryError ? "error" : "default",
      helperTextInvalid: errors.discoveryError
    }, /* @__PURE__ */ react.createElement(JsonFileUpload, {
      id: "kc-import-config",
      helpText: "identity=providers-help:jsonFileUpload",
      hideDefaultPreview: true,
      unWrap: true,
      validated: errors.discoveryError ? "error" : "default",
      onChange: (value) => fileUpload2(value)
    }))
  }, (readonly) => /* @__PURE__ */ react.createElement(DiscoverySettings, {
    readOnly: readonly
  })));
};

// build/identity-providers/routes/IdentityProviderKeycloakOidc.js
var IdentityProviderKeycloakOidcRoute = {
  path: "/:realm/identity-providers/keycloak-oidc/add",
  component: lazy(() => Promise.resolve().then(() => require_AddOpenIdConnect())),
  breadcrumb: (t5) => t5("identity-providers:addKeycloakOpenIdProvider"),
  access: "manage-identity-providers"
};

// build/identity-providers/routes/IdentityProviderOidc.js
var IdentityProviderOidcRoute = {
  path: "/:realm/identity-providers/oidc/add",
  component: lazy(() => Promise.resolve().then(() => require_AddOpenIdConnect())),
  breadcrumb: (t5) => t5("identity-providers:addOpenIdProvider"),
  access: "manage-identity-providers"
};

// build/identity-providers/add/SamlConnectSettings.js
var SamlConnectSettings = () => {
  const {t: t5} = useTranslation("identity-providers");
  const id3 = "saml";
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const {setValue, register: register2, errors, setError} = useFormContext();
  const setupForm = (result) => {
    Object.entries(result).map(([key, value]) => setValue(`config.${key}`, value));
  };
  const fileUpload2 = async (xml) => {
    const formData = new FormData();
    formData.append("providerId", id3);
    formData.append("file", new Blob([xml]));
    try {
      const response = await fetch(`${getBaseUrl(adminClient)}admin/realms/${realm2}/identity-provider/import-config`, {
        method: "POST",
        body: formData,
        headers: {
          Authorization: `bearer ${await adminClient.getAccessToken()}`
        }
      });
      const result = await response.json();
      setupForm(result);
    } catch (error2) {
      setError("discoveryError", {
        type: "manual",
        message: error2.message
      });
    }
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Title, {
    headingLevel: "h4",
    size: "xl",
    className: "kc-form-panel__title"
  }, t5("samlSettings")), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("serviceProviderEntityId"),
    fieldId: "kc-service-provider-entity-id",
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "identity-providers-help:serviceProviderEntityId",
      fieldLabelId: "identity-providers:serviceProviderEntityId"
    })
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    name: "config.entityId",
    "data-testid": "serviceProviderEntityId",
    id: "kc-service-provider-entity-id",
    ref: register2()
  })), /* @__PURE__ */ react.createElement(DiscoveryEndpointField, {
    id: "saml",
    fileUpload: /* @__PURE__ */ react.createElement(FormGroup, {
      label: t5("importConfig"),
      fieldId: "kc-import-config",
      labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
        helpText: "identity-providers-help:importConfig",
        fieldLabelId: "identity-providers:importConfig"
      }),
      validated: errors.discoveryError ? "error" : "default",
      helperTextInvalid: errors.discoveryError
    }, /* @__PURE__ */ react.createElement(FileUploadForm, {
      id: "kc-import-config",
      extension: ".xml",
      hideDefaultPreview: true,
      unWrap: true,
      validated: errors.discoveryError ? "error" : "default",
      onChange: (value) => fileUpload2(value)
    }))
  }, (readonly) => /* @__PURE__ */ react.createElement(DescriptorSettings, {
    readOnly: readonly
  })));
};

// build/identity-providers/routes/IdentityProviderSaml.js
var IdentityProviderSamlRoute = {
  path: "/:realm/identity-providers/saml/add",
  component: lazy(() => Promise.resolve().then(() => require_AddSamlConnect())),
  breadcrumb: (t5) => t5("identity-providers:addSamlProvider"),
  access: "manage-identity-providers"
};

// build/identity-providers/routes.js
var routes7 = [
  IdentityProviderAddMapperRoute,
  IdentityProviderEditMapperRoute,
  IdentityProvidersRoute,
  IdentityProviderOidcRoute,
  IdentityProviderSamlRoute,
  IdentityProviderKeycloakOidcRoute,
  IdentityProviderCreateRoute,
  IdentityProviderRoute
];
var routes_default7 = routes7;

// build/PageNotFoundSection.js
var PageNotFoundSection = () => {
  return /* @__PURE__ */ react.createElement(react.Fragment, null, "Page Not Found");
};

// build/realm-roles/routes/AddRole.js
var AddRoleRoute = {
  path: "/:realm/roles/add-role",
  component: lazy(() => Promise.resolve().then(() => require_RealmRoleTabs())),
  breadcrumb: (t5) => t5("roles:createRole"),
  access: "manage-realm"
};

// build/realm-roles/routes/AddRoleToClient.js
var AddRoleToClientRoute = {
  path: "/:realm/clients/:clientId/roles/add-role",
  component: lazy(() => Promise.resolve().then(() => require_RealmRoleTabs())),
  breadcrumb: (t5) => t5("roles:createRole"),
  access: "manage-realm"
};

// build/realm-roles/routes/RealmRoles.js
var RealmRolesRoute = {
  path: "/:realm/roles",
  component: lazy(() => Promise.resolve().then(() => require_RealmRolesSection())),
  breadcrumb: (t5) => t5("roles:roleList"),
  access: "view-realm"
};

// build/realm-roles/routes.js
var routes8 = [
  AddRoleToClientRoute,
  ClientRoleRoute,
  RealmRolesRoute,
  AddRoleRoute,
  RealmRoleRoute
];
var routes_default8 = routes8;

// build/realm-settings/routes/AesGeneratedSettings.js
var import_RealmSettingsSection11 = require_RealmSettingsSection();
var AesGeneratedSettingsRoute = {
  path: "/:realm/realm-settings/keys/:id/aes-generated/settings",
  component: lazy(() => Promise.resolve().then(() => require_AESGeneratedForm())),
  breadcrumb: () => import_RealmSettingsSection11.EditProviderCrumb,
  access: "view-realm"
};

// build/realm-settings/routes/EcdsaGeneratedSettings.js
var import_RealmSettingsSection12 = require_RealmSettingsSection();
var EcdsaGeneratedSettingsRoute = {
  path: "/:realm/realm-settings/keys/:id/ecdsa-generated/settings",
  component: lazy(() => Promise.resolve().then(() => require_ECDSAGeneratedForm())),
  breadcrumb: () => import_RealmSettingsSection12.EditProviderCrumb,
  access: "view-realm"
};

// build/realm-settings/routes/HmacGeneratedSettings.js
var import_RealmSettingsSection13 = require_RealmSettingsSection();
var HmacGeneratedSettingsRoute = {
  path: "/:realm/realm-settings/keys/:id/hmac-generated/settings",
  component: lazy(() => Promise.resolve().then(() => require_HMACGeneratedForm())),
  breadcrumb: () => import_RealmSettingsSection13.EditProviderCrumb,
  access: "view-realm"
};

// build/realm-settings/routes/JavaKeystoreSettings.js
var import_RealmSettingsSection14 = require_RealmSettingsSection();
var JavaKeystoreSettingsRoute = {
  path: "/:realm/realm-settings/keys/:id/java-keystore/settings",
  component: lazy(() => Promise.resolve().then(() => require_JavaKeystoreForm())),
  breadcrumb: () => import_RealmSettingsSection14.EditProviderCrumb,
  access: "view-realm"
};

// build/realm-settings/routes/RsaGeneratedSettings.js
var import_RealmSettingsSection15 = require_RealmSettingsSection();
var RsaGeneratedSettingsRoute = {
  path: "/:realm/realm-settings/keys/:id/rsa-generated/settings",
  component: lazy(() => Promise.resolve().then(() => require_RSAGeneratedForm())),
  breadcrumb: () => import_RealmSettingsSection15.EditProviderCrumb,
  access: "view-realm"
};

// build/realm-settings/routes/RsaSettings.js
var import_RealmSettingsSection16 = require_RealmSettingsSection();
var RsaSettingsRoute = {
  path: "/:realm/realm-settings/keys/:id/rsa/settings",
  component: lazy(() => Promise.resolve().then(() => require_RSAForm())),
  breadcrumb: () => import_RealmSettingsSection16.EditProviderCrumb,
  access: "view-realm"
};

// build/realm-settings/routes.js
var routes9 = [
  RealmSettingsRoute,
  AesGeneratedSettingsRoute,
  EcdsaGeneratedSettingsRoute,
  HmacGeneratedSettingsRoute,
  JavaKeystoreSettingsRoute,
  RsaGeneratedSettingsRoute,
  RsaSettingsRoute,
  ClientPoliciesRoute,
  AddClientProfileRoute,
  AddExecutorRoute,
  ClientProfileRoute,
  ExecutorRoute,
  AddClientPolicyRoute,
  EditClientPolicyRoute,
  NewClientPolicyConditionRoute,
  EditClientPolicyConditionRoute
];
var routes_default9 = routes9;

// build/realm/routes.js
var routes10 = [AddRealmRoute];
var routes_default10 = routes10;

// build/sessions/RevocationModal.js
var RevocationModal = ({
  handleModalToggle,
  save
}) => {
  const {t: t5} = useTranslation("sessions");
  const {addAlert} = useAlerts();
  const {realm: realmName} = useRealm();
  const adminClient = useAdminClient();
  const {register: register2, errors, handleSubmit} = useForm();
  const [realm2, setRealm] = useState();
  const [key, setKey] = useState(0);
  const refresh = () => {
    setKey(new Date().getTime());
  };
  useFetch(() => adminClient.realms.findOne({realm: realmName}), (realm22) => {
    setRealm(realm22);
  }, [key]);
  const parseResult = (result, prefixKey) => {
    const successCount = result.successRequests?.length || 0;
    const failedCount = result.failedRequests?.length || 0;
    if (successCount === 0 && failedCount === 0) {
      addAlert(t5("clients:noAdminUrlSet"), AlertVariant.warning);
    } else if (failedCount > 0) {
      addAlert(t5("clients:" + prefixKey + "Success", {
        successNodes: result.successRequests
      }), AlertVariant.success);
      addAlert(t5("clients:" + prefixKey + "Fail", {
        failedNodes: result.failedRequests
      }), AlertVariant.danger);
    } else {
      addAlert(t5("clients:" + prefixKey + "Success", {
        successNodes: result.successRequests
      }), AlertVariant.success);
    }
  };
  const setToNow = async () => {
    try {
      await adminClient.realms.update({realm: realmName}, {
        realm: realmName,
        notBefore: Date.now() / 1e3
      });
      addAlert(t5("notBeforeSuccess"), AlertVariant.success);
    } catch (error2) {
      addAlert(t5("setToNowError", {error: error2}), AlertVariant.danger);
    }
  };
  const clearNotBefore = async () => {
    try {
      await adminClient.realms.update({realm: realmName}, {
        realm: realmName,
        notBefore: 0
      });
      addAlert(t5("notBeforeClearedSuccess"), AlertVariant.success);
      refresh();
    } catch (error2) {
      addAlert(t5("notBeforeError", {error: error2}), AlertVariant.danger);
    }
  };
  const push = async () => {
    const result = adminClient.realms.pushRevocation({
      realm: realmName
    });
    parseResult(result, "notBeforePush");
    refresh();
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    title: t5("revocation"),
    isOpen: true,
    onClose: handleModalToggle,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "set-to-now-button",
        key: "set-to-now",
        variant: "tertiary",
        onClick: () => {
          setToNow();
          handleModalToggle();
        },
        form: "revocation-modal-form"
      }, t5("setToNow")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "clear-not-before-button",
        key: "clear",
        variant: "tertiary",
        onClick: () => {
          clearNotBefore();
          handleModalToggle();
        },
        form: "revocation-modal-form"
      }, t5("clear")),
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "modal-test-connection-button",
        key: "push",
        variant: "secondary",
        onClick: () => {
          push();
          handleModalToggle();
        },
        form: "revocation-modal-form"
      }, t5("push")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          handleModalToggle();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(TextContent, {
    className: "kc-revocation-description-text"
  }, t5("revocationDescription")), /* @__PURE__ */ react.createElement(Form, {
    id: "revocation-modal-form",
    isHorizontal: true,
    onSubmit: handleSubmit(save)
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    className: "kc-revocation-modal-form-group",
    label: t5("notBefore"),
    name: "notBefore",
    fieldId: "not-before",
    validated: errors.email ? ValidatedOptions.error : ValidatedOptions.default
  }, /* @__PURE__ */ react.createElement(TextInput, {
    "data-testid": "not-before-input",
    ref: register2({required: true, pattern: emailRegexPattern}),
    autoFocus: true,
    isReadOnly: true,
    value: realm2?.notBefore === 0 ? t5("none") : new Date(realm2?.notBefore * 1e3).toString(),
    type: "text",
    id: "not-before",
    name: "notBefore",
    validated: errors.email ? ValidatedOptions.error : ValidatedOptions.default
  }))));
};

// build/sessions/LogoutAllSessionsModal.js
var LogoutAllSessionsModal = ({
  handleModalToggle
}) => {
  const {t: t5} = useTranslation("sessions");
  const {addAlert} = useAlerts();
  const {realm: realmName} = useRealm();
  const adminClient = useAdminClient();
  const logoutAllSessions = async () => {
    try {
      await adminClient.realms.logoutAll({realm: realmName});
      adminClient.keycloak?.logout({redirectUri: ""});
    } catch (error2) {
      addAlert(t5("logoutAllSessionsError", {error: error2}), AlertVariant.danger);
    }
  };
  return /* @__PURE__ */ react.createElement(Modal, {
    variant: ModalVariant.small,
    title: t5("signOutAllActiveSessionsQuestion"),
    isOpen: true,
    onClose: handleModalToggle,
    actions: [
      /* @__PURE__ */ react.createElement(Button, {
        "data-testid": "logout-all-confirm-button",
        key: "set-to-now",
        variant: "primary",
        onClick: () => {
          logoutAllSessions();
          handleModalToggle();
        },
        form: "revocation-modal-form"
      }, t5("realm-settings:confirm")),
      /* @__PURE__ */ react.createElement(Button, {
        id: "modal-cancel",
        key: "cancel",
        variant: ButtonVariant.link,
        onClick: () => {
          handleModalToggle();
        }
      }, t5("common:cancel"))
    ]
  }, /* @__PURE__ */ react.createElement(TextContent, {
    className: "kc-logout-all-description-text"
  }, t5("logoutAllDescription")));
};

// build/sessions/routes/Sessions.js
var SessionsRoute = {
  path: "/:realm/sessions",
  component: lazy(() => Promise.resolve().then(() => require_SessionsSection())),
  breadcrumb: (t5) => t5("sessions:title"),
  access: "view-realm"
};

// build/sessions/routes.js
var routes11 = [SessionsRoute];
var routes_default11 = routes11;

// build/components/wizard-section-header/WizardSectionHeader.js
var WizardSectionHeader = ({
  title: title3,
  description,
  showDescription = false
}) => {
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(Title, {
    size: "xl",
    headingLevel: "h2",
    className: showDescription ? "kc-wizard-section-header__title--has-description" : "kc-wizard-section-header__title"
  }, title3), showDescription && /* @__PURE__ */ react.createElement(TextContent, {
    className: "kc-wizard-section-header__description"
  }, /* @__PURE__ */ react.createElement(Text, null, description)));
};

// build/user-federation/kerberos/KerberosSettingsRequired.js
var KerberosSettingsRequired = ({
  form: form2,
  showSectionHeading = false,
  showSectionDescription = false
}) => {
  const {t: t5} = useTranslation("user-federation");
  const {t: helpText} = useTranslation("user-federation-help");
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const [isEditModeDropdownOpen, setIsEditModeDropdownOpen] = useState(false);
  const allowPassAuth = useWatch({
    control: form2.control,
    name: "config.allowPasswordAuthentication"
  });
  useFetch(() => adminClient.realms.findOne({realm: realm2}), (result) => form2.setValue("parentId", result.id), []);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, showSectionHeading && /* @__PURE__ */ react.createElement(WizardSectionHeader, {
    title: t5("requiredSettings"),
    description: helpText("kerberosRequiredSettingsDescription"),
    showDescription: showSectionDescription
  }), /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("consoleDisplayName"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:consoleDisplayNameHelp",
      fieldLabelId: "users-federation:consoleDisplayName"
    }),
    fieldId: "kc-console-display-name",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    hidden: true,
    type: "text",
    id: "kc-console-providerId",
    name: "providerId",
    defaultValue: "kerberos",
    ref: form2.register
  }), /* @__PURE__ */ react.createElement(TextInput, {
    hidden: true,
    type: "text",
    id: "kc-console-providerType",
    name: "providerType",
    defaultValue: "org.keycloak.storage.UserStorageProvider",
    ref: form2.register
  }), /* @__PURE__ */ react.createElement(TextInput, {
    hidden: true,
    type: "text",
    id: "kc-console-parentId",
    name: "parentId",
    defaultValue: realm2,
    ref: form2.register
  }), /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    id: "kc-console-name",
    name: "name",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateName")}`
      }
    }),
    "data-testid": "kerberos-name"
  }), form2.errors.name && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.name.message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("kerberosRealm"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:kerberosRealmHelp",
      fieldLabelId: "users-federation:kc-kerberos-realm"
    }),
    fieldId: "kc-kerberos-realm",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    id: "kc-kerberos-realm",
    name: "config.kerberosRealm[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateRealm")}`
      }
    }),
    "data-testid": "kerberos-realm"
  }), form2.errors.config?.kerberosRealm?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.kerberosRealm[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("serverPrincipal"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:serverPrincipalHelp",
      fieldLabelId: "users-federation:serverPrincipal"
    }),
    fieldId: "kc-server-principal",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    id: "kc-server-principal",
    name: "config.serverPrincipal[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateServerPrincipal")}`
      }
    }),
    "data-testid": "kerberos-principal"
  }), form2.errors.config?.serverPrincipal?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.serverPrincipal[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("keyTab"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:keyTabHelp",
      fieldLabelId: "users-federation:keyTab"
    }),
    fieldId: "kc-key-tab",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    id: "kc-key-tab",
    name: "config.keyTab[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateKeyTab")}`
      }
    }),
    "data-testid": "kerberos-keytab"
  }), form2.errors.config?.keyTab?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.keyTab[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("debug"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:debugHelp",
      fieldLabelId: "users-federation:debug"
    }),
    fieldId: "kc-debug",
    hasNoPaddingTop: true
  }, " ", /* @__PURE__ */ react.createElement(Controller, {
    name: "config.debug",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-debug",
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value?.[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("allowPasswordAuthentication"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:allowPasswordAuthenticationHelp",
      fieldLabelId: "users-federation:allowPasswordAuthentication"
    }),
    fieldId: "kc-allow-password-authentication",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.allowPasswordAuthentication",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-allow-password-authentication",
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value?.[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  })), lodash.isEqual(allowPassAuth, ["true"]) ? /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("editMode"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:editModeKerberosHelp",
      fieldLabelId: "users-federation:editMode"
    }),
    isRequired: true,
    fieldId: "kc-edit-mode"
  }, " ", /* @__PURE__ */ react.createElement(Controller, {
    name: "config.editMode[0]",
    defaultValue: "READ_ONLY",
    control: form2.control,
    rules: {required: true},
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-edit-mode",
      required: true,
      onToggle: () => setIsEditModeDropdownOpen(!isEditModeDropdownOpen),
      isOpen: isEditModeDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setIsEditModeDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      key: 0,
      value: "READ_ONLY",
      isPlaceholder: true
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 1,
      value: "UNSYNCED"
    }))
  })) : null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("updateFirstLogin"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:updateFirstLoginHelp",
      fieldLabelId: "users-federation:updateFirstLogin"
    }),
    fieldId: "kc-update-first-login",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.updateProfileFirstLogin",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-update-first-login",
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value?.[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  }))));
};

// build/user-federation/shared/SettingsCache.js
var SettingsCache = ({
  form: form2,
  showSectionHeading = false,
  showSectionDescription = false
}) => {
  const {t: t5} = useTranslation("user-federation");
  const {t: helpText} = useTranslation("user-federation-help");
  const [isCachePolicyDropdownOpen, setIsCachePolicyDropdownOpen] = useState(false);
  const [isEvictionHourDropdownOpen, setIsEvictionHourDropdownOpen] = useState(false);
  const cachePolicyType = useWatch({
    control: form2.control,
    name: "config.cachePolicy"
  });
  const [isEvictionMinuteDropdownOpen, setIsEvictionMinuteDropdownOpen] = useState(false);
  const [isEvictionDayDropdownOpen, setIsEvictionDayDropdownOpen] = useState(false);
  const hourOptions = [
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: 0,
      value: [`${0}`],
      isPlaceholder: true
    }, [`0${0}`])
  ];
  let hourDisplay = "";
  for (let index3 = 1; index3 < 24; index3++) {
    if (index3 < 10) {
      hourDisplay = `0${index3}`;
    } else {
      hourDisplay = `${index3}`;
    }
    hourOptions.push(/* @__PURE__ */ react.createElement(SelectOption, {
      key: index3,
      value: [`${index3}`]
    }, hourDisplay));
  }
  const minuteOptions = [
    /* @__PURE__ */ react.createElement(SelectOption, {
      key: 0,
      value: [`${0}`],
      isPlaceholder: true
    }, [`0${0}`])
  ];
  let minuteDisplay = "";
  for (let index3 = 1; index3 < 60; index3++) {
    if (index3 < 10) {
      minuteDisplay = `0${index3}`;
    } else {
      minuteDisplay = `${index3}`;
    }
    minuteOptions.push(/* @__PURE__ */ react.createElement(SelectOption, {
      key: index3,
      value: [`${index3}`]
    }, minuteDisplay));
  }
  return /* @__PURE__ */ react.createElement(react.Fragment, null, showSectionHeading && /* @__PURE__ */ react.createElement(WizardSectionHeader, {
    title: t5("cacheSettings"),
    description: helpText("cacheSettingsDescription"),
    showDescription: showSectionDescription
  }), /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("cachePolicy"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:cachePolicyHelp",
      fieldLabelId: "user-federation:cachePolicy"
    }),
    fieldId: "kc-cache-policy"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.cachePolicy",
    defaultValue: ["DEFAULT"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-cache-policy",
      required: true,
      onToggle: () => setIsCachePolicyDropdownOpen(!isCachePolicyDropdownOpen),
      isOpen: isCachePolicyDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setIsCachePolicyDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "data-testid": "kerberos-cache-policy"
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      key: 0,
      value: ["DEFAULT"],
      isPlaceholder: true
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 1,
      value: ["EVICT_DAILY"]
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 2,
      value: ["EVICT_WEEKLY"]
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 3,
      value: ["MAX_LIFESPAN"]
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 4,
      value: ["NO_CACHE"]
    }))
  })), lodash.isEqual(cachePolicyType, ["EVICT_WEEKLY"]) ? /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("evictionDay"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:evictionDayHelp",
      fieldLabelId: "user-federation:evictionDay"
    }),
    isRequired: true,
    fieldId: "kc-eviction-day"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.evictionDay[0]",
    defaultValue: "1",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      "data-testid": "cache-day",
      toggleId: "kc-eviction-day",
      required: true,
      onToggle: () => setIsEvictionDayDropdownOpen(!isEvictionDayDropdownOpen),
      isOpen: isEvictionDayDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setIsEvictionDayDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      key: 0,
      value: "1",
      isPlaceholder: true
    }, t5("common:Sunday")), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 1,
      value: "2"
    }, t5("common:Monday")), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 2,
      value: "3"
    }, t5("common:Tuesday")), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 3,
      value: "4"
    }, t5("common:Wednesday")), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 4,
      value: "5"
    }, t5("common:Thursday")), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 5,
      value: "6"
    }, t5("common:Friday")), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 6,
      value: "7"
    }, t5("common:Saturday")))
  })) : null, lodash.isEqual(cachePolicyType, ["EVICT_DAILY"]) || lodash.isEqual(cachePolicyType, ["EVICT_WEEKLY"]) ? /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("evictionHour"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:evictionHourHelp",
      fieldLabelId: "user-federation:evictionHour"
    }),
    isRequired: true,
    fieldId: "kc-eviction-hour"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.evictionHour",
    defaultValue: ["0"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-eviction-hour",
      onToggle: () => setIsEvictionHourDropdownOpen(!isEvictionHourDropdownOpen),
      isOpen: isEvictionHourDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setIsEvictionHourDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single
    }, hourOptions)
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("evictionMinute"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:evictionMinuteHelp",
      fieldLabelId: "user-federation:evictionMinute"
    }),
    isRequired: true,
    fieldId: "kc-eviction-minute"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.evictionMinute",
    defaultValue: ["0"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-eviction-minute",
      onToggle: () => setIsEvictionMinuteDropdownOpen(!isEvictionMinuteDropdownOpen),
      isOpen: isEvictionMinuteDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setIsEvictionMinuteDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single
    }, minuteOptions)
  }))) : null, lodash.isEqual(cachePolicyType, ["MAX_LIFESPAN"]) ? /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("maxLifespan"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:maxLifespanHelp",
      fieldLabelId: "user-federation:maxLifespan"
    }),
    fieldId: "kc-max-lifespan"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-max-lifespan",
    name: "config.maxLifespan[0]",
    ref: form2.register,
    "data-testid": "kerberos-cache-lifespan"
  })) : null));
};

// build/user-federation/routes/NewKerberosUserFederation.js
var NewKerberosUserFederationRoute = {
  path: "/:realm/user-federation/kerberos/new",
  component: lazy(() => Promise.resolve().then(() => require_UserFederationKerberosSettings())),
  breadcrumb: (t5) => t5("common:settings"),
  access: "view-realm"
};

// build/user-federation/ldap/LdapSettingsAdvanced.js
var LdapSettingsAdvanced = ({
  form: form2,
  showSectionHeading = false,
  showSectionDescription = false
}) => {
  const {t: t5} = useTranslation("user-federation");
  const {t: helpText} = useTranslation("user-federation-help");
  return /* @__PURE__ */ react.createElement(react.Fragment, null, showSectionHeading && /* @__PURE__ */ react.createElement(WizardSectionHeader, {
    title: t5("advancedSettings"),
    description: helpText("ldapAdvancedSettingsDescription"),
    showDescription: showSectionDescription
  }), /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("enableLdapv3Password"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:enableLdapv3PasswordHelp",
      fieldLabelId: "users-federation:enableLdapv3Password"
    }),
    fieldId: "kc-enable-ldapv3-password",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.usePasswordModifyExtendedOp",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-enable-ldapv3-password",
      isDisabled: false,
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("validatePasswordPolicy"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:validatePasswordPolicyHelp",
      fieldLabelId: "users-federation:validatePasswordPolicy"
    }),
    fieldId: "kc-validate-password-policy",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.validatePasswordPolicy",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-validate-password-policy",
      isDisabled: false,
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("trustEmail"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:trustEmailHelp",
      fieldLabelId: "users-federation:trustEmail"
    }),
    fieldId: "kc-trust-email",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.trustEmail",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-trust-email",
      isDisabled: false,
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  }))));
};

// build/user-federation/ldap/LdapSettingsKerberosIntegration.js
var LdapSettingsKerberosIntegration = ({
  form: form2,
  showSectionHeading = false,
  showSectionDescription = false
}) => {
  const {t: t5} = useTranslation("user-federation");
  const {t: helpText} = useTranslation("user-federation-help");
  const allowKerberosAuth = useWatch({
    control: form2.control,
    name: "config.allowKerberosAuthentication",
    defaultValue: ["false"]
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, showSectionHeading && /* @__PURE__ */ react.createElement(WizardSectionHeader, {
    title: t5("kerberosIntegration"),
    description: helpText("ldapKerberosSettingsDescription"),
    showDescription: showSectionDescription
  }), /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("allowKerberosAuthentication"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:allowKerberosAuthenticationHelp",
      fieldLabelId: "users-federation:allowKerberosAuthentication"
    }),
    fieldId: "kc-allow-kerberos-authentication",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.allowKerberosAuthentication",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-allow-kerberos-authentication",
      isDisabled: false,
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  })), allowKerberosAuth[0] === "true" && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("kerberosRealm"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:kerberosRealmHelp",
      fieldLabelId: "users-federation:kerberosRealm"
    }),
    fieldId: "kc-kerberos-realm",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    id: "kc-kerberos-realm",
    name: "config.kerberosRealm[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateRealm")}`
      }
    }),
    "data-testid": "kerberos-realm"
  }), form2.errors.config?.kerberosRealm?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.kerberosRealm[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("serverPrincipal"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:serverPrincipalHelp",
      fieldLabelId: "users-federation:serverPrincipal"
    }),
    fieldId: "kc-server-principal",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    id: "kc-server-principal",
    name: "config.serverPrincipal[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateServerPrincipal")}`
      }
    }),
    "data-testid": "kerberos-principal"
  }), form2.errors.config?.serverPrincipal?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.serverPrincipal[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("keyTab"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:keyTabHelp",
      fieldLabelId: "users-federation:keyTab"
    }),
    fieldId: "kc-key-tab",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    id: "kc-key-tab",
    name: "config.keyTab[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateKeyTab")}`
      }
    }),
    "data-testid": "kerberos-keytab"
  }), form2.errors.config?.keyTab?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.keyTab[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("debug"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:debugHelp",
      fieldLabelId: "users-federation:debug"
    }),
    fieldId: "kc-debug",
    hasNoPaddingTop: true
  }, " ", /* @__PURE__ */ react.createElement(Controller, {
    name: "config.debug",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-debug",
      isDisabled: false,
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  }))), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("useKerberosForPasswordAuthentication"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:useKerberosForPasswordAuthenticationHelp",
      fieldLabelId: "users-federation:useKerberosForPasswordAuthentication"
    }),
    fieldId: "kc-use-kerberos-password-authentication",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.useKerberosForPasswordAuthentication",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-use-kerberos-password-authentication",
      isDisabled: false,
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  }))));
};

// build/user-federation/ldap/LdapSettingsSynchronization.js
var LdapSettingsSynchronization = ({
  form: form2,
  showSectionHeading = false,
  showSectionDescription = false
}) => {
  const {t: t5} = useTranslation("user-federation");
  const {t: helpText} = useTranslation("user-federation-help");
  const watchPeriodicSync = form2.watch("config.periodicFullSync", false);
  const watchChangedSync = form2.watch("config.periodicChangedUsersSync", false);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, showSectionHeading && /* @__PURE__ */ react.createElement(WizardSectionHeader, {
    title: t5("synchronizationSettings"),
    description: helpText("ldapSynchronizationSettingsDescription"),
    showDescription: showSectionDescription
  }), /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("importUsers"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:importUsersHelp",
      fieldLabelId: "user-federation:importUsers"
    }),
    fieldId: "kc-import-users"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.importEnabled",
    defaultValue: ["true"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-import-users",
      name: "importEnabled",
      label: t5("common:on"),
      labelOff: t5("common:off"),
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value[0] === "true",
      isDisabled: false
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("batchSize"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:batchSizeHelp",
      fieldLabelId: "user-federation:batchSize"
    }),
    fieldId: "kc-batch-size"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "number",
    min: 0,
    id: "kc-batch-size",
    name: "config.batchSizeForSync[0]",
    ref: form2.register
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("periodicFullSync"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:periodicFullSyncHelp",
      fieldLabelId: "user-federation:periodicFullSync"
    }),
    fieldId: "kc-periodic-full-sync",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.periodicFullSync",
    defaultValue: false,
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-periodic-full-sync",
      isDisabled: false,
      onChange: (value2) => onChange(value2),
      isChecked: value === true,
      label: t5("common:on"),
      labelOff: t5("common:off"),
      ref: form2.register
    })
  })), watchPeriodicSync && /* @__PURE__ */ react.createElement(FormGroup, {
    hasNoPaddingTop: true,
    label: t5("fullSyncPeriod"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:fullSyncPeriodHelp",
      fieldLabelId: "user-federation:fullSyncPeriod"
    }),
    fieldId: "kc-full-sync-period"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "number",
    min: -1,
    defaultValue: 604800,
    id: "kc-full-sync-period",
    name: "config.fullSyncPeriod[0]",
    ref: form2.register
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("periodicChangedUsersSync"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:periodicChangedUsersSyncHelp",
      fieldLabelId: "user-federation:periodicChangedUsersSync"
    }),
    fieldId: "kc-periodic-changed-users-sync",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.periodicChangedUsersSync",
    defaultValue: false,
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-periodic-changed-users-sync",
      isDisabled: false,
      onChange: (value2) => onChange(value2),
      isChecked: value === true,
      label: t5("common:on"),
      labelOff: t5("common:off"),
      ref: form2.register
    })
  })), watchChangedSync && /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("changedUsersSyncPeriod"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:changedUsersSyncHelp",
      fieldLabelId: "user-federation:changedUsersSyncPeriod"
    }),
    fieldId: "kc-changed-users-sync-period",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "number",
    min: -1,
    defaultValue: 86400,
    id: "kc-changed-users-sync-period",
    name: "config.changedSyncPeriod[0]",
    ref: form2.register
  }))));
};

// build/user-federation/ldap/LdapSettingsGeneral.js
var LdapSettingsGeneral = ({
  form: form2,
  showSectionHeading = false,
  showSectionDescription = false,
  vendorEdit = false
}) => {
  const {t: t5} = useTranslation("user-federation");
  const {t: helpText} = useTranslation("user-federation-help");
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  useFetch(() => adminClient.realms.findOne({realm: realm2}), (result) => form2.setValue("parentId", result.id), []);
  const [isVendorDropdownOpen, setIsVendorDropdownOpen] = useState(false);
  const setVendorDefaultValues = () => {
    switch (form2.getValues("config.vendor[0]")) {
      case "ad":
        form2.setValue("config.usernameLDAPAttribute[0]", "cn");
        form2.setValue("config.rdnLDAPAttribute[0]", "cn");
        form2.setValue("config.uuidLDAPAttribute[0]", "objectGUID");
        form2.setValue("config.userObjectClasses[0]", "person, organizationalPerson, user");
        break;
      case "rhds":
        form2.setValue("config.usernameLDAPAttribute[0]", "uid");
        form2.setValue("config.rdnLDAPAttribute[0]", "uid");
        form2.setValue("config.uuidLDAPAttribute[0]", "nsuniqueid");
        form2.setValue("config.userObjectClasses[0]", "inetOrgPerson, organizationalPerson");
        break;
      case "tivoli":
        form2.setValue("config.usernameLDAPAttribute[0]", "uid");
        form2.setValue("config.rdnLDAPAttribute[0]", "uid");
        form2.setValue("config.uuidLDAPAttribute[0]", "uniqueidentifier");
        form2.setValue("config.userObjectClasses[0]", "inetOrgPerson, organizationalPerson");
        break;
      case "edirectory":
        form2.setValue("config.usernameLDAPAttribute[0]", "uid");
        form2.setValue("config.rdnLDAPAttribute[0]", "uid");
        form2.setValue("config.uuidLDAPAttribute[0]", "guid");
        form2.setValue("config.userObjectClasses[0]", "inetOrgPerson, organizationalPerson");
        break;
      case "other":
        form2.setValue("config.usernameLDAPAttribute[0]", "uid");
        form2.setValue("config.rdnLDAPAttribute[0]", "uid");
        form2.setValue("config.uuidLDAPAttribute[0]", "entryUUID");
        form2.setValue("config.userObjectClasses[0]", "inetOrgPerson, organizationalPerson");
        break;
      default:
        return "";
    }
  };
  return /* @__PURE__ */ react.createElement(react.Fragment, null, showSectionHeading && /* @__PURE__ */ react.createElement(WizardSectionHeader, {
    title: t5("generalOptions"),
    description: helpText("ldapGeneralOptionsSettingsDescription"),
    showDescription: showSectionDescription
  }), /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("consoleDisplayName"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:consoleDisplayNameHelp",
      fieldLabelId: "users-federation:consoleDisplayName"
    }),
    fieldId: "kc-console-display-name",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    hidden: true,
    type: "text",
    id: "kc-console-provider-id",
    name: "providerId",
    defaultValue: "ldap",
    ref: form2.register
  }), /* @__PURE__ */ react.createElement(TextInput, {
    hidden: true,
    type: "text",
    id: "kc-console-provider-type",
    name: "providerType",
    defaultValue: "org.keycloak.storage.UserStorageProvider",
    ref: form2.register
  }), /* @__PURE__ */ react.createElement(TextInput, {
    hidden: true,
    type: "text",
    id: "kc-console-parentId",
    name: "parentId",
    defaultValue: realm2,
    ref: form2.register
  }), /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    id: "kc-console-display-name",
    name: "name",
    defaultValue: "ldap",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateName")}`
      }
    }),
    "data-testid": "ldap-name"
  }), form2.errors.name && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.name.message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("vendor"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:vendorHelp",
      fieldLabelId: "users-federation:vendor"
    }),
    fieldId: "kc-vendor",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.vendor[0]",
    defaultValue: "ad",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      isDisabled: !!vendorEdit,
      toggleId: "kc-vendor",
      required: true,
      onToggle: () => setIsVendorDropdownOpen(!isVendorDropdownOpen),
      isOpen: isVendorDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setIsVendorDropdownOpen(false);
        setVendorDefaultValues();
      },
      selections: value,
      variant: SelectVariant.single
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      key: 0,
      value: "ad",
      isPlaceholder: true
    }, "Active Directory"), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 1,
      value: "rhds"
    }, "Red Hat Directory Server"), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 2,
      value: "tivoli"
    }, "Tivoli"), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 3,
      value: "edirectory"
    }, "Novell eDirectory"), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 4,
      value: "other"
    }, "Other"))
  }))));
};

// build/user-federation/ldap/LdapSettingsConnection.js
var testLdapProperties = [
  "connectionUrl",
  "bindDn",
  "bindCredential",
  "useTruststoreSpi",
  "connectionTimeout",
  "startTls",
  "authType"
];
var convertFormToSettings = (form2) => {
  const settings = {};
  testLdapProperties.forEach((key) => {
    const value = lodash.get(form2.getValues(), `config.${key}`);
    settings[key] = Array.isArray(value) ? value[0] : "";
  });
  return settings;
};
var LdapSettingsConnection = ({
  form: form2,
  showSectionHeading = false,
  showSectionDescription = false,
  edit = false
}) => {
  const {t: t5} = useTranslation("user-federation");
  const {t: helpText} = useTranslation("user-federation-help");
  const adminClient = useAdminClient();
  const {realm: realm2} = useRealm();
  const {addAlert, addError} = useAlerts();
  const testLdap = async (testType) => {
    try {
      const settings = convertFormToSettings(form2);
      await adminClient.realms.testLDAPConnection({realm: realm2}, {...settings, action: testType});
      addAlert(t5("testSuccess"), AlertVariant.success);
    } catch (error2) {
      addError("user-federation:testError", error2);
    }
  };
  const [isTruststoreSpiDropdownOpen, setIsTruststoreSpiDropdownOpen] = useState(false);
  const [isBindTypeDropdownOpen, setIsBindTypeDropdownOpen] = useState(false);
  const ldapBindType = useWatch({
    control: form2.control,
    name: "config.authType",
    defaultValue: ["simple"]
  });
  return /* @__PURE__ */ react.createElement(react.Fragment, null, showSectionHeading && /* @__PURE__ */ react.createElement(WizardSectionHeader, {
    title: t5("connectionAndAuthenticationSettings"),
    description: helpText("ldapConnectionAndAuthorizationSettingsDescription"),
    showDescription: showSectionDescription
  }), /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("connectionURL"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:consoleDisplayConnectionUrlHelp",
      fieldLabelId: "users-federation:connectionURL"
    }),
    fieldId: "kc-console-connection-url",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    id: "kc-console-connection-url",
    "data-testid": "ldap-connection-url",
    name: "config.connectionUrl[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateConnectionUrl")}`
      }
    })
  }), form2.errors.config?.connectionUrl?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.connectionUrl[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("enableStartTls"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:enableStartTlsHelp",
      fieldLabelId: "users-federation:enableStartTls"
    }),
    fieldId: "kc-enable-start-tls",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.startTls",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-enable-start-tls",
      isDisabled: false,
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("useTruststoreSpi"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:useTruststoreSpiHelp",
      fieldLabelId: "users-federation:useTruststoreSpi"
    }),
    fieldId: "kc-use-truststore-spi"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.useTruststoreSpi[0]",
    control: form2.control,
    defaultValue: "ldapsOnly",
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-use-truststore-spi",
      onToggle: () => setIsTruststoreSpiDropdownOpen(!isTruststoreSpiDropdownOpen),
      isOpen: isTruststoreSpiDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setIsTruststoreSpiDropdownOpen(false);
      },
      selections: value
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      value: "always"
    }, t5("always")), /* @__PURE__ */ react.createElement(SelectOption, {
      value: "ldapsOnly"
    }, t5("onlyLdaps")), /* @__PURE__ */ react.createElement(SelectOption, {
      value: "never"
    }, t5("never")))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("connectionPooling"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:connectionPoolingHelp",
      fieldLabelId: "users-federation:connectionPooling"
    }),
    fieldId: "kc-connection-pooling",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.connectionPooling",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-connection-pooling",
      isDisabled: false,
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("connectionTimeout"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:connectionTimeoutHelp",
      fieldLabelId: "users-federation:consoleTimeout"
    }),
    fieldId: "kc-console-connection-timeout"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "number",
    min: 0,
    id: "kc-console-connection-timeout",
    name: "config.connectionTimeout[0]",
    ref: form2.register
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    fieldId: "kc-test-button"
  }, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    id: "kc-connection-test-button",
    onClick: () => testLdap("testConnection")
  }, t5("common:testConnection"))), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("bindType"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:bindTypeHelp",
      fieldLabelId: "users-federation:bindType"
    }),
    fieldId: "kc-bind-type",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.authType[0]",
    defaultValue: "simple",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-bind-type",
      required: true,
      onToggle: () => setIsBindTypeDropdownOpen(!isBindTypeDropdownOpen),
      isOpen: isBindTypeDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setIsBindTypeDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single,
      "data-testid": "ldap-bind-type"
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      value: "simple"
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      value: "none"
    }))
  })), lodash.isEqual(ldapBindType, ["simple"]) && /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("bindDn"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:bindDnHelp",
      fieldLabelId: "users-federation:bindDn"
    }),
    fieldId: "kc-console-bind-dn",
    helperTextInvalid: t5("validateBindDn"),
    validated: form2.errors.config?.bindDn ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-console-bind-dn",
    "data-testid": "ldap-bind-dn",
    name: "config.bindDn[0]",
    ref: form2.register({required: true})
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("bindCredentials"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "users-federation-help:bindCredentialsHelp",
      fieldLabelId: "users-federation:bindCredentials"
    }),
    fieldId: "kc-console-bind-credentials",
    helperTextInvalid: t5("validateBindCredentials"),
    validated: form2.errors.config?.bindCredential ? ValidatedOptions.error : ValidatedOptions.default,
    isRequired: true
  }, /* @__PURE__ */ react.createElement(PasswordInput, {
    hasReveal: !edit,
    isRequired: true,
    id: "kc-console-bind-credentials",
    "data-testid": "ldap-bind-credentials",
    name: "config.bindCredential[0]",
    ref: form2.register({
      required: true
    })
  }))), /* @__PURE__ */ react.createElement(FormGroup, {
    fieldId: "kc-test-button"
  }, /* @__PURE__ */ react.createElement(Button, {
    variant: "secondary",
    id: "kc-test-button",
    onClick: () => testLdap("testAuthentication")
  }, t5("testAuthentication")))));
};

// build/user-federation/ldap/LdapSettingsSearching.js
var LdapSettingsSearching = ({
  form: form2,
  showSectionHeading = false,
  showSectionDescription = false
}) => {
  const {t: t5} = useTranslation("user-federation");
  const {t: helpText} = useTranslation("user-federation-help");
  const [isSearchScopeDropdownOpen, setIsSearchScopeDropdownOpen] = useState(false);
  const [isEditModeDropdownOpen, setIsEditModeDropdownOpen] = useState(false);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, showSectionHeading && /* @__PURE__ */ react.createElement(WizardSectionHeader, {
    title: t5("ldapSearchingAndUpdatingSettings"),
    description: helpText("ldapSearchingAndUpdatingSettingsDescription"),
    showDescription: showSectionDescription
  }), /* @__PURE__ */ react.createElement(FormAccess, {
    role: "manage-realm",
    isHorizontal: true
  }, /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("editMode"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:editModeLdapHelp",
      fieldLabelId: "user-federation:editMode"
    }),
    fieldId: "kc-edit-mode",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.editMode[0]",
    defaultValue: "",
    control: form2.control,
    rules: {
      required: {value: true, message: t5("validateEditMode")}
    },
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-edit-mode",
      required: true,
      onToggle: () => setIsEditModeDropdownOpen(!isEditModeDropdownOpen),
      isOpen: isEditModeDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2.toString());
        setIsEditModeDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      value: "",
      isPlaceholder: true
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      value: "READ_ONLY"
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      value: "WRITABLE"
    }), /* @__PURE__ */ react.createElement(SelectOption, {
      value: "UNSYNCED"
    }))
  }), form2.errors.config?.editMode?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.editMode[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("usersDN"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:usersDNHelp",
      fieldLabelId: "user-federation:usersDn"
    }),
    fieldId: "kc-console-users-dn",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    defaultValue: "",
    id: "kc-console-users-dn",
    "data-testid": "ldap-users-dn",
    name: "config.usersDn[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateUsersDn")}`
      }
    })
  }), form2.errors.config?.usersDn?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.usersDn[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("usernameLdapAttribute"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:usernameLdapAttributeHelp",
      fieldLabelId: "user-federation:usernameLdapAttribute"
    }),
    fieldId: "kc-username-ldap-attribute",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    defaultValue: "cn",
    id: "kc-username-ldap-attribute",
    "data-testid": "ldap-username-attribute",
    name: "config.usernameLDAPAttribute[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateUsernameLDAPAttribute")}`
      }
    })
  }), form2.errors.config?.usernameLDAPAttribute?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.usernameLDAPAttribute[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("rdnLdapAttribute"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:rdnLdapAttributeHelp",
      fieldLabelId: "user-federation:rdnLdapAttribute"
    }),
    fieldId: "kc-rdn-ldap-attribute",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    defaultValue: "cn",
    id: "kc-rdn-ldap-attribute",
    "data-testid": "ldap-rdn-attribute",
    name: "config.rdnLDAPAttribute[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateRdnLdapAttribute")}`
      }
    })
  }), form2.errors.config?.rdnLDAPAttribute?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.rdnLDAPAttribute[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("uuidLdapAttribute"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:uuidLdapAttributeHelp",
      fieldLabelId: "user-federation:uuidLdapAttribute"
    }),
    fieldId: "kc-uuid-ldap-attribute",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    defaultValue: "objectGUID",
    id: "kc-uuid-ldap-attribute",
    "data-testid": "ldap-uuid-attribute",
    name: "config.uuidLDAPAttribute[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateUuidLDAPAttribute")}`
      }
    })
  }), form2.errors.config?.uuidLDAPAttribute?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.uuidLDAPAttribute[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("userObjectClasses"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:userObjectClassesHelp",
      fieldLabelId: "user-federation:userObjectClasses"
    }),
    fieldId: "kc-user-object-classes",
    isRequired: true
  }, /* @__PURE__ */ react.createElement(TextInput, {
    isRequired: true,
    type: "text",
    defaultValue: "person, organizationalPerson, user",
    id: "kc-user-object-classes",
    "data-testid": "ldap-user-object-classes",
    name: "config.userObjectClasses[0]",
    ref: form2.register({
      required: {
        value: true,
        message: `${t5("validateUserObjectClasses")}`
      }
    })
  }), form2.errors.config?.userObjectClasses?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.userObjectClasses[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("userLdapFilter"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:userLdapFilterHelp",
      fieldLabelId: "user-federation:userLdapFilter"
    }),
    fieldId: "kc-user-ldap-filter"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "text",
    id: "kc-user-ldap-filter",
    name: "config.customUserSearchFilter[0]",
    ref: form2.register({
      pattern: {
        value: /(\(.*\))$/,
        message: `${t5("validateCustomUserSearchFilter")}`
      }
    })
  }), form2.errors.config?.customUserSearchFilter?.[0] && /* @__PURE__ */ react.createElement("div", {
    className: "error"
  }, form2.errors.config.customUserSearchFilter[0].message)), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("searchScope"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:searchScopeHelp",
      fieldLabelId: "user-federation:searchScope"
    }),
    fieldId: "kc-search-scope"
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.searchScope[0]",
    defaultValue: "",
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Select, {
      toggleId: "kc-search-scope",
      required: true,
      onToggle: () => setIsSearchScopeDropdownOpen(!isSearchScopeDropdownOpen),
      isOpen: isSearchScopeDropdownOpen,
      onSelect: (_23, value2) => {
        onChange(value2);
        setIsSearchScopeDropdownOpen(false);
      },
      selections: value,
      variant: SelectVariant.single
    }, /* @__PURE__ */ react.createElement(SelectOption, {
      key: 0,
      value: "1",
      isPlaceholder: true
    }, t5("oneLevel")), /* @__PURE__ */ react.createElement(SelectOption, {
      key: 1,
      value: "2"
    }, t5("subtree")))
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("readTimeout"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:readTimeoutHelp",
      fieldLabelId: "user-federation:readTimeout"
    }),
    fieldId: "kc-read-timeout"
  }, /* @__PURE__ */ react.createElement(TextInput, {
    type: "number",
    min: 0,
    id: "kc-read-timeout",
    name: "config.readTimeout[0]",
    ref: form2.register
  })), /* @__PURE__ */ react.createElement(FormGroup, {
    label: t5("pagination"),
    labelIcon: /* @__PURE__ */ react.createElement(HelpItem, {
      helpText: "user-federation-help:paginationHelp",
      fieldLabelId: "user-federation:pagination"
    }),
    fieldId: "kc-console-pagination",
    hasNoPaddingTop: true
  }, /* @__PURE__ */ react.createElement(Controller, {
    name: "config.pagination",
    defaultValue: ["false"],
    control: form2.control,
    render: ({onChange, value}) => /* @__PURE__ */ react.createElement(Switch, {
      id: "kc-console-pagination",
      isDisabled: false,
      onChange: (value2) => onChange([`${value2}`]),
      isChecked: value[0] === "true",
      label: t5("common:on"),
      labelOff: t5("common:off")
    })
  }))));
};

// build/user-federation/ldap/mappers/LdapMapperList.js
var LdapMapperList = () => {
  const history = useHistory();
  const {t: t5} = useTranslation("user-federation");
  const adminClient = useAdminClient();
  const {addAlert, addError} = useAlerts();
  const {url} = useRouteMatch();
  const [key, setKey] = useState(0);
  const refresh = () => setKey(new Date().getTime());
  const {id: id3} = useParams();
  const [selectedMapper, setSelectedMapper] = useState();
  const loader = async () => {
    const testParams = {
      parent: id3,
      type: "org.keycloak.storage.ldap.mappers.LDAPStorageMapper"
    };
    const mappersList = (await adminClient.components.find(testParams)).map((mapper) => {
      return {
        ...mapper,
        name: mapper.name,
        type: mapper.providerId
      };
    });
    return mappersList;
  };
  const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
    titleKey: t5("common:deleteMappingTitle", {mapperId: selectedMapper?.id}),
    messageKey: "common:deleteMappingConfirm",
    continueButtonLabel: "common:delete",
    continueButtonVariant: ButtonVariant.danger,
    onConfirm: async () => {
      try {
        await adminClient.components.del({
          id: selectedMapper.id
        });
        refresh();
        addAlert(t5("common:mappingDeletedSuccess"), AlertVariant.success);
        setSelectedMapper(void 0);
      } catch (error2) {
        addError("common:mappingDeletedError", error2);
      }
    }
  });
  const getUrl = (url2) => {
    if (!url2.includes("/mappers")) {
      return `${url2}/mappers`;
    }
    return `${url2}`;
  };
  const MapperLink = (mapper) => /* @__PURE__ */ react.createElement(Link, {
    to: `${getUrl(url)}/${mapper.id}`
  }, mapper.name);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, /* @__PURE__ */ react.createElement(DeleteConfirm, null), /* @__PURE__ */ react.createElement(KeycloakDataTable, {
    key,
    loader,
    ariaLabelKey: "ldapMappersList",
    searchPlaceholderKey: "common:searchForMapper",
    toolbarItem: /* @__PURE__ */ react.createElement(ToolbarItem, null, /* @__PURE__ */ react.createElement(Button, {
      "data-testid": "add-mapper-btn",
      variant: "primary",
      onClick: () => history.push(`${url}/new`)
    }, t5("common:addMapper"))),
    actions: [
      {
        title: t5("common:delete"),
        onRowClick: (mapper) => {
          setSelectedMapper(mapper);
          toggleDeleteDialog();
        }
      }
    ],
    columns: [
      {
        name: "name",
        cellRenderer: MapperLink
      },
      {
        name: "type"
      }
    ],
    emptyState: /* @__PURE__ */ react.createElement(ListEmptyState, {
      message: t5("common:emptyMappers"),
      instructions: t5("common:emptyMappersInstructions"),
      primaryActionText: t5("common:emptyPrimaryAction"),
      onPrimaryAction: () => history.push(`${url}/new`)
    })
  }));
};

// build/user-federation/routes/NewLdapUserFederation.js
var NewLdapUserFederationRoute = {
  path: "/:realm/user-federation/ldap/new",
  component: lazy(() => Promise.resolve().then(() => require_UserFederationLdapSettings())),
  breadcrumb: (t5) => t5("user-federation:addOneLdap"),
  access: "view-realm"
};

// build/components/keycloak-card/KeycloakCard.js
var KeycloakCard = ({
  id: id3,
  title: title3,
  dropdownItems,
  labelText,
  labelColor,
  footerText,
  providerId
}) => {
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const history = useHistory();
  const {url} = useRouteMatch();
  const onDropdownToggle = () => {
    setIsDropdownOpen(!isDropdownOpen);
  };
  const handleCardMenuClick = (e2) => {
    e2.stopPropagation();
  };
  const openSettings = () => {
    history.push(`${url}/${providerId}/${id3}`);
  };
  return /* @__PURE__ */ react.createElement(Card, {
    isSelectable: true,
    onClick: openSettings
  }, /* @__PURE__ */ react.createElement(CardHeader, null, /* @__PURE__ */ react.createElement(CardActions, null, dropdownItems && /* @__PURE__ */ react.createElement(Dropdown, {
    "data-testid": `${title3}-dropdown`,
    isPlain: true,
    position: "right",
    toggle: /* @__PURE__ */ react.createElement(KebabToggle, {
      onToggle: onDropdownToggle
    }),
    onClick: (e2) => handleCardMenuClick(e2),
    isOpen: isDropdownOpen,
    dropdownItems
  })), /* @__PURE__ */ react.createElement(CardTitle, {
    "data-testid": "keycloak-card-title"
  }, title3)), /* @__PURE__ */ react.createElement(CardBody, null), /* @__PURE__ */ react.createElement(CardFooter, null, /* @__PURE__ */ react.createElement(Flex, null, /* @__PURE__ */ react.createElement(FlexItem, {
    className: "keycloak--keycloak-card__footer"
  }, footerText && footerText), /* @__PURE__ */ react.createElement(FlexItem, null, labelText && /* @__PURE__ */ react.createElement(Label, {
    color: labelColor || "gray"
  }, labelText)))));
};

// build/user-federation/routes/UserFederation.js
var UserFederationRoute = {
  path: "/:realm/user-federation",
  component: lazy(() => Promise.resolve().then(() => require_UserFederationSection())),
  breadcrumb: (t5) => t5("userFederation"),
  access: "view-realm"
};

// build/user-federation/routes/UserFederationKerberos.js
var UserFederationKerberosRoute = {
  path: "/:realm/user-federation/kerberos/:id",
  component: lazy(() => Promise.resolve().then(() => require_UserFederationKerberosSettings())),
  breadcrumb: (t5) => t5("common:settings"),
  access: "view-realm"
};

// build/user-federation/routes/UserFederationLdap.js
var UserFederationLdapRoute = {
  path: "/:realm/user-federation/ldap/:id/:tab?",
  component: lazy(() => Promise.resolve().then(() => require_UserFederationLdapSettings())),
  breadcrumb: (t5) => t5("common:settings"),
  access: "view-realm"
};
var toUserFederationLdap = (params) => ({
  pathname: generatePath(UserFederationLdapRoute.path, params)
});

// build/user-federation/routes/UserFederationLdapMapper.js
var UserFederationLdapMapperRoute = {
  path: "/:realm/user-federation/ldap/:id/:tab/:mapperId",
  component: lazy(() => Promise.resolve().then(() => require_LdapMapperDetails())),
  breadcrumb: (t5) => t5("common:mappingDetails"),
  access: "view-realm"
};

// build/user-federation/routes/UserFederationsKerberos.js
var UserFederationsKerberosRoute = {
  path: "/:realm/user-federation/kerberos",
  component: lazy(() => Promise.resolve().then(() => require_UserFederationSection())),
  access: "view-realm"
};

// build/user-federation/routes/UserFederationsLdap.js
var UserFederationsLdapRoute = {
  path: "/:realm/user-federation/ldap",
  component: lazy(() => Promise.resolve().then(() => require_UserFederationSection())),
  access: "view-realm"
};

// build/user-federation/routes.js
var routes12 = [
  UserFederationRoute,
  UserFederationsKerberosRoute,
  NewKerberosUserFederationRoute,
  UserFederationKerberosRoute,
  UserFederationsLdapRoute,
  NewLdapUserFederationRoute,
  UserFederationLdapRoute,
  UserFederationLdapMapperRoute
];
var routes_default12 = routes12;

// build/user/routes.js
var routes13 = [UsersRoute, AddUserRoute, UserRoute];
var routes_default13 = routes13;

// build/route-config.js
var NotFoundRoute = {
  path: "*",
  component: PageNotFoundSection,
  access: "anyone"
};
var routes14 = [
  ...routes_default,
  ...routes_default3,
  ...routes_default2,
  ...routes_default5,
  ...routes_default7,
  ...routes_default8,
  ...routes_default10,
  ...routes_default9,
  ...routes_default11,
  ...routes_default12,
  ...routes_default13,
  ...routes_default4,
  ...routes_default6,
  NotFoundRoute
];

// build/PageNav.js
var PageNav = () => {
  const {t: t5} = useTranslation("common");
  const {hasAccess, hasSomeAccess} = useAccess();
  const {realm: realm2} = useRealm();
  const history = useHistory();
  const onSelect = (item) => {
    history.push(item.to);
    item.event.preventDefault();
  };
  const LeftNav = ({title: title3, path}) => {
    const route = routes14.find((route2) => route2.path.replace(/\/:.+?(\?|(?:(?!\/).)*|$)/g, "") === path);
    const accessAllowed = route && (route.access instanceof Array ? hasAccess(...route.access) : hasAccess(route.access));
    if (!accessAllowed) {
      return null;
    }
    const activeItem = history.location.pathname.substr(realm2.length + 1);
    return /* @__PURE__ */ react.createElement(NavItem, {
      id: "nav-item" + path.replace("/", "-"),
      to: `/${realm2}${path}`,
      isActive: path === activeItem || path !== "/" && activeItem.startsWith(path)
    }, t5(title3));
  };
  const showManage = hasSomeAccess("view-realm", "query-groups", "query-users", "query-clients", "view-events");
  const showConfigure = hasSomeAccess("view-realm", "query-clients", "view-identity-providers");
  const isOnAddRealm = !!useRouteMatch(AddRealmRoute.path);
  return /* @__PURE__ */ react.createElement(PageSidebar, {
    nav: /* @__PURE__ */ react.createElement(Nav, {
      onSelect
    }, /* @__PURE__ */ react.createElement(NavList, null, /* @__PURE__ */ react.createElement(NavItem, {
      className: "keycloak__page_nav__nav_item__realm-selector"
    }, /* @__PURE__ */ react.createElement(RealmSelector, null))), /* @__PURE__ */ react.createElement(Divider, null), showManage && !isOnAddRealm && /* @__PURE__ */ react.createElement(NavGroup, {
      "aria-label": t5("manage"),
      title: t5("manage")
    }, /* @__PURE__ */ react.createElement(LeftNav, {
      title: "clients",
      path: "/clients"
    }), /* @__PURE__ */ react.createElement(LeftNav, {
      title: "clientScopes",
      path: "/client-scopes"
    }), /* @__PURE__ */ react.createElement(LeftNav, {
      title: "realmRoles",
      path: "/roles"
    }), /* @__PURE__ */ react.createElement(LeftNav, {
      title: "users",
      path: "/users"
    }), /* @__PURE__ */ react.createElement(LeftNav, {
      title: "groups",
      path: "/groups"
    }), /* @__PURE__ */ react.createElement(LeftNav, {
      title: "sessions",
      path: "/sessions"
    }), /* @__PURE__ */ react.createElement(LeftNav, {
      title: "events",
      path: "/events"
    })), showConfigure && !isOnAddRealm && /* @__PURE__ */ react.createElement(NavGroup, {
      "aria-label": t5("configure"),
      title: t5("configure")
    }, /* @__PURE__ */ react.createElement(LeftNav, {
      title: "realmSettings",
      path: "/realm-settings"
    }), /* @__PURE__ */ react.createElement(LeftNav, {
      title: "authentication",
      path: "/authentication"
    }), /* @__PURE__ */ react.createElement(LeftNav, {
      title: "identityProviders",
      path: "/identity-providers"
    }), /* @__PURE__ */ react.createElement(LeftNav, {
      title: "userFederation",
      path: "/user-federation"
    })))
  });
};

// build/_snowpack/pkg/use-react-router-breadcrumbs.js
var arrayWithoutHoles = createCommonjsModule(function(module2) {
  function _arrayWithoutHoles2(arr) {
    if (Array.isArray(arr))
      return arrayLikeToArray(arr);
  }
  module2.exports = _arrayWithoutHoles2;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var iterableToArray = createCommonjsModule(function(module2) {
  function _iterableToArray2(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null)
      return Array.from(iter);
  }
  module2.exports = _iterableToArray2;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var nonIterableSpread = createCommonjsModule(function(module2) {
  function _nonIterableSpread2() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  module2.exports = _nonIterableSpread2;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var toConsumableArray = createCommonjsModule(function(module2) {
  function _toConsumableArray4(arr) {
    return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
  }
  module2.exports = _toConsumableArray4;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
});
var _toConsumableArray3 = /* @__PURE__ */ getDefaultExportFromCjs(toConsumableArray);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

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

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __rest4(s2, e2) {
  var t5 = {};
  for (var p2 in s2)
    if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
      t5[p2] = s2[p2];
  if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i3 = 0, p2 = Object.getOwnPropertySymbols(s2); i3 < p2.length; i3++) {
      if (e2.indexOf(p2[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i3]))
        t5[p2[i3]] = s2[p2[i3]];
    }
  return t5;
}
var DEFAULT_MATCH_OPTIONS = {
  exact: true
};
var NO_BREADCRUMB = "NO_BREADCRUMB";
var humanize = function humanize2(str) {
  return str.replace(/^[\s_]+|[\s_]+$/g, "").replace(/[_\s]+/g, " ").replace(/^[a-z]/, function(m2) {
    return m2.toUpperCase();
  });
};
var render2 = function render3(_ref) {
  var Breadcrumb2 = _ref.breadcrumb, match2 = _ref.match, location2 = _ref.location, props = _ref.props;
  var componentProps = Object.assign({
    match: match2,
    location: location2,
    key: match2.url
  }, props || {});
  return Object.assign(Object.assign({}, componentProps), {
    breadcrumb: typeof Breadcrumb2 === "string" ? /* @__PURE__ */ react.createElement("span", {
      key: componentProps.key
    }, Breadcrumb2) : /* @__PURE__ */ react.createElement(Breadcrumb2, Object.assign({}, componentProps))
  });
};
var getDefaultBreadcrumb = function getDefaultBreadcrumb2(_ref2) {
  var currentSection = _ref2.currentSection, location2 = _ref2.location, pathSection = _ref2.pathSection;
  var match2 = matchPath(pathSection, Object.assign(Object.assign({}, DEFAULT_MATCH_OPTIONS), {
    path: pathSection
  })) || {
    url: "not-found"
  };
  return render2({
    breadcrumb: humanize(currentSection),
    match: match2,
    location: location2
  });
};
var getBreadcrumbMatch = function getBreadcrumbMatch2(_ref3) {
  var currentSection = _ref3.currentSection, disableDefaults = _ref3.disableDefaults, excludePaths = _ref3.excludePaths, location2 = _ref3.location, pathSection = _ref3.pathSection, routes15 = _ref3.routes;
  var breadcrumb2;
  var getIsPathExcluded = function getIsPathExcluded2(path) {
    return matchPath(pathSection, {
      path,
      exact: true,
      strict: false
    }) != null;
  };
  if (excludePaths && excludePaths.some(getIsPathExcluded)) {
    return NO_BREADCRUMB;
  }
  routes15.some(function(_a) {
    var userProvidedBreadcrumb = _a.breadcrumb, matchOptions = _a.matchOptions, path = _a.path, rest = __rest4(_a, ["breadcrumb", "matchOptions", "path"]);
    if (!path) {
      throw new Error("useBreadcrumbs: `path` must be provided in every route object");
    }
    var match2 = matchPath(pathSection, Object.assign(Object.assign({}, matchOptions || DEFAULT_MATCH_OPTIONS), {
      path
    }));
    if (match2 && userProvidedBreadcrumb === null || !match2 && matchOptions) {
      breadcrumb2 = NO_BREADCRUMB;
      return true;
    }
    if (match2) {
      if (!userProvidedBreadcrumb && disableDefaults) {
        breadcrumb2 = NO_BREADCRUMB;
        return true;
      }
      breadcrumb2 = render2(Object.assign({
        breadcrumb: userProvidedBreadcrumb || humanize(currentSection),
        match: match2,
        location: location2
      }, rest));
      return true;
    }
    return false;
  });
  if (breadcrumb2) {
    return breadcrumb2;
  }
  if (disableDefaults) {
    return NO_BREADCRUMB;
  }
  return getDefaultBreadcrumb({
    pathSection,
    currentSection: pathSection === "/" ? "Home" : currentSection,
    location: location2
  });
};
var getBreadcrumbs = function getBreadcrumbs2(_ref4) {
  var routes15 = _ref4.routes, location2 = _ref4.location, _ref4$options = _ref4.options, options = _ref4$options === void 0 ? {} : _ref4$options;
  var matches2 = [];
  var pathname = location2.pathname;
  pathname.split("?")[0].split("/").reduce(function(previousSection, currentSection, index3) {
    var pathSection = !currentSection ? "/" : "".concat(previousSection, "/").concat(currentSection);
    if (pathSection === "/" && index3 !== 0) {
      return "";
    }
    var breadcrumb2 = getBreadcrumbMatch(Object.assign({
      currentSection,
      location: location2,
      pathSection,
      routes: routes15
    }, options));
    if (breadcrumb2 !== NO_BREADCRUMB) {
      matches2.push(breadcrumb2);
    }
    return pathSection === "/" ? "" : pathSection;
  }, "");
  return matches2;
};
var flattenRoutes = function flattenRoutes2(routes15) {
  return routes15.reduce(function(arr, route) {
    if (route.routes) {
      return arr.concat([route].concat(_toConsumableArray3(flattenRoutes2(route.routes))));
    }
    return arr.concat(route);
  }, []);
};
var useReactRouterBreadcrumbs = function useReactRouterBreadcrumbs2(routes15, options) {
  return getBreadcrumbs({
    routes: flattenRoutes(routes15 || []),
    location: useLocation(),
    options
  });
};
var use_react_router_breadcrumbs_default = useReactRouterBreadcrumbs;

// build/components/bread-crumb/GroupBreadCrumbs.js
var GroupBreadCrumbs = () => {
  const {t: t5} = useTranslation();
  const {clear, remove: remove3, subGroups} = useSubGroups();
  const {realm: realm2} = useRealm();
  const history = useHistory();
  const location2 = useLocation();
  useEffect(() => {
    return history.listen(({pathname}) => {
      if (!pathname.includes("/groups") || pathname.endsWith("/groups")) {
        clear();
      }
    });
  }, [history]);
  return subGroups.length !== 0 ? /* @__PURE__ */ react.createElement(Breadcrumb, null, /* @__PURE__ */ react.createElement(BreadcrumbItem, {
    key: "home"
  }, /* @__PURE__ */ react.createElement(Link, {
    to: `/${realm2}/groups`
  }, t5("groups"))), subGroups.map((group, i3) => {
    const isLastGroup = i3 === subGroups.length - 1;
    return /* @__PURE__ */ react.createElement(BreadcrumbItem, {
      key: group.id,
      isActive: isLastGroup
    }, !isLastGroup && /* @__PURE__ */ react.createElement(Link, {
      to: location2.pathname.substr(0, location2.pathname.indexOf(group.id) + group.id.length),
      onClick: () => remove3(group)
    }, group.name), isLastGroup && (group.id === "search" ? group.name : t5("groups:groupDetails")));
  })) : null;
};

// build/components/bread-crumb/PageBreadCrumbs.js
var PageBreadCrumbs = () => {
  const {t: t5} = useTranslation();
  const {realm: realm2} = useRealm();
  const elementText = (crumb) => isValidElement(crumb.breadcrumb) && crumb.breadcrumb.props.children;
  const routesWithCrumbs = routes14.map((route) => ({
    ...route,
    breadcrumb: route.breadcrumb?.(t5)
  }));
  const crumbs = lodash.uniqBy(use_react_router_breadcrumbs_default(routesWithCrumbs, {
    disableDefaults: true,
    excludePaths: ["/", `/${realm2}`]
  }), elementText);
  return /* @__PURE__ */ react.createElement(react.Fragment, null, crumbs.length > 1 && /* @__PURE__ */ react.createElement(Breadcrumb, null, crumbs.map(({match: match2, breadcrumb: crumb}, i3) => /* @__PURE__ */ react.createElement(BreadcrumbItem, {
    key: i3,
    isActive: crumbs.length - 1 === i3
  }, crumbs.length - 1 !== i3 && /* @__PURE__ */ react.createElement(Link, {
    to: match2.url
  }, crumb), crumbs.length - 1 === i3 && crumb))), /* @__PURE__ */ react.createElement(GroupBreadCrumbs, null));
};

// build/ForbiddenSection.js
var ForbiddenSection = () => {
  return /* @__PURE__ */ react.createElement(react.Fragment, null, "Forbidden");
};

// build/components/error/ErrorRenderer.js
var ErrorRenderer = ({error: error2, resetErrorBoundary}) => {
  const {t: t5} = useTranslation();
  return /* @__PURE__ */ react.createElement(PageSection, null, /* @__PURE__ */ react.createElement(Alert, {
    isInline: true,
    variant: AlertVariant.danger,
    title: error2.message,
    actionClose: /* @__PURE__ */ react.createElement(AlertActionCloseButton, {
      title: error2.message,
      onClose: resetErrorBoundary
    }),
    actionLinks: /* @__PURE__ */ react.createElement(AlertActionLink, {
      onClick: resetErrorBoundary
    }, t5("retry"))
  }));
};

// build/App.js
var mainPageContentId = "kc-main-content-page-container";
var AppContexts = ({
  children: children2,
  adminClient
}) => /* @__PURE__ */ react.createElement(HashRouter, null, /* @__PURE__ */ react.createElement(AdminClient.Provider, {
  value: adminClient
}, /* @__PURE__ */ react.createElement(WhoAmIContextProvider, null, /* @__PURE__ */ react.createElement(RealmsProvider, null, /* @__PURE__ */ react.createElement(RealmContextProvider, null, /* @__PURE__ */ react.createElement(AccessContextProvider, null, /* @__PURE__ */ react.createElement(Help, null, /* @__PURE__ */ react.createElement(AlertProvider, null, /* @__PURE__ */ react.createElement(ServerInfoProvider, null, /* @__PURE__ */ react.createElement(SubGroups, null, children2))))))))));
var SecuredRoute = ({route}) => {
  const {hasAccess} = useAccess();
  const accessAllowed = route.access instanceof Array ? hasAccess(...route.access) : hasAccess(route.access);
  if (accessAllowed)
    return /* @__PURE__ */ react.createElement(Suspense, {
      fallback: /* @__PURE__ */ react.createElement(KeycloakSpinner, null)
    }, /* @__PURE__ */ react.createElement(route.component, null));
  return /* @__PURE__ */ react.createElement(ForbiddenSection, null);
};
var App = ({adminClient}) => {
  return /* @__PURE__ */ react.createElement(AppContexts, {
    adminClient
  }, /* @__PURE__ */ react.createElement(Page, {
    header: /* @__PURE__ */ react.createElement(Header, null),
    isManagedSidebar: true,
    sidebar: /* @__PURE__ */ react.createElement(PageNav, null),
    breadcrumb: /* @__PURE__ */ react.createElement(PageBreadCrumbs, null),
    mainContainerId: mainPageContentId
  }, /* @__PURE__ */ react.createElement(ErrorBoundary, {
    FallbackComponent: ErrorRenderer,
    onReset: () => window.location.href = window.location.origin + window.location.pathname
  }, /* @__PURE__ */ react.createElement(Switch2, null, routes14.map((route, i3) => /* @__PURE__ */ react.createElement(Route, {
    exact: route.matchOptions?.exact ?? true,
    key: i3,
    path: route.path,
    component: () => /* @__PURE__ */ react.createElement(SecuredRoute, {
      route
    })
  }))))));
};

// build/context/auth/keycloak.js
var import_keycloak_admin_client = require_keycloak_admin_client();
async function keycloak_default() {
  const kcAdminClient = new import_keycloak_admin_client.default();
  try {
    await kcAdminClient.init({onLoad: "check-sso", pkceMethod: "S256"}, {
      url: environment_default.authUrl,
      realm: environment_default.loginRealm,
      clientId: environment_default.isRunningAsTheme ? "security-admin-console" : "security-admin-console-v2"
    });
    kcAdminClient.setConfig({realmName: environment_default.loginRealm});
    kcAdminClient.baseUrl = environment_default.authUrl;
  } catch (error2) {
    alert("failed to initialize keycloak");
  }
  return kcAdminClient;
}

// build/index.js
import.meta.env = env_exports;
console.info("supported languages", ...i18n_default.languages);
keycloak_default().then((adminClient) => {
  reactDom.render(/* @__PURE__ */ react.createElement(StrictMode, null, /* @__PURE__ */ react.createElement(App, {
    adminClient
  })), document.getElementById("app"));
});
if (void 0) {
  (void 0).accept();
}
//# sourceMappingURL=index.js.map
